text
stringlengths
5
1.04M
/* ==================================================================== * The Vovida Software License, Version 1.0 * * Copyright (c) 2000 Vovida Networks, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "VOCAL", "Vovida Open Communication Application Library", * and "Vovida Open Communication Application Library (VOCAL)" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact vocal@vovida.org. * * 4. Products derived from this software may not be called "VOCAL", nor * may "VOCAL" appear in their name, without prior written * permission of Vovida Networks, Inc. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES * IN EXCESS OF $1,000, NOR FOR ANY 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. * * ==================================================================== * * This software consists of voluntary contributions made by Vovida * Networks, Inc. and many individuals on behalf of Vovida Networks, * Inc. For more information on Vovida Networks, Inc., please see * <http://www.vovida.org/>. * */ static const char* const VocalCommon_cxx_Version = "$Id: VocalCommon.cxx,v 1.1 2004/05/01 04:15:33 greear Exp $"; #include "global.h" #include "VocalCommon.hxx" const Vocal::ReturnCode Vocal::SUCCESS = 0;
/*========================================================================= Program: Visualization Toolkit Module: vtkImagePlaneWidget.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 "vtkImagePlaneWidget.h" #include "vtkActor.h" #include "vtkAlgorithmOutput.h" #include "vtkAssemblyNode.h" #include "vtkAssemblyPath.h" #include "vtkCallbackCommand.h" #include "vtkCamera.h" #include "vtkCellArray.h" #include "vtkCellPicker.h" #include "vtkImageData.h" #include "vtkImageMapToColors.h" #include "vtkImageReslice.h" #include "vtkInformation.h" #include "vtkLookupTable.h" #include "vtkMath.h" #include "vtkMatrix4x4.h" #include "vtkObjectFactory.h" #include "vtkPickingManager.h" #include "vtkPlaneSource.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkTextActor.h" #include "vtkTextProperty.h" #include "vtkTexture.h" #include "vtkTransform.h" vtkStandardNewMacro(vtkImagePlaneWidget); vtkCxxSetObjectMacro(vtkImagePlaneWidget, PlaneProperty, vtkProperty); vtkCxxSetObjectMacro(vtkImagePlaneWidget, SelectedPlaneProperty, vtkProperty); vtkCxxSetObjectMacro(vtkImagePlaneWidget, CursorProperty, vtkProperty); vtkCxxSetObjectMacro(vtkImagePlaneWidget, MarginProperty, vtkProperty); vtkCxxSetObjectMacro(vtkImagePlaneWidget, TexturePlaneProperty, vtkProperty); vtkCxxSetObjectMacro(vtkImagePlaneWidget, ColorMap, vtkImageMapToColors); //------------------------------------------------------------------------------ vtkImagePlaneWidget::vtkImagePlaneWidget() { this->State = vtkImagePlaneWidget::Start; this->EventCallbackCommand->SetCallback(vtkImagePlaneWidget::ProcessEvents); this->Interaction = 1; this->PlaneOrientation = 0; this->PlaceFactor = 1.0; this->RestrictPlaneToVolume = 1; this->OriginalWindow = 1.0; this->OriginalLevel = 0.5; this->CurrentWindow = 1.0; this->CurrentLevel = 0.5; this->TextureInterpolate = 1; this->ResliceInterpolate = VTK_LINEAR_RESLICE; this->UserControlledLookupTable = 0; this->DisplayText = 0; this->CurrentCursorPosition[0] = 0; this->CurrentCursorPosition[1] = 0; this->CurrentCursorPosition[2] = 0; this->CurrentImageValue = VTK_DOUBLE_MAX; this->MarginSelectMode = 8; this->UseContinuousCursor = 0; this->MarginSizeX = 0.05; this->MarginSizeY = 0.05; // Represent the plane's outline // this->PlaneSource = vtkPlaneSource::New(); this->PlaneSource->SetXResolution(1); this->PlaneSource->SetYResolution(1); this->PlaneOutlinePolyData = vtkPolyData::New(); this->PlaneOutlineActor = vtkActor::New(); // Represent the resliced image plane // this->ColorMap = vtkImageMapToColors::New(); this->Reslice = vtkImageReslice::New(); this->Reslice->TransformInputSamplingOff(); this->ResliceAxes = vtkMatrix4x4::New(); this->Texture = vtkTexture::New(); this->TexturePlaneActor = vtkActor::New(); this->Transform = vtkTransform::New(); this->ImageData = nullptr; this->LookupTable = nullptr; // Represent the cross hair cursor // this->CursorPolyData = vtkPolyData::New(); this->CursorActor = vtkActor::New(); // Represent the oblique positioning margins // this->MarginPolyData = vtkPolyData::New(); this->MarginActor = vtkActor::New(); // Represent the text: annotation for cursor position and W/L // this->TextActor = vtkTextActor::New(); this->GeneratePlaneOutline(); // Define some default point coordinates // double bounds[6]; bounds[0] = -0.5; bounds[1] = 0.5; bounds[2] = -0.5; bounds[3] = 0.5; bounds[4] = -0.5; bounds[5] = 0.5; // Initial creation of the widget, serves to initialize it // this->PlaceWidget(bounds); this->GenerateTexturePlane(); this->GenerateCursor(); this->GenerateMargins(); this->GenerateText(); // Manage the picking stuff // this->PlanePicker = nullptr; vtkCellPicker* picker = vtkCellPicker::New(); picker->SetTolerance(0.005); // need some fluff this->SetPicker(picker); picker->Delete(); // Set up the initial properties // this->PlaneProperty = nullptr; this->SelectedPlaneProperty = nullptr; this->TexturePlaneProperty = nullptr; this->CursorProperty = nullptr; this->MarginProperty = nullptr; this->CreateDefaultProperties(); // Set up actions this->LeftButtonAction = vtkImagePlaneWidget::VTK_CURSOR_ACTION; this->MiddleButtonAction = vtkImagePlaneWidget::VTK_SLICE_MOTION_ACTION; this->RightButtonAction = vtkImagePlaneWidget::VTK_WINDOW_LEVEL_ACTION; // Set up modifiers this->LeftButtonAutoModifier = vtkImagePlaneWidget::VTK_NO_MODIFIER; this->MiddleButtonAutoModifier = vtkImagePlaneWidget::VTK_NO_MODIFIER; this->RightButtonAutoModifier = vtkImagePlaneWidget::VTK_NO_MODIFIER; this->LastButtonPressed = vtkImagePlaneWidget::VTK_NO_BUTTON; this->TextureVisibility = 1; } //------------------------------------------------------------------------------ vtkImagePlaneWidget::~vtkImagePlaneWidget() { this->PlaneOutlineActor->Delete(); this->PlaneOutlinePolyData->Delete(); this->PlaneSource->Delete(); if (this->PlanePicker) { this->PlanePicker->UnRegister(this); } if (this->PlaneProperty) { this->PlaneProperty->Delete(); } if (this->SelectedPlaneProperty) { this->SelectedPlaneProperty->Delete(); } if (this->CursorProperty) { this->CursorProperty->Delete(); } if (this->MarginProperty) { this->MarginProperty->Delete(); } this->ResliceAxes->Delete(); this->Transform->Delete(); this->Reslice->Delete(); if (this->LookupTable) { this->LookupTable->UnRegister(this); } this->TexturePlaneActor->Delete(); this->ColorMap->Delete(); this->Texture->Delete(); if (this->TexturePlaneProperty) { this->TexturePlaneProperty->Delete(); } if (this->ImageData) { this->ImageData = nullptr; } this->CursorActor->Delete(); this->CursorPolyData->Delete(); this->MarginActor->Delete(); this->MarginPolyData->Delete(); this->TextActor->Delete(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetTextureVisibility(vtkTypeBool vis) { if (this->TextureVisibility == vis) { return; } this->TextureVisibility = vis; if (this->Enabled) { if (this->TextureVisibility && this->ImageData) { this->CurrentRenderer->AddViewProp(this->TexturePlaneActor); } else { this->CurrentRenderer->RemoveViewProp(this->TexturePlaneActor); } } this->Modified(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetEnabled(int enabling) { if (!this->Interactor) { vtkErrorMacro(<< "The interactor must be set prior to enabling/disabling widget"); return; } if (enabling) //---------------------------------------------------------- { vtkDebugMacro(<< "Enabling plane widget"); if (this->Enabled) // already enabled, just return { return; } if (!this->CurrentRenderer) { this->SetCurrentRenderer(this->Interactor->FindPokedRenderer( this->Interactor->GetLastEventPosition()[0], this->Interactor->GetLastEventPosition()[1])); if (this->CurrentRenderer == nullptr) { return; } } this->Enabled = 1; // we have to honour this ivar: it could be that this->Interaction was // set to off when we were disabled if (this->Interaction) { this->AddObservers(); } // Add the plane this->CurrentRenderer->AddViewProp(this->PlaneOutlineActor); this->PlaneOutlineActor->SetProperty(this->PlaneProperty); // add the TexturePlaneActor if (this->TextureVisibility && this->ImageData) { this->CurrentRenderer->AddViewProp(this->TexturePlaneActor); } this->TexturePlaneActor->SetProperty(this->TexturePlaneProperty); // Add the cross-hair cursor this->CurrentRenderer->AddViewProp(this->CursorActor); this->CursorActor->SetProperty(this->CursorProperty); // Add the margins this->CurrentRenderer->AddViewProp(this->MarginActor); this->MarginActor->SetProperty(this->MarginProperty); // Add the image data annotation this->CurrentRenderer->AddViewProp(this->TextActor); this->RegisterPickers(); this->TexturePlaneActor->PickableOn(); this->InvokeEvent(vtkCommand::EnableEvent, nullptr); } else // disabling---------------------------------------------------------- { vtkDebugMacro(<< "Disabling plane widget"); if (!this->Enabled) // already disabled, just return { return; } this->Enabled = 0; // don't listen for events any more this->Interactor->RemoveObserver(this->EventCallbackCommand); // turn off the plane this->CurrentRenderer->RemoveViewProp(this->PlaneOutlineActor); // turn off the texture plane this->CurrentRenderer->RemoveViewProp(this->TexturePlaneActor); // turn off the cursor this->CurrentRenderer->RemoveViewProp(this->CursorActor); // turn off the margins this->CurrentRenderer->RemoveViewProp(this->MarginActor); // turn off the image data annotation this->CurrentRenderer->RemoveViewProp(this->TextActor); this->TexturePlaneActor->PickableOff(); this->InvokeEvent(vtkCommand::DisableEvent, nullptr); this->SetCurrentRenderer(nullptr); this->UnRegisterPickers(); } this->Interactor->Render(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::ProcessEvents( vtkObject* vtkNotUsed(object), unsigned long event, void* clientdata, void* vtkNotUsed(calldata)) { vtkImagePlaneWidget* self = reinterpret_cast<vtkImagePlaneWidget*>(clientdata); self->LastButtonPressed = vtkImagePlaneWidget::VTK_NO_BUTTON; // okay, let's do the right thing switch (event) { case vtkCommand::LeftButtonPressEvent: self->LastButtonPressed = vtkImagePlaneWidget::VTK_LEFT_BUTTON; self->OnLeftButtonDown(); break; case vtkCommand::LeftButtonReleaseEvent: self->LastButtonPressed = vtkImagePlaneWidget::VTK_LEFT_BUTTON; self->OnLeftButtonUp(); break; case vtkCommand::MiddleButtonPressEvent: self->LastButtonPressed = vtkImagePlaneWidget::VTK_MIDDLE_BUTTON; self->OnMiddleButtonDown(); break; case vtkCommand::MiddleButtonReleaseEvent: self->LastButtonPressed = vtkImagePlaneWidget::VTK_MIDDLE_BUTTON; self->OnMiddleButtonUp(); break; case vtkCommand::RightButtonPressEvent: self->LastButtonPressed = vtkImagePlaneWidget::VTK_RIGHT_BUTTON; self->OnRightButtonDown(); break; case vtkCommand::RightButtonReleaseEvent: self->LastButtonPressed = vtkImagePlaneWidget::VTK_RIGHT_BUTTON; self->OnRightButtonUp(); break; case vtkCommand::MouseMoveEvent: self->OnMouseMove(); break; case vtkCommand::CharEvent: self->OnChar(); break; } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::OnChar() { vtkRenderWindowInteractor* i = this->Interactor; if (i->GetKeyCode() == 'r' || i->GetKeyCode() == 'R') { if (i->GetShiftKey() || i->GetControlKey()) { this->SetWindowLevel(this->OriginalWindow, this->OriginalLevel); double wl[2] = { this->CurrentWindow, this->CurrentLevel }; this->EventCallbackCommand->SetAbortFlag(1); this->InvokeEvent(vtkCommand::ResetWindowLevelEvent, wl); } else { this->Interactor->GetInteractorStyle()->OnChar(); } } else { this->Interactor->GetInteractorStyle()->OnChar(); } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::AddObservers() { // listen for the following events vtkRenderWindowInteractor* i = this->Interactor; if (i) { i->AddObserver(vtkCommand::MouseMoveEvent, this->EventCallbackCommand, this->Priority); i->AddObserver(vtkCommand::LeftButtonPressEvent, this->EventCallbackCommand, this->Priority); i->AddObserver(vtkCommand::LeftButtonReleaseEvent, this->EventCallbackCommand, this->Priority); i->AddObserver(vtkCommand::MiddleButtonPressEvent, this->EventCallbackCommand, this->Priority); i->AddObserver( vtkCommand::MiddleButtonReleaseEvent, this->EventCallbackCommand, this->Priority); i->AddObserver(vtkCommand::RightButtonPressEvent, this->EventCallbackCommand, this->Priority); i->AddObserver(vtkCommand::RightButtonReleaseEvent, this->EventCallbackCommand, this->Priority); i->AddObserver(vtkCommand::CharEvent, this->EventCallbackCommand, this->Priority); } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetInteraction(vtkTypeBool interact) { if (this->Interactor && this->Enabled) { if (this->Interaction == interact) { return; } if (interact == 0) { this->Interactor->RemoveObserver(this->EventCallbackCommand); } else { this->AddObservers(); } this->Interaction = interact; } else { vtkGenericWarningMacro(<< "set interactor and Enabled before changing interaction..."); } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); if (this->PlaneProperty) { os << indent << "Plane Property:\n"; this->PlaneProperty->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "Plane Property: (none)\n"; } if (this->SelectedPlaneProperty) { os << indent << "Selected Plane Property:\n"; this->SelectedPlaneProperty->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "Selected Plane Property: (none)\n"; } if (this->LookupTable) { os << indent << "LookupTable:\n"; this->LookupTable->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "LookupTable: (none)\n"; } if (this->CursorProperty) { os << indent << "Cursor Property:\n"; this->CursorProperty->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "Cursor Property: (none)\n"; } if (this->MarginProperty) { os << indent << "Margin Property:\n"; this->MarginProperty->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "Margin Property: (none)\n"; } if (this->TexturePlaneProperty) { os << indent << "TexturePlane Property:\n"; this->TexturePlaneProperty->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "TexturePlane Property: (none)\n"; } if (this->ColorMap) { os << indent << "ColorMap:\n"; this->ColorMap->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "ColorMap: (none)\n"; } if (this->Reslice) { os << indent << "Reslice:\n"; this->Reslice->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "Reslice: (none)\n"; } if (this->ResliceAxes) { os << indent << "ResliceAxes:\n"; this->ResliceAxes->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "ResliceAxes: (none)\n"; } double* o = this->PlaneSource->GetOrigin(); double* pt1 = this->PlaneSource->GetPoint1(); double* pt2 = this->PlaneSource->GetPoint2(); os << indent << "Origin: (" << o[0] << ", " << o[1] << ", " << o[2] << ")\n"; os << indent << "Point 1: (" << pt1[0] << ", " << pt1[1] << ", " << pt1[2] << ")\n"; os << indent << "Point 2: (" << pt2[0] << ", " << pt2[1] << ", " << pt2[2] << ")\n"; os << indent << "Current Cursor Position: (" << this->CurrentCursorPosition[0] << ", " << this->CurrentCursorPosition[1] << ", " << this->CurrentCursorPosition[2] << ")\n"; os << indent << "Current Image Value: " << this->CurrentImageValue << "\n"; os << indent << "Plane Orientation: " << this->PlaneOrientation << "\n"; os << indent << "Reslice Interpolate: " << this->ResliceInterpolate << "\n"; os << indent << "Texture Interpolate: " << (this->TextureInterpolate ? "On\n" : "Off\n"); os << indent << "Texture Visibility: " << (this->TextureVisibility ? "On\n" : "Off\n"); os << indent << "Restrict Plane To Volume: " << (this->RestrictPlaneToVolume ? "On\n" : "Off\n"); os << indent << "Display Text: " << (this->DisplayText ? "On\n" : "Off\n"); os << indent << "Interaction: " << (this->Interaction ? "On\n" : "Off\n"); os << indent << "User Controlled Lookup Table: " << (this->UserControlledLookupTable ? "On\n" : "Off\n"); os << indent << "LeftButtonAction: " << this->LeftButtonAction << endl; os << indent << "MiddleButtonAction: " << this->MiddleButtonAction << endl; os << indent << "RightButtonAction: " << this->RightButtonAction << endl; os << indent << "LeftButtonAutoModifier: " << this->LeftButtonAutoModifier << endl; os << indent << "MiddleButtonAutoModifier: " << this->MiddleButtonAutoModifier << endl; os << indent << "RightButtonAutoModifier: " << this->RightButtonAutoModifier << endl; os << indent << "UseContinuousCursor: " << (this->UseContinuousCursor ? "On\n" : "Off\n"); os << indent << "MarginSizeX: " << this->MarginSizeX << "\n"; os << indent << "MarginSizeY: " << this->MarginSizeY << "\n"; } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::BuildRepresentation() { this->PlaneSource->Update(); double* o = this->PlaneSource->GetOrigin(); double* pt1 = this->PlaneSource->GetPoint1(); double* pt2 = this->PlaneSource->GetPoint2(); double x[3]; x[0] = o[0] + (pt1[0] - o[0]) + (pt2[0] - o[0]); x[1] = o[1] + (pt1[1] - o[1]) + (pt2[1] - o[1]); x[2] = o[2] + (pt1[2] - o[2]) + (pt2[2] - o[2]); vtkPoints* points = this->PlaneOutlinePolyData->GetPoints(); points->SetPoint(0, o); points->SetPoint(1, pt1); points->SetPoint(2, x); points->SetPoint(3, pt2); points->GetData()->Modified(); this->PlaneOutlinePolyData->Modified(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::HighlightPlane(int highlight) { if (highlight) { this->PlaneOutlineActor->SetProperty(this->SelectedPlaneProperty); this->PlanePicker->GetPickPosition(this->LastPickPosition); } else { this->PlaneOutlineActor->SetProperty(this->PlaneProperty); } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::OnLeftButtonDown() { switch (this->LeftButtonAction) { case vtkImagePlaneWidget::VTK_CURSOR_ACTION: this->StartCursor(); break; case vtkImagePlaneWidget::VTK_SLICE_MOTION_ACTION: this->StartSliceMotion(); break; case vtkImagePlaneWidget::VTK_WINDOW_LEVEL_ACTION: this->StartWindowLevel(); break; } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::OnLeftButtonUp() { switch (this->LeftButtonAction) { case vtkImagePlaneWidget::VTK_CURSOR_ACTION: this->StopCursor(); break; case vtkImagePlaneWidget::VTK_SLICE_MOTION_ACTION: this->StopSliceMotion(); break; case vtkImagePlaneWidget::VTK_WINDOW_LEVEL_ACTION: this->StopWindowLevel(); break; } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::OnMiddleButtonDown() { switch (this->MiddleButtonAction) { case vtkImagePlaneWidget::VTK_CURSOR_ACTION: this->StartCursor(); break; case vtkImagePlaneWidget::VTK_SLICE_MOTION_ACTION: this->StartSliceMotion(); break; case vtkImagePlaneWidget::VTK_WINDOW_LEVEL_ACTION: this->StartWindowLevel(); break; } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::OnMiddleButtonUp() { switch (this->MiddleButtonAction) { case vtkImagePlaneWidget::VTK_CURSOR_ACTION: this->StopCursor(); break; case vtkImagePlaneWidget::VTK_SLICE_MOTION_ACTION: this->StopSliceMotion(); break; case vtkImagePlaneWidget::VTK_WINDOW_LEVEL_ACTION: this->StopWindowLevel(); break; } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::OnRightButtonDown() { switch (this->RightButtonAction) { case vtkImagePlaneWidget::VTK_CURSOR_ACTION: this->StartCursor(); break; case vtkImagePlaneWidget::VTK_SLICE_MOTION_ACTION: this->StartSliceMotion(); break; case vtkImagePlaneWidget::VTK_WINDOW_LEVEL_ACTION: this->StartWindowLevel(); break; } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::OnRightButtonUp() { switch (this->RightButtonAction) { case vtkImagePlaneWidget::VTK_CURSOR_ACTION: this->StopCursor(); break; case vtkImagePlaneWidget::VTK_SLICE_MOTION_ACTION: this->StopSliceMotion(); break; case vtkImagePlaneWidget::VTK_WINDOW_LEVEL_ACTION: this->StopWindowLevel(); break; } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::StartCursor() { int X = this->Interactor->GetEventPosition()[0]; int Y = this->Interactor->GetEventPosition()[1]; // Okay, make sure that the pick is in the current renderer if (!this->CurrentRenderer || !this->CurrentRenderer->IsInViewport(X, Y)) { this->State = vtkImagePlaneWidget::Outside; return; } // Okay, we can process this. If anything is picked, then we // can start pushing the plane. vtkAssemblyPath* path = this->GetAssemblyPath(X, Y, 0., this->PlanePicker); int found = 0; int i; if (path != nullptr) { // Deal with the possibility that we may be using a shared picker vtkCollectionSimpleIterator sit; path->InitTraversal(sit); vtkAssemblyNode* node; for (i = 0; i < path->GetNumberOfItems() && !found; i++) { node = path->GetNextNode(sit); if (node->GetViewProp() == vtkProp::SafeDownCast(this->TexturePlaneActor)) { found = 1; } } } if (!found || path == nullptr) { this->State = vtkImagePlaneWidget::Outside; this->HighlightPlane(0); this->ActivateCursor(0); this->ActivateText(0); return; } else { this->State = vtkImagePlaneWidget::Cursoring; this->HighlightPlane(1); this->ActivateCursor(1); this->ActivateText(1); this->UpdateCursor(X, Y); this->ManageTextDisplay(); } this->EventCallbackCommand->SetAbortFlag(1); this->StartInteraction(); this->InvokeEvent(vtkCommand::StartInteractionEvent, nullptr); this->Interactor->Render(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::StopCursor() { if (this->State == vtkImagePlaneWidget::Outside || this->State == vtkImagePlaneWidget::Start) { return; } this->State = vtkImagePlaneWidget::Start; this->HighlightPlane(0); this->ActivateCursor(0); this->ActivateText(0); this->EventCallbackCommand->SetAbortFlag(1); this->EndInteraction(); this->InvokeEvent(vtkCommand::EndInteractionEvent, nullptr); this->Interactor->Render(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::StartSliceMotion() { int X = this->Interactor->GetEventPosition()[0]; int Y = this->Interactor->GetEventPosition()[1]; // Okay, make sure that the pick is in the current renderer if (!this->CurrentRenderer || !this->CurrentRenderer->IsInViewport(X, Y)) { this->State = vtkImagePlaneWidget::Outside; return; } // Okay, we can process this. If anything is picked, then we // can start pushing or check for adjusted states. vtkAssemblyPath* path = this->GetAssemblyPath(X, Y, 0., this->PlanePicker); int found = 0; int i; if (path != nullptr) { // Deal with the possibility that we may be using a shared picker vtkCollectionSimpleIterator sit; path->InitTraversal(sit); vtkAssemblyNode* node; for (i = 0; i < path->GetNumberOfItems() && !found; i++) { node = path->GetNextNode(sit); if (node->GetViewProp() == vtkProp::SafeDownCast(this->TexturePlaneActor)) { found = 1; } } } if (!found || path == nullptr) { this->State = vtkImagePlaneWidget::Outside; this->HighlightPlane(0); this->ActivateMargins(0); return; } else { this->State = vtkImagePlaneWidget::Pushing; this->HighlightPlane(1); this->ActivateMargins(1); this->AdjustState(); this->UpdateMargins(); } this->EventCallbackCommand->SetAbortFlag(1); this->StartInteraction(); this->InvokeEvent(vtkCommand::StartInteractionEvent, nullptr); this->Interactor->Render(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::StopSliceMotion() { if (this->State == vtkImagePlaneWidget::Outside || this->State == vtkImagePlaneWidget::Start) { return; } this->State = vtkImagePlaneWidget::Start; this->HighlightPlane(0); this->ActivateMargins(0); this->EventCallbackCommand->SetAbortFlag(1); this->EndInteraction(); this->InvokeEvent(vtkCommand::EndInteractionEvent, nullptr); this->Interactor->Render(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::StartWindowLevel() { int X = this->Interactor->GetEventPosition()[0]; int Y = this->Interactor->GetEventPosition()[1]; // Okay, make sure that the pick is in the current renderer if (!this->CurrentRenderer || !this->CurrentRenderer->IsInViewport(X, Y)) { this->State = vtkImagePlaneWidget::Outside; return; } // Okay, we can process this. If anything is picked, then we // can start window-levelling. vtkAssemblyPath* path = this->GetAssemblyPath(X, Y, 0., this->PlanePicker); int found = 0; int i; if (path != nullptr) { // Deal with the possibility that we may be using a shared picker vtkCollectionSimpleIterator sit; path->InitTraversal(sit); vtkAssemblyNode* node; for (i = 0; i < path->GetNumberOfItems() && !found; i++) { node = path->GetNextNode(sit); if (node->GetViewProp() == vtkProp::SafeDownCast(this->TexturePlaneActor)) { found = 1; } } } this->InitialWindow = this->CurrentWindow; this->InitialLevel = this->CurrentLevel; if (!found || path == nullptr) { this->State = vtkImagePlaneWidget::Outside; this->HighlightPlane(0); this->ActivateText(0); return; } else { this->State = vtkImagePlaneWidget::WindowLevelling; this->HighlightPlane(1); this->ActivateText(1); this->StartWindowLevelPositionX = X; this->StartWindowLevelPositionY = Y; this->ManageTextDisplay(); } this->EventCallbackCommand->SetAbortFlag(1); this->StartInteraction(); double wl[2] = { this->CurrentWindow, this->CurrentLevel }; this->InvokeEvent(vtkCommand::StartWindowLevelEvent, wl); this->Interactor->Render(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::StopWindowLevel() { if (this->State == vtkImagePlaneWidget::Outside || this->State == vtkImagePlaneWidget::Start) { return; } this->State = vtkImagePlaneWidget::Start; this->HighlightPlane(0); this->ActivateText(0); this->EventCallbackCommand->SetAbortFlag(1); this->EndInteraction(); double wl[2] = { this->CurrentWindow, this->CurrentLevel }; this->InvokeEvent(vtkCommand::EndWindowLevelEvent, wl); this->Interactor->Render(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::OnMouseMove() { // See whether we're active // if (this->State == vtkImagePlaneWidget::Outside || this->State == vtkImagePlaneWidget::Start) { return; } int X = this->Interactor->GetEventPosition()[0]; int Y = this->Interactor->GetEventPosition()[1]; // Do different things depending on state // Calculations everybody does // double focalPoint[4], pickPoint[4], prevPickPoint[4]; double z, vpn[3]; vtkCamera* camera = this->CurrentRenderer->GetActiveCamera(); if (!camera) { return; } // Compute the two points defining the motion vector // this->ComputeWorldToDisplay( this->LastPickPosition[0], this->LastPickPosition[1], this->LastPickPosition[2], focalPoint); z = focalPoint[2]; this->ComputeDisplayToWorld(double(this->Interactor->GetLastEventPosition()[0]), double(this->Interactor->GetLastEventPosition()[1]), z, prevPickPoint); this->ComputeDisplayToWorld(double(X), double(Y), z, pickPoint); if (this->State == vtkImagePlaneWidget::WindowLevelling) { this->WindowLevel(X, Y); this->ManageTextDisplay(); } else if (this->State == vtkImagePlaneWidget::Pushing) { this->Push(prevPickPoint, pickPoint); this->UpdatePlane(); this->UpdateMargins(); this->BuildRepresentation(); } else if (this->State == vtkImagePlaneWidget::Spinning) { this->Spin(prevPickPoint, pickPoint); this->UpdatePlane(); this->UpdateMargins(); this->BuildRepresentation(); } else if (this->State == vtkImagePlaneWidget::Rotating) { camera->GetViewPlaneNormal(vpn); this->Rotate(prevPickPoint, pickPoint, vpn); this->UpdatePlane(); this->UpdateMargins(); this->BuildRepresentation(); } else if (this->State == vtkImagePlaneWidget::Scaling) { this->Scale(prevPickPoint, pickPoint, X, Y); this->UpdatePlane(); this->UpdateMargins(); this->BuildRepresentation(); } else if (this->State == vtkImagePlaneWidget::Moving) { this->Translate(prevPickPoint, pickPoint); this->UpdatePlane(); this->UpdateMargins(); this->BuildRepresentation(); } else if (this->State == vtkImagePlaneWidget::Cursoring) { this->UpdateCursor(X, Y); this->ManageTextDisplay(); } // Interact, if desired // this->EventCallbackCommand->SetAbortFlag(1); if (this->State == vtkImagePlaneWidget::WindowLevelling) { double wl[2] = { this->CurrentWindow, this->CurrentLevel }; this->InvokeEvent(vtkCommand::WindowLevelEvent, wl); } else { this->InvokeEvent(vtkCommand::InteractionEvent, nullptr); } this->Interactor->Render(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::WindowLevel(int X, int Y) { const int* size = this->CurrentRenderer->GetSize(); double window = this->InitialWindow; double level = this->InitialLevel; // Compute normalized delta double dx = 4.0 * (X - this->StartWindowLevelPositionX) / size[0]; double dy = 4.0 * (this->StartWindowLevelPositionY - Y) / size[1]; // Scale by current values if (fabs(window) > 0.01) { dx = dx * window; } else { dx = dx * (window < 0 ? -0.01 : 0.01); } if (fabs(level) > 0.01) { dy = dy * level; } else { dy = dy * (level < 0 ? -0.01 : 0.01); } // Abs so that direction does not flip if (window < 0.0) { dx = -1 * dx; } if (level < 0.0) { dy = -1 * dy; } // Compute new window level double newWindow = dx + window; double newLevel = level - dy; if (fabs(newWindow) < 0.01) { newWindow = 0.01 * (newWindow < 0 ? -1 : 1); } if (fabs(newLevel) < 0.01) { newLevel = 0.01 * (newLevel < 0 ? -1 : 1); } if (!this->UserControlledLookupTable) { if ((newWindow < 0 && this->CurrentWindow > 0) || (newWindow > 0 && this->CurrentWindow < 0)) { this->InvertTable(); } double rmin = newLevel - 0.5 * fabs(newWindow); double rmax = rmin + fabs(newWindow); this->LookupTable->SetTableRange(rmin, rmax); } this->CurrentWindow = newWindow; this->CurrentLevel = newLevel; } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::InvertTable() { int index = this->LookupTable->GetNumberOfTableValues(); unsigned char swap[4]; size_t num = 4 * sizeof(unsigned char); vtkUnsignedCharArray* table = this->LookupTable->GetTable(); for (int count = 0; count < --index; count++) { unsigned char* rgba1 = table->GetPointer(4 * count); unsigned char* rgba2 = table->GetPointer(4 * index); memcpy(swap, rgba1, num); memcpy(rgba1, rgba2, num); memcpy(rgba2, swap, num); } // force the lookuptable to update its InsertTime to avoid // rebuilding the array double temp[4]; this->LookupTable->GetTableValue(0, temp); this->LookupTable->SetTableValue(0, temp); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetWindowLevel(double window, double level, int copy) { if (copy) { this->CurrentWindow = window; this->CurrentLevel = level; return; } if (this->CurrentWindow == window && this->CurrentLevel == level) { return; } // if the new window is negative and the old window was positive invert table if (((window < 0 && this->CurrentWindow > 0) || (window > 0 && this->CurrentWindow < 0)) && !this->UserControlledLookupTable) { this->InvertTable(); } this->CurrentWindow = window; this->CurrentLevel = level; if (!this->UserControlledLookupTable) { double rmin = this->CurrentLevel - 0.5 * fabs(this->CurrentWindow); double rmax = rmin + fabs(this->CurrentWindow); this->LookupTable->SetTableRange(rmin, rmax); } if (this->Enabled) { this->Interactor->Render(); } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GetWindowLevel(double wl[2]) { wl[0] = this->CurrentWindow; wl[1] = this->CurrentLevel; } //------------------------------------------------------------------------------ int vtkImagePlaneWidget::GetCursorData(double xyzv[4]) { if (this->State != vtkImagePlaneWidget::Cursoring || this->CurrentImageValue == VTK_DOUBLE_MAX) { return 0; } xyzv[0] = this->CurrentCursorPosition[0]; xyzv[1] = this->CurrentCursorPosition[1]; xyzv[2] = this->CurrentCursorPosition[2]; xyzv[3] = this->CurrentImageValue; return 1; } //------------------------------------------------------------------------------ int vtkImagePlaneWidget::GetCursorDataStatus() { if (this->State != vtkImagePlaneWidget::Cursoring || this->CurrentImageValue == VTK_DOUBLE_MAX) { return 0; } return 1; } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::ManageTextDisplay() { if (!this->DisplayText) { return; } if (this->State == vtkImagePlaneWidget::WindowLevelling) { snprintf(this->TextBuff, VTK_IMAGE_PLANE_WIDGET_MAX_TEXTBUFF, "Window, Level: ( %g, %g )", this->CurrentWindow, this->CurrentLevel); } else if (this->State == vtkImagePlaneWidget::Cursoring) { if (this->CurrentImageValue == VTK_DOUBLE_MAX) { snprintf(this->TextBuff, VTK_IMAGE_PLANE_WIDGET_MAX_TEXTBUFF, "Off Image"); } else { snprintf(this->TextBuff, VTK_IMAGE_PLANE_WIDGET_MAX_TEXTBUFF, "( %g, %g, %g ): %g", this->CurrentCursorPosition[0], this->CurrentCursorPosition[1], this->CurrentCursorPosition[2], this->CurrentImageValue); } } this->TextActor->SetInput(this->TextBuff); this->TextActor->Modified(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::Push(double* p1, double* p2) { // Get the motion vector // double v[3]; v[0] = p2[0] - p1[0]; v[1] = p2[1] - p1[1]; v[2] = p2[2] - p1[2]; this->PlaneSource->Push(vtkMath::Dot(v, this->PlaneSource->GetNormal())); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::CreateDefaultProperties() { if (!this->PlaneProperty) { this->PlaneProperty = vtkProperty::New(); this->PlaneProperty->SetAmbient(1); this->PlaneProperty->SetColor(1, 1, 1); this->PlaneProperty->SetRepresentationToWireframe(); this->PlaneProperty->SetInterpolationToFlat(); } if (!this->SelectedPlaneProperty) { this->SelectedPlaneProperty = vtkProperty::New(); this->SelectedPlaneProperty->SetAmbient(1); this->SelectedPlaneProperty->SetColor(0, 1, 0); this->SelectedPlaneProperty->SetRepresentationToWireframe(); this->SelectedPlaneProperty->SetInterpolationToFlat(); } if (!this->CursorProperty) { this->CursorProperty = vtkProperty::New(); this->CursorProperty->SetAmbient(1); this->CursorProperty->SetColor(1, 0, 0); this->CursorProperty->SetRepresentationToWireframe(); this->CursorProperty->SetInterpolationToFlat(); } if (!this->MarginProperty) { this->MarginProperty = vtkProperty::New(); this->MarginProperty->SetAmbient(1); this->MarginProperty->SetColor(0, 0, 1); this->MarginProperty->SetRepresentationToWireframe(); this->MarginProperty->SetInterpolationToFlat(); } if (!this->TexturePlaneProperty) { this->TexturePlaneProperty = vtkProperty::New(); this->TexturePlaneProperty->SetAmbient(1); this->TexturePlaneProperty->SetDiffuse(0); this->TexturePlaneProperty->SetInterpolationToFlat(); } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::PlaceWidget(double bds[6]) { double bounds[6], center[3]; this->AdjustBounds(bds, bounds, center); if (this->PlaneOrientation == 1) { this->PlaneSource->SetOrigin(bounds[0], center[1], bounds[4]); this->PlaneSource->SetPoint1(bounds[1], center[1], bounds[4]); this->PlaneSource->SetPoint2(bounds[0], center[1], bounds[5]); } else if (this->PlaneOrientation == 2) { this->PlaneSource->SetOrigin(bounds[0], bounds[2], center[2]); this->PlaneSource->SetPoint1(bounds[1], bounds[2], center[2]); this->PlaneSource->SetPoint2(bounds[0], bounds[3], center[2]); } else // default or x-normal { this->PlaneSource->SetOrigin(center[0], bounds[2], bounds[4]); this->PlaneSource->SetPoint1(center[0], bounds[3], bounds[4]); this->PlaneSource->SetPoint2(center[0], bounds[2], bounds[5]); } this->UpdatePlane(); this->BuildRepresentation(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetPlaneOrientation(int i) { // Generate a XY plane if i = 2, z-normal // or a YZ plane if i = 0, x-normal // or a ZX plane if i = 1, y-normal // this->PlaneOrientation = i; // This method must be called _after_ SetInput // if (!this->ImageData) { vtkErrorMacro(<< "SetInput() before setting plane orientation."); return; } vtkAlgorithm* inpAlg = this->Reslice->GetInputAlgorithm(); inpAlg->UpdateInformation(); vtkInformation* outInfo = inpAlg->GetOutputInformation(0); int extent[6]; outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent); double origin[3]; outInfo->Get(vtkDataObject::ORIGIN(), origin); double spacing[3]; outInfo->Get(vtkDataObject::SPACING(), spacing); // Prevent obscuring voxels by offsetting the plane geometry // double xbounds[] = { origin[0] + spacing[0] * (extent[0] - 0.5), origin[0] + spacing[0] * (extent[1] + 0.5) }; double ybounds[] = { origin[1] + spacing[1] * (extent[2] - 0.5), origin[1] + spacing[1] * (extent[3] + 0.5) }; double zbounds[] = { origin[2] + spacing[2] * (extent[4] - 0.5), origin[2] + spacing[2] * (extent[5] + 0.5) }; if (spacing[0] < 0.0) { double t = xbounds[0]; xbounds[0] = xbounds[1]; xbounds[1] = t; } if (spacing[1] < 0.0) { double t = ybounds[0]; ybounds[0] = ybounds[1]; ybounds[1] = t; } if (spacing[2] < 0.0) { double t = zbounds[0]; zbounds[0] = zbounds[1]; zbounds[1] = t; } if (i == 2) // XY, z-normal { this->PlaneSource->SetOrigin(xbounds[0], ybounds[0], zbounds[0]); this->PlaneSource->SetPoint1(xbounds[1], ybounds[0], zbounds[0]); this->PlaneSource->SetPoint2(xbounds[0], ybounds[1], zbounds[0]); } else if (i == 0) // YZ, x-normal { this->PlaneSource->SetOrigin(xbounds[0], ybounds[0], zbounds[0]); this->PlaneSource->SetPoint1(xbounds[0], ybounds[1], zbounds[0]); this->PlaneSource->SetPoint2(xbounds[0], ybounds[0], zbounds[1]); } else // ZX, y-normal { this->PlaneSource->SetOrigin(xbounds[0], ybounds[0], zbounds[0]); this->PlaneSource->SetPoint1(xbounds[0], ybounds[0], zbounds[1]); this->PlaneSource->SetPoint2(xbounds[1], ybounds[0], zbounds[0]); } this->UpdatePlane(); this->BuildRepresentation(); this->Modified(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetInputConnection(vtkAlgorithmOutput* aout) { this->Superclass::SetInputConnection(aout); this->ImageData = vtkImageData::SafeDownCast(aout->GetProducer()->GetOutputDataObject(aout->GetIndex())); if (!this->ImageData) { // If nullptr is passed, remove any reference that Reslice had // on the old ImageData // this->Reslice->SetInputData(nullptr); return; } double range[2]; this->ImageData->GetScalarRange(range); if (!this->UserControlledLookupTable) { this->LookupTable->SetTableRange(range[0], range[1]); this->LookupTable->Build(); } this->OriginalWindow = range[1] - range[0]; this->OriginalLevel = 0.5 * (range[0] + range[1]); if (fabs(this->OriginalWindow) < 0.001) { this->OriginalWindow = 0.001 * (this->OriginalWindow < 0.0 ? -1 : 1); } if (fabs(this->OriginalLevel) < 0.001) { this->OriginalLevel = 0.001 * (this->OriginalLevel < 0.0 ? -1 : 1); } this->SetWindowLevel(this->OriginalWindow, this->OriginalLevel); this->Reslice->SetInputConnection(aout); int interpolate = this->ResliceInterpolate; this->ResliceInterpolate = -1; // Force change this->SetResliceInterpolate(interpolate); this->ColorMap->SetInputConnection(this->Reslice->GetOutputPort()); this->Texture->SetInputConnection(this->ColorMap->GetOutputPort()); this->Texture->SetInterpolate(this->TextureInterpolate); this->SetPlaneOrientation(this->PlaneOrientation); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::UpdatePlane() { if (!this->Reslice || !this->ImageData) { return; } // Calculate appropriate pixel spacing for the reslicing // vtkAlgorithm* inpAlg = this->Reslice->GetInputAlgorithm(); inpAlg->UpdateInformation(); vtkInformation* outInfo = inpAlg->GetOutputInformation(0); double spacing[3]; outInfo->Get(vtkDataObject::SPACING(), spacing); double origin[3]; outInfo->Get(vtkDataObject::ORIGIN(), origin); int extent[6]; outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent); int i; for (i = 0; i < 3; i++) { if (extent[2 * i] > extent[2 * i + 1]) { vtkErrorMacro("Invalid extent [" << extent[0] << ", " << extent[1] << ", " << extent[2] << ", " << extent[3] << ", " << extent[4] << ", " << extent[5] << "]." << " Perhaps the input data is empty?"); break; } } if (this->RestrictPlaneToVolume) { double bounds[] = { origin[0] + spacing[0] * extent[0], // xmin origin[0] + spacing[0] * extent[1], // xmax origin[1] + spacing[1] * extent[2], // ymin origin[1] + spacing[1] * extent[3], // ymax origin[2] + spacing[2] * extent[4], // zmin origin[2] + spacing[2] * extent[5] }; // zmax for (i = 0; i <= 4; i += 2) // reverse bounds if necessary { if (bounds[i] > bounds[i + 1]) { double t = bounds[i + 1]; bounds[i + 1] = bounds[i]; bounds[i] = t; } } double abs_normal[3]; this->PlaneSource->GetNormal(abs_normal); double planeCenter[3]; this->PlaneSource->GetCenter(planeCenter); double nmax = 0.0; int k = 0; for (i = 0; i < 3; i++) { abs_normal[i] = fabs(abs_normal[i]); if (abs_normal[i] > nmax) { nmax = abs_normal[i]; k = i; } } // Force the plane to lie within the true image bounds along its normal // if (planeCenter[k] > bounds[2 * k + 1]) { planeCenter[k] = bounds[2 * k + 1]; } else if (planeCenter[k] < bounds[2 * k]) { planeCenter[k] = bounds[2 * k]; } this->PlaneSource->SetCenter(planeCenter); } double planeAxis1[3]; double planeAxis2[3]; this->GetVector1(planeAxis1); this->GetVector2(planeAxis2); // The x,y dimensions of the plane // double planeSizeX = vtkMath::Normalize(planeAxis1); double planeSizeY = vtkMath::Normalize(planeAxis2); double normal[3]; this->PlaneSource->GetNormal(normal); // Generate the slicing matrix // this->ResliceAxes->Identity(); for (i = 0; i < 3; i++) { this->ResliceAxes->SetElement(0, i, planeAxis1[i]); this->ResliceAxes->SetElement(1, i, planeAxis2[i]); this->ResliceAxes->SetElement(2, i, normal[i]); } double planeOrigin[4]; this->PlaneSource->GetOrigin(planeOrigin); planeOrigin[3] = 1.0; this->ResliceAxes->Transpose(); this->ResliceAxes->SetElement(0, 3, planeOrigin[0]); this->ResliceAxes->SetElement(1, 3, planeOrigin[1]); this->ResliceAxes->SetElement(2, 3, planeOrigin[2]); this->Reslice->SetResliceAxes(this->ResliceAxes); double spacingX = fabs(planeAxis1[0] * spacing[0]) + fabs(planeAxis1[1] * spacing[1]) + fabs(planeAxis1[2] * spacing[2]); double spacingY = fabs(planeAxis2[0] * spacing[0]) + fabs(planeAxis2[1] * spacing[1]) + fabs(planeAxis2[2] * spacing[2]); // Pad extent up to a power of two for efficient texture mapping // make sure we're working with valid values double realExtentX = (spacingX == 0) ? VTK_INT_MAX : planeSizeX / spacingX; int extentX; // Sanity check the input data: // * if realExtentX is too large, extentX will wrap // * if spacingX is 0, things will blow up. if (realExtentX > (VTK_INT_MAX >> 1)) { vtkErrorMacro(<< "Invalid X extent: " << realExtentX); extentX = 0; } else { extentX = 1; while (extentX < realExtentX) { extentX = extentX << 1; } } // make sure extentY doesn't wrap during padding double realExtentY = (spacingY == 0) ? VTK_INT_MAX : planeSizeY / spacingY; int extentY; if (realExtentY > (VTK_INT_MAX >> 1)) { vtkErrorMacro(<< "Invalid Y extent: " << realExtentY); extentY = 0; } else { extentY = 1; while (extentY < realExtentY) { extentY = extentY << 1; } } double outputSpacingX = (extentX == 0) ? 1.0 : planeSizeX / extentX; double outputSpacingY = (extentY == 0) ? 1.0 : planeSizeY / extentY; this->Reslice->SetOutputSpacing(outputSpacingX, outputSpacingY, 1); this->Reslice->SetOutputOrigin(0.5 * outputSpacingX, 0.5 * outputSpacingY, 0); this->Reslice->SetOutputExtent(0, extentX - 1, 0, extentY - 1, 0, 0); } //------------------------------------------------------------------------------ vtkImageData* vtkImagePlaneWidget::GetResliceOutput() { if (!this->Reslice) { return nullptr; } return this->Reslice->GetOutput(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetResliceInterpolate(int i) { if (this->ResliceInterpolate == i) { return; } this->ResliceInterpolate = i; this->Modified(); if (!this->Reslice) { return; } if (i == VTK_NEAREST_RESLICE) { this->Reslice->SetInterpolationModeToNearestNeighbor(); } else if (i == VTK_LINEAR_RESLICE) { this->Reslice->SetInterpolationModeToLinear(); } else { this->Reslice->SetInterpolationModeToCubic(); } this->Texture->SetInterpolate(this->TextureInterpolate); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetPicker(vtkAbstractPropPicker* picker) { // we have to have a picker for slice motion, window level and cursor to work if (this->PlanePicker != picker) { // to avoid destructor recursion vtkAbstractPropPicker* temp = this->PlanePicker; this->PlanePicker = picker; if (temp != nullptr) { temp->UnRegister(this); } int delPicker = 0; if (this->PlanePicker == nullptr) { this->PlanePicker = vtkCellPicker::New(); vtkCellPicker::SafeDownCast(this->PlanePicker)->SetTolerance(0.005); delPicker = 1; } this->PlanePicker->Register(this); this->PlanePicker->AddPickList(this->TexturePlaneActor); this->PlanePicker->PickFromListOn(); if (delPicker) { this->PlanePicker->Delete(); } } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::RegisterPickers() { vtkPickingManager* pm = this->GetPickingManager(); if (!pm) { return; } pm->AddPicker(this->PlanePicker, this); } //------------------------------------------------------------------------------ vtkLookupTable* vtkImagePlaneWidget::CreateDefaultLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->Register(this); lut->Delete(); lut->SetNumberOfColors(256); lut->SetHueRange(0, 0); lut->SetSaturationRange(0, 0); lut->SetValueRange(0, 1); lut->SetAlphaRange(1, 1); lut->Build(); return lut; } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetLookupTable(vtkLookupTable* table) { if (this->LookupTable != table) { // to avoid destructor recursion vtkLookupTable* temp = this->LookupTable; this->LookupTable = table; if (temp != nullptr) { temp->UnRegister(this); } if (this->LookupTable != nullptr) { this->LookupTable->Register(this); } else // create a default lut { this->LookupTable = this->CreateDefaultLookupTable(); } } this->ColorMap->SetLookupTable(this->LookupTable); this->Texture->SetLookupTable(this->LookupTable); if (this->ImageData && !this->UserControlledLookupTable) { double range[2]; this->ImageData->GetScalarRange(range); this->LookupTable->SetTableRange(range[0], range[1]); this->LookupTable->Build(); this->OriginalWindow = range[1] - range[0]; this->OriginalLevel = 0.5 * (range[0] + range[1]); if (fabs(this->OriginalWindow) < 0.001) { this->OriginalWindow = 0.001 * (this->OriginalWindow < 0.0 ? -1 : 1); } if (fabs(this->OriginalLevel) < 0.001) { this->OriginalLevel = 0.001 * (this->OriginalLevel < 0.0 ? -1 : 1); } this->SetWindowLevel(this->OriginalWindow, this->OriginalLevel); } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetSlicePosition(double position) { double amount = 0.0; double planeOrigin[3]; this->PlaneSource->GetOrigin(planeOrigin); if (this->PlaneOrientation == 2) // z axis { amount = position - planeOrigin[2]; } else if (this->PlaneOrientation == 0) // x axis { amount = position - planeOrigin[0]; } else if (this->PlaneOrientation == 1) // y axis { amount = position - planeOrigin[1]; } else { vtkGenericWarningMacro("only works for ortho planes: set plane orientation first"); return; } this->PlaneSource->Push(amount); this->UpdatePlane(); this->BuildRepresentation(); this->Modified(); } //------------------------------------------------------------------------------ double vtkImagePlaneWidget::GetSlicePosition() { double planeOrigin[3]; this->PlaneSource->GetOrigin(planeOrigin); if (this->PlaneOrientation == 2) { return planeOrigin[2]; } else if (this->PlaneOrientation == 1) { return planeOrigin[1]; } else if (this->PlaneOrientation == 0) { return planeOrigin[0]; } else { vtkGenericWarningMacro("only works for ortho planes: set plane orientation first"); } return 0.0; } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetSliceIndex(int index) { if (!this->Reslice) { return; } if (!this->ImageData) { return; } vtkAlgorithm* inpAlg = this->Reslice->GetInputAlgorithm(); inpAlg->UpdateInformation(); vtkInformation* outInfo = inpAlg->GetOutputInformation(0); double origin[3]; outInfo->Get(vtkDataObject::ORIGIN(), origin); double spacing[3]; outInfo->Get(vtkDataObject::SPACING(), spacing); double planeOrigin[3]; this->PlaneSource->GetOrigin(planeOrigin); double pt1[3]; this->PlaneSource->GetPoint1(pt1); double pt2[3]; this->PlaneSource->GetPoint2(pt2); if (this->PlaneOrientation == 2) { planeOrigin[2] = origin[2] + index * spacing[2]; pt1[2] = planeOrigin[2]; pt2[2] = planeOrigin[2]; } else if (this->PlaneOrientation == 1) { planeOrigin[1] = origin[1] + index * spacing[1]; pt1[1] = planeOrigin[1]; pt2[1] = planeOrigin[1]; } else if (this->PlaneOrientation == 0) { planeOrigin[0] = origin[0] + index * spacing[0]; pt1[0] = planeOrigin[0]; pt2[0] = planeOrigin[0]; } else { vtkGenericWarningMacro("only works for ortho planes: set plane orientation first"); return; } this->PlaneSource->SetOrigin(planeOrigin); this->PlaneSource->SetPoint1(pt1); this->PlaneSource->SetPoint2(pt2); this->UpdatePlane(); this->BuildRepresentation(); this->Modified(); } //------------------------------------------------------------------------------ int vtkImagePlaneWidget::GetSliceIndex() { if (!this->Reslice) { return 0; } if (!this->ImageData) { return 0; } vtkAlgorithm* inpAlg = this->Reslice->GetInputAlgorithm(); inpAlg->UpdateInformation(); vtkInformation* outInfo = inpAlg->GetOutputInformation(0); double origin[3]; outInfo->Get(vtkDataObject::ORIGIN(), origin); double spacing[3]; outInfo->Get(vtkDataObject::SPACING(), spacing); double planeOrigin[3]; this->PlaneSource->GetOrigin(planeOrigin); if (this->PlaneOrientation == 2) { return static_cast<int>(std::round((planeOrigin[2] - origin[2]) / spacing[2])); } else if (this->PlaneOrientation == 1) { return static_cast<int>(std::round((planeOrigin[1] - origin[1]) / spacing[1])); } else if (this->PlaneOrientation == 0) { return static_cast<int>(std::round((planeOrigin[0] - origin[0]) / spacing[0])); } else { vtkGenericWarningMacro("only works for ortho planes: set plane orientation first"); } return 0; } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::ActivateCursor(int i) { if (!this->CurrentRenderer) { return; } if (i == 0) { this->CursorActor->VisibilityOff(); } else { this->CursorActor->VisibilityOn(); } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::ActivateMargins(int i) { if (!this->CurrentRenderer) { return; } if (i == 0) { this->MarginActor->VisibilityOff(); } else { this->MarginActor->VisibilityOn(); } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::ActivateText(int i) { if (!this->CurrentRenderer || !this->DisplayText) { return; } if (i == 0) { this->TextActor->VisibilityOff(); } else { this->TextActor->VisibilityOn(); } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::UpdateCursor(int X, int Y) { if (!this->ImageData) { return; } // We're going to be extracting values with GetScalarComponentAsDouble(), // we might as well make sure that the data is there. If the data is // up to date already, this call doesn't cost very much. If we don't make // this call and the data is not up to date, the GetScalar... call will // cause a segfault. this->Reslice->GetInputAlgorithm()->Update(); vtkAssemblyPath* path = this->GetAssemblyPath(X, Y, 0., this->PlanePicker); this->CurrentImageValue = VTK_DOUBLE_MAX; int found = 0; int i; if (path) { // Deal with the possibility that we may be using a shared picker vtkCollectionSimpleIterator sit; path->InitTraversal(sit); vtkAssemblyNode* node; for (i = 0; i < path->GetNumberOfItems() && !found; i++) { node = path->GetNextNode(sit); if (node->GetViewProp() == vtkProp::SafeDownCast(this->TexturePlaneActor)) { found = 1; } } } if (!found || path == nullptr) { this->CursorActor->VisibilityOff(); return; } else { this->CursorActor->VisibilityOn(); } double q[3]; this->PlanePicker->GetPickPosition(q); if (this->UseContinuousCursor) { found = this->UpdateContinuousCursor(q); } else { found = this->UpdateDiscreteCursor(q); } if (!found) { this->CursorActor->VisibilityOff(); return; } double o[3]; this->PlaneSource->GetOrigin(o); // q relative to the plane origin // double qro[3]; qro[0] = q[0] - o[0]; qro[1] = q[1] - o[1]; qro[2] = q[2] - o[2]; double p1o[3]; double p2o[3]; this->GetVector1(p1o); this->GetVector2(p2o); double Lp1 = vtkMath::Dot(qro, p1o) / vtkMath::Dot(p1o, p1o); double Lp2 = vtkMath::Dot(qro, p2o) / vtkMath::Dot(p2o, p2o); double p1[3]; this->PlaneSource->GetPoint1(p1); double p2[3]; this->PlaneSource->GetPoint2(p2); double a[3]; double b[3]; double c[3]; double d[3]; for (i = 0; i < 3; i++) { a[i] = o[i] + Lp2 * p2o[i]; // left b[i] = p1[i] + Lp2 * p2o[i]; // right c[i] = o[i] + Lp1 * p1o[i]; // bottom d[i] = p2[i] + Lp1 * p1o[i]; // top } vtkPoints* cursorPts = this->CursorPolyData->GetPoints(); cursorPts->SetPoint(0, a); cursorPts->SetPoint(1, b); cursorPts->SetPoint(2, c); cursorPts->SetPoint(3, d); cursorPts->GetData()->Modified(); this->CursorPolyData->Modified(); } //------------------------------------------------------------------------------ int vtkImagePlaneWidget::UpdateContinuousCursor(double* q) { double tol2; vtkCell* cell; vtkPointData* pd; int subId; double pcoords[3], weights[8]; this->CurrentCursorPosition[0] = q[0]; this->CurrentCursorPosition[1] = q[1]; this->CurrentCursorPosition[2] = q[2]; pd = this->ImageData->GetPointData(); vtkPointData* outPD = vtkPointData::New(); outPD->InterpolateAllocate(pd, 1, 1); // Use tolerance as a function of size of source data // tol2 = this->ImageData->GetLength(); tol2 = tol2 ? tol2 * tol2 / 1000.0 : 0.001; // Find the cell that contains q and get it // cell = this->ImageData->FindAndGetCell(q, nullptr, -1, tol2, subId, pcoords, weights); int found = 0; if (cell) { // Interpolate the point data // outPD->InterpolatePoint(pd, 0, cell->PointIds, weights); this->CurrentImageValue = outPD->GetScalars()->GetTuple1(0); found = 1; } outPD->Delete(); return found; } //------------------------------------------------------------------------------ int vtkImagePlaneWidget::UpdateDiscreteCursor(double* q) { // vtkImageData will find the nearest implicit point to q // vtkIdType ptId = this->ImageData->FindPoint(q); if (ptId == -1) { return 0; } double closestPt[3]; this->ImageData->GetPoint(ptId, closestPt); double origin[3]; this->ImageData->GetOrigin(origin); double spacing[3]; this->ImageData->GetSpacing(spacing); int extent[6]; this->ImageData->GetExtent(extent); int iq[3]; int iqtemp; for (int i = 0; i < 3; i++) { // compute world to image coords iqtemp = static_cast<int>(std::round((closestPt[i] - origin[i]) / spacing[i])); // we have a valid pick already, just enforce bounds check iq[i] = (iqtemp < extent[2 * i]) ? extent[2 * i] : ((iqtemp > extent[2 * i + 1]) ? extent[2 * i + 1] : iqtemp); // compute image to world coords q[i] = iq[i] * spacing[i] + origin[i]; this->CurrentCursorPosition[i] = iq[i]; } this->CurrentImageValue = this->ImageData->GetScalarComponentAsDouble(static_cast<int>(this->CurrentCursorPosition[0]), static_cast<int>(this->CurrentCursorPosition[1]), static_cast<int>(this->CurrentCursorPosition[2]), 0); return 1; } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetOrigin(double x, double y, double z) { this->PlaneSource->SetOrigin(x, y, z); this->Modified(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetOrigin(double xyz[3]) { this->PlaneSource->SetOrigin(xyz); this->Modified(); } //------------------------------------------------------------------------------ double* vtkImagePlaneWidget::GetOrigin() { return this->PlaneSource->GetOrigin(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GetOrigin(double xyz[3]) { this->PlaneSource->GetOrigin(xyz); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetPoint1(double x, double y, double z) { this->PlaneSource->SetPoint1(x, y, z); this->Modified(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetPoint1(double xyz[3]) { this->PlaneSource->SetPoint1(xyz); this->Modified(); } //------------------------------------------------------------------------------ double* vtkImagePlaneWidget::GetPoint1() { return this->PlaneSource->GetPoint1(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GetPoint1(double xyz[3]) { this->PlaneSource->GetPoint1(xyz); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetPoint2(double x, double y, double z) { this->PlaneSource->SetPoint2(x, y, z); this->Modified(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetPoint2(double xyz[3]) { this->PlaneSource->SetPoint2(xyz); this->Modified(); } //------------------------------------------------------------------------------ double* vtkImagePlaneWidget::GetPoint2() { return this->PlaneSource->GetPoint2(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GetPoint2(double xyz[3]) { this->PlaneSource->GetPoint2(xyz); } //------------------------------------------------------------------------------ double* vtkImagePlaneWidget::GetCenter() { return this->PlaneSource->GetCenter(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GetCenter(double xyz[3]) { this->PlaneSource->GetCenter(xyz); } //------------------------------------------------------------------------------ double* vtkImagePlaneWidget::GetNormal() { return this->PlaneSource->GetNormal(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GetNormal(double xyz[3]) { this->PlaneSource->GetNormal(xyz); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GetPolyData(vtkPolyData* pd) { pd->ShallowCopy(this->PlaneSource->GetOutput()); } //------------------------------------------------------------------------------ vtkPolyDataAlgorithm* vtkImagePlaneWidget::GetPolyDataAlgorithm() { return this->PlaneSource; } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::UpdatePlacement() { this->UpdatePlane(); this->UpdateMargins(); this->BuildRepresentation(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::SetTextProperty(vtkTextProperty* tprop) { this->TextActor->SetTextProperty(tprop); } //------------------------------------------------------------------------------ vtkTextProperty* vtkImagePlaneWidget::GetTextProperty() { return this->TextActor->GetTextProperty(); } //------------------------------------------------------------------------------ vtkTexture* vtkImagePlaneWidget::GetTexture() { return this->Texture; } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GetVector1(double v1[3]) { double* p1 = this->PlaneSource->GetPoint1(); double* o = this->PlaneSource->GetOrigin(); v1[0] = p1[0] - o[0]; v1[1] = p1[1] - o[1]; v1[2] = p1[2] - o[2]; } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GetVector2(double v2[3]) { double* p2 = this->PlaneSource->GetPoint2(); double* o = this->PlaneSource->GetOrigin(); v2[0] = p2[0] - o[0]; v2[1] = p2[1] - o[1]; v2[2] = p2[2] - o[2]; } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::AdjustState() { int* auto_modifier = nullptr; switch (this->LastButtonPressed) { case vtkImagePlaneWidget::VTK_LEFT_BUTTON: auto_modifier = &this->LeftButtonAutoModifier; break; case vtkImagePlaneWidget::VTK_MIDDLE_BUTTON: auto_modifier = &this->MiddleButtonAutoModifier; break; case vtkImagePlaneWidget::VTK_RIGHT_BUTTON: auto_modifier = &this->RightButtonAutoModifier; break; } if (this->Interactor->GetShiftKey() || (auto_modifier && (*auto_modifier & vtkImagePlaneWidget::VTK_SHIFT_MODIFIER))) { this->State = vtkImagePlaneWidget::Scaling; return; } double v1[3]; this->GetVector1(v1); double v2[3]; this->GetVector2(v2); double planeSize1 = vtkMath::Normalize(v1); double planeSize2 = vtkMath::Normalize(v2); double* planeOrigin = this->PlaneSource->GetOrigin(); double ppo[3] = { this->LastPickPosition[0] - planeOrigin[0], this->LastPickPosition[1] - planeOrigin[1], this->LastPickPosition[2] - planeOrigin[2] }; double x2D = vtkMath::Dot(ppo, v1); double y2D = vtkMath::Dot(ppo, v2); if (x2D > planeSize1) { x2D = planeSize1; } else if (x2D < 0.0) { x2D = 0.0; } if (y2D > planeSize2) { y2D = planeSize2; } else if (y2D < 0.0) { y2D = 0.0; } // Divide plane into three zones for different user interactions: // four corners -- spin around the plane's normal at its center // four edges -- rotate around one of the plane's axes at its center // center area -- push // double marginX = planeSize1 * this->MarginSizeX; double marginY = planeSize2 * this->MarginSizeY; double x0 = marginX; double y0 = marginY; double x1 = planeSize1 - marginX; double y1 = planeSize2 - marginY; if (x2D < x0) // left margin { if (y2D < y0) // bottom left corner { this->MarginSelectMode = 0; } else if (y2D > y1) // top left corner { this->MarginSelectMode = 3; } else // left edge { this->MarginSelectMode = 4; } } else if (x2D > x1) // right margin { if (y2D < y0) // bottom right corner { this->MarginSelectMode = 1; } else if (y2D > y1) // top right corner { this->MarginSelectMode = 2; } else // right edge { this->MarginSelectMode = 5; } } else // middle or on the very edge { if (y2D < y0) // bottom edge { this->MarginSelectMode = 6; } else if (y2D > y1) // top edge { this->MarginSelectMode = 7; } else // central area { this->MarginSelectMode = 8; } } if (this->Interactor->GetControlKey() || (auto_modifier && (*auto_modifier & vtkImagePlaneWidget::VTK_CONTROL_MODIFIER))) { this->State = vtkImagePlaneWidget::Moving; } else { if (this->MarginSelectMode >= 0 && this->MarginSelectMode < 4) { this->State = vtkImagePlaneWidget::Spinning; return; } else if (this->MarginSelectMode == 8) { this->State = vtkImagePlaneWidget::Pushing; return; } else { this->State = vtkImagePlaneWidget::Rotating; } } double* raPtr = nullptr; double* rvPtr = nullptr; double rvfac = 1.0; double rafac = 1.0; switch (this->MarginSelectMode) { // left bottom corner case 0: raPtr = v2; rvPtr = v1; rvfac = -1.0; rafac = -1.0; break; // right bottom corner case 1: raPtr = v2; rvPtr = v1; rafac = -1.0; break; // right top corner case 2: raPtr = v2; rvPtr = v1; break; // left top corner case 3: raPtr = v2; rvPtr = v1; rvfac = -1.0; break; case 4: raPtr = v2; rvPtr = v1; rvfac = -1.0; break; // left case 5: raPtr = v2; rvPtr = v1; break; // right case 6: raPtr = v1; rvPtr = v2; rvfac = -1.0; break; // bottom case 7: raPtr = v1; rvPtr = v2; break; // top default: raPtr = v1; rvPtr = v2; break; } for (int i = 0; i < 3; i++) { this->RotateAxis[i] = *raPtr++ * rafac; this->RadiusVector[i] = *rvPtr++ * rvfac; } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::Spin(double* p1, double* p2) { // Disable cursor snap // this->PlaneOrientation = 3; // Get the motion vector, in world coords // double v[3]; v[0] = p2[0] - p1[0]; v[1] = p2[1] - p1[1]; v[2] = p2[2] - p1[2]; // Plane center and normal before transform // double* wc = this->PlaneSource->GetCenter(); double* wn = this->PlaneSource->GetNormal(); // Radius vector from center to cursor position // double rv[3] = { p2[0] - wc[0], p2[1] - wc[1], p2[2] - wc[2] }; // Distance between center and cursor location // double rs = vtkMath::Normalize(rv); // Spin direction // double wn_cross_rv[3]; vtkMath::Cross(wn, rv, wn_cross_rv); // Spin angle // double dw = vtkMath::DegreesFromRadians(vtkMath::Dot(v, wn_cross_rv) / rs); this->Transform->Identity(); this->Transform->Translate(wc[0], wc[1], wc[2]); this->Transform->RotateWXYZ(dw, wn); this->Transform->Translate(-wc[0], -wc[1], -wc[2]); double newpt[3]; this->Transform->TransformPoint(this->PlaneSource->GetPoint1(), newpt); this->PlaneSource->SetPoint1(newpt); this->Transform->TransformPoint(this->PlaneSource->GetPoint2(), newpt); this->PlaneSource->SetPoint2(newpt); this->Transform->TransformPoint(this->PlaneSource->GetOrigin(), newpt); this->PlaneSource->SetOrigin(newpt); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::Rotate(double* p1, double* p2, double* vpn) { // Disable cursor snap // this->PlaneOrientation = 3; // Get the motion vector, in world coords // double v[3]; v[0] = p2[0] - p1[0]; v[1] = p2[1] - p1[1]; v[2] = p2[2] - p1[2]; // Plane center and normal // double* wc = this->PlaneSource->GetCenter(); // Radius of the rotating circle of the picked point // double radius = fabs(this->RadiusVector[0] * (p2[0] - wc[0]) + this->RadiusVector[1] * (p2[1] - wc[1]) + this->RadiusVector[2] * (p2[2] - wc[2])); // Rotate direction ra_cross_rv // double rd[3]; vtkMath::Cross(this->RotateAxis, this->RadiusVector, rd); // Direction cosin between rotating direction and view normal // double rd_dot_vpn = rd[0] * vpn[0] + rd[1] * vpn[1] + rd[2] * vpn[2]; // 'push' plane edge when mouse moves away from plane center // 'pull' plane edge when mouse moves toward plane center // double dw = vtkMath::DegreesFromRadians(vtkMath::Dot(this->RadiusVector, v) / radius) * -rd_dot_vpn; this->Transform->Identity(); this->Transform->Translate(wc[0], wc[1], wc[2]); this->Transform->RotateWXYZ(dw, this->RotateAxis); this->Transform->Translate(-wc[0], -wc[1], -wc[2]); double newpt[3]; this->Transform->TransformPoint(this->PlaneSource->GetPoint1(), newpt); this->PlaneSource->SetPoint1(newpt); this->Transform->TransformPoint(this->PlaneSource->GetPoint2(), newpt); this->PlaneSource->SetPoint2(newpt); this->Transform->TransformPoint(this->PlaneSource->GetOrigin(), newpt); this->PlaneSource->SetOrigin(newpt); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GeneratePlaneOutline() { vtkPoints* points = vtkPoints::New(VTK_DOUBLE); points->SetNumberOfPoints(4); int i; for (i = 0; i < 4; i++) { points->SetPoint(i, 0.0, 0.0, 0.0); } vtkCellArray* cells = vtkCellArray::New(); cells->AllocateEstimate(4, 2); vtkIdType pts[2]; pts[0] = 3; pts[1] = 2; // top edge cells->InsertNextCell(2, pts); pts[0] = 0; pts[1] = 1; // bottom edge cells->InsertNextCell(2, pts); pts[0] = 0; pts[1] = 3; // left edge cells->InsertNextCell(2, pts); pts[0] = 1; pts[1] = 2; // right edge cells->InsertNextCell(2, pts); this->PlaneOutlinePolyData->SetPoints(points); points->Delete(); this->PlaneOutlinePolyData->SetLines(cells); cells->Delete(); vtkPolyDataMapper* planeOutlineMapper = vtkPolyDataMapper::New(); planeOutlineMapper->SetInputData(this->PlaneOutlinePolyData); planeOutlineMapper->SetResolveCoincidentTopologyToPolygonOffset(); this->PlaneOutlineActor->SetMapper(planeOutlineMapper); this->PlaneOutlineActor->PickableOff(); planeOutlineMapper->Delete(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GenerateTexturePlane() { this->SetResliceInterpolate(this->ResliceInterpolate); this->LookupTable = this->CreateDefaultLookupTable(); this->ColorMap->SetLookupTable(this->LookupTable); this->ColorMap->SetOutputFormatToRGBA(); this->ColorMap->PassAlphaToOutputOn(); vtkPolyDataMapper* texturePlaneMapper = vtkPolyDataMapper::New(); texturePlaneMapper->SetInputConnection(this->PlaneSource->GetOutputPort()); this->Texture->SetQualityTo32Bit(); this->Texture->SetColorMode(VTK_COLOR_MODE_DEFAULT); this->Texture->SetInterpolate(this->TextureInterpolate); this->Texture->RepeatOff(); this->Texture->SetLookupTable(this->LookupTable); this->TexturePlaneActor->SetMapper(texturePlaneMapper); this->TexturePlaneActor->SetTexture(this->Texture); this->TexturePlaneActor->PickableOn(); texturePlaneMapper->Delete(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GenerateMargins() { // Construct initial points vtkPoints* points = vtkPoints::New(VTK_DOUBLE); points->SetNumberOfPoints(8); int i; for (i = 0; i < 8; i++) { points->SetPoint(i, 0.0, 0.0, 0.0); } vtkCellArray* cells = vtkCellArray::New(); cells->AllocateEstimate(4, 2); vtkIdType pts[2]; pts[0] = 0; pts[1] = 1; // top margin cells->InsertNextCell(2, pts); pts[0] = 2; pts[1] = 3; // bottom margin cells->InsertNextCell(2, pts); pts[0] = 4; pts[1] = 5; // left margin cells->InsertNextCell(2, pts); pts[0] = 6; pts[1] = 7; // right margin cells->InsertNextCell(2, pts); this->MarginPolyData->SetPoints(points); points->Delete(); this->MarginPolyData->SetLines(cells); cells->Delete(); vtkPolyDataMapper* marginMapper = vtkPolyDataMapper::New(); marginMapper->SetInputData(this->MarginPolyData); marginMapper->SetResolveCoincidentTopologyToPolygonOffset(); this->MarginActor->SetMapper(marginMapper); this->MarginActor->PickableOff(); this->MarginActor->VisibilityOff(); marginMapper->Delete(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GenerateCursor() { // Construct initial points // vtkPoints* points = vtkPoints::New(VTK_DOUBLE); points->SetNumberOfPoints(4); int i; for (i = 0; i < 4; i++) { points->SetPoint(i, 0.0, 0.0, 0.0); } vtkCellArray* cells = vtkCellArray::New(); cells->AllocateEstimate(2, 2); vtkIdType pts[2]; pts[0] = 0; pts[1] = 1; // horizontal segment cells->InsertNextCell(2, pts); pts[0] = 2; pts[1] = 3; // vertical segment cells->InsertNextCell(2, pts); this->CursorPolyData->SetPoints(points); points->Delete(); this->CursorPolyData->SetLines(cells); cells->Delete(); vtkPolyDataMapper* cursorMapper = vtkPolyDataMapper::New(); cursorMapper->SetInputData(this->CursorPolyData); cursorMapper->SetResolveCoincidentTopologyToPolygonOffset(); this->CursorActor->SetMapper(cursorMapper); this->CursorActor->PickableOff(); this->CursorActor->VisibilityOff(); cursorMapper->Delete(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::GenerateText() { snprintf(this->TextBuff, VTK_IMAGE_PLANE_WIDGET_MAX_TEXTBUFF, "NA"); this->TextActor->SetInput(this->TextBuff); this->TextActor->SetTextScaleModeToNone(); vtkTextProperty* textprop = this->TextActor->GetTextProperty(); textprop->SetColor(1, 1, 1); textprop->SetFontFamilyToArial(); textprop->SetFontSize(18); textprop->BoldOff(); textprop->ItalicOff(); textprop->ShadowOff(); textprop->SetJustificationToLeft(); textprop->SetVerticalJustificationToBottom(); vtkCoordinate* coord = this->TextActor->GetPositionCoordinate(); coord->SetCoordinateSystemToNormalizedViewport(); coord->SetValue(.01, .01); this->TextActor->VisibilityOff(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::UpdateMargins() { double v1[3]; this->GetVector1(v1); double v2[3]; this->GetVector2(v2); double o[3]; this->PlaneSource->GetOrigin(o); double p1[3]; this->PlaneSource->GetPoint1(p1); double p2[3]; this->PlaneSource->GetPoint2(p2); double a[3]; double b[3]; double c[3]; double d[3]; double s = this->MarginSizeX; double t = this->MarginSizeY; int i; for (i = 0; i < 3; i++) { a[i] = o[i] + v2[i] * (1 - t); b[i] = p1[i] + v2[i] * (1 - t); c[i] = o[i] + v2[i] * t; d[i] = p1[i] + v2[i] * t; } vtkPoints* marginPts = this->MarginPolyData->GetPoints(); marginPts->SetPoint(0, a); marginPts->SetPoint(1, b); marginPts->SetPoint(2, c); marginPts->SetPoint(3, d); for (i = 0; i < 3; i++) { a[i] = o[i] + v1[i] * s; b[i] = p2[i] + v1[i] * s; c[i] = o[i] + v1[i] * (1 - s); d[i] = p2[i] + v1[i] * (1 - s); } marginPts->SetPoint(4, a); marginPts->SetPoint(5, b); marginPts->SetPoint(6, c); marginPts->SetPoint(7, d); marginPts->GetData()->Modified(); this->MarginPolyData->Modified(); } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::Translate(double* p1, double* p2) { // Get the motion vector // double v[3]; v[0] = p2[0] - p1[0]; v[1] = p2[1] - p1[1]; v[2] = p2[2] - p1[2]; double* o = this->PlaneSource->GetOrigin(); double* pt1 = this->PlaneSource->GetPoint1(); double* pt2 = this->PlaneSource->GetPoint2(); double origin[3], point1[3], point2[3]; double vdrv = this->RadiusVector[0] * v[0] + this->RadiusVector[1] * v[1] + this->RadiusVector[2] * v[2]; double vdra = this->RotateAxis[0] * v[0] + this->RotateAxis[1] * v[1] + this->RotateAxis[2] * v[2]; int i; if (this->MarginSelectMode == 8) // everybody comes along { for (i = 0; i < 3; i++) { origin[i] = o[i] + v[i]; point1[i] = pt1[i] + v[i]; point2[i] = pt2[i] + v[i]; } this->PlaneSource->SetOrigin(origin); this->PlaneSource->SetPoint1(point1); this->PlaneSource->SetPoint2(point2); } else if (this->MarginSelectMode == 4) // left edge { for (i = 0; i < 3; i++) { origin[i] = o[i] + vdrv * this->RadiusVector[i]; point2[i] = pt2[i] + vdrv * this->RadiusVector[i]; } this->PlaneSource->SetOrigin(origin); this->PlaneSource->SetPoint2(point2); } else if (this->MarginSelectMode == 5) // right edge { for (i = 0; i < 3; i++) { point1[i] = pt1[i] + vdrv * this->RadiusVector[i]; } this->PlaneSource->SetPoint1(point1); } else if (this->MarginSelectMode == 6) // bottom edge { for (i = 0; i < 3; i++) { origin[i] = o[i] + vdrv * this->RadiusVector[i]; point1[i] = pt1[i] + vdrv * this->RadiusVector[i]; } this->PlaneSource->SetOrigin(origin); this->PlaneSource->SetPoint1(point1); } else if (this->MarginSelectMode == 7) // top edge { for (i = 0; i < 3; i++) { point2[i] = pt2[i] + vdrv * this->RadiusVector[i]; } this->PlaneSource->SetPoint2(point2); } else if (this->MarginSelectMode == 3) // top left corner { for (i = 0; i < 3; i++) { origin[i] = o[i] + vdrv * this->RadiusVector[i]; point2[i] = pt2[i] + vdrv * this->RadiusVector[i] + vdra * this->RotateAxis[i]; } this->PlaneSource->SetOrigin(origin); this->PlaneSource->SetPoint2(point2); } else if (this->MarginSelectMode == 0) // bottom left corner { for (i = 0; i < 3; i++) { origin[i] = o[i] + vdrv * this->RadiusVector[i] + vdra * this->RotateAxis[i]; point1[i] = pt1[i] + vdra * this->RotateAxis[i]; point2[i] = pt2[i] + vdrv * this->RadiusVector[i]; } this->PlaneSource->SetOrigin(origin); this->PlaneSource->SetPoint1(point1); this->PlaneSource->SetPoint2(point2); } else if (this->MarginSelectMode == 2) // top right corner { for (i = 0; i < 3; i++) { point1[i] = pt1[i] + vdrv * this->RadiusVector[i]; point2[i] = pt2[i] + vdra * this->RotateAxis[i]; } this->PlaneSource->SetPoint1(point1); this->PlaneSource->SetPoint2(point2); } else // bottom right corner { for (i = 0; i < 3; i++) { origin[i] = o[i] + vdra * this->RotateAxis[i]; point1[i] = pt1[i] + vdrv * this->RadiusVector[i] + vdra * this->RotateAxis[i]; } this->PlaneSource->SetPoint1(point1); this->PlaneSource->SetOrigin(origin); } } //------------------------------------------------------------------------------ void vtkImagePlaneWidget::Scale(double* p1, double* p2, int vtkNotUsed(X), int Y) { // Get the motion vector // double v[3]; v[0] = p2[0] - p1[0]; v[1] = p2[1] - p1[1]; v[2] = p2[2] - p1[2]; double* o = this->PlaneSource->GetOrigin(); double* pt1 = this->PlaneSource->GetPoint1(); double* pt2 = this->PlaneSource->GetPoint2(); double* center = this->PlaneSource->GetCenter(); // Compute the scale factor // double sf = vtkMath::Norm(v) / sqrt(vtkMath::Distance2BetweenPoints(pt1, pt2)); if (Y > this->Interactor->GetLastEventPosition()[1]) { sf = 1.0 + sf; } else { sf = 1.0 - sf; } // Move the corner points // double origin[3], point1[3], point2[3]; for (int i = 0; i < 3; i++) { origin[i] = sf * (o[i] - center[i]) + center[i]; point1[i] = sf * (pt1[i] - center[i]) + center[i]; point2[i] = sf * (pt2[i] - center[i]) + center[i]; } this->PlaneSource->SetOrigin(origin); this->PlaneSource->SetPoint1(point1); this->PlaneSource->SetPoint2(point2); }
// -*- coding: us-ascii-unix -*- // Copyright 2012 Lukas Kemmer // // 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 "geo/canvas-geo.hh" #include "geo/geo-func.hh" #include "geo/int-point.hh" #include "geo/int-rect.hh" #include "geo/point.hh" #include "util/mouse.hh" namespace faint::mouse { Point view_to_image(const IntPoint& p, const CanvasGeo& g){ return (p + g.pos - point_from_size(g.border)) / g.Scale(); } IntPoint image_to_view(const IntPoint& p, const CanvasGeo& g){ return floored(p * g.Scale()) - g.pos + point_from_size(g.border); } IntRect image_to_view(const IntRect& r, const CanvasGeo& g){ return {image_to_view(r.TopLeft(), g), image_to_view(r.BottomRight(), g)}; } } // namespace
#include <makeshift/tuple.hpp> #include <tuple> #include <gsl-lite/gsl-lite.hpp> // for index #include <catch2/catch.hpp> namespace { namespace mk = ::makeshift; namespace gsl = ::gsl_lite; TEST_CASE("tuple", "[flags]") { constexpr auto numbers = std::make_tuple(2, 3u); SECTION("foreach") { int sum = 0; mk::template_for([&](auto x) { sum += int(x); }, numbers); CHECK(sum == 5); } SECTION("transform") { auto square = mk::tuple_transform([](auto x) { return x*x; }, numbers); CHECK(square == std::make_tuple(4, 9u)); } SECTION("index") { int offset = 100; auto result_tuple = std::make_tuple(0, 0, 0); auto lhs_tuple = std::make_tuple(10, 20, 30); auto rhs_scalar = 1; mk::template_for([offset, rhs = rhs_scalar](auto& result, auto lhs, auto indexC) { constexpr gsl::index index = indexC(); result = lhs + rhs + int(index*offset); }, result_tuple, lhs_tuple, mk::tuple_index); CHECK(result_tuple == std::make_tuple(11, 121, 231)); } SECTION("reduce") { int sum = mk::template_reduce(0, std::plus<int>{ }, numbers); CHECK(sum == 5); } SECTION("all/any/none") { bool allGreaterThan0 = mk::template_all_of([](auto x) { return x > 0; }, numbers); CHECK(allGreaterThan0); bool allGreaterThan2 = mk::template_all_of([](auto x) { return x > 2; }, numbers); CHECK_FALSE(allGreaterThan2); bool anyGreaterThan2 = mk::template_any_of([](auto x) { return x > 2; }, numbers); CHECK(anyGreaterThan2); bool anyGreaterThan4 = mk::template_any_of([](auto x) { return x > 4; }, numbers); CHECK_FALSE(anyGreaterThan4); bool noneGreaterThan2 = mk::template_none_of([](auto x) { return x > 2; }, numbers); CHECK_FALSE(noneGreaterThan2); bool noneGreaterThan4 = mk::template_none_of([](auto x) { return x > 4; }, numbers); CHECK(noneGreaterThan4); } } } // anonymous namespace
// ColourPopup.cpp : implementation file // // Written by Chris Maunder (chrismaunder@codeguru.com) // Extended by Alexander Bischofberger (bischofb@informatik.tu-muenchen.de) // Copyright (c) 1998. // // Updated 30 May 1998 to allow any number of colours, and to // make the appearance closer to Office 97. // Also added "Default" text area. (CJM) // // 13 June 1998 Fixed change of focus bug (CJM) // 30 June 1998 Fixed bug caused by focus bug fix (D'oh!!) // Solution suggested by Paul Wilkerson. // // ColourPopup is a helper class for the colour picker control // CColourPicker. Check out the header file or the accompanying // HTML doc file for details. // // This code may be used in compiled form in any way you desire. This // file may be redistributed unmodified by any means PROVIDING it is // not sold for profit without the authors written consent, and // providing that this notice and the authors name is included. // // This file is provided "as is" with no expressed or implied warranty. // The author accepts no liability if it causes any damage to you or your // computer whatsoever. It's free, so don't hassle me about it. // // Expect bugs. // // Please use and enjoy. Please let me know of any bugs/mods/improvements // that you have found/implemented and I will fix/incorporate them into this // file. #include "stdafx.h" #include <math.h> #include "ColourPopup.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define DEFAULT_BOX_VALUE -3 #define CUSTOM_BOX_VALUE -2 #define INVALID_COLOUR -1 #define MAX_COLOURS 100 ColourTableEntry CColourPopup::m_crColours[] = { { RGB(0x00, 0x00, 0x00), _T("Black") }, { RGB(0xA5, 0x2A, 0x00), _T("Brown") }, { RGB(0x00, 0x40, 0x40), _T("Dark Olive Green") }, { RGB(0x00, 0x55, 0x00), _T("Dark Green") }, { RGB(0x00, 0x00, 0x5E), _T("Dark Teal") }, { RGB(0x00, 0x00, 0x8B), _T("Dark blue") }, { RGB(0x4B, 0x00, 0x82), _T("Indigo") }, { RGB(0x28, 0x28, 0x28), _T("Dark grey") }, { RGB(0x8B, 0x00, 0x00), _T("Dark red") }, { RGB(0xFF, 0x68, 0x20), _T("Orange") }, { RGB(0x8B, 0x8B, 0x00), _T("Dark yellow") }, { RGB(0x00, 0x93, 0x00), _T("Green") }, { RGB(0x38, 0x8E, 0x8E), _T("Teal") }, { RGB(0x00, 0x00, 0xFF), _T("Blue") }, { RGB(0x7B, 0x7B, 0xC0), _T("Blue-grey") }, { RGB(0x66, 0x66, 0x66), _T("Grey - 40") }, { RGB(0xFF, 0x00, 0x00), _T("Red") }, { RGB(0xFF, 0xAD, 0x5B), _T("Light orange") }, { RGB(0x32, 0xCD, 0x32), _T("Lime") }, { RGB(0x3C, 0xB3, 0x71), _T("Sea green") }, { RGB(0x7F, 0xFF, 0xD4), _T("Aqua") }, { RGB(0x7D, 0x9E, 0xC0), _T("Light blue") }, { RGB(0x80, 0x00, 0x80), _T("Violet") }, { RGB(0x7F, 0x7F, 0x7F), _T("Grey - 50") }, { RGB(0xFF, 0xC0, 0xCB), _T("Pink") }, { RGB(0xFF, 0xD7, 0x00), _T("Gold") }, { RGB(0xFF, 0xFF, 0x00), _T("Yellow") }, { RGB(0x00, 0xFF, 0x00), _T("Bright green") }, { RGB(0x40, 0xE0, 0xD0), _T("Turquoise") }, { RGB(0xC0, 0xFF, 0xFF), _T("Skyblue") }, { RGB(0x48, 0x00, 0x48), _T("Plum") }, { RGB(0xC0, 0xC0, 0xC0), _T("Light grey") }, { RGB(0xFF, 0xE4, 0xE1), _T("Rose") }, { RGB(0xD2, 0xB4, 0x8C), _T("Tan") }, { RGB(0xFF, 0xFF, 0xE0), _T("Light yellow") }, { RGB(0x98, 0xFB, 0x98), _T("Pale green ") }, { RGB(0xAF, 0xEE, 0xEE), _T("Pale turquoise") }, { RGB(0x68, 0x83, 0x8B), _T("Pale blue") }, { RGB(0xE6, 0xE6, 0xFA), _T("Lavender") }, { RGB(0xFF, 0xFF, 0xFF), _T("White") } }; ///////////////////////////////////////////////////////////////////////////// // CColourPopup CColourPopup::CColourPopup() { Initialise(); } CColourPopup::CColourPopup(CPoint p, COLORREF crColour, CWnd* pParentWnd, LPCTSTR szDefaultText /* = NULL */, LPCTSTR szCustomText /* = NULL */) { Initialise(); m_crColour = m_crInitialColour = crColour; m_pParent = pParentWnd; m_strDefaultText = (szDefaultText)? szDefaultText : _T(""); m_strCustomText = (szCustomText)? szCustomText : _T(""); CColourPopup::Create(p, crColour, pParentWnd, szDefaultText, szCustomText); } void CColourPopup::Initialise() { m_nNumColours = sizeof(m_crColours)/sizeof(ColourTableEntry); ASSERT(m_nNumColours <= MAX_COLOURS); if (m_nNumColours > MAX_COLOURS) m_nNumColours = MAX_COLOURS; m_nNumColumns = 0; m_nNumRows = 0; m_nBoxSize = 18; m_nMargin = ::GetSystemMetrics(SM_CXEDGE); m_nCurrentSel = INVALID_COLOUR; m_nChosenColourSel = INVALID_COLOUR; m_pParent = NULL; m_crColour = m_crInitialColour = RGB(0,0,0); m_bChildWindowVisible = FALSE; // Idiot check: Make sure the colour square is at least 5 x 5; if (m_nBoxSize - 2*m_nMargin - 2 < 5) m_nBoxSize = 5 + 2*m_nMargin + 2; // Create the font NONCLIENTMETRICS ncm; ncm.cbSize = sizeof(NONCLIENTMETRICS); VERIFY(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0)); m_Font.CreateFontIndirect(&(ncm.lfMessageFont)); // Create the palette struct { LOGPALETTE LogPalette; PALETTEENTRY PalEntry[MAX_COLOURS]; } pal; LOGPALETTE* pLogPalette = (LOGPALETTE*) &pal; pLogPalette->palVersion = 0x300; pLogPalette->palNumEntries = (WORD) m_nNumColours; for (int i = 0; i < m_nNumColours; i++) { pLogPalette->palPalEntry[i].peRed = GetRValue(m_crColours[i].crColour); pLogPalette->palPalEntry[i].peGreen = GetGValue(m_crColours[i].crColour); pLogPalette->palPalEntry[i].peBlue = GetBValue(m_crColours[i].crColour); pLogPalette->palPalEntry[i].peFlags = 0; } m_Palette.CreatePalette(pLogPalette); } CColourPopup::~CColourPopup() { m_Font.DeleteObject(); m_Palette.DeleteObject(); } BOOL CColourPopup::Create(CPoint p, COLORREF crColour, CWnd* pParentWnd, LPCTSTR szDefaultText /* = NULL */, LPCTSTR szCustomText /* = NULL */) { ASSERT(pParentWnd && ::IsWindow(pParentWnd->GetSafeHwnd())); m_pParent = pParentWnd; m_crColour = m_crInitialColour = crColour; // Get the class name and create the window CString szClassName = AfxRegisterWndClass(CS_CLASSDC|CS_SAVEBITS|CS_HREDRAW|CS_VREDRAW, 0, (HBRUSH) (COLOR_BTNFACE+1), 0); if (!CWnd::CreateEx(0, szClassName, _T(""), WS_VISIBLE|WS_POPUP, p.x, p.y, 100, 100, // size updated soon pParentWnd->GetSafeHwnd(), 0, NULL)) return FALSE; // Store the Custom text if (szCustomText != NULL) m_strCustomText = szCustomText; // Store the Default Area text if (szDefaultText != NULL) m_strDefaultText = szDefaultText; // Set the window size SetWindowSize(); // Create the tooltips CreateToolTips(); // Find which cell (if any) corresponds to the initial colour FindCellFromColour(crColour); // Capture all mouse events for the life of this window SetCapture(); return TRUE; } BEGIN_MESSAGE_MAP(CColourPopup, CWnd) //{{AFX_MSG_MAP(CColourPopup) ON_WM_NCDESTROY() ON_WM_LBUTTONUP() ON_WM_PAINT() ON_WM_MOUSEMOVE() ON_WM_KEYDOWN() ON_WM_QUERYNEWPALETTE() ON_WM_PALETTECHANGED() ON_WM_KILLFOCUS() ON_WM_ACTIVATEAPP() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CColourPopup message handlers // For tooltips BOOL CColourPopup::PreTranslateMessage(MSG* pMsg) { m_ToolTip.RelayEvent(pMsg); // Fix (Adrian Roman): Sometimes if the picker loses focus it is never destroyed if (GetCapture() && GetCapture()->GetSafeHwnd() != m_hWnd) { SetCapture(); return TRUE; } else return CWnd::PreTranslateMessage(pMsg); } // If an arrow key is pressed, then move the selection void CColourPopup::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { int row = GetRow(m_nCurrentSel), col = GetColumn(m_nCurrentSel); if (nChar == VK_DOWN) { if (row == DEFAULT_BOX_VALUE) row = col = 0; else if (row == CUSTOM_BOX_VALUE) { if (m_strDefaultText.GetLength()) row = col = DEFAULT_BOX_VALUE; else row = col = 0; } else { row++; if (GetIndex(row,col) < 0) { if (m_strCustomText.GetLength()) row = col = CUSTOM_BOX_VALUE; else if (m_strDefaultText.GetLength()) row = col = DEFAULT_BOX_VALUE; else row = col = 0; } } ChangeSelection(GetIndex(row, col)); } if (nChar == VK_UP) { if (row == DEFAULT_BOX_VALUE) { if (m_strCustomText.GetLength()) row = col = CUSTOM_BOX_VALUE; else { row = GetRow(m_nNumColours-1); col = GetColumn(m_nNumColours-1); } } else if (row == CUSTOM_BOX_VALUE) { row = GetRow(m_nNumColours-1); col = GetColumn(m_nNumColours-1); } else if (row > 0) row--; else /* row == 0 */ { if (m_strDefaultText.GetLength()) row = col = DEFAULT_BOX_VALUE; else if (m_strCustomText.GetLength()) row = col = CUSTOM_BOX_VALUE; else { row = GetRow(m_nNumColours-1); col = GetColumn(m_nNumColours-1); } } ChangeSelection(GetIndex(row, col)); } if (nChar == VK_RIGHT) { if (row == DEFAULT_BOX_VALUE) row = col = 0; else if (row == CUSTOM_BOX_VALUE) { if (m_strDefaultText.GetLength()) row = col = DEFAULT_BOX_VALUE; else row = col = 0; } else if (col < m_nNumColumns-1) col++; else { col = 0; row++; } if (GetIndex(row,col) == INVALID_COLOUR) { if (m_strCustomText.GetLength()) row = col = CUSTOM_BOX_VALUE; else if (m_strDefaultText.GetLength()) row = col = DEFAULT_BOX_VALUE; else row = col = 0; } ChangeSelection(GetIndex(row, col)); } if (nChar == VK_LEFT) { if (row == DEFAULT_BOX_VALUE) { if (m_strCustomText.GetLength()) row = col = CUSTOM_BOX_VALUE; else { row = GetRow(m_nNumColours-1); col = GetColumn(m_nNumColours-1); } } else if (row == CUSTOM_BOX_VALUE) { row = GetRow(m_nNumColours-1); col = GetColumn(m_nNumColours-1); } else if (col > 0) col--; else /* col == 0 */ { if (row > 0) { row--; col = m_nNumColumns-1; } else { if (m_strDefaultText.GetLength()) row = col = DEFAULT_BOX_VALUE; else if (m_strCustomText.GetLength()) row = col = CUSTOM_BOX_VALUE; else { row = GetRow(m_nNumColours-1); col = GetColumn(m_nNumColours-1); } } } ChangeSelection(GetIndex(row, col)); } if (nChar == VK_ESCAPE) { m_crColour = m_crInitialColour; EndSelection(CPN_SELENDCANCEL); return; } if (nChar == VK_RETURN || nChar == VK_SPACE) { EndSelection(CPN_SELENDOK); return; } CWnd::OnKeyDown(nChar, nRepCnt, nFlags); } // auto-deletion void CColourPopup::OnNcDestroy() { CWnd::OnNcDestroy(); delete this; } void CColourPopup::OnPaint() { CPaintDC dc(this); // device context for painting // Draw the Default Area text if (m_strDefaultText.GetLength()) DrawCell(&dc, DEFAULT_BOX_VALUE); // Draw colour cells for (int i = 0; i < m_nNumColours; i++) DrawCell(&dc, i); // Draw custom text if (m_strCustomText.GetLength()) DrawCell(&dc, CUSTOM_BOX_VALUE); // Draw raised window edge (ex-window style WS_EX_WINDOWEDGE is sposed to do this, // but for some reason isn't CRect rect; GetClientRect(rect); dc.DrawEdge(rect, EDGE_RAISED, BF_RECT); } void CColourPopup::OnMouseMove(UINT nFlags, CPoint point) { int nNewSelection = INVALID_COLOUR; // Translate points to be relative raised window edge point.x -= m_nMargin; point.y -= m_nMargin; // First check we aren't in text box if (m_strCustomText.GetLength() && m_CustomTextRect.PtInRect(point)) nNewSelection = CUSTOM_BOX_VALUE; else if (m_strDefaultText.GetLength() && m_DefaultTextRect.PtInRect(point)) nNewSelection = DEFAULT_BOX_VALUE; else { // Take into account text box if (m_strDefaultText.GetLength()) point.y -= m_DefaultTextRect.Height(); // Get the row and column nNewSelection = GetIndex(point.y / m_nBoxSize, point.x / m_nBoxSize); // In range? If not, default and exit if (nNewSelection < 0 || nNewSelection >= m_nNumColours) { CWnd::OnMouseMove(nFlags, point); return; } } // OK - we have the row and column of the current selection (may be CUSTOM_BOX_VALUE) // Has the row/col selection changed? If yes, then redraw old and new cells. if (nNewSelection != m_nCurrentSel) ChangeSelection(nNewSelection); CWnd::OnMouseMove(nFlags, point); } // End selection on LButtonUp void CColourPopup::OnLButtonUp(UINT nFlags, CPoint point) { CWnd::OnLButtonUp(nFlags, point); DWORD pos = GetMessagePos(); point = CPoint(LOWORD(pos), HIWORD(pos)); if (m_WindowRect.PtInRect(point)) EndSelection(CPN_SELENDOK); else EndSelection(CPN_SELENDCANCEL); } ///////////////////////////////////////////////////////////////////////////// // CColourPopup implementation int CColourPopup::GetIndex(int row, int col) const { if ((row == CUSTOM_BOX_VALUE || col == CUSTOM_BOX_VALUE) && m_strCustomText.GetLength()) return CUSTOM_BOX_VALUE; else if ((row == DEFAULT_BOX_VALUE || col == DEFAULT_BOX_VALUE) && m_strDefaultText.GetLength()) return DEFAULT_BOX_VALUE; else if (row < 0 || col < 0 || row >= m_nNumRows || col >= m_nNumColumns) return INVALID_COLOUR; else { if (row*m_nNumColumns + col >= m_nNumColours) return INVALID_COLOUR; else return row*m_nNumColumns + col; } } int CColourPopup::GetRow(int nIndex) const { if (nIndex == CUSTOM_BOX_VALUE && m_strCustomText.GetLength()) return CUSTOM_BOX_VALUE; else if (nIndex == DEFAULT_BOX_VALUE && m_strDefaultText.GetLength()) return DEFAULT_BOX_VALUE; else if (nIndex < 0 || nIndex >= m_nNumColours) return INVALID_COLOUR; else return nIndex / m_nNumColumns; } int CColourPopup::GetColumn(int nIndex) const { if (nIndex == CUSTOM_BOX_VALUE && m_strCustomText.GetLength()) return CUSTOM_BOX_VALUE; else if (nIndex == DEFAULT_BOX_VALUE && m_strDefaultText.GetLength()) return DEFAULT_BOX_VALUE; else if (nIndex < 0 || nIndex >= m_nNumColours) return INVALID_COLOUR; else return nIndex % m_nNumColumns; } void CColourPopup::FindCellFromColour(COLORREF crColour) { if (crColour == CLR_DEFAULT && m_strDefaultText.GetLength()) { m_nChosenColourSel = DEFAULT_BOX_VALUE; return; } for (int i = 0; i < m_nNumColours; i++) { if (GetColour(i) == crColour) { m_nChosenColourSel = i; return; } } if (m_strCustomText.GetLength()) m_nChosenColourSel = CUSTOM_BOX_VALUE; else m_nChosenColourSel = INVALID_COLOUR; } // Gets the dimensions of the colour cell given by (row,col) BOOL CColourPopup::GetCellRect(int nIndex, const LPRECT& rect) { if (nIndex == CUSTOM_BOX_VALUE) { ::SetRect(rect, m_CustomTextRect.left, m_CustomTextRect.top, m_CustomTextRect.right, m_CustomTextRect.bottom); return TRUE; } else if (nIndex == DEFAULT_BOX_VALUE) { ::SetRect(rect, m_DefaultTextRect.left, m_DefaultTextRect.top, m_DefaultTextRect.right, m_DefaultTextRect.bottom); return TRUE; } if (nIndex < 0 || nIndex >= m_nNumColours) return FALSE; rect->left = GetColumn(nIndex) * m_nBoxSize + m_nMargin; rect->top = GetRow(nIndex) * m_nBoxSize + m_nMargin; // Move everything down if we are displaying a default text area if (m_strDefaultText.GetLength()) rect->top += (m_nMargin + m_DefaultTextRect.Height()); rect->right = rect->left + m_nBoxSize; rect->bottom = rect->top + m_nBoxSize; return TRUE; } // Works out an appropriate size and position of this window void CColourPopup::SetWindowSize() { CSize TextSize; // If we are showing a custom or default text area, get the font and text size. if (m_strCustomText.GetLength() || m_strDefaultText.GetLength()) { CClientDC dc(this); CFont* pOldFont = (CFont*) dc.SelectObject(&m_Font); // Get the size of the custom text (if there IS custom text) TextSize = CSize(0,0); if (m_strCustomText.GetLength()) TextSize = dc.GetTextExtent(m_strCustomText); // Get the size of the default text (if there IS default text) if (m_strDefaultText.GetLength()) { CSize DefaultSize = dc.GetTextExtent(m_strDefaultText); if (DefaultSize.cx > TextSize.cx) TextSize.cx = DefaultSize.cx; if (DefaultSize.cy > TextSize.cy) TextSize.cy = DefaultSize.cy; } dc.SelectObject(pOldFont); TextSize += CSize(2*m_nMargin,2*m_nMargin); // Add even more space to draw the horizontal line TextSize.cy += 2*m_nMargin + 2; } // Get the number of columns and rows //m_nNumColumns = (int) sqrt((double)m_nNumColours); // for a square window (yuk) m_nNumColumns = 8; m_nNumRows = m_nNumColours / m_nNumColumns; if (m_nNumColours % m_nNumColumns) m_nNumRows++; // Get the current window position, and set the new size CRect rect; GetWindowRect(rect); m_WindowRect.SetRect(rect.left, rect.top, rect.left + m_nNumColumns*m_nBoxSize + 2*m_nMargin, rect.top + m_nNumRows*m_nBoxSize + 2*m_nMargin); // if custom text, then expand window if necessary, and set text width as // window width if (m_strDefaultText.GetLength()) { if (TextSize.cx > m_WindowRect.Width()) m_WindowRect.right = m_WindowRect.left + TextSize.cx; TextSize.cx = m_WindowRect.Width()-2*m_nMargin; // Work out the text area m_DefaultTextRect.SetRect(m_nMargin, m_nMargin, m_nMargin+TextSize.cx, 2*m_nMargin+TextSize.cy); m_WindowRect.bottom += m_DefaultTextRect.Height() + 2*m_nMargin; } // if custom text, then expand window if necessary, and set text width as // window width if (m_strCustomText.GetLength()) { if (TextSize.cx > m_WindowRect.Width()) m_WindowRect.right = m_WindowRect.left + TextSize.cx; TextSize.cx = m_WindowRect.Width()-2*m_nMargin; // Work out the text area m_CustomTextRect.SetRect(m_nMargin, m_WindowRect.Height(), m_nMargin+TextSize.cx, m_WindowRect.Height()+m_nMargin+TextSize.cy); m_WindowRect.bottom += m_CustomTextRect.Height() + 2*m_nMargin; } // Need to check it'll fit on screen: Too far right? CSize ScreenSize(::GetSystemMetrics(SM_CXSCREEN), ::GetSystemMetrics(SM_CYSCREEN)); if (m_WindowRect.right > ScreenSize.cx) m_WindowRect.OffsetRect(-(m_WindowRect.right - ScreenSize.cx), 0); // Too far left? if (m_WindowRect.left < 0) m_WindowRect.OffsetRect( -m_WindowRect.left, 0); // Bottom falling out of screen? if (m_WindowRect.bottom > ScreenSize.cy) { CRect ParentRect; m_pParent->GetWindowRect(ParentRect); m_WindowRect.OffsetRect(0, -(ParentRect.Height() + m_WindowRect.Height())); } // Set the window size and position MoveWindow(m_WindowRect, TRUE); } void CColourPopup::CreateToolTips() { // Create the tool tip if (!m_ToolTip.Create(this)) return; // Add a tool for each cell for (int i = 0; i < m_nNumColours; i++) { CRect rect; if (!GetCellRect(i, rect)) continue; m_ToolTip.AddTool(this, GetColourName(i), rect, 1); } } void CColourPopup::ChangeSelection(int nIndex) { CClientDC dc(this); // device context for drawing if (nIndex > m_nNumColours) nIndex = CUSTOM_BOX_VALUE; if ((m_nCurrentSel >= 0 && m_nCurrentSel < m_nNumColours) || m_nCurrentSel == CUSTOM_BOX_VALUE || m_nCurrentSel == DEFAULT_BOX_VALUE) { // Set Current selection as invalid and redraw old selection (this way // the old selection will be drawn unselected) int OldSel = m_nCurrentSel; m_nCurrentSel = INVALID_COLOUR; DrawCell(&dc, OldSel); } // Set the current selection as row/col and draw (it will be drawn selected) m_nCurrentSel = nIndex; DrawCell(&dc, m_nCurrentSel); // Store the current colour if (m_nCurrentSel == CUSTOM_BOX_VALUE) m_pParent->SendMessage(CPN_SELCHANGE, (WPARAM) m_crInitialColour, 0); else if (m_nCurrentSel == DEFAULT_BOX_VALUE) { m_crColour = CLR_DEFAULT; m_pParent->SendMessage(CPN_SELCHANGE, (WPARAM) CLR_DEFAULT, 0); } else { m_crColour = GetColour(m_nCurrentSel); m_pParent->SendMessage(CPN_SELCHANGE, (WPARAM) m_crColour, 0); } } void CColourPopup::EndSelection(int nMessage) { ReleaseCapture(); // If custom text selected, perform a custom colour selection if (nMessage != CPN_SELENDCANCEL && m_nCurrentSel == CUSTOM_BOX_VALUE) { m_bChildWindowVisible = TRUE; CColorDialog dlg(m_crInitialColour, CC_FULLOPEN | CC_ANYCOLOR, this); if (dlg.DoModal() == IDOK) m_crColour = dlg.GetColor(); else nMessage = CPN_SELENDCANCEL; m_bChildWindowVisible = FALSE; } if (nMessage == CPN_SELENDCANCEL) m_crColour = m_crInitialColour; m_pParent->SendMessage(nMessage, (WPARAM) m_crColour, 0); // Kill focus bug fixed by Martin Wawrusch if (!m_bChildWindowVisible) DestroyWindow(); } void CColourPopup::DrawCell(CDC* pDC, int nIndex) { // For the Custom Text area if (m_strCustomText.GetLength() && nIndex == CUSTOM_BOX_VALUE) { // The extent of the actual text button CRect TextButtonRect = m_CustomTextRect; TextButtonRect.top += 2*m_nMargin; // Fill background pDC->FillSolidRect(TextButtonRect, ::GetSysColor(COLOR_3DFACE)); // Draw horizontal line pDC->FillSolidRect(m_CustomTextRect.left+2*m_nMargin, m_CustomTextRect.top, m_CustomTextRect.Width()-4*m_nMargin, 1, ::GetSysColor(COLOR_3DSHADOW)); pDC->FillSolidRect(m_CustomTextRect.left+2*m_nMargin, m_CustomTextRect.top+1, m_CustomTextRect.Width()-4*m_nMargin, 1, ::GetSysColor(COLOR_3DHILIGHT)); TextButtonRect.DeflateRect(1,1); // fill background if (m_nChosenColourSel == nIndex && m_nCurrentSel != nIndex) pDC->FillSolidRect(TextButtonRect, ::GetSysColor(COLOR_3DLIGHT)); else pDC->FillSolidRect(TextButtonRect, ::GetSysColor(COLOR_3DFACE)); // Draw button if (m_nCurrentSel == nIndex) pDC->DrawEdge(TextButtonRect, BDR_RAISEDINNER, BF_RECT); else if (m_nChosenColourSel == nIndex) pDC->DrawEdge(TextButtonRect, BDR_SUNKENOUTER, BF_RECT); // Draw custom text CFont *pOldFont = (CFont*) pDC->SelectObject(&m_Font); pDC->SetBkMode(TRANSPARENT); pDC->DrawText(m_strCustomText, TextButtonRect, DT_CENTER | DT_VCENTER | DT_SINGLELINE); pDC->SelectObject(pOldFont); return; } // For the Default Text area if (m_strDefaultText.GetLength() && nIndex == DEFAULT_BOX_VALUE) { // Fill background pDC->FillSolidRect(m_DefaultTextRect, ::GetSysColor(COLOR_3DFACE)); // The extent of the actual text button CRect TextButtonRect = m_DefaultTextRect; TextButtonRect.DeflateRect(1,1); // fill background if (m_nChosenColourSel == nIndex && m_nCurrentSel != nIndex) pDC->FillSolidRect(TextButtonRect, ::GetSysColor(COLOR_3DLIGHT)); else pDC->FillSolidRect(TextButtonRect, ::GetSysColor(COLOR_3DFACE)); // Draw thin line around text CRect LineRect = TextButtonRect; LineRect.DeflateRect(2*m_nMargin,2*m_nMargin); CPen pen(PS_SOLID, 1, ::GetSysColor(COLOR_3DSHADOW)); CPen* pOldPen = pDC->SelectObject(&pen); pDC->SelectStockObject(NULL_BRUSH); pDC->Rectangle(LineRect); pDC->SelectObject(pOldPen); // Draw button if (m_nCurrentSel == nIndex) pDC->DrawEdge(TextButtonRect, BDR_RAISEDINNER, BF_RECT); else if (m_nChosenColourSel == nIndex) pDC->DrawEdge(TextButtonRect, BDR_SUNKENOUTER, BF_RECT); // Draw custom text CFont *pOldFont = (CFont*) pDC->SelectObject(&m_Font); pDC->SetBkMode(TRANSPARENT); pDC->DrawText(m_strDefaultText, TextButtonRect, DT_CENTER | DT_VCENTER | DT_SINGLELINE); pDC->SelectObject(pOldFont); return; } CRect rect; if (!GetCellRect(nIndex, rect)) return; // Select and realize the palette CPalette* pOldPalette = NULL; if (pDC->GetDeviceCaps(RASTERCAPS) & RC_PALETTE) { pOldPalette = pDC->SelectPalette(&m_Palette, FALSE); pDC->RealizePalette(); } // fill background if (m_nChosenColourSel == nIndex && m_nCurrentSel != nIndex) pDC->FillSolidRect(rect, ::GetSysColor(COLOR_3DHILIGHT)); else pDC->FillSolidRect(rect, ::GetSysColor(COLOR_3DFACE)); // Draw button if (m_nCurrentSel == nIndex) pDC->DrawEdge(rect, BDR_RAISEDINNER, BF_RECT); else if (m_nChosenColourSel == nIndex) pDC->DrawEdge(rect, BDR_SUNKENOUTER, BF_RECT); CBrush brush(PALETTERGB(GetRValue(GetColour(nIndex)), GetGValue(GetColour(nIndex)), GetBValue(GetColour(nIndex)) )); CPen pen; pen.CreatePen(PS_SOLID, 1, ::GetSysColor(COLOR_3DSHADOW)); CBrush* pOldBrush = (CBrush*) pDC->SelectObject(&brush); CPen* pOldPen = (CPen*) pDC->SelectObject(&pen); // Draw the cell colour rect.DeflateRect(m_nMargin+1, m_nMargin+1); pDC->Rectangle(rect); // restore DC and cleanup pDC->SelectObject(pOldBrush); pDC->SelectObject(pOldPen); brush.DeleteObject(); pen.DeleteObject(); if (pOldPalette && pDC->GetDeviceCaps(RASTERCAPS) & RC_PALETTE) pDC->SelectPalette(pOldPalette, FALSE); } BOOL CColourPopup::OnQueryNewPalette() { Invalidate(); return CWnd::OnQueryNewPalette(); } void CColourPopup::OnPaletteChanged(CWnd* pFocusWnd) { CWnd::OnPaletteChanged(pFocusWnd); if (pFocusWnd->GetSafeHwnd() != GetSafeHwnd()) Invalidate(); } void CColourPopup::OnKillFocus(CWnd* pNewWnd) { CWnd::OnKillFocus(pNewWnd); ReleaseCapture(); } // KillFocus problem fix suggested by Paul Wilkerson. void CColourPopup::OnActivateApp(BOOL bActive, DWORD hTask) { #if _MFC_VER < 0x700 CWnd::OnActivateApp(bActive, (HTASK) hTask); #else CWnd::OnActivateApp(bActive, hTask); #endif // If Deactivating App, cancel this selection if (!bActive) EndSelection(CPN_SELENDCANCEL); }
/* * Copyright (C) 2015 Open Source Robotics Foundation * * 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 <ignition/math/Pose3.hh> #include <ignition/math/Vector3.hh> #include "gazebo/common/Console.hh" #include "gazebo/rendering/Material.hh" #include "gazebo/gui/ConfigWidget.hh" #include "gazebo/gui/GuiIface.hh" #include "gazebo/gui/MainWindow.hh" #include "gazebo/gui/model/JointCreationDialog.hh" #include "gazebo/gui/model/JointCreationDialogPrivate.hh" #include "gazebo/gui/model/JointMaker.hh" using namespace gazebo; using namespace gui; ///////////////////////////////////////////////// JointCreationDialog::JointCreationDialog(JointMaker *_jointMaker, QWidget *_parent) : QDialog(_parent), dataPtr(new JointCreationDialogPrivate) { this->setObjectName("JointCreationDialog"); this->setWindowTitle(tr("Create Joint")); this->setWindowFlags(this->windowFlags() | Qt::WindowStaysOnTopHint); this->setModal(false); // Dialog size this->setMinimumWidth(500); this->setMinimumHeight(300); int desiredHeight = 940; MainWindow *mainWindow = qobject_cast<MainWindow *>(_parent); if (mainWindow) { desiredHeight = std::min(desiredHeight, (mainWindow->height()-100)); } this->resize(500, desiredHeight); this->dataPtr->jointMaker = _jointMaker; // ConfigWidget this->dataPtr->configWidget = new ConfigWidget(); // Joint types QRadioButton *fixedJointRadio = new QRadioButton(tr("Fixed")); QRadioButton *prismaticJointRadio = new QRadioButton(tr("Prismatic")); QRadioButton *revoluteJointRadio = new QRadioButton(tr("Revolute")); QRadioButton *revolute2JointRadio = new QRadioButton(tr("Revolute2")); QRadioButton *screwJointRadio = new QRadioButton(tr("Screw")); QRadioButton *universalJointRadio = new QRadioButton(tr("Universal")); QRadioButton *ballJointRadio = new QRadioButton(tr("Ball")); QRadioButton *gearboxJointRadio = new QRadioButton(tr("Gearbox")); this->dataPtr->typeButtons = new QButtonGroup(); this->dataPtr->typeButtons->addButton(fixedJointRadio, 1); this->dataPtr->typeButtons->addButton(prismaticJointRadio, 2); this->dataPtr->typeButtons->addButton(revoluteJointRadio, 3); this->dataPtr->typeButtons->addButton(revolute2JointRadio, 4); this->dataPtr->typeButtons->addButton(screwJointRadio, 5); this->dataPtr->typeButtons->addButton(universalJointRadio, 6); this->dataPtr->typeButtons->addButton(ballJointRadio, 7); this->dataPtr->typeButtons->addButton(gearboxJointRadio, 8); connect(this->dataPtr->typeButtons, SIGNAL(buttonClicked(int)), this->dataPtr->jointMaker, SLOT(OnType(int))); connect(this->dataPtr->typeButtons, SIGNAL(buttonClicked(int)), this, SLOT(OnType(int))); for (auto button : this->dataPtr->typeButtons->buttons()) { button->setStyleSheet("QRadioButton{color : #d0d0d0}"); } // Types layout QGridLayout *typesLayout = new QGridLayout(); typesLayout->addWidget(fixedJointRadio, 0, 0); typesLayout->addWidget(revoluteJointRadio, 1, 0); typesLayout->addWidget(revolute2JointRadio, 2, 0); typesLayout->addWidget(prismaticJointRadio, 3, 0); typesLayout->addWidget(screwJointRadio, 0, 1); typesLayout->addWidget(universalJointRadio, 1, 1); typesLayout->addWidget(ballJointRadio, 2, 1); typesLayout->addWidget(gearboxJointRadio, 3, 1); // Types group widget ConfigChildWidget *typesWidget = new ConfigChildWidget(); typesWidget->setLayout(typesLayout); QWidget *typesGroupWidget = this->dataPtr->configWidget->CreateGroupWidget("Joint types", typesWidget, 0); // Link selections this->dataPtr->selectionsText = new QLabel(tr( "Click a link in the scene to select parent.\n" "Click again to select child.")); // Parent config std::vector<std::string> links; this->dataPtr->parentLinkWidget = this->dataPtr->configWidget->CreateEnumWidget("parent", links, 0); this->dataPtr->parentLinkWidget->setStyleSheet( ConfigWidget::StyleSheet("active", 1)); this->dataPtr->configWidget->AddConfigChildWidget("parentCombo", this->dataPtr->parentLinkWidget); // Resize parent label auto parentLabel = this->dataPtr->parentLinkWidget->findChild<QLabel *>(); parentLabel->setMaximumWidth(50); // Add parent icon this->dataPtr->parentIcon = new QLabel(); this->dataPtr->parentIcon->setMinimumWidth(15); this->dataPtr->parentIcon->setMaximumHeight(15); auto parentLayout = qobject_cast<QHBoxLayout *>( this->dataPtr->parentLinkWidget->layout()); if (parentLayout) { parentLayout->insertWidget(1, this->dataPtr->parentIcon); parentLayout->setAlignment(this->dataPtr->parentIcon, Qt::AlignLeft); } // Child config this->dataPtr->childLinkWidget = this->dataPtr->configWidget->CreateEnumWidget("child", links, 0); this->dataPtr->childLinkWidget->setStyleSheet( ConfigWidget::StyleSheet("normal", 1)); this->dataPtr->configWidget->AddConfigChildWidget("childCombo", this->dataPtr->childLinkWidget); this->dataPtr->configWidget->SetWidgetReadOnly("childCombo", true); // Resize child label auto childLabel = this->dataPtr->childLinkWidget->findChild<QLabel *>(); childLabel->setMaximumWidth(50); // Add child icon QPixmap childPix(":/images/child-link.png"); childPix = childPix.scaled(15, 15); auto childIcon = new QLabel(); childIcon->setPixmap(childPix); childIcon->setMaximumWidth(15); auto childLayout = qobject_cast<QHBoxLayout *>( this->dataPtr->childLinkWidget->layout()); if (childLayout) { childLayout->insertWidget(1, childIcon); childLayout->setAlignment(childIcon, Qt::AlignLeft); } // Connect all enum value changes QObject::connect(this->dataPtr->configWidget, SIGNAL(EnumValueChanged(const QString &, const QString &)), this, SLOT(OnEnumChanged(const QString &, const QString &))); // Swap button this->dataPtr->swapButton = new QToolButton(); this->dataPtr->swapButton->setObjectName("JointCreationSwapButton"); this->dataPtr->swapButton->setToolButtonStyle(Qt::ToolButtonIconOnly); this->dataPtr->swapButton->setIcon( QPixmap(":/images/swap-parent-child.png")); this->dataPtr->swapButton->setFixedSize(QSize(50, 50)); this->dataPtr->swapButton->setIconSize(QSize(35, 35)); this->dataPtr->swapButton->setToolTip("Swap parent and child"); this->dataPtr->swapButton->setStyleSheet( "QToolButton\ {\ background-color: " + ConfigWidget::bgColors[0] + "}"); connect(this->dataPtr->swapButton, SIGNAL(clicked()), this, SLOT(OnSwap())); // Links layout QGridLayout *linksLayout = new QGridLayout(); linksLayout->setContentsMargins(0, 0, 0, 0); linksLayout->setSpacing(0); linksLayout->addWidget(this->dataPtr->selectionsText, 0, 0, 1, 2); linksLayout->addWidget(this->dataPtr->parentLinkWidget, 1, 0); linksLayout->addWidget(this->dataPtr->childLinkWidget, 2, 0); linksLayout->addWidget(this->dataPtr->swapButton, 1, 1, 2, 1); // Links group widget ConfigChildWidget *linksWidget = new ConfigChildWidget(); linksWidget->setLayout(linksLayout); QWidget *linksGroupWidget = this->dataPtr->configWidget->CreateGroupWidget( "Link Selections", linksWidget, 0); // Label when joint has no axes this->dataPtr->axis0Widget = new QLabel( tr("The joint type chosen has no axes")); // Axis1 widget this->dataPtr->axis1Widget = this->dataPtr->configWidget->CreateVector3dWidget("axis1", 0); this->dataPtr->configWidget->AddConfigChildWidget("axis1", this->dataPtr->axis1Widget); this->dataPtr->configWidget->SetVector3dWidgetValue("axis1", ignition::math::Vector3d::UnitX); this->dataPtr->configWidget->SetWidgetReadOnly("axis1", true); // Axis2 widget this->dataPtr->axis2Widget = this->dataPtr->configWidget->CreateVector3dWidget("axis2", 0); this->dataPtr->configWidget->AddConfigChildWidget("axis2", this->dataPtr->axis2Widget); this->dataPtr->configWidget->SetVector3dWidgetValue("axis2", ignition::math::Vector3d::UnitY); this->dataPtr->configWidget->SetWidgetReadOnly("axis2", true); // Axis general layout auto axisGeneralLayout = new QVBoxLayout(); axisGeneralLayout->setContentsMargins(0, 0, 0, 0); axisGeneralLayout->setSpacing(0); axisGeneralLayout->addWidget(this->dataPtr->axis0Widget); axisGeneralLayout->addWidget(this->dataPtr->axis1Widget); axisGeneralLayout->addWidget(this->dataPtr->axis2Widget); ConfigChildWidget *axisGeneralWidget = new ConfigChildWidget(); axisGeneralWidget->setLayout(axisGeneralLayout); QWidget *axisGroupWidget = this->dataPtr->configWidget->CreateGroupWidget( "Joint axis", axisGeneralWidget, 0); // Axis signals connect(this->dataPtr->configWidget, SIGNAL(Vector3dValueChanged(const QString, const ignition::math::Vector3d)), this, SLOT(OnVector3dFromDialog(const QString, const ignition::math::Vector3d))); // Align widgets QLabel *xAlignLabel = new QLabel(tr("X: ")); xAlignLabel->setMaximumWidth(20); QLabel *yAlignLabel = new QLabel(tr("Y: ")); yAlignLabel->setMaximumWidth(20); QLabel *zAlignLabel = new QLabel(tr("Z: ")); zAlignLabel->setMaximumWidth(20); auto xAlignMin = new QToolButton(); xAlignMin->setToolButtonStyle(Qt::ToolButtonIconOnly); xAlignMin->setIcon(QIcon(":/images/x_min.png")); xAlignMin->setToolTip("X Align Min"); xAlignMin->setCheckable(true); auto xAlignCenter = new QToolButton(); xAlignCenter->setToolButtonStyle(Qt::ToolButtonIconOnly); xAlignCenter->setIcon(QIcon(":/images/x_center.png")); xAlignCenter->setToolTip("X Align Center"); xAlignCenter->setCheckable(true); auto xAlignMax = new QToolButton(); xAlignMax->setToolButtonStyle(Qt::ToolButtonIconOnly); xAlignMax->setIcon(QIcon(":/images/x_max.png")); xAlignMax->setToolTip("X Align Max"); xAlignMax->setCheckable(true); auto yAlignMin = new QToolButton(); yAlignMin->setToolButtonStyle(Qt::ToolButtonIconOnly); yAlignMin->setIcon(QIcon(":/images/y_min.png")); yAlignMin->setToolTip("Y Align Min"); yAlignMin->setCheckable(true); auto yAlignCenter = new QToolButton(); yAlignCenter->setToolButtonStyle(Qt::ToolButtonIconOnly); yAlignCenter->setIcon(QIcon(":/images/y_center.png")); yAlignCenter->setToolTip("Y Align Center"); yAlignCenter->setCheckable(true); auto yAlignMax = new QToolButton(); yAlignMax->setToolButtonStyle(Qt::ToolButtonIconOnly); yAlignMax->setIcon(QIcon(":/images/y_max.png")); yAlignMax->setToolTip("Y Align Max"); yAlignMax->setCheckable(true); auto zAlignMin = new QToolButton(); zAlignMin->setToolButtonStyle(Qt::ToolButtonIconOnly); zAlignMin->setIcon(QIcon(":/images/z_min.png")); zAlignMin->setToolTip("Z Align Min"); zAlignMin->setCheckable(true); auto zAlignCenter = new QToolButton(); zAlignCenter->setToolButtonStyle(Qt::ToolButtonIconOnly); zAlignCenter->setIcon(QIcon(":/images/z_center.png")); zAlignCenter->setToolTip("Z Align Center"); zAlignCenter->setCheckable(true); auto zAlignMax = new QToolButton(); zAlignMax->setToolButtonStyle(Qt::ToolButtonIconOnly); zAlignMax->setIcon(QIcon(":/images/z_max.png")); zAlignMax->setToolTip("Z Align Max"); zAlignMax->setCheckable(true); auto alignXButtonGroup = new QButtonGroup(); alignXButtonGroup->setExclusive(false); alignXButtonGroup->addButton(xAlignMin, 0); alignXButtonGroup->addButton(xAlignCenter, 1); alignXButtonGroup->addButton(xAlignMax, 2); connect(alignXButtonGroup, SIGNAL(buttonClicked(const int)), this, SLOT(OnAlign(const int))); this->dataPtr->alignGroups.push_back(alignXButtonGroup); auto alignYButtonGroup = new QButtonGroup(); alignYButtonGroup->setExclusive(false); alignYButtonGroup->addButton(yAlignMin, 0); alignYButtonGroup->addButton(yAlignCenter, 1); alignYButtonGroup->addButton(yAlignMax, 2); connect(alignYButtonGroup, SIGNAL(buttonClicked(const int)), this, SLOT(OnAlign(const int))); this->dataPtr->alignGroups.push_back(alignYButtonGroup); auto alignZButtonGroup = new QButtonGroup(); alignZButtonGroup->setExclusive(false); alignZButtonGroup->addButton(zAlignMin, 0); alignZButtonGroup->addButton(zAlignCenter, 1); alignZButtonGroup->addButton(zAlignMax, 2); connect(alignZButtonGroup, SIGNAL(buttonClicked(const int)), this, SLOT(OnAlign(const int))); this->dataPtr->alignGroups.push_back(alignZButtonGroup); // Reverse checkboxes this->dataPtr->reverseXBox = new QCheckBox("Reverse"); connect(this->dataPtr->reverseXBox, SIGNAL(stateChanged(const int)), this, SLOT(OnAlign(const int))); this->dataPtr->reverseYBox = new QCheckBox("Reverse"); connect(this->dataPtr->reverseYBox, SIGNAL(stateChanged(const int)), this, SLOT(OnAlign(const int))); this->dataPtr->reverseZBox = new QCheckBox("Reverse"); connect(this->dataPtr->reverseZBox, SIGNAL(stateChanged(const int)), this, SLOT(OnAlign(const int))); // Target dropdown this->dataPtr->alignCombo = new QComboBox(); this->dataPtr->alignCombo->addItem("Child to Parent", 0); this->dataPtr->alignCombo->addItem("Parent to Child", 1); this->dataPtr->alignCombo->setToolTip("Choose alignment reference"); connect(this->dataPtr->alignCombo, SIGNAL(currentIndexChanged(const int)), this, SLOT(OnAlign(const int))); // Align layout QGridLayout *alignLayout = new QGridLayout(); alignLayout->addWidget(xAlignLabel, 0, 0); alignLayout->addWidget(xAlignMin, 0, 1); alignLayout->addWidget(xAlignCenter, 0, 2); alignLayout->addWidget(xAlignMax, 0, 3); alignLayout->addWidget(yAlignLabel, 1, 0); alignLayout->addWidget(yAlignMin, 1, 1); alignLayout->addWidget(yAlignCenter, 1, 2); alignLayout->addWidget(yAlignMax, 1, 3); alignLayout->addWidget(zAlignLabel, 2, 0); alignLayout->addWidget(zAlignMin, 2, 1); alignLayout->addWidget(zAlignCenter, 2, 2); alignLayout->addWidget(zAlignMax, 2, 3); alignLayout->addWidget(this->dataPtr->reverseXBox, 0, 4, 1, 3); alignLayout->addWidget(this->dataPtr->reverseYBox, 1, 4, 1, 3); alignLayout->addWidget(this->dataPtr->reverseZBox, 2, 4, 1, 3); alignLayout->addWidget(this->dataPtr->alignCombo, 3, 0, 1, 5); alignLayout->setAlignment(xAlignLabel, Qt::AlignRight); alignLayout->setAlignment(yAlignLabel, Qt::AlignRight); alignLayout->setAlignment(zAlignLabel, Qt::AlignRight); // Align group widget ConfigChildWidget *alignWidget = new ConfigChildWidget(); alignWidget->setLayout(alignLayout); this->dataPtr->configWidget->AddConfigChildWidget("align", alignWidget); this->dataPtr->configWidget->SetWidgetReadOnly("align", true); QWidget *alignGroupWidget = this->dataPtr->configWidget->CreateGroupWidget("Align links", alignWidget, 0); // Joint pose widget ConfigChildWidget *jointPoseWidget = this->dataPtr->configWidget->CreatePoseWidget("joint_pose", 0); this->dataPtr->configWidget->AddConfigChildWidget("joint_pose", jointPoseWidget); this->dataPtr->configWidget->SetWidgetReadOnly("joint_pose", true); QWidget *jointPoseGroupWidget = this->dataPtr->configWidget->CreateGroupWidget( "Joint Pose", jointPoseWidget, 0); jointPoseGroupWidget->setToolTip( "Joint pose expressed in the child link frame"); // Relative pose widget ConfigChildWidget *relativePoseWidget = this->dataPtr->configWidget->CreatePoseWidget("relative_pose", 0); this->dataPtr->configWidget->AddConfigChildWidget("relative_pose", relativePoseWidget); this->dataPtr->configWidget->SetWidgetReadOnly("relative_pose", true); QWidget *relativePoseGroupWidget = this->dataPtr->configWidget->CreateGroupWidget( "Relative Pose", relativePoseWidget, 0); relativePoseGroupWidget->setToolTip( "Child link pose expressed in parent link frame"); // Connect pose widgets signal connect(this->dataPtr->configWidget, SIGNAL(PoseValueChanged(const QString, const ignition::math::Pose3d)), this, SLOT(OnPoseFromDialog(const QString, const ignition::math::Pose3d))); // Spacer QWidget *spacer = new QWidget(); spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); // Config Widget layout QVBoxLayout *configLayout = new QVBoxLayout(); configLayout->setSpacing(0); configLayout->addWidget(typesGroupWidget); configLayout->addWidget(linksGroupWidget); configLayout->addWidget(axisGroupWidget); configLayout->addWidget(alignGroupWidget); configLayout->addWidget(jointPoseGroupWidget); configLayout->addWidget(relativePoseGroupWidget); configLayout->addWidget(spacer); this->dataPtr->configWidget->setLayout(configLayout); // Scroll area QScrollArea *scrollArea = new QScrollArea; scrollArea->setWidget(this->dataPtr->configWidget); scrollArea->setWidgetResizable(true); // General layout QVBoxLayout *generalLayout = new QVBoxLayout; generalLayout->setContentsMargins(0, 0, 0, 0); generalLayout->addWidget(scrollArea); // Reset all button QPushButton *resetAllButton = new QPushButton(tr("Reset")); resetAllButton->setObjectName("JointCreationResetButton"); resetAllButton->setToolTip("Reset"); connect(resetAllButton, SIGNAL(clicked()), this, SLOT(OnResetAll())); // Cancel button QPushButton *cancelButton = new QPushButton(tr("Cancel")); cancelButton->setObjectName("JointCreationCancelButton"); connect(cancelButton, SIGNAL(clicked()), this, SLOT(OnCancel())); // Create button this->dataPtr->createButton = new QPushButton(tr("Create")); this->dataPtr->createButton->setObjectName("JointCreationCreateButton"); this->dataPtr->createButton->setEnabled(false); connect(this->dataPtr->createButton, SIGNAL(clicked()), this, SLOT(OnCreate())); // Buttons layout QHBoxLayout *buttonsLayout = new QHBoxLayout; buttonsLayout->addWidget(resetAllButton); buttonsLayout->addWidget(cancelButton); buttonsLayout->addWidget(this->dataPtr->createButton); buttonsLayout->setAlignment(Qt::AlignRight); // Main layout QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addLayout(generalLayout); mainLayout->addLayout(buttonsLayout); this->setLayout(mainLayout); // Qt signal-slot connections connect(this, SIGNAL(rejected()), this, SLOT(OnCancel())); // Initialize variables this->dataPtr->validLinks = false; this->dataPtr->validAxis1 = true; this->dataPtr->validAxis2 = true; } ///////////////////////////////////////////////// JointCreationDialog::~JointCreationDialog() { } ///////////////////////////////////////////////// void JointCreationDialog::Open(const JointMaker::JointType _type) { if (!this->dataPtr->jointMaker) { gzerr << "Joint maker not found, can't open joint creation dialog." << std::endl; this->OnCancel(); } // Check joint type this->dataPtr->typeButtons->button(static_cast<int>(_type)) ->setChecked(true); this->OnType(_type); // Clear links this->dataPtr->configWidget->ClearEnumWidget("parentCombo"); this->dataPtr->configWidget->ClearEnumWidget("childCombo"); // Add an empty option to each this->dataPtr->configWidget->AddItemEnumWidget("parentCombo", ""); this->dataPtr->configWidget->AddItemEnumWidget("childCombo", ""); // Fill with all existing links for (auto link : this->dataPtr->jointMaker->LinkList()) { this->dataPtr->configWidget->AddItemEnumWidget("parentCombo", link.second); this->dataPtr->configWidget->AddItemEnumWidget("childCombo", link.second); } // Reset fields this->OnResetAll(); // Reset enabled states this->dataPtr->createButton->setEnabled(false); this->dataPtr->swapButton->setEnabled(false); this->dataPtr->configWidget->SetWidgetReadOnly("childCombo", true); this->dataPtr->configWidget->SetWidgetReadOnly("axis1", true); this->dataPtr->configWidget->SetWidgetReadOnly("axis2", true); this->dataPtr->configWidget->SetWidgetReadOnly("align", true); this->dataPtr->configWidget->SetWidgetReadOnly("joint_pose", true); this->dataPtr->configWidget->SetWidgetReadOnly("relative_pose", true); this->dataPtr->parentLinkWidget->setStyleSheet( ConfigWidget::StyleSheet("active", 1)); this->dataPtr->childLinkWidget->setStyleSheet( ConfigWidget::StyleSheet("normal", 1)); this->dataPtr->axis1Widget->setStyleSheet( ConfigWidget::StyleSheet("normal", 1)); this->dataPtr->axis2Widget->setStyleSheet( ConfigWidget::StyleSheet("normal", 1)); if (this->parentWidget()) this->move(this->parentWidget()->pos()); this->show(); QApplication::setOverrideCursor(QCursor(Qt::CrossCursor)); } ///////////////////////////////////////////////// void JointCreationDialog::OnLinkFromDialog() { std::string currentParent = this->dataPtr->configWidget->EnumWidgetValue("parentCombo"); std::string currentChild = this->dataPtr->configWidget->EnumWidgetValue("childCombo"); // Notify so 3D is updated if (currentParent != currentChild) { if (currentParent != "") this->dataPtr->jointMaker->SetParentLink(currentParent); if (currentChild != "") this->dataPtr->jointMaker->SetChildLink(currentChild); } if (currentParent != "") this->OnParentImpl(currentParent); if (currentChild != "") this->OnChildImpl(currentChild); this->UncheckAllAlign(); } ///////////////////////////////////////////////// void JointCreationDialog::OnPoseFromDialog(const QString &_name, const ignition::math::Pose3d &_pose) { if (_name == "relative_pose") this->dataPtr->jointMaker->SetLinksRelativePose(_pose, false); if (_name == "joint_pose") this->dataPtr->jointMaker->SetJointPose(_pose); } ///////////////////////////////////////////////// void JointCreationDialog::OnVector3dFromDialog(const QString &_name, const ignition::math::Vector3d &_value) { if (_value == ignition::math::Vector3d::Zero) { if (_name == "axis1") { this->dataPtr->axis1Widget->setStyleSheet( ConfigWidget::StyleSheet("warning", 1)); this->dataPtr->validAxis1 = false; } else if (_name == "axis2") { this->dataPtr->axis2Widget->setStyleSheet( ConfigWidget::StyleSheet("warning", 1)); this->dataPtr->validAxis2 = false; } } else { if (_name == "axis1") { this->dataPtr->axis1Widget->setStyleSheet( ConfigWidget::StyleSheet("normal", 1)); this->dataPtr->validAxis1 = true; } else if (_name == "axis2") { this->dataPtr->axis2Widget->setStyleSheet( ConfigWidget::StyleSheet("normal", 1)); this->dataPtr->validAxis2 = true; } } if (this->CheckValid()) this->dataPtr->jointMaker->SetAxis(_name.toStdString(), _value); } ///////////////////////////////////////////////// void JointCreationDialog::SetParent(const std::string &_linkName) { if (_linkName.empty()) { gzerr << "Empty link name for parent" << std::endl; return; } std::string unscopedName = _linkName; size_t idx = _linkName.find("::"); if (idx != std::string::npos) unscopedName = _linkName.substr(idx+2); this->dataPtr->configWidget->blockSignals(true); if (!this->dataPtr->configWidget->SetEnumWidgetValue("parentCombo", unscopedName)) { gzerr << "Requested link [" << unscopedName << "] not found" << std::endl; return; } this->dataPtr->configWidget->blockSignals(false); this->OnParentImpl(_linkName); } ///////////////////////////////////////////////// void JointCreationDialog::SetChild(const std::string &_linkName) { if (_linkName.empty()) { gzerr << "Empty link name for child" << std::endl; return; } if (this->dataPtr->configWidget->WidgetReadOnly("childCombo")) { gzerr << "It's not possible to set child yet." << std::endl; return; } // Update child combo box std::string unscopedName = _linkName; size_t idx = _linkName.find("::"); if (idx != std::string::npos) unscopedName = _linkName.substr(idx+2); this->dataPtr->configWidget->blockSignals(true); if (!this->dataPtr->configWidget->SetEnumWidgetValue("childCombo", unscopedName)) { gzerr << "Requested link [" << unscopedName << "] not found" << std::endl; return; } this->dataPtr->configWidget->blockSignals(false); this->OnChildImpl(_linkName); } ///////////////////////////////////////////////// void JointCreationDialog::OnParentImpl(const std::string &_linkName) { if (_linkName.empty()) { gzerr << "Empty link name for parent" << std::endl; return; } // Remove empty option this->dataPtr->configWidget->RemoveItemEnumWidget("parentCombo", ""); // Check if links are valid this->CheckLinksValid(); // Enable child selection if (this->dataPtr->configWidget->WidgetReadOnly("childCombo")) { this->dataPtr->configWidget->SetWidgetReadOnly("childCombo", false); this->dataPtr->childLinkWidget->setStyleSheet( ConfigWidget::StyleSheet("active", 1)); } } ///////////////////////////////////////////////// void JointCreationDialog::OnChildImpl(const std::string &_linkName) { if (_linkName.empty()) { gzerr << "Empty link name for child" << std::endl; return; } // Enable features this->dataPtr->createButton->setEnabled(true); this->dataPtr->swapButton->setEnabled(true); this->dataPtr->configWidget->SetWidgetReadOnly("axis1", false); this->dataPtr->configWidget->SetWidgetReadOnly("axis2", false); this->dataPtr->configWidget->SetWidgetReadOnly("joint_pose", false); this->dataPtr->configWidget->SetWidgetReadOnly("align", false); this->dataPtr->configWidget->SetWidgetReadOnly("relative_pose", false); // Remove empty option this->dataPtr->configWidget->RemoveItemEnumWidget("childCombo", ""); // Hide selection text this->dataPtr->selectionsText->setVisible(false); QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor)); // Check if links are valid this->CheckLinksValid(); } ///////////////////////////////////////////////// void JointCreationDialog::OnCancel() { this->close(); this->dataPtr->jointMaker->Stop(); } ///////////////////////////////////////////////// void JointCreationDialog::OnCreate() { this->accept(); this->dataPtr->jointMaker->FinalizeCreation(); } ///////////////////////////////////////////////// void JointCreationDialog::OnSwap() { // Get current values std::string currentParent = this->dataPtr->configWidget->EnumWidgetValue("parentCombo"); std::string currentChild = this->dataPtr->configWidget->EnumWidgetValue("childCombo"); // Choose new values this->dataPtr->configWidget->SetEnumWidgetValue("parentCombo", currentChild); this->dataPtr->configWidget->SetEnumWidgetValue("childCombo", currentParent); } ///////////////////////////////////////////////// void JointCreationDialog::UpdateRelativePose( const ignition::math::Pose3d &_pose) { this->dataPtr->configWidget->SetPoseWidgetValue("relative_pose", _pose); if (this->dataPtr->alignPending) { this->dataPtr->alignPending = false; return; } this->UncheckAllAlign(true); } ///////////////////////////////////////////////// void JointCreationDialog::OnResetAll() { this->dataPtr->jointMaker->SetLinksRelativePose(ignition::math::Pose3d::Zero, true); this->dataPtr->configWidget->SetVector3dWidgetValue("axis1", ignition::math::Vector3d::UnitX); this->dataPtr->configWidget->SetVector3dWidgetValue("axis2", ignition::math::Vector3d::UnitY); this->dataPtr->configWidget->SetPoseWidgetValue("joint_pose", ignition::math::Pose3d::Zero); this->OnPoseFromDialog("joint_pose", ignition::math::Pose3d::Zero); this->UncheckAllAlign(); } ///////////////////////////////////////////////// void JointCreationDialog::OnEnumChanged(const QString &_name, const QString &/*_value*/) { if (_name == "parentCombo" || _name == "childCombo") this->OnLinkFromDialog(); } ///////////////////////////////////////////////// void JointCreationDialog::CheckLinksValid() { std::string currentParent = this->dataPtr->configWidget->EnumWidgetValue("parentCombo"); std::string currentChild = this->dataPtr->configWidget->EnumWidgetValue("childCombo"); // Warning if parent is the same as the child and don't allow creation if (currentParent == currentChild) { this->dataPtr->parentLinkWidget->setStyleSheet( ConfigWidget::StyleSheet("warning", 1)); this->dataPtr->childLinkWidget->setStyleSheet( ConfigWidget::StyleSheet("warning", 1)); this->dataPtr->validLinks = false; } else { this->dataPtr->parentLinkWidget->setStyleSheet( ConfigWidget::StyleSheet("normal", 1)); if (!this->dataPtr->configWidget->WidgetReadOnly("childCombo")) { this->dataPtr->childLinkWidget->setStyleSheet( ConfigWidget::StyleSheet("normal", 1)); this->dataPtr->validLinks = true; } } // Disable align and relative_pose widgets if parent or child link // is a nested link // TODO: re-enable once pose of nested model links can be updated if (currentParent.find("::") != std::string::npos || currentChild.find("::") != std::string::npos) { this->dataPtr->configWidget->SetWidgetReadOnly("align", true); this->dataPtr->configWidget->SetWidgetReadOnly("relative_pose", true); gzwarn << "Pose updates for nested model links are not yet supported. " << "The Align and Relative Pose widgets will be disabled for now." << std::endl; } this->CheckValid(); } ///////////////////////////////////////////////// bool JointCreationDialog::CheckValid() { bool valid = this->dataPtr->validLinks && this->dataPtr->validAxis1 && this->dataPtr->validAxis2; if (this->dataPtr->createButton) this->dataPtr->createButton->setEnabled(valid); return valid; } ///////////////////////////////////////////////// void JointCreationDialog::OnAlign(const int _int) { // Button groups std::vector<std::string> axes = {"x", "y", "z"}; std::vector<std::string> configs = {"min", "center", "max"}; // Find out which axis was changed QButtonGroup *group = NULL; unsigned int g; QObject *senderObject = this->sender(); if (senderObject == this->dataPtr->reverseXBox) { g = 0; group = this->dataPtr->alignGroups[g]; } else if (senderObject == this->dataPtr->reverseYBox) { g = 1; group = this->dataPtr->alignGroups[g]; } else if (senderObject == this->dataPtr->reverseZBox) { g = 2; group = this->dataPtr->alignGroups[g]; } else { for (g = 0; g < this->dataPtr->alignGroups.size(); ++g) { group = this->dataPtr->alignGroups[g]; if (senderObject == group) { break; } } } // When changing target, reset everything if (senderObject == this->dataPtr->alignCombo) { this->dataPtr->jointMaker->SetLinksRelativePose( ignition::math::Pose3d::Zero, true); } // Reset only the axis which was changed else { this->dataPtr->jointMaker->SetLinksRelativePose( ignition::math::Pose3d::Zero, false, g); } // Uncheck other buttons in the same group if (group && qobject_cast<QButtonGroup *>(senderObject)) { for (int i = 0; i < group->buttons().size(); ++i) { if (i != _int) { group->buttons()[i]->setChecked(false); } } } // Reference link bool childToParent = this->dataPtr->alignCombo->currentIndex() == 0; // Direction std::vector<bool> reverse; reverse.push_back(this->dataPtr->reverseXBox->isChecked()); reverse.push_back(this->dataPtr->reverseYBox->isChecked()); reverse.push_back(this->dataPtr->reverseZBox->isChecked()); // Go through all groups and align for (g = 0; g < this->dataPtr->alignGroups.size(); ++g) { group = this->dataPtr->alignGroups[g]; // Align if there is a checked button int checked = group->checkedId(); if (checked >= 0 && checked <=2) { // Align this->dataPtr->jointMaker->AlignLinks(childToParent, axes[g], configs[checked], reverse[g]); } } this->dataPtr->alignPending = true; } ///////////////////////////////////////////////// void JointCreationDialog::UncheckAllAlign(const bool _blockSignals) { for (auto group : this->dataPtr->alignGroups) { for (auto button : group->buttons()) { bool blocked = button->signalsBlocked(); button->blockSignals(_blockSignals); button->setChecked(false); button->blockSignals(blocked); } } bool blocked = this->dataPtr->reverseXBox->signalsBlocked(); this->dataPtr->reverseXBox->blockSignals(_blockSignals); this->dataPtr->reverseXBox->setChecked(false); this->dataPtr->reverseXBox->blockSignals(blocked); blocked = this->dataPtr->reverseYBox->signalsBlocked(); this->dataPtr->reverseYBox->blockSignals(_blockSignals); this->dataPtr->reverseYBox->setChecked(false); this->dataPtr->reverseYBox->blockSignals(blocked); blocked = this->dataPtr->reverseZBox->signalsBlocked(); this->dataPtr->reverseZBox->blockSignals(_blockSignals); this->dataPtr->reverseZBox->setChecked(false); this->dataPtr->reverseZBox->blockSignals(blocked); } ///////////////////////////////////////////////// void JointCreationDialog::OnType(const int _typeInt) { auto type = static_cast<JointMaker::JointType>(_typeInt); unsigned int axisCount = JointMaker::JointAxisCount(type); // Display correct number of axes for this type this->dataPtr->axis0Widget->setVisible(axisCount == 0); this->dataPtr->axis1Widget->setVisible(axisCount > 0); this->dataPtr->axis2Widget->setVisible(axisCount > 1); // Change parent icon color according to type common::Color matAmbient, matDiffuse, matSpecular, matEmissive; rendering::Material::GetMaterialAsColor( this->dataPtr->jointMaker->jointMaterials[type], matAmbient, matDiffuse, matSpecular, matEmissive); std::ostringstream sheet; sheet << "QLabel{background-color: rgb(" << (matAmbient[0] * 255) << ", " << (matAmbient[1] * 255) << ", " << (matAmbient[2] * 255) << "); }"; this->dataPtr->parentIcon->setStyleSheet(QString::fromStdString(sheet.str())); } ///////////////////////////////////////////////// void JointCreationDialog::keyPressEvent(QKeyEvent *_event) { if (_event->key() == Qt::Key_Enter) _event->accept(); else QDialog::keyPressEvent(_event); }
/** \file AccessType.hh * * Auto generated C++ code started by /home/hongyu/gem5-fy/src/mem/slicc/symbols/Type.py:555 */ #include <cassert> #include <iostream> #include <string> #include "base/misc.hh" #include "mem/protocol/AccessType.hh" using namespace std; // Code for output operator ostream& operator<<(ostream& out, const AccessType& obj) { out << AccessType_to_string(obj); out << flush; return out; } // Code to convert state to a string string AccessType_to_string(const AccessType& obj) { switch(obj) { case AccessType_Read: return "Read"; case AccessType_Write: return "Write"; default: panic("Invalid range for type AccessType"); } } // Code to convert from a string to the enumeration AccessType string_to_AccessType(const string& str) { if (str == "Read") { return AccessType_Read; } else if (str == "Write") { return AccessType_Write; } else { panic("Invalid string conversion for %s, type AccessType", str); } } // Code to increment an enumeration type AccessType& operator++(AccessType& e) { assert(e < AccessType_NUM); return e = AccessType(e+1); }
class Solution { public: int XXX(vector<int>& prices) { int n = prices.size(); vector<int> dp(n+1); dp[0] = 0; int max_num = 0; for(int i=1; i<n; ++i){ if(prices[i] - prices[i-1] <= 0) dp[i] = dp[i-1]; else{ int temp = max(prices[i] - prices[i-1], prices[i] - prices[dp[i-1]]); dp[i] = (prices[i] - prices[dp[i-1]]) == temp ? dp[i-1] : i-1; max_num = max(max_num, temp); } } return max_num; } };
/* 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/core/profiler/utils/op_utils.h" #include <algorithm> #include <string> #include "absl/strings/string_view.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/profiler/convert/op_metrics_db_combiner.h" #include "tensorflow/core/profiler/protobuf/op_metrics.pb.h" #include "tensorflow/core/profiler/utils/tf_op_utils.h" namespace tensorflow { namespace profiler { namespace { // Return capped performance. If time == 0, returns the original perf. // Otherwise, returns the minimum of perf and the product of rate_limit // and time. double GetCappedPerf(double perf, uint64 time, double rate_limit) { if (perf <= 0) return 0; if (time == 0) return perf; return std::min(perf, time * rate_limit); } } // namespace void HostOpMetricsDbBuilder::EnterOp(absl::string_view name, absl::string_view category, bool is_eager, uint64 time_ps, uint64 children_time_ps) { uint64 self_time_ps = time_ps - children_time_ps; DCHECK_GE(time_ps, self_time_ps); OpMetrics* op_metrics = LookupOrInsertNewOpMetrics(/*hlo_module_id=*/0, name); if (op_metrics->category().empty()) op_metrics->set_category(category.data(), category.size()); op_metrics->set_is_eager(op_metrics->is_eager() || is_eager); op_metrics->set_occurrences(op_metrics->occurrences() + 1); op_metrics->set_time_ps(op_metrics->time_ps() + time_ps); op_metrics->set_self_time_ps(op_metrics->self_time_ps() + self_time_ps); db()->set_total_op_time_ps(db()->total_op_time_ps() + self_time_ps); } void HostOpMetricsDbBuilder::UpdateHostInfeedEnqInfo( uint64 duration_ps, uint64 start_timestamp_ps_diff) { db()->set_total_host_infeed_enq_duration_ps( db()->total_host_infeed_enq_duration_ps() + duration_ps); db()->set_total_host_infeed_enq_start_timestamp_ps_diff( db()->total_host_infeed_enq_start_timestamp_ps_diff() + start_timestamp_ps_diff); } void DeviceOpMetricsDbBuilder::EnterOp( uint64 program_id, absl::string_view name, absl::string_view category, absl::string_view provenance, bool is_eager, uint64 occurrences, uint64 time_ps, uint64 children_time_ps, int64 flops, int64 bytes_accessed, const protobuf::RepeatedPtrField<OpMetrics::MemoryAccessed>& memory_accessed_breakdown) { uint64 self_time_ps = time_ps - children_time_ps; DCHECK_GE(time_ps, self_time_ps); OpMetrics* op_metrics = LookupOrInsertNewOpMetrics(program_id, name); if (op_metrics->category().empty()) op_metrics->set_category(category == kUnknownOp ? "unknown" : std::string(category)); if (op_metrics->provenance().empty()) op_metrics->set_provenance(std::string(provenance)); op_metrics->set_is_eager(op_metrics->is_eager() || is_eager); op_metrics->set_occurrences(op_metrics->occurrences() + occurrences); op_metrics->set_time_ps(op_metrics->time_ps() + time_ps); op_metrics->set_self_time_ps(op_metrics->self_time_ps() + self_time_ps); op_metrics->set_flops(op_metrics->flops() + flops * occurrences); op_metrics->set_bytes_accessed(op_metrics->bytes_accessed() + bytes_accessed * occurrences); CombineMemoryAccessedBreakdown( memory_accessed_breakdown, op_metrics->mutable_memory_accessed_breakdown()); db()->set_total_op_time_ps(db()->total_op_time_ps() + self_time_ps); } } // namespace profiler } // namespace tensorflow
#include <gcdpp/source.h> GCDPP_NS_BEGIN struct DispatchSourceContext { DispatchWork registrationHandler; DispatchWork eventHandler; DispatchWork cancelHandler; static void destroy(void *ctx) { DispatchSourceContext *self = reinterpret_cast<DispatchSourceContext *>(ctx); delete self; } static void invokeRegistrationHandler(void *ctx) { DispatchSourceContext *self = reinterpret_cast<DispatchSourceContext *>(ctx); if (self->registrationHandler) { self->registrationHandler(); } } static void invokeEventHandler(void *ctx) { DispatchSourceContext *self = reinterpret_cast<DispatchSourceContext *>(ctx); if (self->eventHandler) { self->eventHandler(); } } static void invokeCancelHandler(void *ctx) { DispatchSourceContext *self = reinterpret_cast<DispatchSourceContext *>(ctx); if (self->cancelHandler) { self->cancelHandler(); } } }; DispatchSource::DispatchSource(dispatch_source_type_t type, uintptr_t handle, uintptr_t mask, DispatchQueue const &dq) : Base(dispatch_source_create(type, handle, mask, dq.nativeHandle())) { DispatchSourceContext *ctx = new DispatchSourceContext; dispatch_set_context(_dobject, ctx); dispatch_set_finalizer_f(_dobject, &DispatchSourceContext::destroy); } void DispatchSource::setRegistrationHandler(DispatchWork handler) { DispatchSourceContext *ctx = reinterpret_cast<DispatchSourceContext *>(dispatch_get_context(_dobject)); ctx->registrationHandler = handler; dispatch_source_set_registration_handler_f(_dobject, &DispatchSourceContext::invokeRegistrationHandler); } void DispatchSource::setEventHandler(DispatchWork handler) { DispatchSourceContext *ctx = reinterpret_cast<DispatchSourceContext *>(dispatch_get_context(_dobject)); ctx->eventHandler = handler; dispatch_source_set_event_handler_f(_dobject, &DispatchSourceContext::invokeEventHandler); } void DispatchSource::setCancelHandler(DispatchWork handler) { DispatchSourceContext *ctx = reinterpret_cast<DispatchSourceContext *>(dispatch_get_context(_dobject)); ctx->cancelHandler = handler; dispatch_source_set_cancel_handler_f(_dobject, &DispatchSourceContext::invokeCancelHandler); } void DispatchSource::activate() const { dispatch_activate(_dobject); } void DispatchSource::cancel() const { dispatch_source_cancel(_dobject); } bool DispatchSource::isCancelled() const { return dispatch_source_testcancel(_dobject) != 0; } uintptr_t DispatchSource::data() const { return dispatch_source_get_data(_dobject); } uintptr_t DispatchSource::handle() const { return dispatch_source_get_handle(_dobject); } DispatchSourceTimer::DispatchSourceTimer(DispatchQueue const &targetQueue) : DispatchSource(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, targetQueue) {} void DispatchSourceTimer::setTimer(DispatchTime start, uint64_t interval, uint64_t leeway) { dispatch_source_set_timer(_dobject, start._dt, interval, leeway); } GCDPP_NS_END
#include <absl/strings/str_split.h> #include <arpa/inet.h> #include <fmt/format.h> #include <netinet/in.h> #include <sys/socket.h> #include <chrono> #include <iostream> #include <string> #include <vector> #include "common/cmd_channel_impl.hpp" #include "common/cmd_channel_socket_utilities.hpp" #include "common/cmd_handler.hpp" #include "common/logging.h" #include "common/support/io.h" #include "common/support/socket.h" #include "guest_config.h" #include "guestlib.h" #include "manager_service.proto.h" namespace { extern struct command_channel_vtable command_channel_socket_tcp_vtable; } extern int nw_global_vm_id; /** * TCP channel guestlib endpoint. * * The `manager_tcp` is required to use the TCP channel. */ std::vector<struct command_channel *> command_channel_socket_tcp_guest_new() { //addresses of workers we will connect to (usually one) std::vector<std::string> worker_address; std::vector<std::string> manager_addr; //env variable takes priority if(const char* env_mngr_addr = std::getenv("AVA_MANAGER_ADDR")) { std::string addr(std::getenv("AVA_MANAGER_ADDR")); manager_addr = absl::StrSplit(addr, absl::ByAnyChar(":-/ ")); } else { manager_addr = absl::StrSplit(guestconfig::config->manager_address_, absl::ByAnyChar(":-/ ")); } std::cerr << "Connecting to manager at " << manager_addr[0] << " : " << manager_addr[1] << std::endl; // Connect API server manager DCHECK(manager_addr.size() == 2) << "Invalid API server manager address"; struct sockaddr_in addr; if (!ava::support::ResolveTcpAddr(&addr, manager_addr[0], manager_addr[1])) { AVA_LOG(FATAL) << fmt::format("Cannot resolve manager address {}:{}", manager_addr[0], manager_addr[1]); abort(); } int manager_sock = ava::support::TcpSocketConnect(&addr); if (manager_sock == -1) { AVA_LOG(FATAL) << "Cannot connect to manager"; abort(); } // Serialize configurations ava_proto::WorkerAssignRequest request; // always request just one, and use our memory request stuff //request.gpu_count() = guestconfig::config->gpu_memory_.size(); //for (auto m : guestconfig::config->gpu_memory_) { // request.gpu_mem().push_back(m << 20); //} request.gpu_count() = 1; uint32_t gpu_mem = 0; printf("!!! requesting memory %s\n", std::getenv("AVA_REQUESTED_GPU_MEMORY")); if (std::getenv("AVA_REQUESTED_GPU_MEMORY")) gpu_mem = std::stoul(std::getenv("AVA_REQUESTED_GPU_MEMORY")); request.gpu_mem().push_back(gpu_mem); auto cstart = std::chrono::steady_clock::now(); std::vector<unsigned char> request_buf; zpp::serializer::memory_output_archive out(request_buf); out(request); uint32_t request_length = static_cast<uint32_t>(request_buf.size()); if (!ava::support::SendData(manager_sock, reinterpret_cast<const char *>(&request_length), sizeof(uint32_t))) { AVA_LOG(FATAL) << "Fail to send request len to manager"; abort(); } if (!ava::support::SendData(manager_sock, reinterpret_cast<const char *>(request_buf.data()), request_length)) { AVA_LOG(FATAL) << "Fail to send request body to manager"; abort(); } auto queue_start = std::chrono::steady_clock::now(); // De-serialize API server addresses uint32_t reply_length = 0; if (!ava::support::RecvData(manager_sock, reinterpret_cast<char *>(&reply_length), sizeof(uint32_t), /* eof= */ nullptr)) { AVA_LOG(FATAL) << "Fail to receive reply len"; abort(); } std::vector<unsigned char> reply_buf(reply_length); zpp::serializer::memory_input_archive in(reply_buf); if (!ava::support::RecvData(manager_sock, reinterpret_cast<char *>(reply_buf.data()), reply_length, /* eof= */ nullptr)) { AVA_LOG(FATAL) << "Fail to receive reply from manager"; abort(); } //auto cend = std::chrono::steady_clock::now(); //std::cout << "ava-queue-time, " << std::chrono::duration_cast<std::chrono::milliseconds>(cend - cstart).count() << std::endl; ava_proto::WorkerAssignReply reply; in(reply); for (auto &wa : reply.worker_address()) { worker_address.push_back(wa); } if (worker_address.empty()) { AVA_ERROR << "No API server is assigned"; } /* Connect API servers. */ std::vector<struct command_channel *> channels; for (const auto &wa : worker_address) { /* Create a channel for every API server. */ struct chansocketutil::command_channel_socket *chan = (struct chansocketutil::command_channel_socket *)malloc(sizeof(struct chansocketutil::command_channel_socket)); command_channel_preinitialize((struct command_channel *)chan, &command_channel_socket_tcp_vtable); pthread_mutex_init(&chan->send_mutex, NULL); pthread_mutex_init(&chan->recv_mutex, NULL); channels.push_back((struct command_channel *)chan); char worker_name[128]; int worker_port; struct hostent *worker_server_info; parseServerAddress(wa.c_str(), &worker_server_info, worker_name, &worker_port); assert(worker_server_info != NULL && "Unknown API server address"); assert(worker_port > 0 && "Invalid API server port"); AVA_INFO << "Assigned worker at " << worker_name << ":" << worker_port; chan->vm_id = nw_global_vm_id = 1; chan->listen_port = nw_worker_id = worker_port; /* Start a TCP client to connect API server at `worker_name:worker_port`. */ struct sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_addr = *(struct in_addr *)worker_server_info->h_addr; address.sin_port = htons(worker_port); std::cerr << "Connect target API server (" << wa << ") at " << inet_ntoa(address.sin_addr) << ":" << worker_port << std::endl; int connect_ret = -1; auto connect_start = std::chrono::steady_clock::now(); while (connect_ret) { chan->sock_fd = socket(AF_INET, SOCK_STREAM, 0); setsockopt_lowlatency(chan->sock_fd); connect_ret = connect(chan->sock_fd, (struct sockaddr *)&address, sizeof(address)); if (!connect_ret) break; close(chan->sock_fd); auto connect_checkpoint = std::chrono::steady_clock::now(); if ((uint64_t)std::chrono::duration_cast<std::chrono::milliseconds>(connect_checkpoint - connect_start).count() > guestconfig::config->connect_timeout_) { std::cerr << "Connection to " << worker_address[0] << " timeout" << std::endl; goto error; } } auto queue_end = std::chrono::steady_clock::now(); std::cout << ">!>queue_time," << std::chrono::duration_cast<std::chrono::milliseconds>(queue_end - queue_start).count() << std::endl; chan->pfd.fd = chan->sock_fd; chan->pfd.events = POLLIN | POLLRDHUP; } return channels; error: for (auto &chan : channels) free(chan); channels.clear(); return channels; } namespace { struct command_channel_vtable command_channel_socket_tcp_vtable = { chansocketutil::command_channel_socket_buffer_size, chansocketutil::command_channel_socket_new_command, chansocketutil::command_channel_socket_attach_buffer, chansocketutil::command_channel_socket_send_command, chansocketutil::command_channel_socket_transfer_command, chansocketutil::command_channel_socket_receive_command, chansocketutil::command_channel_socket_get_buffer, chansocketutil::command_channel_socket_get_data_region, chansocketutil::command_channel_socket_free_command, chansocketutil::command_channel_socket_free, chansocketutil::command_channel_socket_print_command}; }
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Type namespace: System.Xml namespace System::Xml { // Forward declaring type: BitStack class BitStack; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Xml::BitStack); DEFINE_IL2CPP_ARG_TYPE(::System::Xml::BitStack*, "System.Xml", "BitStack"); // Type namespace: System.Xml namespace System::Xml { // Size: 0x20 #pragma pack(push, 1) // Autogenerated type: System.Xml.BitStack // [TokenAttribute] Offset: FFFFFFFF class BitStack : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private System.UInt32[] bitStack // Size: 0x8 // Offset: 0x10 ::ArrayW<uint> bitStack; // Field size check static_assert(sizeof(::ArrayW<uint>) == 0x8); // private System.Int32 stackPos // Size: 0x4 // Offset: 0x18 int stackPos; // Field size check static_assert(sizeof(int) == 0x4); // private System.UInt32 curr // Size: 0x4 // Offset: 0x1C uint curr; // Field size check static_assert(sizeof(uint) == 0x4); public: // Get instance field reference: private System.UInt32[] bitStack ::ArrayW<uint>& dyn_bitStack(); // Get instance field reference: private System.Int32 stackPos int& dyn_stackPos(); // Get instance field reference: private System.UInt32 curr uint& dyn_curr(); // public System.Void PushBit(System.Boolean bit) // Offset: 0x1A806AC void PushBit(bool bit); // public System.Boolean PopBit() // Offset: 0x1A807DC bool PopBit(); // public System.Boolean PeekBit() // Offset: 0x1A80860 bool PeekBit(); // private System.Void PushCurr() // Offset: 0x1A806E8 void PushCurr(); // private System.Void PopCurr() // Offset: 0x1A80810 void PopCurr(); // public System.Void .ctor() // Offset: 0x1A80680 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static BitStack* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::BitStack::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<BitStack*, creationType>())); } }; // System.Xml.BitStack #pragma pack(pop) static check_size<sizeof(BitStack), 28 + sizeof(uint)> __System_Xml_BitStackSizeCheck; static_assert(sizeof(BitStack) == 0x20); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Xml::BitStack::PushBit // Il2CppName: PushBit template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::BitStack::*)(bool)>(&System::Xml::BitStack::PushBit)> { static const MethodInfo* get() { static auto* bit = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Xml::BitStack*), "PushBit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{bit}); } }; // Writing MetadataGetter for method: System::Xml::BitStack::PopBit // Il2CppName: PopBit template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Xml::BitStack::*)()>(&System::Xml::BitStack::PopBit)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Xml::BitStack*), "PopBit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Xml::BitStack::PeekBit // Il2CppName: PeekBit template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Xml::BitStack::*)()>(&System::Xml::BitStack::PeekBit)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Xml::BitStack*), "PeekBit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Xml::BitStack::PushCurr // Il2CppName: PushCurr template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::BitStack::*)()>(&System::Xml::BitStack::PushCurr)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Xml::BitStack*), "PushCurr", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Xml::BitStack::PopCurr // Il2CppName: PopCurr template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::BitStack::*)()>(&System::Xml::BitStack::PopCurr)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Xml::BitStack*), "PopCurr", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Xml::BitStack::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
/* Copyright 2017-2018 ccls Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #pragma once #include "lsp.hh" #include "utils.hh" #include <mutex> #include <optional> #include <string> namespace ccls { struct WorkingFile { int64_t timestamp = 0; int version = 0; std::string filename; std::string buffer_content; // Note: This assumes 0-based lines (1-based lines are normally assumed). std::vector<std::string> index_lines; // Note: This assumes 0-based lines (1-based lines are normally assumed). std::vector<std::string> buffer_lines; // Mappings between index line number and buffer line number. // Empty indicates either buffer or index has been changed and re-computation // is required. // For index_to_buffer[i] == j, if j >= 0, we are confident that index line // i maps to buffer line j; if j == -1, FindMatchingLine will use the nearest // confident lines to resolve its line number. std::vector<int> index_to_buffer; std::vector<int> buffer_to_index; // A set of diagnostics that have been reported for this file. std::vector<Diagnostic> diagnostics; WorkingFile(const std::string &filename, const std::string &buffer_content); // This should be called when the indexed content has changed. void SetIndexContent(const std::string &index_content); // This should be called whenever |buffer_content| has changed. void OnBufferContentUpdated(); // Finds the buffer line number which maps to index line number |line|. // Also resolves |column| if not NULL. // When resolving a range, use is_end = false for begin() and is_end = // true for end() to get a better alignment of |column|. std::optional<int> GetBufferPosFromIndexPos(int line, int *column, bool is_end); // Finds the index line number which maps to buffer line number |line|. // Also resolves |column| if not NULL. std::optional<int> GetIndexPosFromBufferPos(int line, int *column, bool is_end); // Returns a relatively stable completion position (it jumps back until there // is a non-alphanumeric character). // // The out param |is_global_completion| is set to true if this looks like a // global completion. // The out param |existing_completion| is set to any existing completion // content the user has entered. Position FindStableCompletionSource(Position position, std::string *existing_completion, Position *replace_end_pos) const; private: // Compute index_to_buffer and buffer_to_index. void ComputeLineMapping(); }; struct WorkingFiles { WorkingFile *GetFile(const std::string &path); WorkingFile *GetFileUnlocked(const std::string &path); std::string GetContent(const std::string &path); template <typename Fn> void WithLock(Fn &&fn) { std::lock_guard lock(mutex); fn(); } WorkingFile *OnOpen(const TextDocumentItem &open); void OnChange(const TextDocumentDidChangeParam &change); void OnClose(const std::string &close); std::mutex mutex; std::unordered_map<std::string, std::unique_ptr<WorkingFile>> files; }; int GetOffsetForPosition(Position pos, std::string_view content); std::string_view LexIdentifierAroundPos(Position position, std::string_view content); } // namespace ccls
//////////////////////////////////////////////////////////////////////////////// // ExTextureList.cpp #include "ExExporter.h" #include "ExTextureList.h" #include "FsFile.h" #include "PaMemoryResource.h" #include "PaArchive.h" //////////////////////////////////////////////////////////////////////////////// // pFind ExTexture* ExTextureList::pFind( const BtChar* pFilename ) { BtU32 nTextureCount = (BtU32) m_pTextures.size(); for( BtU32 nTexture=0; nTexture<nTextureCount; nTexture++ ) { // Cache each Texture ExTexture* pTexture = m_pTextures[nTexture]; if( BtStrCompare( pTexture->GetFilename(), pFilename ) == BtTrue ) { return pTexture; } } return BtNull; } //////////////////////////////////////////////////////////////////////////////// // pTexture ExTexture* ExTextureList::pTexture( BtU32 nTexture ) { return m_pTextures[nTexture]; } //////////////////////////////////////////////////////////////////////////////// // Add ExTexture* ExTextureList::Add( ExTexture* pTexture ) { // Add the texture as a dependency ExExporter::Instance().pCurrentAsset()->AddDependency( pTexture->GetFilename() ); for( BtU32 i=0; i<m_pTextures.size(); i++ ) { ExTexture* pCurrentTexture = m_pTextures[i]; if( BtStrCompare( pCurrentTexture->GetFilename(), pTexture->GetFilename() ) == BtTrue ) { return pCurrentTexture; } } // Export this texture pTexture->Export(); // Add the texture to the list m_pTextures.push_back( pTexture ); return pTexture; }
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018 The Quantlab developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bip38.h" #include "init.h" #include "main.h" #include "rpcserver.h" #include "script/script.h" #include "script/standard.h" #include "sync.h" #include "util.h" #include "utilstrencodings.h" #include "utiltime.h" #include "wallet.h" #include <fstream> #include <secp256k1.h> #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <openssl/aes.h> #include <openssl/sha.h> #include <univalue.h> using namespace std; void EnsureWalletIsUnlocked(); std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } int64_t static DecodeDumpTime(const std::string& str) { static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0); static const std::locale loc(std::locale::classic(), new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ")); std::istringstream iss(str); iss.imbue(loc); boost::posix_time::ptime ptime(boost::date_time::not_a_date_time); iss >> ptime; if (ptime.is_not_a_date_time()) return 0; return (ptime - epoch).total_seconds(); } std::string static EncodeDumpString(const std::string& str) { std::stringstream ret; BOOST_FOREACH (unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string& str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos + 2 < str.length()) { c = (((str[pos + 1] >> 6) * 9 + ((str[pos + 1] - '0') & 15)) << 4) | ((str[pos + 2] >> 6) * 9 + ((str[pos + 2] - '0') & 15)); pos += 2; } ret << c; } return ret.str(); } UniValue importprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey \"quantlabprivkey\" ( \"label\" rescan )\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n" "\nArguments:\n" "1. \"quantlabprivkey\" (string, required) The private key (see dumpprivkey)\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key with rescan\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID vchAddress = pubkey.GetID(); { pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, strLabel, "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return NullUniValue; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } } return NullUniValue; } UniValue importaddress(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importaddress \"address\" ( \"label\" rescan )\n" "\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n" "\nArguments:\n" "1. \"address\" (string, required) The address\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nImport an address with rescan\n" + HelpExampleCli("importaddress", "\"myaddress\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importaddress", "\"myaddress\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importaddress", "\"myaddress\", \"testing\", false")); LOCK2(cs_main, pwalletMain->cs_wallet); CScript script; CBitcoinAddress address(params[0].get_str()); if (address.IsValid()) { script = GetScriptForDestination(address.Get()); } else if (IsHex(params[0].get_str())) { std::vector<unsigned char> data(ParseHex(params[0].get_str())); script = CScript(data.begin(), data.end()); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Quantlab address or script"); } string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); { if (::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE) throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); // add to address book or update label if (address.IsValid()) pwalletMain->SetAddressBook(address.Get(), strLabel, "receive"); // Don't throw error in case an address is already there if (pwalletMain->HaveWatchOnly(script)) return NullUniValue; pwalletMain->MarkDirty(); if (!pwalletMain->AddWatchOnly(script)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); pwalletMain->ReacceptWalletTransactions(); } } return NullUniValue; } UniValue importwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet \"filename\"\n" "\nImports keys from a wallet dump file (see dumpwallet).\n" "\nArguments:\n" "1. \"filename\" (string, required) The wallet file\n" "\nExamples:\n" "\nDump the wallet\n" + HelpExampleCli("dumpwallet", "\"test\"") + "\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\"")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str(), std::ios::in | std::ios::ate); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = chainActive.Tip()->GetBlockTime(); bool fGood = true; int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg()); file.seekg(0, file.beg); pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI while (file.good()) { pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100)))); std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKeyPubKey(key, pubkey)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBook(keyid, strLabel, "receive"); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI CBlockIndex* pindex = chainActive.Tip(); while (pindex && pindex->pprev && pindex->GetBlockTime() > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return NullUniValue; } UniValue dumpprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey \"quantlabaddress\"\n" "\nReveals the private key corresponding to 'quantlabaddress'.\n" "Then the importprivkey can be used with this output\n" "\nArguments:\n" "1. \"quantlabaddress\" (string, required) The quantlab address for the private key\n" "\nResult:\n" "\"key\" (string) The private key\n" "\nExamples:\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\"")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Quantlab address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } UniValue dumpwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet \"filename\"\n" "\nDumps all wallet keys in a human-readable format.\n" "\nArguments:\n" "1. \"filename\" (string, required) The filename\n" "\nExamples:\n" + HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\"")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by Quantlab %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime())); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID& keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr); } else if (setKeyPool.count(keyid)) { file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } else { file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return NullUniValue; } UniValue bip38encrypt(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "bip38encrypt \"quantlabaddress\"\n" "\nEncrypts a private key corresponding to 'quantlabaddress'.\n" "\nArguments:\n" "1. \"quantlabaddress\" (string, required) The quantlab address for the private key (you must hold the key already)\n" "2. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with - Valid special chars: !#$%&'()*+,-./:;<=>?`{|}~ \n" "\nResult:\n" "\"key\" (string) The encrypted private key\n" "\nExamples:\n"); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strPassphrase = params[1].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Quantlab address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); uint256 privKey = vchSecret.GetPrivKey_256(); string encryptedOut = BIP38_Encrypt(strAddress, strPassphrase, privKey, vchSecret.IsCompressed()); UniValue result(UniValue::VOBJ); result.push_back(Pair("Addess", strAddress)); result.push_back(Pair("Encrypted Key", encryptedOut)); return result; } UniValue bip38decrypt(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "bip38decrypt \"quantlabaddress\"\n" "\nDecrypts and then imports password protected private key.\n" "\nArguments:\n" "1. \"encryptedkey\" (string, required) The encrypted private key\n" "2. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with\n" "\nResult:\n" "\"key\" (string) The decrypted private key\n" "\nExamples:\n"); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); /** Collect private key and passphrase **/ string strKey = params[0].get_str(); string strPassphrase = params[1].get_str(); uint256 privKey; bool fCompressed; if (!BIP38_Decrypt(strPassphrase, strKey, privKey, fCompressed)) throw JSONRPCError(RPC_WALLET_ERROR, "Failed To Decrypt"); UniValue result(UniValue::VOBJ); result.push_back(Pair("privatekey", HexStr(privKey))); CKey key; key.Set(privKey.begin(), privKey.end(), fCompressed); if (!key.IsValid()) throw JSONRPCError(RPC_WALLET_ERROR, "Private Key Not Valid"); CPubKey pubkey = key.GetPubKey(); pubkey.IsCompressed(); assert(key.VerifyPubKey(pubkey)); result.push_back(Pair("Address", CBitcoinAddress(pubkey.GetID()).ToString())); CKeyID vchAddress = pubkey.GetID(); { pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, "", "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) throw JSONRPCError(RPC_WALLET_ERROR, "Key already held by wallet"); pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } return result; }
// Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "db.h" #include "init.h" #include "main.h" #include "masternode-budget.h" #include "masternode-payments.h" #include "masternodeconfig.h" #include "masternodeman.h" #include "rpcserver.h" #include "utilmoneystr.h" #include <univalue.h> #include <boost/tokenizer.hpp> #include <fstream> void SendMoney(const CTxDestination& address, CAmount nValue, CWalletTx& wtxNew, AvailableCoinsType coin_type = ALL_COINS) { // Check amount if (nValue <= 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount"); if (nValue > pwalletMain->GetBalance()) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); string strError; if (pwalletMain->IsLocked()) { strError = "Error: Wallet locked, unable to create transaction!"; LogPrintf("SendMoney() : %s", strError); throw JSONRPCError(RPC_WALLET_ERROR, strError); } // Parse DEO address CScript scriptPubKey = GetScriptForDestination(address); // Create and send the transaction CReserveKey reservekey(pwalletMain); CAmount nFeeRequired; if (!pwalletMain->CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strError, NULL, coin_type)) { if (nValue + nFeeRequired > pwalletMain->GetBalance()) strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired)); LogPrintf("SendMoney() : %s\n", strError); throw JSONRPCError(RPC_WALLET_ERROR, strError); } if (!pwalletMain->CommitTransaction(wtxNew, reservekey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); } // This command is retained for backwards compatibility, but is deprecated. // Future removal of this command is planned to keep things clean. UniValue masternode(const UniValue& params, bool fHelp) { string strCommand; if (params.size() >= 1) strCommand = params[0].get_str(); if (fHelp || (strCommand != "start" && strCommand != "start-alias" && strCommand != "start-many" && strCommand != "start-all" && strCommand != "start-missing" && strCommand != "start-disabled" && strCommand != "list" && strCommand != "list-conf" && strCommand != "count" && strCommand != "enforce" && strCommand != "debug" && strCommand != "current" && strCommand != "winners" && strCommand != "genkey" && strCommand != "connect" && strCommand != "outputs" && strCommand != "status" && strCommand != "calcscore")) throw runtime_error( "masternode \"command\"...\n" "\nSet of commands to execute masternode related actions\n" "This command is deprecated, please see individual command documentation for future reference\n\n" "\nArguments:\n" "1. \"command\" (string or set of strings, required) The command to execute\n" "\nAvailable commands:\n" " count - Print count information of all known masternodes\n" " current - Print info on current masternode winner\n" " debug - Print masternode status\n" " genkey - Generate new masternodeprivkey\n" " outputs - Print masternode compatible outputs\n" " start - Start masternode configured in destocoin.conf\n" " start-alias - Start single masternode by assigned alias configured in masternode.conf\n" " start-<mode> - Start masternodes configured in masternode.conf (<mode>: 'all', 'missing', 'disabled')\n" " status - Print masternode status information\n" " list - Print list of all known masternodes (see masternodelist for more info)\n" " list-conf - Print masternode.conf in JSON format\n" " winners - Print list of masternode winners\n"); if (strCommand == "list") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return listmasternodes(newParams, fHelp); } if (strCommand == "connect") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return masternodeconnect(newParams, fHelp); } if (strCommand == "count") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return getmasternodecount(newParams, fHelp); } if (strCommand == "current") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return masternodecurrent(newParams, fHelp); } if (strCommand == "debug") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return masternodedebug(newParams, fHelp); } if (strCommand == "start" || strCommand == "start-alias" || strCommand == "start-many" || strCommand == "start-all" || strCommand == "start-missing" || strCommand == "start-disabled") { return startmasternode(params, fHelp); } if (strCommand == "genkey") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return createmasternodekey(newParams, fHelp); } if (strCommand == "list-conf") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return listmasternodeconf(newParams, fHelp); } if (strCommand == "outputs") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return getmasternodeoutputs(newParams, fHelp); } if (strCommand == "status") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return getmasternodestatus(newParams, fHelp); } if (strCommand == "winners") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return getmasternodewinners(newParams, fHelp); } if (strCommand == "calcscore") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return getmasternodescores(newParams, fHelp); } return NullUniValue; } UniValue listmasternodes(const UniValue& params, bool fHelp) { std::string strFilter = ""; if (params.size() == 1) strFilter = params[0].get_str(); if (fHelp || (params.size() > 1)) throw runtime_error( "listmasternodes ( \"filter\" )\n" "\nGet a ranked list of masternodes\n" "\nArguments:\n" "1. \"filter\" (string, optional) Filter search text. Partial match by txhash, status, or addr.\n" "\nResult:\n" "[\n" " {\n" " \"rank\": n, (numeric) Masternode Rank (or 0 if not enabled)\n" " \"txhash\": \"hash\", (string) Collateral transaction hash\n" " \"outidx\": n, (numeric) Collateral transaction output index\n" " \"status\": s, (string) Status (ENABLED/EXPIRED/REMOVE/etc)\n" " \"addr\": \"addr\", (string) Masternode DEO address\n" " \"version\": v, (numeric) Masternode protocol version\n" " \"lastseen\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last seen\n" " \"activetime\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) masternode has been active\n" " \"lastpaid\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) masternode was last paid\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("masternodelist", "") + HelpExampleRpc("masternodelist", "")); UniValue ret(UniValue::VARR); int nHeight; { LOCK(cs_main); CBlockIndex* pindex = chainActive.Tip(); if(!pindex) return 0; nHeight = pindex->nHeight; } std::vector<pair<int, CMasternode> > vMasternodeRanks = mnodeman.GetMasternodeRanks(nHeight); BOOST_FOREACH (PAIRTYPE(int, CMasternode) & s, vMasternodeRanks) { UniValue obj(UniValue::VOBJ); std::string strVin = s.second.vin.prevout.ToStringShort(); std::string strTxHash = s.second.vin.prevout.hash.ToString(); uint32_t oIdx = s.second.vin.prevout.n; CMasternode* mn = mnodeman.Find(s.second.vin); if (mn != NULL) { if (strFilter != "" && strTxHash.find(strFilter) == string::npos && mn->Status().find(strFilter) == string::npos && CBitcoinAddress(mn->pubKeyCollateralAddress.GetID()).ToString().find(strFilter) == string::npos) continue; std::string strStatus = mn->Status(); std::string strHost; int port; SplitHostPort(mn->addr.ToString(), port, strHost); CNetAddr node = CNetAddr(strHost, false); std::string strNetwork = GetNetworkName(node.GetNetwork()); obj.push_back(Pair("rank", (strStatus == "ENABLED" ? s.first : 0))); obj.push_back(Pair("network", strNetwork)); obj.push_back(Pair("txhash", strTxHash)); obj.push_back(Pair("outidx", (uint64_t)oIdx)); obj.push_back(Pair("status", strStatus)); obj.push_back(Pair("addr", CBitcoinAddress(mn->pubKeyCollateralAddress.GetID()).ToString())); obj.push_back(Pair("version", mn->protocolVersion)); obj.push_back(Pair("lastseen", (int64_t)mn->lastPing.sigTime)); obj.push_back(Pair("activetime", (int64_t)(mn->lastPing.sigTime - mn->sigTime))); obj.push_back(Pair("lastpaid", (int64_t)mn->GetLastPaid())); ret.push_back(obj); } } return ret; } UniValue masternodeconnect(const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 1)) throw runtime_error( "masternodeconnect \"address\"\n" "\nAttempts to connect to specified masternode address\n" "\nArguments:\n" "1. \"address\" (string, required) IP or net address to connect to\n" "\nExamples:\n" + HelpExampleCli("masternodeconnect", "\"192.168.0.6:8833\"") + HelpExampleRpc("masternodeconnect", "\"192.168.0.6:8833\"")); std::string strAddress = params[0].get_str(); CService addr = CService(strAddress); CNode* pnode = ConnectNode((CAddress)addr, NULL); if (pnode) { pnode->Release(); return NullUniValue; } else { throw runtime_error("error connecting\n"); } } UniValue getmasternodecount (const UniValue& params, bool fHelp) { if (fHelp || (params.size() > 0)) throw runtime_error( "getmasternodecount\n" "\nGet masternode count values\n" "\nResult:\n" "{\n" " \"total\": n, (numeric) Total masternodes\n" " \"stable\": n, (numeric) Stable count\n" " \"enabled\": n, (numeric) Enabled masternodes\n" " \"inqueue\": n (numeric) Masternodes in queue\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmasternodecount", "") + HelpExampleRpc("getmasternodecount", "")); UniValue obj(UniValue::VOBJ); int nCount = 0; int ipv4 = 0, ipv6 = 0, onion = 0; if (chainActive.Tip()) mnodeman.GetNextMasternodeInQueueForPayment(chainActive.Tip()->nHeight, true, nCount); mnodeman.CountNetworks(ActiveProtocol(), ipv4, ipv6, onion); obj.push_back(Pair("total", mnodeman.size())); obj.push_back(Pair("stable", mnodeman.stable_size())); obj.push_back(Pair("enabled", mnodeman.CountEnabled())); obj.push_back(Pair("inqueue", nCount)); obj.push_back(Pair("ipv4", ipv4)); obj.push_back(Pair("ipv6", ipv6)); obj.push_back(Pair("onion", onion)); return obj; } UniValue masternodecurrent (const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 0)) throw runtime_error( "masternodecurrent\n" "\nGet current masternode winner\n" "\nResult:\n" "{\n" " \"protocol\": xxxx, (numeric) Protocol version\n" " \"txhash\": \"xxxx\", (string) Collateral transaction hash\n" " \"pubkey\": \"xxxx\", (string) MN Public key\n" " \"lastseen\": xxx, (numeric) Time since epoch of last seen\n" " \"activeseconds\": xxx, (numeric) Seconds MN has been active\n" "}\n" "\nExamples:\n" + HelpExampleCli("masternodecurrent", "") + HelpExampleRpc("masternodecurrent", "")); CMasternode* winner = mnodeman.GetCurrentMasterNode(1); if (winner) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("protocol", (int64_t)winner->protocolVersion)); obj.push_back(Pair("txhash", winner->vin.prevout.hash.ToString())); obj.push_back(Pair("pubkey", CBitcoinAddress(winner->pubKeyCollateralAddress.GetID()).ToString())); obj.push_back(Pair("lastseen", (winner->lastPing == CMasternodePing()) ? winner->sigTime : (int64_t)winner->lastPing.sigTime)); obj.push_back(Pair("activeseconds", (winner->lastPing == CMasternodePing()) ? 0 : (int64_t)(winner->lastPing.sigTime - winner->sigTime))); return obj; } throw runtime_error("unknown"); } UniValue masternodedebug (const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 0)) throw runtime_error( "masternodedebug\n" "\nPrint masternode status\n" "\nResult:\n" "\"status\" (string) Masternode status message\n" "\nExamples:\n" + HelpExampleCli("masternodedebug", "") + HelpExampleRpc("masternodedebug", "")); if (activeMasternode.status != ACTIVE_MASTERNODE_INITIAL || !masternodeSync.IsSynced()) return activeMasternode.GetStatus(); CTxIn vin = CTxIn(); CPubKey pubkey = CScript(); CKey key; if (!activeMasternode.GetMasterNodeVin(vin, pubkey, key)) throw runtime_error("Missing masternode input, please look at the documentation for instructions on masternode creation\n"); else return activeMasternode.GetStatus(); } UniValue startmasternode (const UniValue& params, bool fHelp) { std::string strCommand; if (params.size() >= 1) { strCommand = params[0].get_str(); // Backwards compatibility with legacy 'masternode' super-command forwarder if (strCommand == "start") strCommand = "local"; if (strCommand == "start-alias") strCommand = "alias"; if (strCommand == "start-all") strCommand = "all"; if (strCommand == "start-many") strCommand = "many"; if (strCommand == "start-missing") strCommand = "missing"; if (strCommand == "start-disabled") strCommand = "disabled"; } if (fHelp || params.size() < 2 || params.size() > 3 || (params.size() == 2 && (strCommand != "local" && strCommand != "all" && strCommand != "many" && strCommand != "missing" && strCommand != "disabled")) || (params.size() == 3 && strCommand != "alias")) throw runtime_error( "startmasternode \"local|all|many|missing|disabled|alias\" lockwallet ( \"alias\" )\n" "\nAttempts to start one or more masternode(s)\n" "\nArguments:\n" "1. set (string, required) Specify which set of masternode(s) to start.\n" "2. lockwallet (boolean, required) Lock wallet after completion.\n" "3. alias (string) Masternode alias. Required if using 'alias' as the set.\n" "\nResult: (for 'local' set):\n" "\"status\" (string) Masternode status message\n" "\nResult: (for other sets):\n" "{\n" " \"overall\": \"xxxx\", (string) Overall status message\n" " \"detail\": [\n" " {\n" " \"node\": \"xxxx\", (string) Node name or alias\n" " \"result\": \"xxxx\", (string) 'success' or 'failed'\n" " \"error\": \"xxxx\" (string) Error message, if failed\n" " }\n" " ,...\n" " ]\n" "}\n" "\nExamples:\n" + HelpExampleCli("startmasternode", "\"alias\" \"0\" \"my_mn\"") + HelpExampleRpc("startmasternode", "\"alias\" \"0\" \"my_mn\"")); bool fLock = (params[1].get_str() == "true" ? true : false); if (strCommand == "local") { if (!fMasterNode) throw runtime_error("you must set masternode=1 in the configuration\n"); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); if (activeMasternode.status != ACTIVE_MASTERNODE_STARTED) { activeMasternode.status = ACTIVE_MASTERNODE_INITIAL; // TODO: consider better way activeMasternode.ManageStatus(); if (fLock) pwalletMain->Lock(); } return activeMasternode.GetStatus(); } if (strCommand == "all" || strCommand == "many" || strCommand == "missing" || strCommand == "disabled") { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); if ((strCommand == "missing" || strCommand == "disabled") && (masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_LIST || masternodeSync.RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED)) { throw runtime_error("You can't use this command until masternode list is synced\n"); } std::vector<CMasternodeConfig::CMasternodeEntry> mnEntries; mnEntries = masternodeConfig.getEntries(); int successful = 0; int failed = 0; UniValue resultsObj(UniValue::VARR); BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { std::string errorMessage; int nIndex; if(!mne.castOutputIndex(nIndex)) continue; CTxIn vin = CTxIn(uint256(mne.getTxHash()), uint32_t(nIndex)); CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL) { if (strCommand == "missing") continue; if (strCommand == "disabled" && pmn->IsEnabled()) continue; } bool result = activeMasternode.Register(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), errorMessage); UniValue statusObj(UniValue::VOBJ); statusObj.push_back(Pair("alias", mne.getAlias())); statusObj.push_back(Pair("result", result ? "success" : "failed")); if (result) { successful++; statusObj.push_back(Pair("error", "")); } else { failed++; statusObj.push_back(Pair("error", errorMessage)); } resultsObj.push_back(statusObj); } if (fLock) pwalletMain->Lock(); UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Successfully started %d masternodes, failed to start %d, total %d", successful, failed, successful + failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } if (strCommand == "alias") { std::string alias = params[2].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); bool found = false; int successful = 0; int failed = 0; UniValue resultsObj(UniValue::VARR); UniValue statusObj(UniValue::VOBJ); statusObj.push_back(Pair("alias", alias)); BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { if (mne.getAlias() == alias) { found = true; std::string errorMessage; bool result = activeMasternode.Register(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), errorMessage); statusObj.push_back(Pair("result", result ? "successful" : "failed")); if (result) { successful++; statusObj.push_back(Pair("error", "")); } else { failed++; statusObj.push_back(Pair("error", errorMessage)); } break; } } if (!found) { failed++; statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "could not find alias in config. Verify with list-conf.")); } resultsObj.push_back(statusObj); if (fLock) pwalletMain->Lock(); UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Successfully started %d masternodes, failed to start %d, total %d", successful, failed, successful + failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } return NullUniValue; } UniValue createmasternodekey (const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 0)) throw runtime_error( "createmasternodekey\n" "\nCreate a new masternode private key\n" "\nResult:\n" "\"key\" (string) Masternode private key\n" "\nExamples:\n" + HelpExampleCli("createmasternodekey", "") + HelpExampleRpc("createmasternodekey", "")); CKey secret; secret.MakeNewKey(false); return CBitcoinSecret(secret).ToString(); } UniValue getmasternodeoutputs (const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 0)) throw runtime_error( "getmasternodeoutputs\n" "\nPrint all masternode transaction outputs\n" "\nResult:\n" "[\n" " {\n" " \"txhash\": \"xxxx\", (string) output transaction hash\n" " \"outputidx\": n (numeric) output index number\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getmasternodeoutputs", "") + HelpExampleRpc("getmasternodeoutputs", "")); // Find possible candidates vector<COutput> possibleCoins = activeMasternode.SelectCoinsMasternode(); UniValue ret(UniValue::VARR); BOOST_FOREACH (COutput& out, possibleCoins) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("txhash", out.tx->GetHash().ToString())); obj.push_back(Pair("outputidx", out.i)); ret.push_back(obj); } return ret; } UniValue listmasternodeconf (const UniValue& params, bool fHelp) { std::string strFilter = ""; if (params.size() == 1) strFilter = params[0].get_str(); if (fHelp || (params.size() > 1)) throw runtime_error( "listmasternodeconf ( \"filter\" )\n" "\nPrint masternode.conf in JSON format\n" "\nArguments:\n" "1. \"filter\" (string, optional) Filter search text. Partial match on alias, address, txHash, or status.\n" "\nResult:\n" "[\n" " {\n" " \"alias\": \"xxxx\", (string) masternode alias\n" " \"address\": \"xxxx\", (string) masternode IP address\n" " \"privateKey\": \"xxxx\", (string) masternode private key\n" " \"txHash\": \"xxxx\", (string) transaction hash\n" " \"outputIndex\": n, (numeric) transaction output index\n" " \"status\": \"xxxx\" (string) masternode status\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listmasternodeconf", "") + HelpExampleRpc("listmasternodeconf", "")); std::vector<CMasternodeConfig::CMasternodeEntry> mnEntries; mnEntries = masternodeConfig.getEntries(); UniValue ret(UniValue::VARR); BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { int nIndex; if(!mne.castOutputIndex(nIndex)) continue; CTxIn vin = CTxIn(uint256(mne.getTxHash()), uint32_t(nIndex)); CMasternode* pmn = mnodeman.Find(vin); std::string strStatus = pmn ? pmn->Status() : "MISSING"; if (strFilter != "" && mne.getAlias().find(strFilter) == string::npos && mne.getIp().find(strFilter) == string::npos && mne.getTxHash().find(strFilter) == string::npos && strStatus.find(strFilter) == string::npos) continue; UniValue mnObj(UniValue::VOBJ); mnObj.push_back(Pair("alias", mne.getAlias())); mnObj.push_back(Pair("address", mne.getIp())); mnObj.push_back(Pair("privateKey", mne.getPrivKey())); mnObj.push_back(Pair("txHash", mne.getTxHash())); mnObj.push_back(Pair("outputIndex", mne.getOutputIndex())); mnObj.push_back(Pair("status", strStatus)); ret.push_back(mnObj); } return ret; } UniValue getmasternodestatus (const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 0)) throw runtime_error( "getmasternodestatus\n" "\nPrint masternode status\n" "\nResult:\n" "{\n" " \"txhash\": \"xxxx\", (string) Collateral transaction hash\n" " \"outputidx\": n, (numeric) Collateral transaction output index number\n" " \"netaddr\": \"xxxx\", (string) Masternode network address\n" " \"addr\": \"xxxx\", (string) DEO address for masternode payments\n" " \"status\": \"xxxx\", (string) Masternode status\n" " \"message\": \"xxxx\" (string) Masternode status message\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmasternodestatus", "") + HelpExampleRpc("getmasternodestatus", "")); if (!fMasterNode) throw runtime_error("This is not a masternode"); CMasternode* pmn = mnodeman.Find(activeMasternode.vin); if (pmn) { UniValue mnObj(UniValue::VOBJ); mnObj.push_back(Pair("txhash", activeMasternode.vin.prevout.hash.ToString())); mnObj.push_back(Pair("outputidx", (uint64_t)activeMasternode.vin.prevout.n)); mnObj.push_back(Pair("netaddr", activeMasternode.service.ToString())); mnObj.push_back(Pair("addr", CBitcoinAddress(pmn->pubKeyCollateralAddress.GetID()).ToString())); mnObj.push_back(Pair("status", activeMasternode.status)); mnObj.push_back(Pair("message", activeMasternode.GetStatus())); return mnObj; } throw runtime_error("Masternode not found in the list of available masternodes. Current status: " + activeMasternode.GetStatus()); } UniValue getmasternodewinners (const UniValue& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "getmasternodewinners ( blocks \"filter\" )\n" "\nPrint the masternode winners for the last n blocks\n" "\nArguments:\n" "1. blocks (numeric, optional) Number of previous blocks to show (default: 10)\n" "2. filter (string, optional) Search filter matching MN address\n" "\nResult (single winner):\n" "[\n" " {\n" " \"nHeight\": n, (numeric) block height\n" " \"winner\": {\n" " \"address\": \"xxxx\", (string) DEO MN Address\n" " \"nVotes\": n, (numeric) Number of votes for winner\n" " }\n" " }\n" " ,...\n" "]\n" "\nResult (multiple winners):\n" "[\n" " {\n" " \"nHeight\": n, (numeric) block height\n" " \"winner\": [\n" " {\n" " \"address\": \"xxxx\", (string) DEO MN Address\n" " \"nVotes\": n, (numeric) Number of votes for winner\n" " }\n" " ,...\n" " ]\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getmasternodewinners", "") + HelpExampleRpc("getmasternodewinners", "")); int nHeight; { LOCK(cs_main); CBlockIndex* pindex = chainActive.Tip(); if(!pindex) return 0; nHeight = pindex->nHeight; } int nLast = 10; std::string strFilter = ""; if (params.size() >= 1) nLast = atoi(params[0].get_str()); if (params.size() == 2) strFilter = params[1].get_str(); UniValue ret(UniValue::VARR); for (int i = nHeight - nLast; i < nHeight + 20; i++) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("nHeight", i)); std::string strPayment = GetRequiredPaymentsString(i); if (strFilter != "" && strPayment.find(strFilter) == std::string::npos) continue; if (strPayment.find(',') != std::string::npos) { UniValue winner(UniValue::VARR); boost::char_separator<char> sep(","); boost::tokenizer< boost::char_separator<char> > tokens(strPayment, sep); BOOST_FOREACH (const string& t, tokens) { UniValue addr(UniValue::VOBJ); std::size_t pos = t.find(":"); std::string strAddress = t.substr(0,pos); uint64_t nVotes = atoi(t.substr(pos+1)); addr.push_back(Pair("address", strAddress)); addr.push_back(Pair("nVotes", nVotes)); winner.push_back(addr); } obj.push_back(Pair("winner", winner)); } else if (strPayment.find("Unknown") == std::string::npos) { UniValue winner(UniValue::VOBJ); std::size_t pos = strPayment.find(":"); std::string strAddress = strPayment.substr(0,pos); uint64_t nVotes = atoi(strPayment.substr(pos+1)); winner.push_back(Pair("address", strAddress)); winner.push_back(Pair("nVotes", nVotes)); obj.push_back(Pair("winner", winner)); } else { UniValue winner(UniValue::VOBJ); winner.push_back(Pair("address", strPayment)); winner.push_back(Pair("nVotes", 0)); obj.push_back(Pair("winner", winner)); } ret.push_back(obj); } return ret; } UniValue getmasternodescores (const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getmasternodescores ( blocks )\n" "\nPrint list of winning masternode by score\n" "\nArguments:\n" "1. blocks (numeric, optional) Show the last n blocks (default 10)\n" "\nResult:\n" "{\n" " xxxx: \"xxxx\" (numeric : string) Block height : Masternode hash\n" " ,...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmasternodescores", "") + HelpExampleRpc("getmasternodescores", "")); int nLast = 10; if (params.size() == 1) { try { nLast = std::stoi(params[0].get_str()); } catch (const boost::bad_lexical_cast &) { throw runtime_error("Exception on param 2"); } } UniValue obj(UniValue::VOBJ); std::vector<CMasternode> vMasternodes = mnodeman.GetFullMasternodeVector(); for (int nHeight = chainActive.Tip()->nHeight - nLast; nHeight < chainActive.Tip()->nHeight + 20; nHeight++) { uint256 nHigh = 0; CMasternode* pBestMasternode = NULL; BOOST_FOREACH (CMasternode& mn, vMasternodes) { uint256 n = mn.CalculateScore(1, nHeight - 100); if (n > nHigh) { nHigh = n; pBestMasternode = &mn; } } if (pBestMasternode) obj.push_back(Pair(strprintf("%d", nHeight), pBestMasternode->vin.prevout.hash.ToString().c_str())); } return obj; }
#include "PolygonTopology.h" #include "TopologyEdge.h" #include <map> #include <set> #include <data_structures/VectorOperations.h> PolygonTopology::PolygonTopology() { } PolygonTopology::PolygonTopology(const Faces& faces, ID nVertices) { init(faces, nVertices); } PolygonTopology::~PolygonTopology() { } void PolygonTopology::removeVertices(std::vector<ID>& vertexIds) { if (vertexIds.empty()) return; size_t nVerticesAfter = mVertices.size() - vertexIds.size(); std::vector<ID> oldToNew = createOldToNewMapping(vertexIds, mVertices.size()); // 1.) remove all faces / cells that reference the to be removed vertices // from: // mFacesIndices // 2.) adapt the indices in the remaining faces / cells (w.r.t. the removed vertices) // change indices in: // mFacesIndices // 3.) reinit everything with the adapted data // 1.) VectorOperations::removeArrayIfContains<unsigned int, 3>( vertexIds.begin(), vertexIds.end(), mFacesIndices); // 2.) // mFacesIndices for (size_t fId = 0; fId < mFacesIndices.size(); ++fId) { for (size_t i = 0; i < 3; ++i) { mFacesIndices[fId][i] = static_cast<unsigned int>( oldToNew[mFacesIndices[fId][i]]); } } // 3.) init(mFacesIndices, nVerticesAfter); } std::vector<ID> PolygonTopology::retrieveNotReferencedByEdges() const { std::set<ID> referenced; for (const TopologyEdge& e : mEdges) { for (size_t i = 0; i < 2; ++i) { referenced.insert(e.getVertexIds()[i]); } } std::vector<ID> allVertices; allVertices.reserve(mVertices.size()); for (size_t i = 0; i < mVertices.size(); ++i) { allVertices.push_back(i); } return VectorOperations::sub(allVertices, referenced); } std::vector<ID> PolygonTopology::retrieveNotReferencedByFaces() const { std::set<ID> referenced; for (const TopologyFace& f : mFaces) { for (size_t i = 0; i < 3; ++i) { referenced.insert(f.getVertexIds()[i]); } } std::vector<ID> allVertices; allVertices.reserve(mVertices.size()); for (size_t i = 0; i < mVertices.size(); ++i) { allVertices.push_back(i); } return VectorOperations::sub(allVertices, referenced); } Edges PolygonTopology::retrieveEdges() const { Edges edges; edges.reserve(mEdges.size()); for (const TopologyEdge& e : mEdges) { edges.push_back(e.getVertexIds()); } return edges; } Faces PolygonTopology::retrieveFaces() const { Faces faces; faces.reserve(mFaces.size()); for (const TopologyFace& f : mFaces) { const Face& vIds = f.getVertexIds(); faces.push_back({static_cast<unsigned int>(vIds[0]), static_cast<unsigned int>(vIds[1]), static_cast<unsigned int>(vIds[2])}); } return faces; } std::string PolygonTopology::toString() const { std::stringstream ss; ss << "Number of vertices: " << mVertices.size() << "Number of edges: " << mEdges.size() << "Number of faces: " << mFaces.size(); return ss.str(); } void PolygonTopology::init(const Faces& faces, ID nVertices) { mFacesIndices = faces; buildTopology(mFacesIndices, nVertices, mVertices, mEdges, mFaces); setFaceOwnerships(); } std::vector<TopologyEdge> PolygonTopology::calculateEdges(const Faces& faces) const { // First create a vector of all edges of all faces. // Insert edges (v1, v2) so that v1 < v2 std::vector<Edge> duplicatedEdges; for (const Face& f : faces) { if (f[0] < f[1] && f[0] < f[2]) { // 9 is smallest // (0, 1), (0, 2) duplicatedEdges.push_back({f[0], f[1]}); duplicatedEdges.push_back({f[0], f[2]}); if (f[1] < f[2]) { // (1, 2) duplicatedEdges.push_back({f[1], f[2]}); } else { // (2, 1) duplicatedEdges.push_back({f[2], f[1]}); } } else if (f[1] < f[0] && f[1] < f[2]) { // 1 is smallest // (1, 0), (1, 2) duplicatedEdges.push_back({f[1], f[0]}); duplicatedEdges.push_back({f[1], f[2]}); if (f[0] < f[2]) { // (0, 2) duplicatedEdges.push_back({f[0], f[2]}); } else { // (2, 0) duplicatedEdges.push_back({f[2], f[0]}); } } else { // 2 is smallest // (2, 0), (2, 1) duplicatedEdges.push_back({f[2], f[0]}); duplicatedEdges.push_back({f[2], f[1]}); if (f[0] < f[1]) { // (0, 1) duplicatedEdges.push_back({f[0], f[1]}); } else { // (1, 0) duplicatedEdges.push_back({f[1], f[0]}); } } } // edgesMap stores the // all edges with vertex indices (i0, i1) with i0 < i1 are gathered // in edges. std::map<ID, std::vector<ID>> edgesMap; for (Edge& e : duplicatedEdges) { auto it = edgesMap.find(e[0]); if (it != edgesMap.end()) { std::vector<ID>& edgesEntry = it->second; auto it2 = std::find(edgesEntry.begin(), edgesEntry.end(), e[1]); if (it2 == edgesEntry.end()) { edgesEntry.push_back(e[1]); } } else { std::vector<ID> edgesEntry; edgesEntry.push_back(e[1]); edgesMap[e[0]] = edgesEntry; } } std::vector<TopologyEdge> edges; for (const std::pair<unsigned int, std::vector<ID>> entry : edgesMap) { for (ID i2 : entry.second) { TopologyEdge e(edges.size(), mVertices.size() + edges.size()); e.getVertexIds()[0] = entry.first; e.getVertexIds()[1] = static_cast<unsigned int>(i2); edges.push_back(e); } } return edges; } void PolygonTopology::buildTopology( const Faces& faces, ID nVertices, std::vector<TopologyVertex>& verticesOut, std::vector<TopologyEdge>& edgesOut, std::vector<TopologyFace>& facesOut) const { // TopologyVertices verticesOut.clear(); verticesOut.reserve(nVertices); for (ID i = 0; i < nVertices; ++i) { verticesOut.push_back(TopologyVertex(verticesOut.size(), verticesOut.size())); } // create set of vertices std::set<std::pair<ID, ID>> edgesSet; for (const Face& f : faces) { edgesSet.insert(makeSmallerPair(f[0], f[1])); edgesSet.insert(makeSmallerPair(f[0], f[2])); edgesSet.insert(makeSmallerPair(f[1], f[2])); } // TopologyEdges edgesOut.clear(); edgesOut.reserve(edgesSet.size()); for (const std::pair<ID, ID>& p : edgesSet) { TopologyEdge te(edgesOut.size(), verticesOut.size() + edgesOut.size()); // add edge start and end vertex te.getVertexIds()[0] = static_cast<unsigned int>(p.first); te.getVertexIds()[1] = static_cast<unsigned int>(p.second); // add this edge to both its vertices verticesOut[p.first].getEdgeIds().push_back(edgesOut.size()); verticesOut[p.second].getEdgeIds().push_back(edgesOut.size()); edgesOut.push_back(te); } // points from edges represented by vertex ids to edge ids std::map<std::pair<unsigned int, unsigned int>, unsigned int> edgesMap; for (unsigned int i = 0; i < edgesOut.size(); ++i) { TopologyEdge& p = edgesOut[i]; edgesMap[std::make_pair(p.getVertexIds()[0], p.getVertexIds()[1])] = i; } // TopologyFaces facesOut.clear(); facesOut.reserve(faces.size()); for (ID i = 0; i < faces.size(); ++i) { const Face& f = faces[i]; TopologyFace tFace(facesOut.size(), verticesOut.size() + edgesOut.size() + facesOut.size()); // add surrounding edges tFace.getEdgeIds()[0] = edgesMap[makeSmallerPair(f[0], f[1])]; tFace.getEdgeIds()[1] = edgesMap[makeSmallerPair(f[0], f[2])]; tFace.getEdgeIds()[2] = edgesMap[makeSmallerPair(f[1], f[2])]; // add surrounding vertices tFace.getVertexIds()[0] = f[0]; tFace.getVertexIds()[1] = f[1]; tFace.getVertexIds()[2] = f[2]; // add this face to all surrounding edges and vertices for (ID j = 0; j < 3; ++j) { verticesOut[tFace.getVertexIds()[j]].getFaceIds().push_back(i); edgesOut[tFace.getEdgeIds()[j]].getFaceIds().push_back(i); } facesOut.push_back(tFace); } // insert adjacent faces for (ID i = 0; i < facesOut.size(); ++i) { TopologyFace& tFace = facesOut[i]; for (ID j = 0; j < 3; ++j) { TopologyEdge& e = edgesOut[tFace.getEdgeIds()[j]]; if (e.getFaceIds().size() > 1) tFace.getAdjacentFaces().push_back(e.getOtherFaceId(i)); } } } void PolygonTopology::setFaceOwnerships() { // Reset all to zero. for (TopologyFace& f : mFaces) { for (size_t i = 0; i < 6; ++i) { f.setVertexOwner(i, false); } } std::set<ID> vertexIds; std::set<ID> edgeIds; for (TopologyFace& f : mFaces) { for (size_t i = 0; i < 3; ++i) { unsigned int vId = f.getVertexIds()[i]; if (vertexIds.find(vId) == vertexIds.end()) { // Assign ownership f.setVertexOwner(i, true); vertexIds.insert(vId); } } for (size_t i = 0; i < 3; ++i) { unsigned int eId = f.getEdgeIds()[i]; if (edgeIds.find(eId) == edgeIds.end()) { // Assign ownership f.setEdgeOwner(i, true); edgeIds.insert(eId); } } } } std::pair<ID, ID> PolygonTopology::makeSmallerPair(ID i1, ID i2) const { if (i1 < i2) return std::make_pair(i1, i2); return std::make_pair(i2, i1); }
//================================================================================================= /*! // \file src/mathtest/smatdmatschur/MCbHDb.cpp // \brief Source file for the MCbHDb sparse matrix/dense matrix Schur product math test // // Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/HermitianMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/smatdmatschur/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'MCbHDb'..." << std::endl; using blazetest::mathtest::NumericB; try { // Matrix type definitions using MCb = blaze::CompressedMatrix<NumericB>; using HDb = blaze::HermitianMatrix< blaze::DynamicMatrix<NumericB> >; // Creator type definitions using CMCb = blazetest::Creator<MCb>; using CHDb = blazetest::Creator<HDb>; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=i*i; ++j ) { RUN_SMATDMATSCHUR_OPERATION_TEST( CMCb( i, i, j ), CHDb( i ) ); } } // Running tests with large matrices RUN_SMATDMATSCHUR_OPERATION_TEST( CMCb( 67UL, 67UL, 7UL ), CHDb( 67UL ) ); RUN_SMATDMATSCHUR_OPERATION_TEST( CMCb( 128UL, 128UL, 16UL ), CHDb( 128UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix Schur product:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
#ifndef FSLBASE_LOG_MATH_PIXEL_FMTPXSIZE2D_HPP #define FSLBASE_LOG_MATH_PIXEL_FMTPXSIZE2D_HPP /**************************************************************************************************************************************************** * Copyright 2020 NXP * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the NXP. nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************************************************************************************/ #include <FslBase/Math/Pixel/PxSize2D.hpp> #include <fmt/format.h> namespace fmt { template <> struct formatter<Fsl::PxSize2D> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(const Fsl::PxSize2D& value, FormatContext& ctx) { return format_to(ctx.out(), "{{Width={} Height={}}}", value.Width(), value.Height()); } }; } #endif
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "core/common/event_manager.h" #include "base/log/ace_trace.h" #include "core/gestures/gesture_referee.h" #include "core/pipeline/base/element.h" #include "core/pipeline/base/render_node.h" namespace OHOS::Ace { void EventManager::TouchTest( const TouchPoint& touchPoint, const RefPtr<RenderNode>& renderNode, const TouchRestrict& touchRestrict) { ACE_FUNCTION_TRACE(); if (!renderNode) { LOGW("renderNode is null."); return; } // first clean. GestureReferee::GetInstance().CleanGestureScope(touchPoint.id); // collect TouchTestResult hitTestResult; const Point point { touchPoint.x, touchPoint.y }; // For root node, the parent local point is the same as global point. renderNode->TouchTest(point, point, touchRestrict, hitTestResult); LOGI("gesture hit test result size %{public}zu", hitTestResult.size()); touchTestResults_[touchPoint.id] = std::move(hitTestResult); } bool EventManager::DispatchTouchEvent(const TouchPoint& point) { ACE_FUNCTION_TRACE(); const auto iter = touchTestResults_.find(point.id); if (iter != touchTestResults_.end()) { bool dispatchSuccess = true; for (auto entry = iter->second.rbegin(); entry != iter->second.rend(); ++entry) { if (!(*entry)->DispatchEvent(point)) { dispatchSuccess = false; break; } } // If one gesture recognizer has already been won, other gesture recognizers will still be affected by // the event, each recognizer needs to filter the extra events by itself. if (dispatchSuccess) { for (const auto& entry : iter->second) { if (!entry->HandleEvent(point)) { break; } } } if (point.type == TouchType::UP || point.type == TouchType::CANCEL) { GestureReferee::GetInstance().CleanGestureScope(point.id); touchTestResults_.erase(point.id); } return true; } LOGI("the %{public}d touch test result does not exist!", point.id); return false; } bool EventManager::DispatchKeyEvent(const KeyEvent& event, const RefPtr<FocusNode>& focusNode) { if (!focusNode) { LOGW("focusNode is null."); return false; } LOGD("The key code is %{public}d, the key action is %{public}d, the repeat time is %{public}d.", event.code, event.action, event.repeatTime); if (!focusNode->HandleKeyEvent(event)) { LOGD("use platform to handle this event"); return false; } return true; } void EventManager::MouseTest(const MouseEvent& event, const RefPtr<RenderNode>& renderNode) { if (!renderNode) { LOGW("renderNode is null."); return; } MouseTestResult hitTestResult; const Point point { event.x, event.y }; // For root node, the parent local point is the same as global point. renderNode->MouseTest(point, point, hitTestResult); if (hitTestResult.empty()) { LOGI("mouse test result is empty"); } mouseTestResults_[event.GetId()] = std::move(hitTestResult); } void EventManager::MouseHoverTest(const MouseEvent& event, const RefPtr<RenderNode>& renderNode) { if (!renderNode) { LOGW("renderNode is null."); return; } const Point point { event.x, event.y }; renderNode->MouseHoverTest(point); } bool EventManager::DispatchRotationEvent( const RotationEvent& event, const RefPtr<RenderNode>& renderNode, const RefPtr<RenderNode>& requestFocusNode) { if (!renderNode) { LOGW("renderNode is null."); return false; } if (requestFocusNode && renderNode->RotationMatchTest(requestFocusNode)) { LOGD("RotationMatchTest: dispatch rotation to request node."); return requestFocusNode->RotationTestForward(event); } else { LOGD("RotationMatchTest: dispatch rotation to statck render node."); return renderNode->RotationTest(event); } } bool EventManager::DispatchMouseEvent(const MouseEvent& event) { const auto iter = mouseTestResults_.find(event.GetId()); if (iter != mouseTestResults_.end()) { // If one mouse recognizer has already been won, other mouse recognizers will still be affected by // the event, each recognizer needs to filter the extra events by itself. for (const auto& entry : iter->second) { entry->HandleEvent(event); } return true; } LOGI("the %{public}d mouse test result does not exist!", event.GetId()); return false; } } // namespace OHOS::Ace
/* * @name BookFiler Module - SSH * @author Branden Lee * @version 1.00 * @license MIT * @brief SSH module for BookFiler™ applications. */ #ifndef BOOKFILER_MODULE_SSH_TUNNEL_SERVER_LISTENER_H #define BOOKFILER_MODULE_SSH_TUNNEL_SERVER_LISTENER_H // config #include "config.hpp" // C++17 //#include <filesystem> #include <algorithm> #include <functional> #include <iostream> #include <map> #include <memory> #include <string> #include <thread> #include <vector> /* boost 1.72.0 * License: Boost Software License (similar to BSD and MIT) */ #include <boost/config.hpp> // Local Project #include "TunnelServerConnection.hpp" /* * bookfiler - ssh * ssh utilities. The main feature is the ssh tunnel for mysql */ namespace bookfiler { namespace ssh { // Accepts incoming connections and launches the sessions class ListenerImpl { private: boost::asio::io_context &ioContext; boost::asio::ip::tcp::endpoint srcEndpoint, destEndpoint; std::shared_ptr<ServerState> serverState; unsigned int connectionIdIncrement; public: ListenerImpl(boost::asio::io_context &, boost::asio::ip::tcp::endpoint, boost::asio::ip::tcp::endpoint, std::shared_ptr<ServerState>); // Start accepting incoming connections int run(boost::asio::yield_context yieldContext); }; } // namespace port } // namespace bookfiler #endif // end BOOKFILER_MODULE_PORT_FORWARDING_SERVER_LISTENER_H
//------------------------------------------------------------------------------ // // Copyright 2018-2020 Fetch.AI Limited // // 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 "ml/ops/max_pool_1d.hpp" #include <cassert> namespace fetch { namespace ml { namespace ops { template <typename T> MaxPool1D<T>::MaxPool1D(const SPType &sp) : Ops<T>(sp) { kernel_size_ = sp.kernel_size; stride_size_ = sp.stride_size; } template <typename T> std::shared_ptr<OpsSaveableParams> MaxPool1D<T>::GetOpSaveableParams() { SPType sp{}; sp.kernel_size = kernel_size_; sp.stride_size = stride_size_; return std::make_shared<SPType>(sp); } template <typename TensorType> std::shared_ptr<fetch::ml::ops::Ops<TensorType>> MaxPool1D<TensorType>::MakeSharedCopy( std::shared_ptr<fetch::ml::ops::Ops<TensorType>> me) { FETCH_UNUSED(me); assert(me.get() == this); auto copyshare = std::make_shared<MyType>(*this); // calls default copy constructor of MyType return copyshare; } /** * Applies 1D max pooling of kernel_size_ for each channel described here: * http://ais.uni-bonn.de/papers/icann2010_maxpool.pdf * @param inputs vector of tensor references where at: * inputs[0] = input_data[input_channels x input_height] * @param output tensor of size [input_channels=output_channels x number_of_stride_sized_steps] * @return: output tensor parameter */ template <typename T> void MaxPool1D<T>::Forward(const VecTensorType &inputs, TensorType &output) { assert(inputs.size() == 1); // Input must be a 3D tensor [C x W x N] assert(inputs.at(0)->shape().size() == 3); assert(output.shape() == ComputeOutputShape(inputs)); SizeType iter; DataType max; DataType val; auto out_it = output.begin(); for (SizeType n_i{0}; n_i < output.shape().at(2); n_i++) // iterate over batch { // output_channels = input_channels for (SizeType i{0}; i < output.shape().at(1); i++) // Iterate over kernel stride { iter = i * stride_size_; for (SizeType c{0}; c < output.shape().at(0); ++c) // Iterate over output channels { max = inputs.at(0)->At(c, iter, n_i); // Get maximum value on kernel_size_ window for (SizeType j{1}; j < kernel_size_; j++) // Iterate over kernel width { val = inputs.at(0)->At(c, iter + j, n_i); if (val > max) { max = val; } } // Set maximum value for each [kernel_size_] window to output *out_it = max; ++out_it; } } } } /** * Computes gradient of 1D max pooling of kernel_size_ for each channel described here: * http://ais.uni-bonn.de/papers/icann2010_maxpool.pdf * Error signal of max pool is passed only to max node * @param inputs vector of tensor references where at: * inputs[0] = input_data[input_channels x input_height] * @param error_signal tensor of size [output_channels=input_channels x * number_of_stride_sized_steps] * @return: output vector of tensors with back propagated error signal * output[0]=input_error[inputs[0].shape] */ template <typename TensorType> std::vector<TensorType> MaxPool1D<TensorType>::Backward(const VecTensorType &inputs, const TensorType & error_signal) { assert(inputs.size() == 1); assert(error_signal.shape() == ComputeOutputShape(inputs)); TensorType return_signal{inputs.at(0)->shape()}; auto output_shape = error_signal.shape(); SizeType iter; DataType max; DataType val; SizeType max_iter; auto er_it = error_signal.cbegin(); for (SizeType n_i{0}; n_i < output_shape.at(2); n_i++) // iterate over batch { for (SizeType i{0}; i < output_shape.at(1); i++) // Iterate over kernel stride { iter = i * stride_size_; for (SizeType c{0}; c < output_shape.at(0); ++c) // Iterate over output channels { max = inputs.at(0)->At(c, iter, n_i); max_iter = iter; // Find max node for (SizeType j{0}; j < kernel_size_; j++) // Iterate over kernel width { val = inputs.at(0)->At(c, iter + j, n_i); if (val > max) { max = val; max_iter = iter + j; } } // Add error to max node return_signal.Set(c, max_iter, n_i, return_signal.At(c, max_iter, n_i) + *er_it); ++er_it; } } } return {return_signal}; } template <typename T> std::vector<fetch::math::SizeType> MaxPool1D<T>::ComputeOutputShape( const VecTensorType &inputs) const { std::vector<SizeType> output_shape; // output_shape_[0]=number of output channels output_shape.emplace_back(inputs.at(0)->shape().at(0)); // output_shape_[1]=number of stride_size steps over input size SizeType output_height = ((inputs.at(0)->shape().at(1) - kernel_size_) / stride_size_) + 1; if (output_height == 0 || output_height == std::numeric_limits<SizeType>::max()) { throw fetch::math::exceptions::WrongShape( "MaxPool1D::ComputeOutputShape: output shape has 0 or -1 values!"); } output_shape.emplace_back(output_height); // output_shape_[2]=batch dimension output_shape.emplace_back(inputs.at(0)->shape().at(2)); return output_shape; } template <typename TensorType> OperationsCount MaxPool1D<TensorType>::ChargeForward() const { assert(!this->batch_output_shape_.empty()); OperationsCount cost = fetch::ml::charge_estimation::ops::MAX_PER_ELEMENT * this->batch_output_shape_.at(0) * this->batch_output_shape_.at(1) * this->batch_output_shape_.at(2) * this->kernel_size_; return cost; } template <typename TensorType> OperationsCount MaxPool1D<TensorType>::ChargeBackward() const { assert(!this->batch_output_shape_.empty()); OperationsCount cost = fetch::ml::charge_estimation::ops::MAX_PER_ELEMENT * this->batch_output_shape_.at(0) * this->batch_output_shape_.at(1) * this->batch_output_shape_.at(2) * this->kernel_size_; return cost; } /////////////////////////////// /// EXPLICIT INSTANTIATIONS /// /////////////////////////////// template class MaxPool1D<math::Tensor<int8_t>>; template class MaxPool1D<math::Tensor<int16_t>>; template class MaxPool1D<math::Tensor<int32_t>>; template class MaxPool1D<math::Tensor<int64_t>>; template class MaxPool1D<math::Tensor<float>>; template class MaxPool1D<math::Tensor<double>>; template class MaxPool1D<math::Tensor<fixed_point::fp32_t>>; template class MaxPool1D<math::Tensor<fixed_point::fp64_t>>; template class MaxPool1D<math::Tensor<fixed_point::fp128_t>>; } // namespace ops } // namespace ml } // namespace fetch
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/bookmarks/browser/url_index.h" #include "base/containers/adapters.h" #include "base/guid.h" #include "components/bookmarks/browser/url_and_title.h" namespace bookmarks { UrlIndex::UrlIndex(std::unique_ptr<BookmarkNode> root) : root_(std::move(root)) { base::AutoLock url_lock(url_lock_); AddImpl(root_.get()); } void UrlIndex::Add(BookmarkNode* parent, size_t index, std::unique_ptr<BookmarkNode> node) { base::AutoLock url_lock(url_lock_); AddImpl(parent->Add(std::move(node), index)); } std::unique_ptr<BookmarkNode> UrlIndex::Remove(BookmarkNode* node, std::set<GURL>* removed_urls) { base::AutoLock url_lock(url_lock_); RemoveImpl(node, removed_urls); if (removed_urls) { // RemoveImpl() adds an entry to removed_urls for each node of type URL. As // duplicates are allowed we need to remove any entries that are still // bookmarked. for (auto i = removed_urls->begin(); i != removed_urls->end();) { if (IsBookmarkedNoLock(*i)) { // When we erase the iterator pointing at the erasee is // invalidated, so using i++ here within the "erase" call is // important as it advances the iterator before passing the // old value through to erase. removed_urls->erase(i++); } else { ++i; } } } BookmarkNode* parent = node->parent(); return parent->Remove(size_t{parent->GetIndexOf(node)}); } void UrlIndex::SetUrl(BookmarkNode* node, const GURL& url) { base::AutoLock url_lock(url_lock_); RemoveImpl(node, nullptr); node->set_url(url); AddImpl(node); } void UrlIndex::SetTitle(BookmarkNode* node, const base::string16& title) { // Acquiring the lock is necessary to avoid races with // UrlIndex::GetBookmarks(). base::AutoLock url_lock(url_lock_); node->SetTitle(title); } void UrlIndex::GetNodesWithIconUrl(const GURL& icon_url, std::set<const BookmarkNode*>* nodes) { base::AutoLock url_lock(url_lock_); for (const BookmarkNode* node : nodes_ordered_by_url_set_) { if (node->icon_url() && icon_url == *node->icon_url()) nodes->insert(node); } } void UrlIndex::GetNodesByUrl(const GURL& url, std::vector<const BookmarkNode*>* nodes) { base::AutoLock url_lock(url_lock_); BookmarkNode tmp_node(/*id=*/0, base::GenerateGUID(), url); auto i = nodes_ordered_by_url_set_.find(&tmp_node); while (i != nodes_ordered_by_url_set_.end() && (*i)->url() == url) { nodes->push_back(*i); ++i; } } bool UrlIndex::HasBookmarks() const { base::AutoLock url_lock(url_lock_); return !nodes_ordered_by_url_set_.empty(); } size_t UrlIndex::UrlCount() const { base::AutoLock url_lock(url_lock_); return nodes_ordered_by_url_set_.size(); } bool UrlIndex::IsBookmarked(const GURL& url) { base::AutoLock url_lock(url_lock_); return IsBookmarkedNoLock(url); } void UrlIndex::GetBookmarks(std::vector<UrlAndTitle>* bookmarks) { base::AutoLock url_lock(url_lock_); const GURL* last_url = nullptr; for (auto i = nodes_ordered_by_url_set_.begin(); i != nodes_ordered_by_url_set_.end(); ++i) { const GURL* url = &((*i)->url()); // Only add unique URLs. if (!last_url || *url != *last_url) { UrlAndTitle bookmark; bookmark.url = *url; bookmark.title = (*i)->GetTitle(); bookmarks->push_back(bookmark); } last_url = url; } } UrlIndex::~UrlIndex() = default; bool UrlIndex::IsBookmarkedNoLock(const GURL& url) { url_lock_.AssertAcquired(); BookmarkNode tmp_node(/*id=*/0, base::GenerateGUID(), url); return (nodes_ordered_by_url_set_.find(&tmp_node) != nodes_ordered_by_url_set_.end()); } void UrlIndex::AddImpl(BookmarkNode* node) { url_lock_.AssertAcquired(); if (node->is_url()) nodes_ordered_by_url_set_.insert(node); for (const auto& child : node->children()) AddImpl(child.get()); } void UrlIndex::RemoveImpl(BookmarkNode* node, std::set<GURL>* removed_urls) { url_lock_.AssertAcquired(); if (node->is_url()) { auto i = nodes_ordered_by_url_set_.find(node); DCHECK(i != nodes_ordered_by_url_set_.end()); // i points to the first node with the URL, advance until we find the // node we're removing. while (*i != node) ++i; nodes_ordered_by_url_set_.erase(i); if (removed_urls) removed_urls->insert(node->url()); } for (const auto& child : base::Reversed(node->children())) RemoveImpl(child.get(), removed_urls); } } // namespace bookmarks
/* ======================================================================== * Copyright (c) 2006, * Institute for Computer Graphics and Vision * Graz University of Technology * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Graz University of Technology 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. * ======================================================================== * PROJECT: OpenTracker * ======================================================================== */ /** source file for P5GloveModule module. * * @author Hannes Kaufmann, Istvan Barakonyi, Mathis Csisinko * * $Id$ * @file */ /* ======================================================================= */ // this will remove the warning 4786 #include <OpenTracker/tool/disable4786.h> #include <OpenTracker/input/P5GloveModule.h> #ifdef USE_P5GLOVE #include <cstdio> #include <string> #include <iostream> #include <cmath> #include <OpenTracker/input/P5GloveSource.h> namespace ot { OT_MODULE_REGISTER_FUNC(P5GloveModule){ OT_MODULE_REGISTRATION_DEFAULT(P5GloveModule , "P5GloveConfig"); } P5GloveModule::P5GloveModule() : Module(), NodeFactory() { P5device=new CP5DLL(); } // Destructor method P5GloveModule::~P5GloveModule() { nodes.clear(); } // initializes trackers void P5GloveModule::init(StringTable& attributes, ConfigNode * localTree) { if( attributes.get("P5Id", &P5Id ) == 0 ) P5Id = 0; if( attributes.get("relative").compare("true") == 0) relative = true; logPrintI("P5 Glove is configured with id %d\n",P5Id); Module::init( attributes, localTree ); } // This method is called to construct a new Node. Node * P5GloveModule::createNode( const std::string& name, const StringTable& attributes) { if( name.compare("P5GloveSource") == 0 ) { int num,finger; std::vector<float> vector,axis; num = attributes.get("finger", &finger); if (num == 0) finger=0; else if( finger < 0 || finger > 4) { /// finger: 0 - 4, 0 = thumb, 1 = index, 2 = middle, 3 = ring, 4 = pinky logPrintE("Finger index must be between 0 and 4 \n"); return NULL; } attributes.get("vector",vector,3); if (vector.size() != 3) { logPrintE("Vector length must be 3 \n"); return NULL; } attributes.get("axis",axis,3); if (axis.size() != 3) { logPrintE("Axis length must be 3 \n"); return NULL; } P5GloveSource *source = new P5GloveSource(finger,vector,axis); nodes.push_back( source ); logPrintI("Built P5GloveSource node for finger %d \n",finger); initialized = 1; return source; } return NULL; } // opens P5Glove library void P5GloveModule::start() { if( isInitialized() == 1 ) { // The P5 can always be initialized, no matter if it is turned on or off // The P5_Init() method always returns 1 // P5_Init() probably only checks if the device is registered in Windows. // printf("P5 status %d \n",P5device->P5_Init()); if (P5device->P5_Init() != (P5BOOL)true) { logPrintE("No P5 detected...\n"); } else { logPrintI("P5 Found...\n"); //P5device->P5_SetMouseEvent(P5Id, false); } } logPrintI("P5Glove started\n"); } // closes P5Glove library void P5GloveModule::close() { // if P5 glove is turned ON and actually used by stb, than mouseEvent must be set back, // otherwise calling SetMouseEvent would cause a crash on exit /*if( isInitialized() == 1 ) P5device->P5_SetMouseEvent(0, true);*/ P5device->P5_Close(); logPrintI("Closing P5Glove \n"); } // pushes events into the tracker tree. void P5GloveModule::pushEvent() { if( isInitialized() == 1 ) { std::vector<float> orientation(4); if( P5device->m_P5Devices != NULL ) { // P5Motion_InvertMouse(P5MOTION_INVERTAXIS, P5MOTION_NORMALAXIS, P5MOTION_NORMALAXIS); // P5Motion_SetClipRegion((-dwHeight), dwHeight, (-dwWidth), dwWidth, 0, 1000); P5Motion_Process(); // Rotation (Roll, Pitch, Yaw) is internally presented in Degrees // Must convert it to radiant to pass it to the eulerToQuaternion conversion routine // pure data without filtering would be // P5device->m_P5Devices[P5Id].m_froll, P5device->m_P5Devices[P5Id].m_fpitch // P5device->m_P5Devices[P5Id].m_fyaw MathUtils::eulerToQuaternion(fAbsRollPos*MathUtils::Pi/180, fAbsPitchPos*MathUtils::Pi/180, fAbsYawPos*MathUtils::Pi/180, orientation); } for( NodeVector::iterator it = nodes.begin(); it != nodes.end(); ++ it ) { P5GloveSource *source = (P5GloveSource *)((Node*)*it); Event &event = source->getEvent(P5device->m_P5Devices[P5Id]); if (! relative) { std::vector<float> newOrientation(4),newPosition(3); MathUtils::rotateVector(orientation,event.getPosition(),newPosition); newPosition[0] += fFilterX; newPosition[1] += fFilterY; newPosition[2] += fFilterZ; MathUtils::multiplyQuaternion(orientation,event.getOrientation(),newOrientation); event.getPosition() = newPosition; event.getOrientation() = newOrientation; } event.setConfidence(1.f); event.timeStamp(); source->updateObservers( event ); } } } //These variables contain the actual x, Y, Z position of the cursor static int nXPos = 0, nYPos = 0, nZPos = 0; //These variables contain the frame to frame deltas of the cursor static float fXMickey = 0.0f, fYMickey = 0.0f, fZMickey = 0.0f; //These variables contain the filtered orientation information static float fRelYawPos, fRelPitchPos, fRelRollPos; /*********************************************** Function: P5Motion_SetClipRegion() Use: Call this function to initialize a clipping region Parameters: int xstart - low side xclip point int xend - high side xclip point int ystart - low side yclip point int yend - high side yclip point int zstart - low side zclip point int zend - high side zclip point ***********************************************/ static int nxclipstart = 0, nxclipend = 1024, nyclipstart = 0, nyclipend = 768, nzclipstart = 0, nzclipend = 1024; static void P5Motion_SetClipRegion(int xstart, int xend, int ystart, int yend, int zstart, int zend) { nxclipstart = xstart; nxclipend = xend; nyclipstart = ystart; nyclipend = yend; nzclipstart = zstart; nzclipend = zend; } /*********************************************** Function: P5Motion_InvertMouse() Use: Call this function to flip an axis if necessary Parameters: int xaxis - P5MOTION_NORMALAXIS or P5MOTION_INVERTAXIS int yaxis - P5MOTION_NORMALAXIS or P5MOTION_INVERTAXIS int zaxis - P5MOTION_NORMALAXIS or P5MOTION_INVERTAXIS ***********************************************/ int nxinvert = 0, nyinvert = 0, nzinvert = 0; static void P5Motion_InvertMouse(int xaxis, int yaxis, int zaxis) { nxinvert = xaxis; nyinvert = yaxis; nzinvert = zaxis; } /*********************************************** Function: P5Motion_FilterXYZ() Use: Internal Function. Used to filter XYZ Data Parameter: None ***********************************************/ float fXPos[P5MOTION_XYZFILTERSIZE], fYPos[P5MOTION_XYZFILTERSIZE], fZPos[P5MOTION_XYZFILTERSIZE]; void P5GloveModule::P5Motion_FilterXYZ() { static int firsttime = 1; if (P5device != NULL) { if (firsttime==1) { //dont process anything on the first call, just init our filter arrays for (int i=0; i<P5MOTION_XYZFILTERSIZE; i++) { fXPos[i] = P5device->m_P5Devices[P5Id].m_fx; fYPos[i] = P5device->m_P5Devices[P5Id].m_fy; fZPos[i] = P5device->m_P5Devices[P5Id].m_fz; } firsttime = 0; } else { //We are going to implement a dynamic filter, which will flush the filter array values at different rates //based on the rate of change of the users hand. This will allow for greater latency of motion. //The setpoint determines the number of pixel motion that will flush the entire filter. //The idea is when the user doensnt move much, we average alot of frames, but during fast motion, we //average fewer and fewer frames in order to reduce latency #define FLUSH_SETPOINT 30.0f float xflushsize, yflushsize, zflushsize; int i, j; //Lets determine the number of frames we intend to average together xflushsize = fabs(P5device->m_P5Devices[P5Id].m_fx - fXPos[P5MOTION_XYZFILTERSIZE-1])/2.0f; xflushsize *= P5MOTION_XYZFILTERSIZE/FLUSH_SETPOINT; xflushsize = floor(xflushsize+1.0f); if (xflushsize>(P5MOTION_XYZFILTERSIZE-1)) xflushsize = P5MOTION_XYZFILTERSIZE-1; yflushsize = fabs(P5device->m_P5Devices[P5Id].m_fy - fYPos[P5MOTION_XYZFILTERSIZE-1])/2.0f; yflushsize *= P5MOTION_XYZFILTERSIZE/FLUSH_SETPOINT; yflushsize = floor(yflushsize+1.0f); if (yflushsize>(P5MOTION_XYZFILTERSIZE-1)) yflushsize = P5MOTION_XYZFILTERSIZE-1; zflushsize = fabs(P5device->m_P5Devices[P5Id].m_fz - fZPos[P5MOTION_XYZFILTERSIZE-1])/2.0f; zflushsize *= P5MOTION_XYZFILTERSIZE/FLUSH_SETPOINT; zflushsize = floor(zflushsize+1.0f); if (zflushsize>(P5MOTION_XYZFILTERSIZE-1)) zflushsize = P5MOTION_XYZFILTERSIZE-1; //flush the array based on the number of values determined before. for (j=0; j<(int)(xflushsize); j++) { for (i=0; i<(P5MOTION_XYZFILTERSIZE-1); i++) { fXPos[i] = fXPos[i+1]; } fXPos[P5MOTION_XYZFILTERSIZE-1] = P5device->m_P5Devices[P5Id].m_fx; } for (j=0; j<(int)(yflushsize); j++) { for (i=0; i<(P5MOTION_XYZFILTERSIZE-1); i++) { fYPos[i] = fYPos[i+1]; } fYPos[P5MOTION_XYZFILTERSIZE-1] = P5device->m_P5Devices[P5Id].m_fy; } for (j=0; j<(int)(zflushsize); j++) { for (i=0; i<(P5MOTION_XYZFILTERSIZE-1); i++) { fZPos[i] = fZPos[i+1]; } fZPos[P5MOTION_XYZFILTERSIZE-1] = P5device->m_P5Devices[P5Id].m_fz; } } //Average all the values in the filter to smoothen the data fFilterX = 0.0f; fFilterY = 0.0f; fFilterZ = 0.0f; for (int i=0; i<P5MOTION_XYZFILTERSIZE; i++) { //we are going to divide the values to get rid of some jitter fFilterX += fXPos[i]/2.0f; fFilterY += fYPos[i]/2.0f; fFilterZ += fZPos[i]/2.0f; } fFilterX /= P5MOTION_XYZFILTERSIZE; fFilterY /= P5MOTION_XYZFILTERSIZE; fFilterZ /= P5MOTION_XYZFILTERSIZE; } } /*********************************************** Function: P5Motion_FilterYPR() Use: Internal Function. Used to filter Orientation Data Parameter: None ***********************************************/ static float fYaw[P5MOTION_YPRFILTERSIZE], fPitch[P5MOTION_YPRFILTERSIZE], fRoll[P5MOTION_YPRFILTERSIZE]; static float fFilterYaw, fFilterPitch, fFilterRoll; void P5GloveModule::P5Motion_FilterYPR() { static int firsttime = 1; if (P5device != NULL) { if (firsttime==1) { //dont process anything on the first call, just init our filter arrays for (int i=0; i<P5MOTION_YPRFILTERSIZE; i++) { fYaw[i] = P5device->m_P5Devices[P5Id].m_fyaw; fPitch[i] = P5device->m_P5Devices[P5Id].m_fpitch; fRoll[i] = P5device->m_P5Devices[P5Id].m_froll; } firsttime = 0; } else { for (int i=0; i<(P5MOTION_YPRFILTERSIZE-1); i++) { fYaw[i] = fYaw[i+1]; fPitch[i] = fPitch[i+1]; fRoll[i] = fRoll[i+1]; } fYaw[P5MOTION_YPRFILTERSIZE-1] = P5device->m_P5Devices[P5Id].m_fyaw; fPitch[P5MOTION_YPRFILTERSIZE-1] = P5device->m_P5Devices[P5Id].m_fpitch; fRoll[P5MOTION_YPRFILTERSIZE-1] = P5device->m_P5Devices[P5Id].m_froll; } //Average all the values in the filter to smoothen the data fFilterYaw = 0.0f; fFilterPitch = 0.0f; fFilterRoll = 0.0f; for (int i=0; i<P5MOTION_YPRFILTERSIZE; i++) { fFilterYaw += fYaw[i]; fFilterPitch += fPitch[i]; fFilterRoll += fRoll[i]; } fFilterYaw /= P5MOTION_YPRFILTERSIZE; fFilterPitch /= P5MOTION_YPRFILTERSIZE; fFilterRoll /= P5MOTION_YPRFILTERSIZE; } } /*********************************************** Function: P5Motion_Process() Use: Processes the XYZ motion information every frame. Call this function to calculate a pointer's position and oreintation with filtering and acceleration Parameter: None ***********************************************/ void P5GloveModule::P5Motion_Process() { //XYZ information first static float fLastXpos = 0.0f, fLastYpos = 0.0f, fLastZpos = 0.0f; P5Motion_FilterXYZ(); //apply axis invertion if required and calculate the delta from last frame fXMickey = (fLastXpos - fFilterX) * nxinvert; fYMickey = (fLastYpos - fFilterY) * nyinvert; fZMickey = (fLastZpos - fFilterZ) * nzinvert; #define COEFF1 0.0042f #define COEFF2 1.2403f //this is a third degree polynomial acceleration function.. seems to give the best results //by trial and error fXMickey = COEFF1*fXMickey*fXMickey*fXMickey + COEFF2*fXMickey; fYMickey = COEFF1*fYMickey*fYMickey*fYMickey + COEFF2*fYMickey; fZMickey = COEFF1*fZMickey*fZMickey*fZMickey + COEFF2*fZMickey; //A step function gain to speed up the high end motion for faster travel across the screen if ( fabs(fXMickey) > 3.0f) fXMickey *= 4.0f; else fXMickey *= 2.0f; if ( fabs(fYMickey) > 3.0f) fYMickey *= 4.0f; else fYMickey *= 2.0f; if ( fabs(fZMickey) > 3.0f) fZMickey *= 4.0f; else fZMickey *= 2.0f; nXPos += (int)(fXMickey); nYPos += (int)(fYMickey); nZPos += (int)(fZMickey); //Clip the data to fit the clipping region if (nXPos > nxclipend) nXPos = nxclipend; else if (nXPos < nxclipstart) nXPos = nxclipstart; if (nYPos > nyclipend) nYPos = nyclipend; else if (nYPos < nyclipstart) nYPos = nyclipstart; if (nZPos > nzclipend) nZPos = nzclipend; else if (nZPos < nzclipstart) nZPos = nzclipstart; fLastXpos = fFilterX; fLastYpos = fFilterY; fLastZpos = fFilterZ; //Lets process Yaw, Pitch, Roll information now P5Motion_FilterYPR(); //Only prcess YPR information if a fist is made.. like grabbing the object //This is just an example gesture, and can be changed to be anything at all static float fZeroYawPos, fZeroPitchPos, fZeroRollPos; fZeroYawPos = fFilterYaw; fZeroPitchPos = fFilterPitch; fZeroRollPos = fFilterRoll; fAbsYawPos = fFilterYaw; fAbsPitchPos = fFilterPitch; fAbsRollPos = fFilterRoll; //In relative mode, YPR acts as a rate controller, providing continuous motion when a certain //limit is hit #define YPR_ROTSPEED 0.5f if ( fFilterRoll > (fZeroRollPos+30.0f) ) fRelRollPos += YPR_ROTSPEED; else if ( fFilterRoll<(fZeroRollPos-30.0f) ) fRelRollPos -= YPR_ROTSPEED; if (fRelRollPos > 180.0f) fRelRollPos = -180.0f; else if (fRelRollPos < -180.0f) fRelRollPos = 180.0f; if (fFilterYaw > (fZeroYawPos+25.0f)) fRelYawPos += YPR_ROTSPEED; else if (fFilterYaw < (fZeroYawPos-25.0f)) fRelYawPos -= YPR_ROTSPEED; if (fRelYawPos > 180.0f) fRelYawPos = -180.0f; else if (fRelYawPos < -180.0f) fRelYawPos = 180.0f; if (fFilterPitch > (fZeroPitchPos+25.0f)) fRelPitchPos += YPR_ROTSPEED; else if (fFilterPitch < (fZeroPitchPos-25.0f)) fRelPitchPos -= YPR_ROTSPEED; if (fRelPitchPos > 180.0f) fRelPitchPos = -180.0f; else if (fRelPitchPos < -180.0f) fRelPitchPos = 180.0f; } } // namespace ot #else #ifdef WIN32 #pragma message(">>> no P5 glove support") #endif #endif /* * ------------------------------------------------------------ * End of P5GloveModule.cxx * ------------------------------------------------------------ * Automatic Emacs configuration follows. * Local Variables: * mode:c++ * c-basic-offset: 4 * eval: (c-set-offset 'substatement-open 0) * eval: (c-set-offset 'case-label '+) * eval: (c-set-offset 'statement 'c-lineup-runin-statements) * eval: (setq indent-tabs-mode nil) * End: * ------------------------------------------------------------ */
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_TEST_PRECOMP_HPP__ #define __OPENCV_TEST_PRECOMP_HPP__ #include "opencv2/ts.hpp" #include "opencv2/ts/ts_perf.hpp" #include "opencv2/core/utility.hpp" #include "opencv2/dnn.hpp" #include "test_common.hpp" namespace opencv_test { using namespace cv::dnn; } #endif
/* * Copyright (c) 2019-2021, 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. */ //! //! \file sw_filter_pipe.cpp //! \brief Defines the common interface for vp features manager //! \details The vp manager is further sub-divided by vp type //! this file is for the base interface which is shared by all components. //! #include "sw_filter_pipe.h" #include "vp_obj_factories.h" #include "vp_feature_manager.h" #include "sw_filter_handle.h" using namespace vp; /****************************************************************************************************/ /* SwFilterSubPipe */ /****************************************************************************************************/ SwFilterSubPipe::SwFilterSubPipe() { } SwFilterSubPipe::~SwFilterSubPipe() { Clean(); } MOS_STATUS SwFilterSubPipe::Clean() { VP_FUNC_CALL(); for (auto &filterSet : m_OrderedFilters) { if (filterSet) { // Loop orderred feature set. VP_PUBLIC_CHK_STATUS_RETURN(filterSet->Clean()); MOS_Delete(filterSet); } } m_OrderedFilters.clear(); // Process remaining unordered features VP_PUBLIC_CHK_STATUS_RETURN(m_UnorderedFilters.Clean()); return MOS_STATUS_SUCCESS; } MOS_STATUS SwFilterSubPipe::Update(VP_SURFACE *inputSurf, VP_SURFACE *outputSurf) { VP_FUNC_CALL(); for (auto &featureSet : m_OrderedFilters) { if (featureSet) { VP_PUBLIC_CHK_STATUS_RETURN(featureSet->Update(inputSurf, outputSurf, *this)); } } VP_PUBLIC_CHK_STATUS_RETURN(m_UnorderedFilters.Update(inputSurf, outputSurf, *this)); return MOS_STATUS_SUCCESS; } SwFilter *SwFilterSubPipe::GetSwFilter(FeatureType type) { VP_FUNC_CALL(); // Search unordered filters firstly. SwFilter *swFilter = m_UnorderedFilters.GetSwFilter(type); if (swFilter) { return swFilter; } for (auto &swFilterSet : m_OrderedFilters) { swFilter = swFilterSet->GetSwFilter(type); if (swFilter) { return swFilter; } } return nullptr; } MOS_STATUS SwFilterSubPipe::AddSwFilterOrdered(SwFilter *swFilter, bool useNewSwFilterSet) { VP_FUNC_CALL(); VP_PUBLIC_CHK_NULL_RETURN(swFilter); MOS_STATUS status = MOS_STATUS_SUCCESS; SwFilterSet *swFilterSet = nullptr; auto &pipe = m_OrderedFilters; if (useNewSwFilterSet || pipe.empty()) { swFilterSet = MOS_New(SwFilterSet); useNewSwFilterSet = true; } else { swFilterSet = pipe[pipe.size() - 1]; } VP_PUBLIC_CHK_NULL_RETURN(swFilterSet); status = swFilterSet->AddSwFilter(swFilter); if (MOS_FAILED(status)) { if (useNewSwFilterSet) { MOS_Delete(swFilterSet); } return status; } pipe.push_back(swFilterSet); swFilterSet->SetLocation(&pipe); return MOS_STATUS_SUCCESS; } MOS_STATUS SwFilterSubPipe::AddSwFilterUnordered(SwFilter *swFilter) { VP_FUNC_CALL(); VP_PUBLIC_CHK_NULL_RETURN(swFilter); return m_UnorderedFilters.AddSwFilter(swFilter); } /****************************************************************************************************/ /* SwFilterPipe */ /****************************************************************************************************/ SwFilterPipe::SwFilterPipe(VpInterface &vpInterface) : m_vpInterface(vpInterface) { m_surfacesSetting.Clean(); } SwFilterPipe::~SwFilterPipe() { Clean(); } MOS_STATUS SwFilterPipe::Initialize(VP_PIPELINE_PARAMS &params, FeatureRule &featureRule) { VP_FUNC_CALL(); Clean(); uint32_t i = 0; for (i = 0; i < params.uSrcCount; ++i) { if (nullptr == params.pSrc[i]) { Clean(); return MOS_STATUS_INVALID_PARAMETER; } VP_SURFACE *surf = m_vpInterface.GetAllocator().AllocateVpSurface(*params.pSrc[i]); if (nullptr == surf) { Clean(); return MOS_STATUS_NULL_POINTER; } surf->Palette = params.pSrc[i]->Palette; m_InputSurfaces.push_back(surf); // Keep m_pastSurface/m_futureSurface same size as m_InputSurfaces. VP_SURFACE *pastSurface = nullptr; if (params.pSrc[i]->pBwdRef) { pastSurface = m_vpInterface.GetAllocator().AllocateVpSurface(*params.pSrc[i]->pBwdRef); } VP_SURFACE *futureSurface = nullptr; if (params.pSrc[i]->pFwdRef) { futureSurface = m_vpInterface.GetAllocator().AllocateVpSurface(*params.pSrc[i]->pFwdRef); } m_pastSurface.push_back(pastSurface); m_futureSurface.push_back(futureSurface); m_linkedLayerIndex.push_back(0); // Initialize m_InputPipes. SwFilterSubPipe *pipe = MOS_New(SwFilterSubPipe); if (nullptr == pipe) { Clean(); return MOS_STATUS_NULL_POINTER; } m_InputPipes.push_back(pipe); } for (i = 0; i < params.uDstCount; ++i) { if (nullptr == params.pTarget[i]) { Clean(); return MOS_STATUS_INVALID_PARAMETER; } VP_SURFACE *surf = m_vpInterface.GetAllocator().AllocateVpSurface(*params.pTarget[i]); if (nullptr == surf) { Clean(); return MOS_STATUS_NULL_POINTER; } m_OutputSurfaces.push_back(surf); // Initialize m_OutputPipes. SwFilterSubPipe *pipe = MOS_New(SwFilterSubPipe); if (nullptr == pipe) { Clean(); return MOS_STATUS_NULL_POINTER; } m_OutputPipes.push_back(pipe); } UpdateSwFilterPipeType(); MOS_STATUS status = ConfigFeatures(params, featureRule); if (MOS_FAILED(status)) { Clean(); return status; } return MOS_STATUS_SUCCESS; } MOS_STATUS SwFilterPipe::Initialize(VEBOX_SFC_PARAMS &params) { VP_FUNC_CALL(); Clean(); // Initialize input surface. { if (nullptr == params.input.surface) { Clean(); return MOS_STATUS_INVALID_PARAMETER; } // The value of plane offset are different between vp and codec. updatePlaneOffset need be set to true when create vp surface // with mos surface from codec hal. VP_SURFACE *input = m_vpInterface.GetAllocator().AllocateVpSurface(*params.input.surface, params.input.colorSpace, params.input.chromaSiting, params.input.rcSrc, params.output.rcDst, SURF_IN_PRIMARY, true); if (nullptr == input) { Clean(); return MOS_STATUS_NULL_POINTER; } m_InputSurfaces.push_back(input); // Keep m_PastSurface same size as m_InputSurfaces. m_pastSurface.push_back(nullptr); m_futureSurface.push_back(nullptr); m_linkedLayerIndex.push_back(0); // Initialize m_InputPipes. SwFilterSubPipe *pipe = MOS_New(SwFilterSubPipe); if (nullptr == pipe) { Clean(); return MOS_STATUS_NULL_POINTER; } m_InputPipes.push_back(pipe); } // Initialize output surface. { if (nullptr == params.output.surface) { Clean(); return MOS_STATUS_INVALID_PARAMETER; } RECT recOutput = {0, 0, (int32_t)params.output.surface->dwWidth, (int32_t)params.output.surface->dwHeight}; // The value of plane offset are different between vp and codec. updatePlaneOffset need be set to true when create vp surface // with mos surface from codec hal. VP_SURFACE *output = m_vpInterface.GetAllocator().AllocateVpSurface(*params.output.surface, params.output.colorSpace, params.output.chromaSiting, recOutput, recOutput, SURF_OUT_RENDERTARGET, true); if (nullptr == output) { Clean(); return MOS_STATUS_NULL_POINTER; } m_OutputSurfaces.push_back(output); // Initialize m_OutputPipes. SwFilterSubPipe *pipe = MOS_New(SwFilterSubPipe); if (nullptr == pipe) { Clean(); return MOS_STATUS_NULL_POINTER; } m_OutputPipes.push_back(pipe); } UpdateSwFilterPipeType(); MOS_STATUS status = ConfigFeatures(params); if (MOS_FAILED(status)) { Clean(); return status; } return MOS_STATUS_SUCCESS; } void SwFilterPipe::UpdateSwFilterPipeType() { VP_FUNC_CALL(); m_swFilterPipeType = SwFilterPipeTypeInvalid; if (1 == m_InputSurfaces.size() && 1 == m_OutputSurfaces.size()) { m_swFilterPipeType = SwFilterPipeType1To1; } else if (m_InputSurfaces.size() > 1 && 1 == m_OutputSurfaces.size()) { m_swFilterPipeType = SwFilterPipeTypeNTo1; } else if (1 == m_InputSurfaces.size() && m_OutputSurfaces.size() > 1) { m_swFilterPipeType = SwFilterPipeType1ToN; } else if (0 == m_InputSurfaces.size() && 1 == m_OutputSurfaces.size()) { m_swFilterPipeType = SwFilterPipeType0To1; } } MOS_STATUS SwFilterPipe::Clean() { VP_FUNC_CALL(); // Do not unregister features in Clean, which will be reused until swFilterPipe being destroyed. m_swFilterPipeType = SwFilterPipeTypeInvalid; CleanFeatures(); std::vector<SwFilterSubPipe *> *pipes[] = {&m_InputPipes, &m_OutputPipes}; for (auto pipe : pipes) { while (!pipe->empty()) { auto p = pipe->back(); MOS_Delete(p); pipe->pop_back(); } } std::vector<VP_SURFACE *> *surfacesArray[] = {&m_InputSurfaces, &m_OutputSurfaces, &m_pastSurface, &m_futureSurface}; for (auto surfaces : surfacesArray) { while (!surfaces->empty()) { auto p = surfaces->back(); m_vpInterface.GetAllocator().DestroyVpSurface(p); surfaces->pop_back(); } } m_linkedLayerIndex.clear(); m_isExePipe = false; return MOS_STATUS_SUCCESS; } bool SwFilterPipe::IsEmpty() { VP_FUNC_CALL(); for (auto pipe : m_InputPipes) { if (!pipe->IsEmpty()) { return false; } } for (auto pipe : m_OutputPipes) { if (!pipe->IsEmpty()) { return false; } } return true; } bool SwFilterPipe::IsPrimaryEmpty() { VP_FUNC_CALL(); uint32_t index; auto pipe = GetSwFilterPrimaryPipe(index); if (pipe->IsEmpty()) { return true; } return false; } MOS_STATUS SwFilterPipe::ConfigFeaturesToPipe(VP_PIPELINE_PARAMS &params, FeatureRule &featureRule, bool isInputPipe) { VP_FUNC_CALL(); std::vector<SwFilterSubPipe *> &pipes = isInputPipe ? m_InputPipes : m_OutputPipes; std::vector<FeatureSubRule> &rulePipes = isInputPipe ? featureRule.m_InputPipes : featureRule.m_OutputPipes; SwFilter *swFilter = nullptr; // Loop all input surfaces. for (uint32_t pipeIndex = 0; pipeIndex < pipes.size(); ++pipeIndex) { // Get a copy list for feature handler. auto featureHander = *m_vpInterface.GetSwFilterHandlerMap(); if (pipeIndex < rulePipes.size()) { auto &featurePipe = rulePipes[pipeIndex]; for (auto &featureSet : featurePipe.m_Rule) { // Loop orderred feature set. bool useNewSwFilterSet = true; for (auto &feature : featureSet.m_Features) { // Loop all features in feature set. SwFilterFeatureHandler *handler = featureHander.find(feature)->second; VP_PUBLIC_CHK_NULL_RETURN(handler); VP_PUBLIC_CHK_STATUS_RETURN(handler->CreateSwFilter(swFilter, params, isInputPipe, pipeIndex, m_swFilterPipeType)); if (swFilter) { VP_PUBLIC_CHK_STATUS_RETURN(AddSwFilterOrdered(swFilter, isInputPipe, pipeIndex, useNewSwFilterSet)); featureHander.erase(feature); useNewSwFilterSet = false; } // nullptr == swFilter means no such feature in params, which is also the valid case. } } } // Process remaining unordered features for (auto &handler : featureHander) { VP_PUBLIC_CHK_STATUS_RETURN(handler.second->CreateSwFilter(swFilter, params, isInputPipe, pipeIndex, m_swFilterPipeType)); if (swFilter) { VP_PUBLIC_CHK_STATUS_RETURN(AddSwFilterUnordered(swFilter, isInputPipe, pipeIndex)); } } } return MOS_STATUS_SUCCESS; } MOS_STATUS SwFilterPipe::ConfigFeatures(VP_PIPELINE_PARAMS &params, FeatureRule &featureRule) { VP_FUNC_CALL(); MOS_STATUS status1 = ConfigFeaturesToPipe(params, featureRule, true); MOS_STATUS status2 = ConfigFeaturesToPipe(params, featureRule, false); // Return the status for the failure one. return MOS_STATUS_SUCCESS == status1 ? status2 : status1; } MOS_STATUS SwFilterPipe::ConfigFeatures(VEBOX_SFC_PARAMS &params) { VP_FUNC_CALL(); std::vector<SwFilterSubPipe *> &pipes = m_InputPipes; SwFilter *swFilter = nullptr; // Loop all input surfaces. for (uint32_t pipeIndex = 0; pipeIndex < pipes.size(); ++pipeIndex) { auto featureHander = m_vpInterface.GetSwFilterHandlerMap(); // Process remaining unordered features if (featureHander) { for (auto handler = featureHander->begin(); handler != featureHander->end(); handler++) { VP_PUBLIC_CHK_STATUS_RETURN(handler->second->CreateSwFilter(swFilter, params)); if (swFilter) { VP_PUBLIC_CHK_STATUS_RETURN(AddSwFilterUnordered(swFilter, true, 0)); } } } else { VP_PUBLIC_ASSERTMESSAGE("No VP Feature Manager Created"); return MOS_STATUS_UNIMPLEMENTED; } } return MOS_STATUS_SUCCESS; } MOS_STATUS SwFilterPipe::UpdateFeatures(bool isInputPipe, uint32_t pipeIndex, VP_EXECUTE_CAPS *caps) { VP_FUNC_CALL(); auto &pipes = isInputPipe ? m_InputPipes : m_OutputPipes; auto &surfaces = isInputPipe ? m_InputSurfaces : m_OutputSurfaces; if (pipeIndex >= pipes.size() || pipeIndex >= surfaces.size() || 0 == m_OutputPipes.size() || m_InputPipes.size() != m_InputSurfaces.size() || m_OutputPipes.size() != m_OutputSurfaces.size()) { return MOS_STATUS_INVALID_PARAMETER; } // Always use index 0 for the pipe whose pipeIndex not being specified. auto inputPipe = isInputPipe ? m_InputPipes[pipeIndex] : (m_InputPipes.size() > 0 ? m_InputPipes[0] : nullptr); auto outputPipe = isInputPipe ? m_OutputPipes[0] : m_OutputPipes[pipeIndex]; auto inputSurf = isInputPipe ? m_InputSurfaces[pipeIndex] : (m_InputSurfaces.size() > 0 ? m_InputSurfaces[0] : nullptr); auto outputSurf = isInputPipe ? m_OutputSurfaces[0] : m_OutputSurfaces[pipeIndex]; if (nullptr == outputPipe || nullptr == outputSurf) { return MOS_STATUS_INVALID_PARAMETER; } // Input surface/pipe may be empty for some feature. if (inputPipe) { if (caps && caps->bComposite) { // Always keep csc filter in fc pipe. The csc filter for multi-pass intermediate surface case will be added here. if (nullptr == inputPipe->GetSwFilter(FeatureTypeCsc)) { auto handler = m_vpInterface.GetSwFilterHandler(FeatureTypeCsc); VP_PUBLIC_CHK_NULL_RETURN(handler); SwFilterCsc* swfilter = dynamic_cast<SwFilterCsc *>(handler->CreateSwFilter()); swfilter->Configure(inputSurf, outputSurf, *caps); inputPipe->AddSwFilterUnordered(swfilter); } } VP_PUBLIC_CHK_STATUS_RETURN(inputPipe->Update(inputSurf, outputSurf)); } VP_PUBLIC_CHK_STATUS_RETURN(outputPipe->Update(inputSurf, outputSurf)); return MOS_STATUS_SUCCESS; } MOS_STATUS SwFilterPipe::CleanFeaturesFromPipe(bool isInputPipe, uint32_t index) { VP_FUNC_CALL(); MOS_STATUS status = MOS_STATUS_SUCCESS; std::vector<SwFilterSubPipe *> &pipes = isInputPipe ? m_InputPipes : m_OutputPipes; if (index < pipes.size() && pipes[index]) { return pipes[index]->Clean(); } return MOS_STATUS_INVALID_PARAMETER; } MOS_STATUS SwFilterPipe::CleanFeaturesFromPipe(bool isInputPipe) { VP_FUNC_CALL(); MOS_STATUS status = MOS_STATUS_SUCCESS; std::vector<SwFilterSubPipe *> &pipes = isInputPipe ? m_InputPipes : m_OutputPipes; for (uint32_t pipeIndex = 0; pipeIndex < pipes.size(); ++pipeIndex) { MOS_STATUS tmpStat = CleanFeaturesFromPipe(isInputPipe, pipeIndex); if (MOS_FAILED(tmpStat)) { VP_PUBLIC_ASSERTMESSAGE("CleanFeaturesFromPipe failed for pipe %d with status = %08x.", pipeIndex, tmpStat); // Always record first failure. status = MOS_FAILED(status) ? status : tmpStat; } } // Do not clear pipe here since it should align with m_InputSurfaces/m_OutputSurfaces. return status; } MOS_STATUS SwFilterPipe::CleanFeatures() { VP_FUNC_CALL(); MOS_STATUS status1 = CleanFeaturesFromPipe(true); MOS_STATUS status2 = CleanFeaturesFromPipe(false); // Return the status for the failure one. return MOS_STATUS_SUCCESS == status1 ? status2 : status1; } SwFilter *SwFilterPipe::GetSwFilter(bool isInputPipe, int index, FeatureType type) { VP_FUNC_CALL(); SwFilterSubPipe * pipe = GetSwFilterSubPipe(isInputPipe, index); if (nullptr == pipe) { VP_PUBLIC_ASSERTMESSAGE("Invalid parameter! No sub pipe exists!"); return nullptr; } return pipe->GetSwFilter(type); } SwFilterSubPipe* SwFilterPipe::GetSwFilterSubPipe(bool isInputPipe, int index) { VP_FUNC_CALL(); SwFilterSubPipe* pSubPipe = nullptr; auto& pipes = isInputPipe ? m_InputPipes : m_OutputPipes; if ((uint32_t)index < pipes.size()) { pSubPipe = pipes[index]; } return pSubPipe; } SwFilterSubPipe* SwFilterPipe::GetSwFilterPrimaryPipe(uint32_t& index) { VP_FUNC_CALL(); SwFilterSubPipe* pSubPipe = nullptr; index = 0; if (m_InputPipes.size() == 0) { return nullptr; } for (auto item : m_InputSurfaces) { if (item->SurfType == SURF_IN_PRIMARY) { pSubPipe = m_InputPipes[index]; return pSubPipe; } ++index; } return pSubPipe; } // useNewSwFilterSet: true if insert new swFilterSet in pipe, otherwise, reuse the last one in pipe. MOS_STATUS SwFilterPipe::AddSwFilterOrdered(SwFilter *swFilter, bool isInputPipe, int index, bool useNewSwFilterSet) { VP_FUNC_CALL(); VP_PUBLIC_CHK_NULL_RETURN(swFilter); SwFilterSubPipe *pSubPipe = GetSwFilterSubPipe(isInputPipe, index); VP_PUBLIC_CHK_NULL_RETURN(pSubPipe); VP_PUBLIC_CHK_STATUS_RETURN(pSubPipe->AddSwFilterOrdered(swFilter, useNewSwFilterSet)); swFilter->SetExePipeFlag(m_isExePipe); return MOS_STATUS_SUCCESS; } MOS_STATUS SwFilterPipe::AddSwFilterUnordered(SwFilter *swFilter, bool isInputPipe, int index) { VP_FUNC_CALL(); VP_PUBLIC_CHK_NULL_RETURN(swFilter); SwFilterSubPipe *pSubPipe = GetSwFilterSubPipe(isInputPipe, index); if (nullptr == pSubPipe && !isInputPipe) { auto& pipes = isInputPipe ? m_InputPipes : m_OutputPipes; SwFilterSubPipe *pipe = MOS_New(SwFilterSubPipe); VP_PUBLIC_CHK_NULL_RETURN(pipe); if ((size_t)index <= pipes.size()) { for (int32_t i = (int)pipes.size(); i <= index; ++i) { pipes.push_back(nullptr); } } pipes[index] = pipe; pSubPipe = GetSwFilterSubPipe(isInputPipe, index); } VP_PUBLIC_CHK_NULL_RETURN(pSubPipe); VP_PUBLIC_CHK_STATUS_RETURN(pSubPipe->AddSwFilterUnordered(swFilter)); swFilter->SetExePipeFlag(m_isExePipe); return MOS_STATUS_SUCCESS; } MOS_STATUS SwFilterPipe::RemoveSwFilter(SwFilter *swFilter) { VP_FUNC_CALL(); VP_PUBLIC_CHK_NULL_RETURN(swFilter); SwFilterSet *swFilterSet = swFilter->GetLocation(); VP_PUBLIC_CHK_NULL_RETURN(swFilterSet); VP_PUBLIC_CHK_STATUS_RETURN(swFilterSet->RemoveSwFilter(swFilter)); // Delete swFilterSet if needed. auto pipe = swFilterSet->GetLocation(); if (pipe && swFilterSet->IsEmpty()) { for (auto it = pipe->begin(); it != pipe->end(); ++it) { if (*it == swFilterSet) { pipe->erase(it); break; } } swFilterSet->SetLocation(nullptr); MOS_Delete(swFilterSet); } return MOS_STATUS_SUCCESS; } VP_SURFACE *SwFilterPipe::GetSurface(bool isInputSurface, uint32_t index) { VP_FUNC_CALL(); if (isInputSurface) { return index < m_InputSurfaces.size() ? m_InputSurfaces[index] : nullptr; } else { return index < m_OutputSurfaces.size() ? m_OutputSurfaces[index] : nullptr; } } VP_SURFACE *SwFilterPipe::GetPastSurface(uint32_t index) { VP_FUNC_CALL(); return index < m_pastSurface.size() ? m_pastSurface[index] : nullptr; } VP_SURFACE *SwFilterPipe::GetFutureSurface(uint32_t index) { VP_FUNC_CALL(); return index < m_futureSurface.size() ? m_futureSurface[index] : nullptr; } MOS_STATUS SwFilterPipe::SetPastSurface(uint32_t index, VP_SURFACE *surf) { VP_FUNC_CALL(); if (index >= m_pastSurface.size()) { return MOS_STATUS_INVALID_PARAMETER; } m_pastSurface[index] = surf; return MOS_STATUS_SUCCESS; } MOS_STATUS SwFilterPipe::SetFutureSurface(uint32_t index, VP_SURFACE *surf) { VP_FUNC_CALL(); if (index >= m_futureSurface.size()) { return MOS_STATUS_INVALID_PARAMETER; } m_futureSurface[index] = surf; return MOS_STATUS_SUCCESS; } VP_SURFACE *SwFilterPipe::RemovePastSurface(uint32_t index) { VP_FUNC_CALL(); if (index >= m_pastSurface.size()) { return nullptr; } VP_SURFACE *surf = m_pastSurface[index]; m_pastSurface[index] = nullptr; return surf; } VP_SURFACE *SwFilterPipe::RemoveFutureSurface(uint32_t index) { VP_FUNC_CALL(); if (index >= m_futureSurface.size()) { return nullptr; } VP_SURFACE *surf = m_futureSurface[index]; m_futureSurface[index] = nullptr; return surf; } MOS_STATUS SwFilterPipe::DestroySurface(bool isInputSurface, uint32_t index) { VP_SURFACE *surf = SwFilterPipe::RemoveSurface(isInputSurface, index); VP_PUBLIC_CHK_NULL_RETURN(surf); m_vpInterface.GetAllocator().DestroyVpSurface(surf); return MOS_STATUS_SUCCESS; } VP_SURFACE *SwFilterPipe::RemoveSurface(bool isInputSurface, uint32_t index) { VP_FUNC_CALL(); auto &surfaces = isInputSurface ? m_InputSurfaces : m_OutputSurfaces; if (index < surfaces.size()) { VP_SURFACE *surf = surfaces[index]; surfaces[index] = nullptr; if (isInputSurface) { // Keep m_pastSurface and m_futureSurface same status as m_InputSurfaces. if (m_pastSurface[index]) { m_vpInterface.GetAllocator().DestroyVpSurface(m_pastSurface[index]); } if (m_futureSurface[index]) { m_vpInterface.GetAllocator().DestroyVpSurface(m_futureSurface[index]); } if (m_linkedLayerIndex[index]) { m_linkedLayerIndex[index] = 0; } } return surf; } return nullptr; } VP_SURFACE *SwFilterPipe::ReplaceSurface(VP_SURFACE *surf, bool isInputSurface, uint32_t index) { VP_FUNC_CALL(); auto &surfaces = isInputSurface ? m_InputSurfaces : m_OutputSurfaces; if (index < surfaces.size()) { VP_SURFACE *ret = surfaces[index]; surfaces[index] = surf; return ret; } return nullptr; } MOS_STATUS SwFilterPipe::AddSurface(VP_SURFACE *&surf, bool isInputSurface, uint32_t index) { VP_FUNC_CALL(); auto &surfaces = isInputSurface ? m_InputSurfaces : m_OutputSurfaces; auto &pipes = isInputSurface ? m_InputPipes : m_OutputPipes; for (uint32_t i = surfaces.size(); i <= index; ++i) { surfaces.push_back(nullptr); if (isInputSurface) { // Keep m_PastSurface same size as m_InputSurfaces. m_pastSurface.push_back(nullptr); m_futureSurface.push_back(nullptr); m_linkedLayerIndex.push_back(0); } } if (index >= surfaces.size()) { return MOS_STATUS_INVALID_PARAMETER; } if (nullptr != surfaces[index]) { return MOS_STATUS_INVALID_PARAMETER; } for (uint32_t i = pipes.size(); i <= index; ++i) { pipes.push_back(nullptr); } if (index >= surfaces.size()) { return MOS_STATUS_INVALID_PARAMETER; } if (nullptr == pipes[index]) { SwFilterSubPipe *pipe = MOS_New(SwFilterSubPipe); VP_PUBLIC_CHK_NULL_RETURN(pipe); pipes[index] = pipe; } surfaces[index] = surf; return MOS_STATUS_SUCCESS; } template<class T> MOS_STATUS RemoveUnusedLayers(std::vector<uint32_t> &indexForRemove, std::vector<T> &layers) { VP_FUNC_CALL(); if (indexForRemove.size() == 0) { return MOS_STATUS_SUCCESS; } if (sizeof(T) < sizeof(int)) { VP_PUBLIC_CHK_STATUS_RETURN(MOS_STATUS_INVALID_PARAMETER); } const int keyForDelete = 0xabcdabcd; for (uint32_t index : indexForRemove) { if (index >= layers.size()) { VP_PUBLIC_CHK_STATUS_RETURN(MOS_STATUS_INVALID_PARAMETER); } // Mark the items to be removed. *(int *)&layers[index] = keyForDelete; } for (auto it = layers.begin(); it != layers.end();) { if (keyForDelete == *(int *)&(*it)) { it = layers.erase(it); } else { ++it; } } return MOS_STATUS_SUCCESS; } template<class T> MOS_STATUS RemoveUnusedLayers(std::vector<uint32_t> &indexForRemove, std::vector<T*> &layers, bool freeObj) { VP_FUNC_CALL(); if (indexForRemove.size() == 0) { return MOS_STATUS_SUCCESS; } if (freeObj) { std::map<T*, T*> objForRemove; for (uint32_t index : indexForRemove) { if (index >= layers.size()) { VP_PUBLIC_CHK_STATUS_RETURN(MOS_STATUS_INVALID_PARAMETER); } objForRemove.insert(std::make_pair(layers[index], layers[index])); layers[index] = nullptr; } for (auto it : objForRemove) { MOS_Delete(it.second); } } return RemoveUnusedLayers(indexForRemove, layers); } MOS_STATUS SwFilterPipe::RemoveUnusedLayers(bool bUpdateInput) { VP_FUNC_CALL(); // If bUpdateInput == true, surfaces1 is input layers, which will be updated, and surfaces2 is output layers, // otherwise, surfaces1 is output layers, which will be updated, and surfaces2 is input layers. auto &surfaces1 = bUpdateInput ? m_InputSurfaces : m_OutputSurfaces; auto &surfaces2 = !bUpdateInput ? m_InputSurfaces : m_OutputSurfaces; auto &pipes = bUpdateInput ? m_InputPipes : m_OutputPipes; std::vector<uint32_t> indexForRemove; uint32_t i = 0; for (i = 0; i < surfaces1.size(); ++i) { if (nullptr == surfaces1[i] || 0 == surfaces2.size() || 1 == surfaces2.size() && nullptr == surfaces2[0]) { indexForRemove.push_back(i); CleanFeaturesFromPipe(bUpdateInput, i); } } VP_PUBLIC_CHK_STATUS_RETURN(::RemoveUnusedLayers(indexForRemove, surfaces1, false)); if (bUpdateInput) { // Keep m_pastSurface same size as m_InputSurfaces. VP_PUBLIC_CHK_STATUS_RETURN(::RemoveUnusedLayers(indexForRemove, m_pastSurface, false)); // Keep m_futureSurface same size as m_InputSurfaces. VP_PUBLIC_CHK_STATUS_RETURN(::RemoveUnusedLayers(indexForRemove, m_futureSurface, false)); // Keep m_linkedLayerIndex same size as m_InputSurfaces. VP_PUBLIC_CHK_STATUS_RETURN(::RemoveUnusedLayers(indexForRemove, m_linkedLayerIndex)); } VP_PUBLIC_CHK_STATUS_RETURN(::RemoveUnusedLayers(indexForRemove, pipes, true)); return MOS_STATUS_SUCCESS; } MOS_STATUS SwFilterPipe::Update(VP_EXECUTE_CAPS *caps) { VP_FUNC_CALL(); uint32_t i = 0; VP_PUBLIC_CHK_STATUS_RETURN(RemoveUnusedLayers(true)); VP_PUBLIC_CHK_STATUS_RETURN(RemoveUnusedLayers(false)); for (i = 0; i < m_InputPipes.size(); ++i) { VP_PUBLIC_CHK_STATUS_RETURN(UpdateFeatures(true, i, caps)); } for (i = 0; i < m_OutputPipes.size(); ++i) { VP_PUBLIC_CHK_STATUS_RETURN(UpdateFeatures(false, i)); } UpdateSwFilterPipeType(); return MOS_STATUS_SUCCESS; } uint32_t SwFilterPipe::GetSurfaceCount(bool isInputSurface) { VP_FUNC_CALL(); return isInputSurface ? m_InputSurfaces.size() : m_OutputSurfaces.size(); } bool SwFilterPipe::IsAllInputPipeEmpty() { for (uint32_t i = 0; i < GetSurfaceCount(true); ++i) { SwFilterSubPipe *inputPipe = GetSwFilterSubPipe(true, i); if (inputPipe && !inputPipe->IsEmpty()) { return false; } } return true; } bool SwFilterPipe::IsAllInputPipeSurfaceFeatureEmpty() { for (uint32_t i = 0; i < GetSurfaceCount(true); ++i) { SwFilterSubPipe *inputPipe = GetSwFilterSubPipe(true, i); if (inputPipe && !inputPipe->IsSurfaceFeatureEmpty()) { return false; } } return true; } bool SwFilterPipe::IsAllInputPipeSurfaceFeatureEmpty(std::vector<int> &layerIndexes) { for (uint32_t i = 0; i < layerIndexes.size(); ++i) { uint32_t executedIndex = layerIndexes[i]; SwFilterSubPipe *inputPipe = GetSwFilterSubPipe(true, executedIndex); if (inputPipe && !inputPipe->IsSurfaceFeatureEmpty()) { return false; } } return true; }
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "precomp.hpp" #if !defined (HAVE_CUDA) || defined (CUDA_DISABLER) cv::cuda::HOGDescriptor::HOGDescriptor(Size, Size, Size, Size, int, double, double, bool, int) { throw_no_cuda(); } size_t cv::cuda::HOGDescriptor::getDescriptorSize() const { throw_no_cuda(); return 0; } size_t cv::cuda::HOGDescriptor::getBlockHistogramSize() const { throw_no_cuda(); return 0; } double cv::cuda::HOGDescriptor::getWinSigma() const { throw_no_cuda(); return 0; } bool cv::cuda::HOGDescriptor::checkDetectorSize() const { throw_no_cuda(); return false; } void cv::cuda::HOGDescriptor::setSVMDetector(const std::vector<float>&) { throw_no_cuda(); } void cv::cuda::HOGDescriptor::detect(const GpuMat&, std::vector<Point>&, double, Size, Size) { throw_no_cuda(); } void cv::cuda::HOGDescriptor::detectMultiScale(const GpuMat&, std::vector<Rect>&, double, Size, Size, double, int) { throw_no_cuda(); } void cv::cuda::HOGDescriptor::computeBlockHistograms(const GpuMat&) { throw_no_cuda(); } void cv::cuda::HOGDescriptor::getDescriptors(const GpuMat&, Size, GpuMat&, int) { throw_no_cuda(); } std::vector<float> cv::cuda::HOGDescriptor::getDefaultPeopleDetector() { throw_no_cuda(); return std::vector<float>(); } std::vector<float> cv::cuda::HOGDescriptor::getPeopleDetector48x96() { throw_no_cuda(); return std::vector<float>(); } std::vector<float> cv::cuda::HOGDescriptor::getPeopleDetector64x128() { throw_no_cuda(); return std::vector<float>(); } void cv::cuda::HOGDescriptor::computeConfidence(const GpuMat&, std::vector<Point>&, double, Size, Size, std::vector<Point>&, std::vector<double>&) { throw_no_cuda(); } void cv::cuda::HOGDescriptor::computeConfidenceMultiScale(const GpuMat&, std::vector<Rect>&, double, Size, Size, std::vector<HOGConfidence>&, int) { throw_no_cuda(); } #else namespace cv { namespace cuda { namespace device { namespace hog { void set_up_constants(int nbins, int block_stride_x, int block_stride_y, int nblocks_win_x, int nblocks_win_y); void compute_hists(int nbins, int block_stride_x, int blovck_stride_y, int height, int width, const cv::cuda::PtrStepSzf& grad, const cv::cuda::PtrStepSzb& qangle, float sigma, float* block_hists); void normalize_hists(int nbins, int block_stride_x, int block_stride_y, int height, int width, float* block_hists, float threshold); void classify_hists(int win_height, int win_width, int block_stride_y, int block_stride_x, int win_stride_y, int win_stride_x, int height, int width, float* block_hists, float* coefs, float free_coef, float threshold, unsigned char* labels); void compute_confidence_hists(int win_height, int win_width, int block_stride_y, int block_stride_x, int win_stride_y, int win_stride_x, int height, int width, float* block_hists, float* coefs, float free_coef, float threshold, float *confidences); void extract_descrs_by_rows(int win_height, int win_width, int block_stride_y, int block_stride_x, int win_stride_y, int win_stride_x, int height, int width, float* block_hists, cv::cuda::PtrStepSzf descriptors); void extract_descrs_by_cols(int win_height, int win_width, int block_stride_y, int block_stride_x, int win_stride_y, int win_stride_x, int height, int width, float* block_hists, cv::cuda::PtrStepSzf descriptors); void compute_gradients_8UC1(int nbins, int height, int width, const cv::cuda::PtrStepSzb& img, float angle_scale, cv::cuda::PtrStepSzf grad, cv::cuda::PtrStepSzb qangle, bool correct_gamma); void compute_gradients_8UC4(int nbins, int height, int width, const cv::cuda::PtrStepSzb& img, float angle_scale, cv::cuda::PtrStepSzf grad, cv::cuda::PtrStepSzb qangle, bool correct_gamma); void resize_8UC1(const cv::cuda::PtrStepSzb& src, cv::cuda::PtrStepSzb dst); void resize_8UC4(const cv::cuda::PtrStepSzb& src, cv::cuda::PtrStepSzb dst); } }}} using namespace ::cv::cuda::device; cv::cuda::HOGDescriptor::HOGDescriptor(Size win_size_, Size block_size_, Size block_stride_, Size cell_size_, int nbins_, double win_sigma_, double threshold_L2hys_, bool gamma_correction_, int nlevels_) : win_size(win_size_), block_size(block_size_), block_stride(block_stride_), cell_size(cell_size_), nbins(nbins_), win_sigma(win_sigma_), threshold_L2hys(threshold_L2hys_), gamma_correction(gamma_correction_), nlevels(nlevels_) { CV_Assert((win_size.width - block_size.width ) % block_stride.width == 0 && (win_size.height - block_size.height) % block_stride.height == 0); CV_Assert(block_size.width % cell_size.width == 0 && block_size.height % cell_size.height == 0); CV_Assert(block_stride == cell_size); CV_Assert(cell_size == Size(8, 8)); Size cells_per_block = Size(block_size.width / cell_size.width, block_size.height / cell_size.height); CV_Assert(cells_per_block == Size(2, 2)); cv::Size blocks_per_win = numPartsWithin(win_size, block_size, block_stride); hog::set_up_constants(nbins, block_stride.width, block_stride.height, blocks_per_win.width, blocks_per_win.height); } size_t cv::cuda::HOGDescriptor::getDescriptorSize() const { return numPartsWithin(win_size, block_size, block_stride).area() * getBlockHistogramSize(); } size_t cv::cuda::HOGDescriptor::getBlockHistogramSize() const { Size cells_per_block = Size(block_size.width / cell_size.width, block_size.height / cell_size.height); return (size_t)(nbins * cells_per_block.area()); } double cv::cuda::HOGDescriptor::getWinSigma() const { return win_sigma >= 0 ? win_sigma : (block_size.width + block_size.height) / 8.0; } bool cv::cuda::HOGDescriptor::checkDetectorSize() const { size_t detector_size = detector.rows * detector.cols; size_t descriptor_size = getDescriptorSize(); return detector_size == 0 || detector_size == descriptor_size || detector_size == descriptor_size + 1; } void cv::cuda::HOGDescriptor::setSVMDetector(const std::vector<float>& _detector) { std::vector<float> detector_reordered(_detector.size()); size_t block_hist_size = getBlockHistogramSize(); cv::Size blocks_per_img = numPartsWithin(win_size, block_size, block_stride); for (int i = 0; i < blocks_per_img.height; ++i) for (int j = 0; j < blocks_per_img.width; ++j) { const float* src = &_detector[0] + (j * blocks_per_img.height + i) * block_hist_size; float* dst = &detector_reordered[0] + (i * blocks_per_img.width + j) * block_hist_size; for (size_t k = 0; k < block_hist_size; ++k) dst[k] = src[k]; } this->detector.upload(Mat(detector_reordered).reshape(1, 1)); size_t descriptor_size = getDescriptorSize(); free_coef = _detector.size() > descriptor_size ? _detector[descriptor_size] : 0; CV_Assert(checkDetectorSize()); } cv::cuda::GpuMat cv::cuda::HOGDescriptor::getBuffer(const Size& sz, int type, GpuMat& buf) { if (buf.empty() || buf.type() != type) buf.create(sz, type); else if (buf.cols < sz.width || buf.rows < sz.height) buf.create(std::max(buf.rows, sz.height), std::max(buf.cols, sz.width), type); return buf(Rect(Point(0,0), sz)); } cv::cuda::GpuMat cv::cuda::HOGDescriptor::getBuffer(int rows, int cols, int type, GpuMat& buf) { return getBuffer(Size(cols, rows), type, buf); } void cv::cuda::HOGDescriptor::computeGradient(const GpuMat& img, GpuMat& _grad, GpuMat& _qangle) { CV_Assert(img.type() == CV_8UC1 || img.type() == CV_8UC4); // grad.create(img.size(), CV_32FC2); _grad = getBuffer(img.size(), CV_32FC2, grad_buf); // qangle.create(img.size(), CV_8UC2); _qangle = getBuffer(img.size(), CV_8UC2, qangle_buf); float angleScale = (float)(nbins / CV_PI); switch (img.type()) { case CV_8UC1: hog::compute_gradients_8UC1(nbins, img.rows, img.cols, img, angleScale, _grad, _qangle, gamma_correction); break; case CV_8UC4: hog::compute_gradients_8UC4(nbins, img.rows, img.cols, img, angleScale, _grad, _qangle, gamma_correction); break; } } void cv::cuda::HOGDescriptor::computeBlockHistograms(const GpuMat& img) { computeGradient(img, grad, qangle); size_t block_hist_size = getBlockHistogramSize(); Size blocks_per_img = numPartsWithin(img.size(), block_size, block_stride); // block_hists.create(1, block_hist_size * blocks_per_img.area(), CV_32F); block_hists = getBuffer(1, static_cast<int>(block_hist_size * blocks_per_img.area()), CV_32F, block_hists_buf); hog::compute_hists(nbins, block_stride.width, block_stride.height, img.rows, img.cols, grad, qangle, (float)getWinSigma(), block_hists.ptr<float>()); hog::normalize_hists(nbins, block_stride.width, block_stride.height, img.rows, img.cols, block_hists.ptr<float>(), (float)threshold_L2hys); } void cv::cuda::HOGDescriptor::getDescriptors(const GpuMat& img, Size win_stride, GpuMat& descriptors, int descr_format) { CV_Assert(win_stride.width % block_stride.width == 0 && win_stride.height % block_stride.height == 0); computeBlockHistograms(img); const size_t block_hist_size = getBlockHistogramSize(); Size blocks_per_win = numPartsWithin(win_size, block_size, block_stride); Size wins_per_img = numPartsWithin(img.size(), win_size, win_stride); descriptors.create(wins_per_img.area(), static_cast<int>(blocks_per_win.area() * block_hist_size), CV_32F); switch (descr_format) { case DESCR_FORMAT_ROW_BY_ROW: hog::extract_descrs_by_rows(win_size.height, win_size.width, block_stride.height, block_stride.width, win_stride.height, win_stride.width, img.rows, img.cols, block_hists.ptr<float>(), descriptors); break; case DESCR_FORMAT_COL_BY_COL: hog::extract_descrs_by_cols(win_size.height, win_size.width, block_stride.height, block_stride.width, win_stride.height, win_stride.width, img.rows, img.cols, block_hists.ptr<float>(), descriptors); break; default: CV_Error(cv::Error::StsBadArg, "Unknown descriptor format"); } } void cv::cuda::HOGDescriptor::computeConfidence(const GpuMat& img, std::vector<Point>& hits, double hit_threshold, Size win_stride, Size padding, std::vector<Point>& locations, std::vector<double>& confidences) { CV_Assert(padding == Size(0, 0)); hits.clear(); if (detector.empty()) return; computeBlockHistograms(img); if (win_stride == Size()) win_stride = block_stride; else CV_Assert(win_stride.width % block_stride.width == 0 && win_stride.height % block_stride.height == 0); Size wins_per_img = numPartsWithin(img.size(), win_size, win_stride); labels.create(1, wins_per_img.area(), CV_32F); hog::compute_confidence_hists(win_size.height, win_size.width, block_stride.height, block_stride.width, win_stride.height, win_stride.width, img.rows, img.cols, block_hists.ptr<float>(), detector.ptr<float>(), (float)free_coef, (float)hit_threshold, labels.ptr<float>()); labels.download(labels_host); float* vec = labels_host.ptr<float>(); // does not support roi for now.. locations.clear(); confidences.clear(); for (int i = 0; i < wins_per_img.area(); i++) { int y = i / wins_per_img.width; int x = i - wins_per_img.width * y; if (vec[i] >= hit_threshold) hits.push_back(Point(x * win_stride.width, y * win_stride.height)); Point pt(win_stride.width * x, win_stride.height * y); locations.push_back(pt); confidences.push_back((double)vec[i]); } } void cv::cuda::HOGDescriptor::computeConfidenceMultiScale(const GpuMat& img, std::vector<Rect>& found_locations, double hit_threshold, Size win_stride, Size padding, std::vector<HOGConfidence> &conf_out, int group_threshold) { std::vector<double> level_scale; double scale = 1.; int levels = 0; for (levels = 0; levels < (int)conf_out.size(); levels++) { scale = conf_out[levels].scale; level_scale.push_back(scale); if (cvRound(img.cols/scale) < win_size.width || cvRound(img.rows/scale) < win_size.height) break; } levels = std::max(levels, 1); level_scale.resize(levels); std::vector<Rect> all_candidates; std::vector<Point> locations; for (size_t i = 0; i < level_scale.size(); i++) { scale = level_scale[i]; Size sz(cvRound(img.cols / scale), cvRound(img.rows / scale)); GpuMat smaller_img; if (sz == img.size()) smaller_img = img; else { smaller_img.create(sz, img.type()); switch (img.type()) { case CV_8UC1: hog::resize_8UC1(img, smaller_img); break; case CV_8UC4: hog::resize_8UC4(img, smaller_img); break; } } computeConfidence(smaller_img, locations, hit_threshold, win_stride, padding, conf_out[i].locations, conf_out[i].confidences); Size scaled_win_size(cvRound(win_size.width * scale), cvRound(win_size.height * scale)); for (size_t j = 0; j < locations.size(); j++) all_candidates.push_back(Rect(Point2d(locations[j]) * scale, scaled_win_size)); } found_locations.assign(all_candidates.begin(), all_candidates.end()); groupRectangles(found_locations, group_threshold, 0.2/*magic number copied from CPU version*/); } void cv::cuda::HOGDescriptor::detect(const GpuMat& img, std::vector<Point>& hits, double hit_threshold, Size win_stride, Size padding) { CV_Assert(img.type() == CV_8UC1 || img.type() == CV_8UC4); CV_Assert(padding == Size(0, 0)); hits.clear(); if (detector.empty()) return; computeBlockHistograms(img); if (win_stride == Size()) win_stride = block_stride; else CV_Assert(win_stride.width % block_stride.width == 0 && win_stride.height % block_stride.height == 0); Size wins_per_img = numPartsWithin(img.size(), win_size, win_stride); // labels.create(1, wins_per_img.area(), CV_8U); labels = getBuffer(1, wins_per_img.area(), CV_8U, labels_buf); hog::classify_hists(win_size.height, win_size.width, block_stride.height, block_stride.width, win_stride.height, win_stride.width, img.rows, img.cols, block_hists.ptr<float>(), detector.ptr<float>(), (float)free_coef, (float)hit_threshold, labels.ptr()); labels.download(labels_host); unsigned char* vec = labels_host.ptr(); for (int i = 0; i < wins_per_img.area(); i++) { int y = i / wins_per_img.width; int x = i - wins_per_img.width * y; if (vec[i]) hits.push_back(Point(x * win_stride.width, y * win_stride.height)); } } void cv::cuda::HOGDescriptor::detectMultiScale(const GpuMat& img, std::vector<Rect>& found_locations, double hit_threshold, Size win_stride, Size padding, double scale0, int group_threshold) { CV_Assert(img.type() == CV_8UC1 || img.type() == CV_8UC4); std::vector<double> level_scale; double scale = 1.; int levels = 0; for (levels = 0; levels < nlevels; levels++) { level_scale.push_back(scale); if (cvRound(img.cols/scale) < win_size.width || cvRound(img.rows/scale) < win_size.height || scale0 <= 1) break; scale *= scale0; } levels = std::max(levels, 1); level_scale.resize(levels); image_scales.resize(levels); std::vector<Rect> all_candidates; std::vector<Point> locations; for (size_t i = 0; i < level_scale.size(); i++) { scale = level_scale[i]; Size sz(cvRound(img.cols / scale), cvRound(img.rows / scale)); GpuMat smaller_img; if (sz == img.size()) smaller_img = img; else { image_scales[i].create(sz, img.type()); switch (img.type()) { case CV_8UC1: hog::resize_8UC1(img, image_scales[i]); break; case CV_8UC4: hog::resize_8UC4(img, image_scales[i]); break; } smaller_img = image_scales[i]; } detect(smaller_img, locations, hit_threshold, win_stride, padding); Size scaled_win_size(cvRound(win_size.width * scale), cvRound(win_size.height * scale)); for (size_t j = 0; j < locations.size(); j++) all_candidates.push_back(Rect(Point2d(locations[j]) * scale, scaled_win_size)); } found_locations.assign(all_candidates.begin(), all_candidates.end()); groupRectangles(found_locations, group_threshold, 0.2/*magic number copied from CPU version*/); } int cv::cuda::HOGDescriptor::numPartsWithin(int size, int part_size, int stride) { return (size - part_size + stride) / stride; } cv::Size cv::cuda::HOGDescriptor::numPartsWithin(cv::Size size, cv::Size part_size, cv::Size stride) { return Size(numPartsWithin(size.width, part_size.width, stride.width), numPartsWithin(size.height, part_size.height, stride.height)); } std::vector<float> cv::cuda::HOGDescriptor::getDefaultPeopleDetector() { return getPeopleDetector64x128(); } std::vector<float> cv::cuda::HOGDescriptor::getPeopleDetector48x96() { static const float detector[] = { 0.294350f, -0.098796f, -0.129522f, 0.078753f, 0.387527f, 0.261529f, 0.145939f, 0.061520f, 0.328699f, 0.227148f, -0.066467f, -0.086723f, 0.047559f, 0.106714f, 0.037897f, 0.111461f, -0.024406f, 0.304769f, 0.254676f, -0.069235f, 0.082566f, 0.147260f, 0.326969f, 0.148888f, 0.055270f, -0.087985f, 0.261720f, 0.143442f, 0.026812f, 0.238212f, 0.194020f, 0.056341f, -0.025854f, -0.034444f, -0.156631f, 0.205174f, 0.089008f, -0.139811f, -0.100147f, -0.037830f, -0.029230f, -0.055641f, 0.033248f, -0.016512f, 0.155244f, 0.247315f, -0.124694f, -0.048414f, -0.062219f, 0.193683f, 0.004574f, 0.055089f, 0.093565f, 0.167712f, 0.167581f, 0.018895f, 0.215258f, 0.122609f, 0.090520f, -0.067219f, -0.049029f, -0.099615f, 0.241804f, -0.094893f, -0.176248f, 0.001727f, -0.134473f, 0.104442f, 0.050942f, 0.081165f, 0.072156f, 0.121646f, 0.002656f, -0.297974f, -0.133587f, -0.060121f, -0.092515f, -0.048974f, -0.084754f, -0.180111f, -0.038590f, 0.086283f, -0.134636f, -0.107249f, 0.132890f, 0.141556f, 0.249425f, 0.130273f, -0.030031f, 0.073212f, -0.008155f, 0.019931f, 0.071688f, 0.000300f, -0.019525f, -0.021725f, -0.040993f, -0.086841f, 0.070124f, 0.240033f, 0.265350f, 0.043208f, 0.166754f, 0.091453f, 0.060916f, -0.036972f, -0.091043f, 0.079873f, 0.219781f, 0.158102f, -0.140618f, -0.043016f, 0.124802f, 0.093668f, 0.103208f, 0.094872f, 0.080541f, 0.137711f, 0.160566f, -0.169231f, 0.013983f, 0.309508f, -0.004217f, -0.057200f, -0.064489f, 0.014066f, 0.361009f, 0.251328f, -0.080983f, -0.044183f, 0.061436f, -0.037381f, -0.078786f, 0.030993f, 0.066314f, 0.037683f, 0.152325f, -0.091683f, 0.070203f, 0.217856f, 0.036435f, -0.076462f, 0.006254f, -0.094431f, 0.154829f, -0.023038f, -0.196961f, -0.024594f, 0.178465f, -0.050139f, -0.045932f, -0.000965f, 0.109112f, 0.046165f, -0.159373f, -0.008713f, 0.041307f, 0.097129f, -0.057211f, -0.064599f, 0.077165f, 0.176167f, 0.138322f, 0.065753f, -0.104950f, 0.017933f, 0.136255f, -0.011598f, 0.047007f, 0.080550f, 0.068619f, 0.084661f, -0.035493f, -0.091314f, -0.041411f, 0.060971f, -0.101912f, -0.079870f, -0.085977f, -0.022686f, 0.079788f, -0.098064f, -0.054603f, 0.040383f, 0.300794f, 0.128603f, 0.094844f, 0.047407f, 0.101825f, 0.061832f, -0.162160f, -0.204553f, -0.035165f, 0.101450f, -0.016641f, -0.027140f, -0.134392f, -0.008743f, 0.102331f, 0.114853f, 0.009644f, 0.062823f, 0.237339f, 0.167843f, 0.053066f, -0.012592f, 0.043158f, 0.002305f, 0.065001f, -0.038929f, -0.020356f, 0.152343f, 0.043469f, -0.029967f, -0.042948f, 0.032481f, 0.068488f, -0.110840f, -0.111083f, 0.111980f, -0.002072f, -0.005562f, 0.082926f, 0.006635f, -0.108153f, 0.024242f, -0.086464f, -0.189884f, -0.017492f, 0.191456f, -0.007683f, -0.128769f, -0.038017f, -0.132380f, 0.091926f, 0.079696f, -0.106728f, -0.007656f, 0.172744f, 0.011576f, 0.009883f, 0.083258f, -0.026516f, 0.145534f, 0.153924f, -0.130290f, -0.108945f, 0.124490f, -0.003186f, -0.100485f, 0.015024f, -0.060512f, 0.026288f, -0.086713f, -0.169012f, 0.076517f, 0.215778f, 0.043701f, -0.131642f, -0.012585f, -0.045181f, -0.118183f, -0.241544f, -0.167293f, -0.020107f, -0.019917f, -0.101827f, -0.107096f, -0.010503f, 0.044938f, 0.189680f, 0.217119f, -0.046086f, 0.044508f, 0.199716f, -0.036004f, -0.148927f, 0.013355f, -0.078279f, 0.030451f, 0.056301f, -0.024609f, 0.083224f, 0.099533f, -0.039432f, -0.138880f, 0.005482f, -0.024120f, -0.140468f, -0.066381f, -0.017057f, 0.009260f, -0.058004f, -0.028486f, -0.061610f, 0.007483f, -0.158309f, -0.150687f, -0.044595f, -0.105121f, -0.045763f, -0.006618f, -0.024419f, -0.117713f, -0.119366f, -0.175941f, -0.071542f, 0.119027f, 0.111362f, 0.043080f, 0.034889f, 0.093003f, 0.007842f, 0.057368f, -0.108834f, -0.079968f, 0.230959f, 0.020205f, 0.011470f, 0.098877f, 0.101310f, -0.030215f, -0.018018f, -0.059552f, -0.106157f, 0.021866f, -0.036471f, 0.080051f, 0.041165f, -0.082101f, 0.117726f, 0.030961f, -0.054763f, -0.084102f, -0.185778f, -0.061305f, -0.038089f, -0.110728f, -0.264010f, 0.076675f, -0.077111f, -0.137644f, 0.036232f, 0.277995f, 0.019116f, 0.107738f, 0.144003f, 0.080304f, 0.215036f, 0.228897f, 0.072713f, 0.077773f, 0.120168f, 0.075324f, 0.062730f, 0.122478f, -0.049008f, 0.164912f, 0.162450f, 0.041246f, 0.009891f, -0.097827f, -0.038700f, -0.023027f, -0.120020f, 0.203364f, 0.248474f, 0.149810f, -0.036276f, -0.082814f, -0.090343f, -0.027143f, -0.075689f, -0.320310f, -0.000500f, -0.143334f, -0.065077f, -0.186936f, 0.129372f, 0.116431f, 0.181699f, 0.170436f, 0.418854f, 0.460045f, 0.333719f, 0.230515f, 0.047822f, -0.044954f, -0.068086f, 0.140179f, -0.044821f, 0.085550f, 0.092483f, -0.107296f, -0.130670f, -0.206629f, 0.114601f, -0.317869f, -0.076663f, 0.038680f, 0.212753f, -0.016059f, -0.126526f, -0.163602f, 0.210154f, 0.099887f, -0.126366f, 0.118453f, 0.019309f, -0.021611f, -0.096499f, -0.111809f, -0.200489f, 0.142854f, 0.228840f, -0.353346f, -0.179151f, 0.116834f, 0.252389f, -0.031728f, -0.188135f, -0.158998f, 0.386523f, 0.122315f, 0.209944f, 0.394023f, 0.359030f, 0.260717f, 0.170335f, 0.013683f, -0.142596f, -0.026138f, -0.011878f, -0.150519f, 0.047159f, -0.107062f, -0.147347f, -0.187689f, -0.186027f, -0.208048f, 0.058468f, -0.073026f, -0.236556f, -0.079788f, -0.146216f, -0.058563f, -0.101361f, -0.071294f, -0.071093f, 0.116919f, 0.234304f, 0.306781f, 0.321866f, 0.240000f, 0.073261f, -0.012173f, 0.026479f, 0.050173f, 0.166127f, 0.228955f, 0.061905f, 0.156460f, 0.205990f, 0.120672f, 0.037350f, 0.167884f, 0.290099f, 0.420900f, -0.012601f, 0.189839f, 0.306378f, 0.118383f, -0.095598f, -0.072360f, -0.132496f, -0.224259f, -0.126021f, 0.022714f, 0.284039f, 0.051369f, -0.000927f, -0.058735f, -0.083354f, -0.141254f, -0.187578f, -0.202669f, 0.048902f, 0.246597f, 0.441863f, 0.342519f, 0.066979f, 0.215286f, 0.188191f, -0.072240f, -0.208142f, -0.030196f, 0.178141f, 0.136985f, -0.043374f, -0.181098f, 0.091815f, 0.116177f, -0.126690f, -0.386625f, 0.368165f, 0.269149f, -0.088042f, -0.028823f, 0.092961f, 0.024099f, 0.046112f, 0.176756f, 0.135849f, 0.124955f, 0.195467f, -0.037218f, 0.167217f, 0.188938f, 0.053528f, -0.066561f, 0.133721f, -0.070565f, 0.115898f, 0.152435f, -0.116993f, -0.110592f, -0.179005f, 0.026668f, 0.080530f, 0.075084f, -0.070401f, 0.012497f, 0.021849f, -0.139764f, -0.022020f, -0.096301f, -0.064954f, -0.127446f, -0.013806f, -0.108315f, 0.156285f, 0.149867f, -0.011382f, 0.064532f, 0.029168f, 0.027393f, 0.069716f, 0.153735f, 0.038459f, 0.230714f, 0.253840f, 0.059522f, -0.045053f, 0.014083f, 0.071103f, 0.068747f, 0.095887f, 0.005832f, 0.144887f, 0.026357f, -0.067359f, -0.044151f, -0.123283f, -0.019911f, 0.005318f, 0.109208f, -0.003201f, -0.021734f, 0.142025f, -0.066907f, -0.120070f, -0.188639f, 0.012472f, -0.048704f, -0.012366f, -0.184828f, 0.168591f, 0.267166f, 0.058208f, -0.044101f, 0.033500f, 0.178558f, 0.104550f, 0.122418f, 0.080177f, 0.173246f, 0.298537f, 0.064173f, 0.053397f, 0.174341f, 0.230984f, 0.117025f, 0.166242f, 0.227781f, 0.120623f, 0.176952f, -0.011393f, -0.086483f, -0.008270f, 0.051700f, -0.153369f, -0.058837f, -0.057639f, -0.060115f, 0.026349f, -0.160745f, -0.037894f, -0.048575f, 0.041052f, -0.022112f, 0.060365f, 0.051906f, 0.162657f, 0.138519f, -0.050185f, -0.005938f, 0.071301f, 0.127686f, 0.062342f, 0.144400f, 0.072600f, 0.198436f, 0.246219f, -0.078185f, -0.036169f, 0.075934f, 0.047328f, -0.013601f, 0.087205f, 0.019900f, 0.022606f, -0.015365f, -0.092506f, 0.075275f, -0.116375f, 0.050500f, 0.045118f, 0.166567f, 0.072073f, 0.060371f, 0.131747f, -0.169863f, -0.039352f, -0.047486f, -0.039797f, -0.204312f, 0.021710f, 0.129443f, -0.021173f, 0.173416f, -0.070794f, -0.063986f, 0.069689f, -0.064099f, -0.123201f, -0.017372f, -0.206870f, 0.065863f, 0.113226f, 0.024707f, -0.071341f, -0.066964f, -0.098278f, -0.062927f, 0.075840f, 0.014716f, 0.019378f, 0.132699f, -0.074191f, -0.089557f, -0.078446f, -0.197488f, -0.173665f, 0.052583f, 0.044361f, 0.113549f, 0.098492f, 0.077379f, -0.011146f, -0.192593f, -0.164435f, 0.045568f, 0.205699f, 0.049187f, -0.082281f, 0.134874f, 0.185499f, 0.034968f, -0.119561f, -0.112372f, -0.115091f, -0.054042f, -0.183816f, -0.078100f, 0.190695f, 0.091617f, 0.004257f, -0.041135f, -0.061453f, -0.141592f, -0.194809f, -0.120638f, 0.020168f, 0.109672f, 0.067398f, -0.015238f, -0.239145f, -0.264671f, -0.185176f, 0.050472f, 0.020793f, 0.035678f, 0.022839f, -0.052055f, -0.127968f, -0.113049f, -0.228416f, -0.258281f, -0.053437f, 0.076424f, 0.061450f, 0.237478f, 0.003618f, -0.055865f, -0.108087f, -0.028937f, 0.045585f, 0.052829f, -0.001471f, 0.022826f, 0.059565f, -0.104430f, -0.077266f, -0.211882f, -0.212078f, 0.028074f, 0.075846f, 0.016265f, 0.161879f, 0.134477f, 0.008935f, -0.048041f, 0.074692f, 0.004928f, -0.025156f, 0.192874f, 0.074410f, 0.308732f, 0.267400f, 0.094208f, -0.005251f, 0.042041f, -0.032148f, 0.015588f, 0.252869f, 0.175302f, 0.022892f, 0.081673f, 0.063208f, 0.162626f, 0.194426f, 0.233890f, 0.262292f, 0.186930f, 0.084079f, -0.286388f, -0.213034f, -0.048867f, -0.207669f, -0.170050f, 0.011673f, -0.092958f, -0.192786f, -0.273536f, 0.230904f, 0.266732f, 0.320519f, 0.297155f, 0.548169f, 0.304922f, 0.132687f, 0.247333f, 0.212488f, -0.271472f, -0.142105f, -0.002627f, -0.119215f, 0.128383f, 0.100079f, -0.057490f, -0.121902f, -0.228892f, 0.202292f, -0.399795f, -0.371326f, -0.095836f, -0.063626f, -0.161375f, -0.311180f, -0.294797f, 0.242122f, 0.011788f, 0.095573f, 0.322523f, 0.511840f, 0.322880f, 0.313259f, 0.173331f, 0.002542f, -0.029802f, 0.324766f, -0.326170f, -0.340547f, -0.138288f, -0.002963f, -0.114060f, -0.377312f, -0.442570f, 0.212446f, -0.007759f, -0.011576f, 0.169711f, 0.308689f, 0.317348f, 0.539390f, 0.332845f, 0.057331f, -0.068180f, 0.101994f, 0.266995f, 0.209570f, 0.355730f, 0.091635f, 0.170238f, 0.125215f, 0.274154f, 0.070223f, 0.025515f, 0.049946f, -0.000550f, 0.043715f, -0.141843f, 0.020844f, 0.129871f, 0.256588f, 0.105015f, 0.148339f, 0.170682f, 0.028792f, 0.074037f, 0.160042f, 0.405137f, 0.246187f, 0.352160f, 0.168951f, 0.222263f, 0.264439f, 0.065945f, 0.021963f, -0.075084f, 0.093105f, 0.027318f, 0.098864f, 0.057566f, -0.080282f, 0.185032f, 0.314419f, 0.333727f, 0.125798f, 0.294919f, 0.386002f, 0.217619f, -0.183517f, -0.278622f, -0.002342f, -0.027821f, -0.134266f, -0.331843f, -0.008296f, 0.124564f, 0.053712f, -0.369016f, -0.095036f, 0.209381f, 0.423760f, 0.371760f, 0.106397f, 0.369408f, 0.485608f, 0.231201f, -0.138685f, -0.349208f, -0.070083f, 0.028991f, -0.081630f, -0.395992f, -0.146791f, -0.027354f, 0.063396f, -0.272484f, 0.058299f, 0.338207f, 0.110767f, -0.052642f, -0.233848f, -0.027448f, 0.030328f, 0.155572f, -0.093826f, 0.019331f, 0.120638f, 0.006292f, -0.106083f, -0.236290f, -0.140933f, -0.088067f, -0.025138f, -0.208395f, -0.025502f, 0.144192f, -0.048353f, -0.106144f, -0.305121f, -0.114147f, 0.090963f, 0.327727f, 0.035606f, -0.093779f, 0.002651f, -0.171081f, -0.188131f, -0.216571f, -0.209101f, -0.054402f, 0.157147f, -0.057127f, 0.066584f, 0.008988f, 0.041191f, 0.034456f, -0.078255f, 0.052099f, -0.022239f, 0.066981f, -0.117520f, -0.072637f, 0.062512f, 0.037570f, -0.057544f, -0.312359f, 0.034357f, -0.031549f, 0.002566f, -0.207375f, -0.070654f, -0.018786f, -0.044815f, -0.012814f, -0.076320f, 0.078183f, 0.023877f, 0.117078f, 0.022292f, -0.205424f, -0.060430f, -0.017296f, -0.004827f, -0.321036f, -0.092155f, 0.038837f, 0.073190f, -0.067513f, 0.026521f, 0.171945f, 0.087318f, 0.034495f, -0.034089f, 0.154410f, -0.061431f, 0.007435f, -0.111094f, -0.095976f, 0.014741f, -0.132324f, -0.029517f, -0.192160f, 0.098667f, 0.020762f, 0.177050f, -0.064510f, -0.054437f, -0.058678f, -0.001858f, 0.167602f, 0.015735f, 0.054338f, 0.016477f, 0.186381f, -0.010667f, 0.054692f, 0.126742f, 0.013140f, 0.090353f, -0.133608f, -0.018017f, -0.152619f, 0.027600f, -0.138700f, -0.050274f, 0.045141f, -0.118731f, 0.094797f, -0.167605f, 0.097461f, -0.009131f, 0.199920f, -0.052976f, 0.158194f, 0.178568f, -0.107600f, 0.009671f, -0.084072f, -0.040258f, -0.205673f, 0.102891f, 0.223511f, 0.042699f, 0.118548f, -0.021274f, 0.110997f, -0.155121f, 0.027696f, -0.149968f, 0.051552f, -0.129219f, 0.173524f, 0.073972f, -0.189045f, -0.034523f, -0.106655f, -0.011843f, -0.197381f, 0.219413f, 0.183197f, -0.054920f, 0.144955f, 0.036517f, -0.085412f, -0.229070f, -0.143710f, -0.049486f, 0.156634f, -0.008673f, -0.064778f, 0.082344f, 0.145673f, 0.002912f, -0.210121f, -0.116564f, 0.078425f, 0.220908f, -0.067594f, 0.048610f, 0.084912f, -0.066202f, -0.112515f, -0.217767f, -0.082640f, -0.017414f, 0.230265f, -0.070735f, 0.066073f, 0.215256f, 0.071157f, -0.087220f, -0.202235f, -0.011918f, 0.099562f, 0.174716f, -0.063845f, -0.121055f, 0.014367f, 0.132709f, -0.005060f, -0.244606f, -0.179693f, -0.134690f, 0.023239f, -0.193116f, -0.076975f, -0.021164f, -0.001938f, -0.163799f, -0.111437f, -0.210362f, -0.166376f, 0.034754f, 0.010036f, -0.021917f, 0.068014f, -0.086893f, -0.251746f, -0.267171f, 0.037383f, 0.003966f, 0.033571f, -0.151506f, 0.025437f, -0.020626f, -0.308454f, -0.343143f, -0.092263f, -0.026261f, -0.028345f, 0.036036f, 0.035169f, 0.129470f, 0.122205f, 0.015661f, -0.070612f, -0.094333f, -0.066055f, -0.041083f, 0.159146f, 0.073184f, 0.110044f, 0.174471f, 0.078069f, -0.014881f, 0.008116f, 0.013209f, 0.075857f, 0.195605f, 0.062714f, 0.067955f, 0.056544f, -0.153908f, -0.141749f, -0.072550f, 0.033523f, -0.024665f, 0.134487f, 0.079076f, 0.133562f, 0.227130f, 0.018054f, 0.004928f, 0.169162f, 0.065152f, 0.072160f, 0.131631f, 0.096303f, 0.054288f, 0.106256f, 0.114632f, 0.119038f, 0.515200f, 0.247429f, 0.199134f, 0.211957f, 0.127558f, -0.294684f, -0.194890f, -0.049988f, -0.112247f, -0.008122f, -0.006176f, 0.037035f, -0.110881f, -0.249989f, 0.152434f, 0.234621f, 0.153340f, 0.349283f, 0.683049f, 0.157174f, 0.124844f, 0.099136f, 0.064407f, -0.248400f, -0.155323f, -0.026498f, -0.023450f, 0.049051f, -0.114187f, 0.007195f, -0.176825f, -0.376926f, 0.366159f, -0.179938f, -0.148508f, 0.006043f, 0.170048f, 0.097866f, -0.102658f, -0.260430f, 0.248868f, 0.037019f, -0.118111f, 0.078176f, 0.194171f, 0.211328f, 0.368612f, 0.361213f, 0.130013f, 0.094650f, 0.227396f, -0.178058f, -0.114782f, -0.008093f, 0.231080f, -0.011843f, -0.097917f, -0.325788f, 0.141879f, 0.119738f, -0.230427f, -0.117419f, -0.114153f, 0.037903f, 0.116383f, 0.218773f, -0.101884f, 0.059466f, 0.119255f, 0.010874f, -0.031449f, 0.045996f, 0.119931f, 0.273760f, 0.311700f, 0.261794f, 0.194809f, 0.339829f, 0.239449f, 0.064140f, 0.077597f, 0.098996f, 0.143534f, 0.184602f, 0.037507f, 0.225494f, 0.096142f, -0.147370f, -0.207833f, -0.174742f, -0.086391f, -0.038942f, 0.159577f, -0.088492f, -0.000989f, 0.108154f, -0.025890f, -0.072713f, 0.025997f, -0.006803f, -0.086879f, -0.011290f, -0.269200f, -0.103450f, -0.124910f, -0.116340f, 0.141459f, 0.208800f, 0.042268f, 0.265034f, 0.516474f, 0.217591f, -0.018843f, -0.313328f, -0.168363f, 0.047129f, 0.090480f, -0.109852f, -0.018761f, 0.210669f, 0.281269f, -0.043591f, -0.034147f, -0.237772f, -0.134843f, -0.072481f, -0.103831f, 0.038355f, 0.308619f, 0.148023f, -0.045867f, -0.123950f, -0.210860f, -0.064973f, -0.036308f, -0.046731f, -0.022099f, 0.095776f, 0.409423f, 0.060635f, -0.065196f, 0.051828f, 0.027981f, -0.009609f, -0.137681f, -0.095011f, -0.019045f, 0.177278f, 0.009759f, -0.092119f, -0.016958f, -0.133860f, -0.118421f, -0.032039f, -0.006214f, -0.084541f, 0.063971f, -0.073642f, 0.165676f, 0.110443f, 0.044131f, 0.046568f, 0.053292f, -0.055466f, 0.015512f, 0.371947f, 0.232102f, -0.016923f, 0.103979f, -0.091758f, 0.005907f, 0.209100f, 0.157433f, 0.030518f, 0.250366f, 0.062322f, 0.036720f, 0.094676f, 0.017306f, -0.010328f, -0.079012f, 0.016781f, -0.112435f, 0.061795f, 0.042543f, -0.126799f, -0.009975f, -0.056760f, 0.046424f, -0.194712f, -0.139399f, -0.037731f, 0.157989f, -0.016261f, 0.123345f, 0.230563f, 0.083300f, -0.016392f, 0.059567f, -0.016035f, -0.064767f, 0.231945f, 0.156629f, 0.034602f, 0.145628f, 0.041315f, 0.034535f, 0.019967f, -0.089188f, -0.012091f, 0.307857f, 0.211405f, -0.025091f, -0.148249f, -0.129384f, 0.063536f, -0.068603f, -0.067941f, -0.035104f, 0.210832f, 0.063810f, 0.062764f, -0.089889f, -0.030554f, 0.014791f, -0.053362f, -0.037818f, -0.196640f, 0.008388f, -0.082654f, 0.143056f, 0.064221f, 0.069795f, 0.191040f, 0.097321f, -0.028679f, 0.075794f, 0.313154f, 0.086240f, 0.207643f, 0.017809f, 0.122867f, 0.224586f, 0.167403f, -0.023884f, 0.047434f, 0.344091f, 0.187745f, 0.136177f, 0.141738f, 0.063799f, 0.045233f, -0.077342f, -0.003525f, -0.165041f, -0.025616f, -0.073745f, 0.164439f, 0.011200f, -0.145896f, -0.027954f, -0.061987f, -0.039874f, -0.142775f, 0.151042f, -0.038238f, 0.053152f, 0.078615f, 0.086061f, 0.100593f, 0.128046f, -0.071006f, -0.116558f, 0.208445f, 0.051086f, 0.076843f, 0.023191f, -0.084781f, -0.011790f, 0.147807f, -0.048554f, -0.113932f, 0.283322f, 0.190934f, 0.092789f, 0.033018f, -0.142428f, -0.142480f, -0.099023f, -0.041020f, -0.042760f, 0.203295f, -0.053475f, 0.042424f, 0.222839f, -0.019167f, -0.133176f, -0.276216f, -0.031998f, 0.117290f, 0.177827f, -0.059973f, -0.064744f, -0.117040f, -0.155482f, -0.099531f, 0.164121f, -0.026682f, -0.093810f, 0.238993f, -0.006506f, 0.007830f, 0.065819f, -0.203643f, -0.100925f, -0.053652f, -0.130770f, 0.026277f, 0.131796f, 0.032742f, 0.127186f, 0.116694f, -0.161122f, -0.279773f, -0.252515f, -0.002638f, 0.042812f, 0.096776f, -0.123280f, 0.064858f, -0.010455f, -0.219760f, -0.239331f, -0.104363f, -0.058022f, -0.053584f, 0.025611f, 0.005129f, -0.100418f, -0.045712f, -0.194418f, -0.126366f, -0.030530f, 0.051168f, 0.215959f, 0.172402f, -0.054700f, -0.185995f, -0.278360f, -0.193693f, -0.040309f, 0.003735f, -0.007770f, 0.123556f, 0.190179f, -0.077315f, 0.117403f, 0.212942f, 0.012160f, 0.000113f, 0.027331f, 0.040202f, 0.033293f, 0.219438f, 0.184174f, 0.259349f, 0.311206f, 0.082547f, -0.047875f, -0.078417f, 0.010746f, 0.082620f, 0.311931f, 0.307605f, 0.003863f, 0.021405f, -0.026388f, -0.019572f, 0.020582f, -0.059353f, 0.025199f, 0.261319f, 0.086316f, 0.143614f, 0.107780f, 0.003900f, -0.188397f, -0.038563f, -0.106045f, -0.125154f, -0.010509f, 0.054021f, 0.242130f, 0.279152f, 0.215546f, 0.346995f, 0.440856f, 0.237452f, 0.234154f, 0.301646f, 0.168929f, -0.208358f, -0.126848f, 0.010260f, 0.121018f, -0.062975f, -0.052848f, 0.050341f, -0.061103f, -0.266482f, 0.107186f, 0.140221f, 0.280065f, 0.287889f, 0.373198f, 0.151596f, 0.013593f, 0.115616f, 0.014616f, -0.281710f, -0.237597f, -0.117305f, -0.000034f, -0.136739f, -0.196275f, -0.095225f, -0.125310f, -0.250514f, 0.236804f, -0.071805f, -0.037421f, 0.048230f, 0.321596f, 0.063632f, 0.024039f, -0.029133f, 0.230983f, 0.160593f, -0.154355f, -0.013086f, -0.079929f, 0.094692f, 0.160391f, 0.180239f, 0.053895f, 0.100759f, 0.288631f, 0.038191f, 0.181692f, 0.229682f, 0.440166f, 0.063401f, 0.006273f, 0.020865f, 0.338695f, 0.256244f, -0.043927f, 0.115617f, 0.003296f, 0.173965f, 0.021318f, -0.040936f, -0.118932f, 0.182380f, 0.235922f, -0.053233f, -0.015053f, -0.101057f, 0.095341f, 0.051111f, 0.161831f, 0.032614f, 0.159496f, 0.072375f, 0.025089f, 0.023748f, 0.029151f, 0.161284f, -0.117717f, -0.036191f, -0.176822f, -0.162006f, 0.226542f, -0.078329f, 0.043079f, -0.119172f, 0.054614f, -0.101365f, -0.064541f, -0.115304f, 0.135170f, 0.298872f, 0.098060f, 0.089428f, -0.007497f, 0.110391f, -0.028824f, 0.020835f, -0.036804f, 0.125411f, 0.192105f, -0.048931f, 0.003086f, -0.010681f, 0.074698f, -0.016263f, 0.096063f, 0.060267f, -0.007277f, 0.139139f, -0.080635f, 0.036628f, 0.086058f, 0.131979f, 0.085707f, 0.025301f, 0.226094f, 0.194759f, 0.042193f, -0.157846f, -0.068402f, -0.141450f, -0.112659f, -0.076305f, -0.069085f, -0.114332f, -0.102005f, 0.132193f, -0.067042f, 0.106643f, 0.198964f, 0.171616f, 0.167237f, -0.033730f, -0.026755f, 0.083621f, 0.149459f, -0.002799f, -0.000318f, 0.011753f, 0.065889f, -0.089375f, -0.049610f, 0.224579f, 0.216548f, -0.034908f, -0.017851f, -0.088144f, 0.007530f, 0.240268f, 0.073270f, 0.013263f, 0.175323f, 0.012082f, 0.093993f, 0.015282f, 0.105854f, 0.107990f, 0.077798f, -0.096166f, -0.079607f, 0.177820f, 0.142392f, 0.033337f, -0.078100f, -0.081616f, -0.046993f, 0.139459f, 0.020272f, -0.123161f, 0.175269f, 0.105217f, 0.057328f, 0.080909f, -0.012612f, -0.097081f, 0.082060f, -0.096716f, -0.063921f, 0.201884f, 0.128166f, -0.035051f, -0.032227f, -0.068139f, -0.115915f, 0.095080f, -0.086007f, -0.067543f, 0.030776f, 0.032712f, 0.088937f, 0.054336f, -0.039329f, -0.114022f, 0.171672f, -0.112321f, -0.217646f, 0.065186f, 0.060223f, 0.192174f, 0.055580f, -0.131107f, -0.144338f, 0.056730f, -0.034707f, -0.081616f, -0.135298f, -0.000614f, 0.087189f, 0.014614f, 0.067709f, 0.107689f, 0.225780f, 0.084361f, -0.008544f, 0.051649f, -0.048369f, -0.037739f, -0.060710f, 0.002654f, 0.016935f, 0.085563f, -0.015961f, -0.019265f, 0.111788f, 0.062376f, 0.202019f, 0.047713f, 0.042261f, 0.069716f, 0.242913f, 0.021052f, -0.072812f, -0.155920f, -0.026436f, 0.035621f, -0.079300f, -0.028787f, -0.048329f, 0.084718f, -0.060565f, -0.083750f, -0.164075f, -0.040742f, -0.086219f, 0.015271f, -0.005204f, -0.016038f, 0.045816f, -0.050433f, -0.077652f, 0.117109f, 0.009611f, -0.009045f, -0.008634f, -0.055373f, -0.085968f, 0.028527f, -0.054736f, -0.168089f, 0.175839f, 0.071205f, -0.023603f, 0.037907f, -0.004561f, -0.022634f, 0.123831f, 0.094469f, -0.072920f, -0.133642f, -0.014032f, -0.142754f, -0.026999f, -0.199409f, 0.013268f, 0.226989f, 0.048650f, -0.170988f, -0.050141f, 0.007880f, 0.061880f, 0.019078f, -0.043578f, -0.038139f, 0.134814f, 0.054097f, -0.081670f, 0.176838f, 0.047920f, -0.038176f, 0.050406f, -0.107181f, -0.036279f, 0.027060f, 0.081594f, -0.002820f, 0.090507f, -0.033338f, -0.059571f, 0.013404f, -0.099860f, 0.073371f, 0.342805f, 0.098305f, -0.150910f, -0.020822f, -0.056960f, 0.046262f, -0.043413f, -0.149405f, -0.129105f, -0.010899f, -0.014229f, -0.179949f, -0.113044f, -0.049468f, -0.065513f, 0.090269f, -0.011919f, 0.087846f, 0.095796f, 0.146127f, 0.101599f, 0.078066f, -0.084348f, -0.100002f, -0.020134f, -0.050169f, 0.062122f, 0.014640f, 0.019143f, 0.036543f, 0.180924f, -0.013976f, -0.066768f, -0.001090f, -0.070419f, -0.004839f, -0.001504f, 0.034483f, -0.044954f, -0.050336f, -0.088638f, -0.174782f, -0.116082f, -0.205507f, 0.015587f, -0.042839f, -0.096879f, -0.144097f, -0.050268f, -0.196796f, 0.109639f, 0.271411f, 0.173732f, 0.108070f, 0.156437f, 0.124255f, 0.097242f, 0.238693f, 0.083941f, 0.109105f, 0.223940f, 0.267188f, 0.027385f, 0.025819f, 0.125070f, 0.093738f, 0.040353f, 0.038645f, -0.012730f, 0.144063f, 0.052931f, -0.009138f, 0.084193f, 0.160272f, -0.041366f, 0.011951f, -0.121446f, -0.106713f, -0.047566f, 0.047984f, -0.255224f, -0.076116f, 0.098685f, -0.150845f, -0.171513f, -0.156590f, 0.058331f, 0.187493f, 0.413018f, 0.554265f, 0.372242f, 0.237943f, 0.124571f, 0.110829f, 0.010322f, -0.174477f, -0.067627f, -0.001979f, 0.142913f, 0.040597f, 0.019907f, 0.025963f, -0.043585f, -0.120732f, 0.099937f, 0.091059f, 0.247307f, 0.204226f, -0.042753f, -0.068580f, -0.119002f, 0.026722f, 0.034853f, -0.060934f, -0.025054f, -0.093026f, -0.035372f, -0.233209f, -0.049869f, -0.039151f, -0.022279f, -0.065380f, -9.063785f }; return std::vector<float>(detector, detector + sizeof(detector)/sizeof(detector[0])); } std::vector<float> cv::cuda::HOGDescriptor::getPeopleDetector64x128() { static const float detector[] = { 0.05359386f, -0.14721455f, -0.05532170f, 0.05077307f, 0.11547081f, -0.04268804f, 0.04635834f, -0.05468199f, 0.08232084f, 0.10424068f, -0.02294518f, 0.01108519f, 0.01378693f, 0.11193510f, 0.01268418f, 0.08528346f, -0.06309239f, 0.13054633f, 0.08100729f, -0.05209739f, -0.04315529f, 0.09341384f, 0.11035026f, -0.07596218f, -0.05517511f, -0.04465296f, 0.02947334f, 0.04555536f, -3.55954492e-003f, 0.07818956f, 0.07730991f, 0.07890715f, 0.06222893f, 0.09001380f, -0.03574381f, 0.03414327f, 0.05677258f, -0.04773581f, 0.03746637f, -0.03521175f, 0.06955440f, -0.03849038f, 0.01052293f, 0.01736112f, 0.10867710f, 0.08748853f, 3.29739624e-003f, 0.10907028f, 0.07913758f, 0.10393070f, 0.02091867f, 0.11594022f, 0.13182420f, 0.09879354f, 0.05362710f, -0.06745391f, -7.01260753e-003f, 5.24702156e-003f, 0.03236255f, 0.01407916f, 0.02207983f, 0.02537322f, 0.04547948f, 0.07200756f, 0.03129894f, -0.06274468f, 0.02107014f, 0.06035208f, 0.08636236f, 4.53164103e-003f, 0.02193363f, 0.02309801f, 0.05568166f, -0.02645093f, 0.04448695f, 0.02837519f, 0.08975694f, 0.04461516f, 0.08975355f, 0.07514391f, 0.02306982f, 0.10410084f, 0.06368385f, 0.05943464f, 4.58420580e-003f, 0.05220337f, 0.06675851f, 0.08358569f, 0.06712101f, 0.06559004f, -0.03930482f, -9.15936660e-003f, -0.05897915f, 0.02816453f, 0.05032348f, 0.06780671f, 0.03377650f, -6.09417039e-004f, -0.01795146f, -0.03083684f, -0.01302475f, -0.02972313f, 7.88706727e-003f, -0.03525961f, -2.50397739e-003f, 0.05245084f, 0.11791293f, -0.02167498f, 0.05299332f, 0.06640524f, 0.05190265f, -8.27316567e-003f, 0.03033127f, 0.05842173f, -4.01050318e-003f, -6.25105947e-003f, 0.05862958f, -0.02465461f, 0.05546781f, -0.08228195f, -0.07234028f, 0.04640540f, -0.01308254f, -0.02506191f, 0.03100746f, -0.04665651f, -0.04591486f, 0.02949927f, 0.06035462f, 0.02244646f, -0.01698639f, 0.01040041f, 0.01131170f, 0.05419579f, -0.02130277f, -0.04321722f, -0.03665198f, 0.01126490f, -0.02606488f, -0.02228328f, -0.02255680f, -0.03427236f, -7.75165204e-003f, -0.06195229f, 8.21638294e-003f, 0.09535975f, -0.03709979f, -0.06942501f, 0.14579427f, -0.05448192f, -0.02055904f, 0.05747357f, 0.02781788f, -0.07077577f, -0.05178314f, -0.10429011f, -0.11235505f, 0.07529039f, -0.07559302f, -0.08786739f, 0.02983843f, 0.02667585f, 0.01382199f, -0.01797496f, -0.03141199f, -0.02098101f, 0.09029204f, 0.04955018f, 0.13718739f, 0.11379953f, 1.80019124e-003f, -0.04577610f, -1.11108483e-003f, -0.09470536f, -0.11596080f, 0.04489342f, 0.01784211f, 3.06850672e-003f, 0.10781866f, 3.36498418e-003f, -0.10842580f, -0.07436839f, -0.10535070f, -0.01866805f, 0.16057891f, -5.07316366e-003f, -0.04295658f, -5.90488780e-003f, 8.82003549e-003f, -0.01492646f, -0.05029279f, -0.12875880f, 8.78831954e-004f, -0.01297184f, -0.07592774f, -0.02668831f, -6.93787413e-004f, 0.02406698f, -0.01773298f, -0.03855745f, -0.05877856f, 0.03259695f, 0.12826584f, 0.06292590f, -4.10733931e-003f, 0.10996531f, 0.01332991f, 0.02088735f, 0.04037504f, -0.05210760f, 0.07760046f, 0.06399347f, -0.05751930f, -0.10053057f, 0.07505023f, -0.02139782f, 0.01796176f, 2.34400877e-003f, -0.04208319f, 0.07355055f, 0.05093350f, -0.02996780f, -0.02219072f, 0.03355330f, 0.04418742f, -0.05580705f, -0.05037573f, -0.04548179f, 0.01379514f, 0.02150671f, -0.02194211f, -0.13682702f, 0.05464972f, 0.01608082f, 0.05309116f, 0.04701022f, 1.33690401e-003f, 0.07575664f, 0.09625306f, 8.92647635e-003f, -0.02819123f, 0.10866830f, -0.03439325f, -0.07092371f, -0.06004780f, -0.02712298f, -7.07467366e-003f, -0.01637020f, 0.01336790f, -0.10313606f, 0.04906582f, -0.05732445f, -0.02731079f, 0.01042235f, -0.08340668f, 0.03686501f, 0.06108340f, 0.01322748f, -0.07809529f, 0.03774724f, -0.03413248f, -0.06096525f, -0.04212124f, -0.07982176f, -1.25973229e-003f, -0.03045501f, -0.01236493f, -0.06312395f, 0.04789570f, -0.04602066f, 0.08576570f, 0.02521080f, 0.02988098f, 0.10314583f, 0.07060035f, 0.04520544f, -0.04426654f, 0.13146530f, 0.08386490f, 0.02164590f, -2.12280243e-003f, -0.03686353f, -0.02074944f, -0.03829959f, -0.01530596f, 0.02689708f, 0.11867401f, -0.06043470f, -0.02785023f, -0.04775074f, 0.04878745f, 0.06350956f, 0.03494788f, 0.01467400f, 1.17890188e-003f, 0.04379614f, 2.03681854e-003f, -0.03958609f, -0.01072688f, 6.43705716e-003f, 0.02996500f, -0.03418507f, -0.01960307f, -0.01219154f, -4.37000440e-003f, -0.02549453f, 0.02646318f, -0.01632513f, 6.46516960e-003f, -0.01929734f, 4.78711911e-003f, 0.04962371f, 0.03809111f, 0.07265724f, 0.05758125f, -0.03741554f, 0.01648608f, -8.45285598e-003f, 0.03996826f, -0.08185477f, 0.02638875f, -0.04026615f, -0.02744674f, -0.04071517f, 1.05096330e-003f, -0.04741232f, -0.06733172f, 8.70434940e-003f, -0.02192543f, 1.35350740e-003f, -0.03056974f, -0.02975521f, -0.02887780f, -0.01210713f, -0.04828526f, -0.09066251f, -0.09969629f, -0.03665164f, -8.88111943e-004f, -0.06826669f, -0.01866150f, -0.03627640f, -0.01408288f, 0.01874239f, -0.02075835f, 0.09145175f, -0.03547291f, 0.05396780f, 0.04198981f, 0.01301925f, -0.03384354f, -0.12201976f, 0.06830920f, -0.03715654f, 9.55848210e-003f, 5.05685573e-003f, 0.05659294f, 3.90764466e-003f, 0.02808490f, -0.05518097f, -0.03711621f, -0.02835565f, -0.04420464f, -0.01031947f, 0.01883466f, -8.49525444e-003f, -0.09419250f, -0.01269387f, -0.02133371f, -0.10190815f, -0.07844430f, 2.43644323e-003f, -4.09610150e-003f, 0.01202551f, -0.06452291f, -0.10593818f, -0.02464746f, -0.02199699f, -0.07401930f, 0.07285886f, 8.87513801e-004f, 9.97662079e-003f, 8.46779719e-003f, 0.03730333f, -0.02905126f, 0.03573337f, -0.04393689f, -0.12014472f, 0.03176554f, -2.76015815e-003f, 0.10824566f, 0.05090732f, -3.30179278e-003f, -0.05123822f, 5.04784798e-003f, -0.05664124f, -5.99415926e-003f, -0.05341901f, -0.01221393f, 0.01291318f, 9.91760660e-003f, -7.56987557e-003f, -0.06193124f, -2.24549137e-003f, 0.01987562f, -0.02018840f, -0.06975540f, -0.06601523f, -0.03349112f, -0.08910118f, -0.03371435f, -0.07406893f, -0.02248047f, -0.06159951f, 2.77751544e-003f, -0.05723337f, -0.04792468f, 0.07518548f, 2.77279224e-003f, 0.04211938f, 0.03100502f, 0.05278448f, 0.03954679f, -0.03006846f, -0.03851741f, -0.02792403f, -0.02875333f, 0.01531280f, 0.02186953f, -0.01989829f, 2.50679464e-003f, -0.10258728f, -0.04785743f, -0.02887216f, 3.85063468e-003f, 0.01112236f, 8.29218887e-003f, -0.04822981f, -0.04503597f, -0.03713100f, -0.06988008f, -0.11002295f, -2.69209221e-003f, 1.85383670e-003f, -0.05921049f, -0.06105053f, -0.08458050f, -0.04527602f, 8.90329306e-004f, -0.05875023f, -2.68602883e-003f, -0.01591195f, 0.03631859f, 0.05493166f, 0.07300330f, 5.53333294e-003f, 0.06400407f, 0.01847740f, -5.76280477e-003f, -0.03210877f, 4.25160583e-003f, 0.01166520f, -1.44864211e-003f, 0.02253744f, -0.03367080f, 0.06983195f, -4.22323542e-003f, -8.89401045e-003f, -0.07943393f, 0.05199728f, 0.06065201f, 0.04133492f, 1.44032843e-003f, -0.09585235f, -0.03964731f, 0.04232114f, 0.01750465f, -0.04487902f, -7.59733608e-003f, 0.02011171f, 0.04673622f, 0.09011173f, -0.07869188f, -0.04682482f, -0.05080139f, -3.99383716e-003f, -0.05346331f, 0.01085723f, -0.03599333f, -0.07097908f, 0.03551549f, 0.02680387f, 0.03471529f, 0.01790393f, 0.05471273f, 9.62048303e-003f, -0.03180215f, 0.05864431f, 0.02330614f, 0.01633144f, -0.05616681f, -0.10245429f, -0.08302189f, 0.07291322f, -0.01972590f, -0.02619633f, -0.02485327f, -0.04627592f, 1.48853404e-003f, 0.05514185f, -0.01270860f, -0.01948900f, 0.06373586f, 0.05002292f, -0.03009798f, 8.76216311e-003f, -0.02474238f, -0.05504891f, 1.74034527e-003f, -0.03333667f, 0.01524987f, 0.11663762f, -1.32344989e-003f, -0.06608453f, 0.05687166f, -6.89525274e-004f, -0.04402352f, 0.09450210f, -0.04222684f, -0.05360983f, 0.01779531f, 0.02561388f, -0.11075410f, -8.77790991e-003f, -0.01099504f, -0.10380266f, 0.03103457f, -0.02105741f, -0.07371717f, 0.05146710f, 0.10581432f, -0.08617968f, -0.02892107f, 0.01092199f, 0.14551543f, -2.24320893e-003f, -0.05818033f, -0.07390742f, 0.05701261f, 0.12937020f, -0.04986651f, 0.10182415f, 0.05028650f, 0.12515625f, 0.09175041f, 0.06404983f, 0.01523394f, 0.09460562f, 0.06106631f, -0.14266998f, -0.02926703f, 0.02762171f, 0.02164151f, -9.58488265e-004f, -0.04231362f, -0.09866509f, 0.04322244f, 0.05872034f, -0.04838847f, 0.06319253f, 0.02443798f, -0.03606876f, 9.38737206e-003f, 0.04289991f, -0.01027411f, 0.08156885f, 0.08751175f, -0.13191354f, 8.16054735e-003f, -0.01452161f, 0.02952677f, 0.03615945f, -2.09128903e-003f, 0.02246693f, 0.09623287f, 0.09412123f, -0.02924758f, -0.07815186f, -0.02203079f, -2.02566991e-003f, 0.01094733f, -0.01442332f, 0.02838561f, 0.11882371f, 7.28798332e-003f, -0.10345965f, 0.07561217f, -0.02049661f, 4.44177445e-003f, 0.01609347f, -0.04893158f, -0.08758243f, -7.67420698e-003f, 0.08862378f, 0.06098121f, 0.06565887f, 7.32981879e-003f, 0.03558407f, -0.03874352f, -0.02490055f, -0.06771075f, 0.09939223f, -0.01066077f, 0.01382995f, -0.07289080f, 7.47184316e-003f, 0.10621431f, -0.02878659f, 0.02383525f, -0.03274646f, 0.02137008f, 0.03837290f, 0.02450992f, -0.04296818f, -0.02895143f, 0.05327370f, 0.01499020f, 0.04998732f, 0.12938657f, 0.09391870f, 0.04292390f, -0.03359194f, -0.06809492f, 0.01125796f, 0.17290455f, -0.03430733f, -0.06255233f, -0.01813114f, 0.11726857f, -0.06127599f, -0.08677909f, -0.03429872f, 0.04684938f, 0.08161420f, 0.03538774f, 0.01833884f, 0.11321855f, 0.03261845f, -0.04826299f, 0.01752407f, -0.01796414f, -0.10464549f, -3.30041884e-003f, 2.29343961e-004f, 0.01457292f, -0.02132982f, -0.02602923f, -9.87351313e-003f, 0.04273872f, -0.02103316f, -0.07994065f, 0.02614958f, -0.02111666f, -0.06964913f, -0.13453490f, -0.06861878f, -6.09341264e-003f, 0.08251446f, 0.15612499f, 2.46531400e-003f, 8.88424646e-003f, -0.04152999f, 0.02054853f, 0.05277953f, -0.03087788f, 0.02817579f, 0.13939077f, 0.07641046f, -0.03627627f, -0.03015098f, -0.04041540f, -0.01360690f, -0.06227205f, -0.02738223f, 0.13577610f, 0.15235767f, -0.05392922f, -0.11175954f, 0.02157129f, 0.01146481f, -0.05264937f, -0.06595174f, -0.02749175f, 0.11812254f, 0.17404149f, -0.06137035f, -0.11003478f, -0.01351621f, -0.01745916f, -0.08577441f, -0.04469909f, -0.06106115f, 0.10559758f, 0.20806813f, -0.09174948f, 7.09621934e-004f, 0.03579374f, 0.07215115f, 0.02221742f, 0.01827742f, -7.90785067e-003f, 0.01489554f, 0.14519960f, -0.06425831f, 0.02990399f, -1.80181325e-003f, -0.01401528f, -0.04171134f, -3.70530109e-003f, -0.09090481f, 0.09520713f, 0.08845516f, -0.02651753f, -0.03016730f, 0.02562448f, 0.03563816f, -0.03817881f, 0.01433385f, 0.02256983f, 0.02872120f, 0.01001934f, -0.06332260f, 0.04338406f, 0.07001807f, -0.04705722f, -0.07318907f, 0.02630457f, 0.03106382f, 0.06648342f, 0.10913180f, -0.01630815f, 0.02910308f, 0.02895109f, 0.08040254f, 0.06969310f, 0.06797734f, 6.08639978e-003f, 4.16588830e-003f, 0.08926726f, -0.03123648f, 0.02700146f, 0.01168734f, -0.01631594f, 4.61015804e-003f, 8.51359498e-003f, -0.03544224f, 0.03571994f, 4.29766066e-003f, -0.01970077f, -8.79793242e-003f, 0.09607988f, 0.01544222f, -0.03923707f, 0.07308586f, 0.06061262f, 1.31683104e-004f, -7.98222050e-003f, 0.02399261f, -0.06084389f, -0.02743429f, -0.05475523f, -0.04131311f, 0.03559756f, 0.03055342f, 0.02981433f, 0.14860515f, 0.01766787f, 0.02945257f, 0.04898238f, 0.01026922f, 0.02811658f, 0.08267091f, 0.02732154f, -0.01237693f, 0.11760156f, 0.03802063f, -0.03309754f, 5.24957618e-003f, -0.02460510f, 0.02691451f, 0.05399988f, -0.10133506f, 0.06385437f, -0.01818005f, 0.02259503f, 0.03573135f, 0.01042848f, -0.04153402f, -0.04043029f, 0.01643575f, 0.08326677f, 4.61383024e-004f, -0.05308095f, -0.08536223f, -1.61011645e-003f, -0.02163720f, -0.01783352f, 0.03859637f, 0.08498885f, -0.01725216f, 0.08625131f, 0.10995087f, 0.09177644f, 0.08498347f, 0.07646490f, 0.05580502f, 0.02693516f, 0.09996913f, 0.09070327f, 0.06667200f, 0.05873008f, -0.02247842f, 0.07772321f, 0.12408436f, 0.12629253f, -8.41997913e-004f, 0.01477783f, 0.09165990f, -2.98401713e-003f, -0.06466447f, -0.07057302f, 2.09516948e-004f, 0.02210209f, -0.02158809f, -0.08602506f, -0.02284836f, 4.01876355e-003f, 9.56660323e-003f, -0.02073978f, -0.04635138f, -7.59423291e-003f, -0.01377393f, -0.04559359f, -0.13284740f, -0.08671406f, -0.03654395f, 0.01142869f, 0.03287891f, -0.04392983f, 0.06142959f, 0.17710890f, 0.10385257f, 0.01329137f, 0.10067633f, 0.12450829f, -0.04476709f, 0.09049144f, 0.04589312f, 0.11167907f, 0.08587538f, 0.04767583f, 1.67188141e-003f, 0.02359802f, -0.03808852f, 0.03126272f, -0.01919029f, -0.05698918f, -0.02365112f, -0.06519032f, -0.05599358f, -0.07097308f, -0.03301812f, -0.04719102f, -0.02566297f, 0.01324074f, -0.09230672f, -0.05518232f, -0.04712864f, -0.03380903f, -0.06719479f, 0.01183908f, -0.09326738f, 0.01642865f, 0.03789867f, -6.61567831e-003f, 0.07796386f, 0.07246574f, 0.04706347f, -0.02523437f, -0.01696830f, -0.08068866f, 0.06030888f, 0.10527060f, -0.06611756f, 0.02977346f, 0.02621830f, 0.01913855f, -0.08479366f, -0.06322418f, -0.13570616f, -0.07644490f, 9.31900274e-003f, -0.08095149f, -0.10197903f, -0.05204025f, 0.01413151f, -0.07800411f, -0.01885122f, -0.07509381f, -0.10136326f, -0.05212355f, -0.09944065f, -1.33606605e-003f, -0.06342617f, -0.04178550f, -0.12373723f, -0.02832736f, -0.06057501f, 0.05830070f, 0.07604282f, -0.06462587f, 8.02447461e-003f, 0.11580125f, 0.12332212f, 0.01978462f, -2.72378162e-003f, 0.05850752f, -0.04674481f, 0.05148062f, -2.62542837e-003f, 0.11253355f, 0.09893716f, 0.09785093f, -0.04659257f, -0.01102429f, -0.07002308f, 0.03088913f, -0.02565549f, -0.07671449f, 3.17443861e-003f, -0.10783514f, -0.02314270f, -0.11089555f, -0.01024768f, 0.03116021f, -0.04964825f, 0.02281825f, 5.50005678e-003f, -0.08427856f, -0.14685495f, -0.07719755f, -0.13342668f, -0.04525511f, -0.09914210f, 0.02588859f, 0.03469279f, 0.04664020f, 0.11688190f, 0.09647275f, 0.10857815f, -0.01448726f, 0.04299758f, -0.06763151f, 1.33257592e-003f, 0.14331576f, 0.07574340f, 0.09166205f, 0.05674926f, 0.11325553f, -0.01106494f, 0.02062161f, -0.11484840f, -0.07492137f, -0.02864293f, -0.01275638f, -0.06946032f, -0.10101652f, -0.04113498f, -0.02214783f, -0.01273942f, -0.07480393f, -0.10556041f, -0.07622112f, -0.09988393f, -0.11453961f, -0.12073903f, -0.09412795f, -0.07146588f, -0.04054537f, -0.06127083f, 0.04221122f, 0.07688113f, 0.04099256f, 0.12663734f, 0.14683802f, 0.21761774f, 0.12525328f, 0.18431792f, -1.66402373e-003f, 2.37777247e-003f, 0.01445475f, 0.03509416f, 0.02654697f, 0.01716739f, 0.05374011f, 0.02944174f, 0.11323927f, -0.01485456f, -0.01611330f, -1.85554172e-003f, -0.01708549f, -0.05435753f, -0.05302101f, 0.05260378f, -0.03582945f, -3.42867890e-004f, 1.36076682e-003f, -0.04436073f, -0.04228432f, 0.03281291f, -0.05480836f, -0.10197772f, -0.07206279f, -0.10741059f, -0.02366946f, 0.10278475f, -2.74783419e-003f, -0.03242477f, 0.02308955f, 0.02835869f, 0.10348799f, 0.19580358f, 0.10252027f, 0.08039929f, 0.05525554f, -0.13250865f, -0.14395352f, 3.13586881e-003f, -0.03387071f, 8.94669443e-003f, 0.05406157f, -4.97324532e-003f, -0.01189114f, 2.82919413e-004f, -0.03901557f, -0.04898705f, 0.02164520f, -0.01382906f, -0.01850416f, 0.01869347f, -0.02450060f, 0.02291678f, 0.08196463f, 0.03309153f, -0.10629974f, 0.02473924f, 0.05344394f, -0.02404823f, -0.03243643f, -5.55244600e-003f, -0.08009996f, 0.02811539f, 0.04235742f, 0.01859004f, 0.04902123f, -0.01438252f, -0.01526853f, 0.02044195f, -0.05008660f, 0.04244113f, 0.07611816f, 0.04950470f, -0.06020549f, -4.26026015e-003f, 0.13133512f, -0.01438738f, -0.01958807f, -0.04044152f, -0.12425045f, 2.84353318e-003f, -0.05042776f, -0.09121484f, 7.34345755e-003f, 0.09388847f, 0.11800314f, 4.72295098e-003f, 4.44378285e-003f, -0.07984917f, -0.03613737f, 0.04490915f, -0.02246483f, 0.04681071f, 0.05240871f, 0.02157206f, -0.04603431f, -0.01197929f, -0.02748779f, 0.13621049f, 0.08812155f, -0.07802048f, 4.86458559e-003f, -0.01598836f, 0.01024450f, -0.03463517f, -0.02304239f, -0.08692665f, 0.06655128f, 0.05785803f, -0.12640759f, 0.02307472f, 0.07337402f, 0.07525434f, 0.04943763f, -0.02241034f, -0.09978238f, 0.14487994f, -0.06570521f, -0.07855482f, 0.02830222f, -5.29603509e-004f, -0.04669895f, -0.11822784f, -0.12246452f, -0.15365660f, -0.02969127f, 0.08078201f, 0.13512598f, 0.11505685f, 0.04740673f, 0.01376022f, -0.05852978f, -0.01537809f, -0.05541119f, 0.02491065f, -0.02870786f, 0.02760978f, 0.23836176f, 0.22347429f, 0.10306466f, -0.06919070f, -0.10132039f, -0.20198342f, -0.05040560f, 0.27163076f, 0.36987007f, 0.34540465f, 0.29095781f, 0.05649706f, 0.04125737f, 0.07505883f, -0.02737836f, -8.43431335e-003f, 0.07368195f, 0.01653876f, -0.09402955f, -0.09574359f, 0.01474337f, -0.07128561f, -0.03460737f, 0.11438941f, 0.13752601f, -0.06385452f, -0.06310338f, 8.19548313e-003f, 0.11622470f, 5.05133113e-003f, -0.07602754f, 0.06695660f, 0.25723928f, 0.09037900f, 0.28826267f, 0.13165380f, -0.05312614f, -0.02137198f, -0.03442232f, -0.06255679f, 0.03899667f, 0.18391028f, 0.26016650f, 0.03374462f, 0.01860465f, 0.19077586f, 0.18160543f, 3.43634398e-003f, -0.03036782f, 0.19683038f, 0.35378191f, 0.24968483f, -0.03222649f, 0.28972381f, 0.43091634f, 0.30778357f, 0.02335266f, -0.09877399f, -6.85245218e-003f, 0.08945240f, -0.08150686f, 0.02792493f, 0.24806842f, 0.17338486f, 0.06231801f, -0.10432383f, -0.16653322f, -0.13197899f, -0.08531576f, -0.19271527f, -0.13536365f, 0.22240199f, 0.39219588f, 0.26597717f, -0.01231649f, 0.01016179f, 0.13379875f, 0.12018334f, -0.04852953f, -0.07915270f, 0.07036012f, 3.87723115e-003f, -0.06126805f, -0.15015170f, -0.11406515f, -0.08556531f, -0.07429333f, -0.16115491f, 0.13214062f, 0.25691369f, 0.05697750f, 0.06861912f, -6.02903729e-003f, -7.94562511e-003f, 0.04799571f, 0.06695165f, -0.01926842f, 0.06206308f, 0.13450983f, -0.06381495f, -2.98370165e-003f, -0.03482971f, 7.53991678e-003f, 0.03895611f, 0.11464261f, 0.01669971f, 8.27818643e-003f, -7.49160210e-003f, -0.11712562f, -0.10650621f, -0.10353880f, -0.04994106f, -7.65618810e-004f, 0.03023767f, -0.04759270f, -0.07302686f, -0.05825012f, -0.13156348f, -0.10639747f, -0.19393684f, -0.09973683f, -0.07918908f, 4.63177625e-004f, -6.61382044e-004f, 0.15853868f, 0.08561199f, -0.07660093f, -0.08015265f, -0.06164073f, 0.01882577f, -7.29908410e-004f, 0.06840892f, 0.03843764f, 0.20274927f, 0.22028814f, -5.26101235e-003f, 0.01452435f, -0.06331623f, 0.02865064f, 0.05673740f, 0.12171564f, 0.03837196f, 0.03555467f, -0.02662914f, -0.10280123f, -0.06526285f, -0.11066351f, -0.08988424f, -0.10103678f, 8.10526591e-003f, 5.95238712e-003f, 0.02617721f, -0.01705742f, -0.10897956f, -0.08004991f, -0.11271993f, -0.06185647f, -0.06103712f, 0.01597041f, -0.05923606f, 0.09410726f, 0.22858568f, 0.03263380f, 0.06772990f, -0.09003516f, 0.01017870f, 0.01931688f, 0.08628357f, -0.01430009f, 0.10954945f, 0.16612452f, -0.02434544f, -0.03310068f, -0.04236627f, 0.01212392f, -6.15046406e-003f, 0.06954194f, 0.03015283f, 0.01787957f, 0.02781667f, -0.05561153f, -8.96244217e-003f, -0.04971489f, 0.07510284f, 0.01775282f, 0.05889897f, -0.07981427f, 0.03647643f, -3.73833324e-003f, -0.08894575f, -0.06429435f, -0.08068276f, 0.03567704f, -0.07131936f, -7.21910037e-003f, -0.09566668f, 0.17886090f, 0.14911725f, 0.02070032f, -0.05017120f, -0.04992622f, 0.01570143f, -0.09906903f, 0.06456193f, 0.15329507f, 0.18820767f, 0.11689861f, -0.01178513f, -0.02225163f, -0.01905318f, 0.10271224f, -7.27029052e-003f, 0.11664233f, 0.14796902f, 0.07771893f, 0.02400013f, -0.05361797f, -0.01972888f, 0.01376177f, 0.06740040f, -0.06525395f, 0.05726178f, -0.02404981f, -0.14018567f, -0.02074987f, -0.04621970f, -0.04688627f, -0.01842059f, 0.07722727f, -0.04852883f, 0.01529004f, -0.19639495f, 0.10817073f, 0.03795860f, -0.09435206f, -0.07984378f, -0.03383440f, 0.11081333f, 0.02237366f, 0.12703256f, 0.21613893f, 0.02918790f, 4.66472283e-003f, -0.10274266f, -0.04854131f, -3.46305710e-003f, 0.08652268f, 0.02251546f, 0.09636052f, 0.17180754f, -0.09272388f, 4.59174305e-004f, -0.11723048f, -0.12210111f, -0.15547538f, 0.07218186f, -0.05297846f, 0.03779940f, 0.05150875f, -0.03802310f, 0.03870645f, -0.15250699f, -0.08696499f, -0.02021560f, 0.04118926f, -0.15177974f, 0.01577647f, 0.10249301f, 7.50041893e-003f, 0.01721806f, -0.06828983f, -0.02397596f, -0.06598977f, -0.04317593f, -0.08064980f, 6.66632550e-003f, 0.03333484f, 0.07093620f, 0.08231064f, -0.06577903f, -0.06698844f, -0.06984019f, -0.06508023f, -0.14145090f, -0.02393239f, 0.06485303f, 8.83263443e-003f, 0.09251080f, -0.07557579f, -0.05067699f, -0.09798748f, -0.06703258f, -0.14056294f, 0.03245994f, 0.12554143f, 0.01761621f, 0.12980327f, -0.04081950f, -0.11906909f, -0.14813015f, -0.08376863f, -0.12200681f, 0.04988137f, 0.05424247f, -3.90952639e-003f, 0.03255733f, -0.12717837f, -0.07461493f, -0.05703964f, -0.01736189f, -0.08026433f, -0.05433894f, -0.01719359f, 0.02886275f, 0.01772653f, -0.09163518f, 3.57789593e-003f, -0.10129993f, -0.02653764f, -0.08131415f, -0.03847986f, -7.62157550e-004f, 0.06486648f, 0.19675669f, -0.04919156f, -0.07059129f, -0.04857785f, -0.01042383f, -0.08328653f, 0.03660302f, -0.03696846f, 0.04969259f, 0.08241162f, -0.12514858f, -0.06122676f, -0.03750202f, 6.52989605e-003f, -0.10247213f, 0.02568346f, 4.51781414e-003f, -0.03734229f, -0.01131264f, -0.05412074f, 8.89345480e-004f, -0.12388977f, -0.05959237f, -0.12418608f, -0.06151643f, -0.07310260f, 0.02441575f, 0.07023528f, -0.07548289f, -7.57147965e-004f, -0.09061348f, -0.08112976f, -0.06920306f, 9.54394229e-003f, -0.01219902f, 1.21273217e-003f, -8.88989680e-003f, -0.08309301f, -0.04552661f, -0.10739882f, -0.05691034f, -0.13928030f, 0.09027749f, 0.15123098f, 0.03175976f, 0.17763577f, 3.29913251e-004f, 0.05151888f, -0.09844074f, -0.09475287f, -0.08571247f, 0.16241577f, 0.19336018f, 8.57454538e-003f, 0.11474732f, -0.01493934f, 0.03352379f, -0.08966240f, -0.02322310f, 0.02663568f, 0.05448750f, -0.03536883f, -0.07210463f, -0.06807277f, -0.03121621f, -0.05932408f, -0.17282860f, -0.15873498f, -0.04956378f, 0.01603377f, -0.12385946f, 0.13878587f, 0.21468069f, 0.13510075f, 0.20992437f, 0.08845878f, 0.08104013f, 0.03754176f, 0.12173114f, 0.11103114f, 0.10643122f, 0.13941477f, 0.11640384f, 0.14786847f, 0.01218238f, 0.01160753f, 0.03547940f, 0.08794311f, -0.01695384f, -0.07692261f, -0.08236158f, 6.79194089e-003f, -0.02458403f, 0.13022894f, 0.10953187f, 0.09857773f, 0.04735930f, -0.04353498f, -0.15173385f, -0.17904443f, -0.10450364f, -0.13418166f, -0.06633098f, -0.03170381f, -0.06839000f, -0.11350126f, -0.06983913f, 0.19083543f, 0.17604128f, 0.07730632f, 0.10022651f, 0.36428109f, 0.28291923f, 0.12688625f, 0.15942036f, 0.14064661f, -0.11201853f, -0.13969108f, -0.09088077f, -0.14107047f, 0.05117374f, -2.63348082e-003f, -0.10794610f, -0.09715455f, -0.05284977f, 0.01565668f, 0.05031200f, 0.07021113f, -0.02963028f, 0.01766960f, 0.08333644f, -0.03211382f, 4.90096770e-003f, 0.05186674f, -0.05045737f, -0.09624767f, -0.02525997f, 0.06916669f, 0.01213916f, 0.05333899f, -0.03443280f, -0.10055527f, -0.06291115f, 5.42851724e-003f, -6.30360236e-003f, 0.02270257f, -0.01769792f, 0.03273688f, 0.07746078f, 7.77099328e-003f, 0.05041346f, 0.01648103f, -0.02321534f, -0.09930186f, -0.02293853f, 0.02034990f, -0.08324204f, 0.08510064f, -0.03732836f, -0.06465405f, -0.06086946f, 0.13680504f, -0.11469388f, -0.03896406f, -0.07142810f, 2.67581246e-003f, -0.03639632f, -0.09849060f, -0.11014334f, 0.17489147f, 0.17610909f, -0.16091567f, -0.07248894f, 0.01567141f, 0.23742996f, 0.07552249f, -0.06270349f, -0.07303379f, 0.25442186f, 0.16903116f, -0.08168741f, -0.05913896f, -0.03954096f, 6.81776879e-003f, -0.05615319f, -0.07303037f, -0.12176382f, 0.12385108f, 0.22084464f, -0.05543206f, -0.03310431f, 0.05731593f, 0.19481890f, 0.04016430f, -0.06480758f, -0.12353460f, 0.18733442f, -0.09631214f, -0.11192076f, 0.12404587f, 0.15671748f, 0.19256128f, 0.10895617f, 0.03391477f, -0.13032004f, -0.05626907f, -0.09025607f, 0.23485197f, 0.27812332f, 0.26725492f, 0.07255980f, 0.16565137f, 0.22388470f, 0.07441066f, -0.21003133f, -0.08075339f, -0.15031935f, 0.07023834f, 0.10872041f, 0.18156518f, 0.20037253f, 0.13571967f, -0.11915682f, -0.11131983f, -0.18878011f, 0.06074620f, 0.20578890f, 0.12413109f, 0.03930207f, 0.29176015f, 0.29502738f, 0.27856228f, -0.01803601f, 0.16646385f, 0.19268319f, 0.01900682f, 0.06026287f, 2.35868432e-003f, 0.01558199f, 0.02707230f, 0.11383014f, 0.12103992f, 0.03907350f, 0.04637353f, 0.09020995f, 0.11919726f, -3.63007211e-003f, 0.02220155f, 0.10336831f, 0.17351882f, 0.12259731f, 0.18983354f, 0.15736865f, 0.01160725f, -0.01690723f, -9.69582412e-004f, 0.07213813f, 0.01161613f, 0.17864859f, 0.24486147f, 0.18208991f, 0.20177495f, 0.05972528f, -8.93934630e-003f, -0.02316955f, 0.14436610f, 0.14114498f, 0.05520950f, 0.06353590f, -0.19124921f, 0.10174713f, 0.29414919f, 0.26448128f, 0.09344960f, 0.15284036f, 0.19797507f, 0.11369792f, -0.12722753f, -0.21396367f, -0.02008235f, -0.06566695f, -0.01662150f, -0.03937003f, 0.04778343f, 0.05017274f, -0.02299062f, -0.20208496f, -0.06395898f, 0.13721776f, 0.22544557f, 0.14888357f, 0.08687132f, 0.27088094f, 0.32206613f, 0.09782200f, -0.18523243f, -0.17232181f, -0.01041531f, 0.04008654f, 0.04199702f, -0.08081299f, -0.03755421f, -0.04809646f, -0.05222081f, -0.21709201f, -0.06622940f, 0.02945281f, -0.04600435f, -0.05256077f, -0.08432942f, 0.02848100f, 0.03490564f, 8.28621630e-003f, -0.11051246f, -0.11210597f, -0.01998289f, -0.05369405f, -0.08869293f, -0.18799506f, -0.05436598f, -0.05011634f, -0.05419716f, -0.06151857f, -0.10827805f, 0.04346735f, 0.04016083f, 0.01520820f, -0.12173316f, -0.04880285f, -0.01101406f, 0.03250847f, -0.06009551f, -0.03082932f, -0.02295134f, -0.06856834f, -0.08775249f, -0.23793389f, -0.09174541f, -0.05538322f, -0.04321031f, -0.11874759f, -0.04221844f, -0.06070468f, 0.01194489f, 0.02608565f, -0.03892140f, -0.01643151f, -0.02602034f, -0.01305472f, 0.03920100f, -0.06514261f, 0.01126918f, -6.27710763e-003f, -0.02720047f, -0.11133634f, 0.03300330f, 0.02398472f, 0.04079665f, -0.10564448f, 0.05966159f, 0.01195221f, -0.03179441f, -0.01692590f, -0.06177841f, 0.01841576f, -5.51078189e-003f, -0.06821765f, -0.03191888f, -0.09545476f, 0.03030550f, -0.04896152f, -0.02914624f, -0.13283344f, -0.04783419f, 6.07836898e-003f, -0.01449538f, -0.13358212f, -0.09687774f, -0.02813793f, 0.01213498f, 0.06650011f, -0.02039067f, 0.13356198f, 0.05986415f, -9.12760664e-003f, -0.18780160f, -0.11992817f, -0.06342237f, 0.01229534f, 0.07143231f, 0.10713009f, 0.11085765f, 0.06569190f, -0.02956399f, -0.16288325f, -0.13993549f, -0.01292515f, 0.03833013f, 0.09130384f, -0.05086257f, 0.05617329f, -0.03896667f, -0.06282311f, -0.11490010f, -0.14264110f, -0.04530499f, 0.01598189f, 0.09167797f, 0.08663294f, 0.04885277f, -0.05741219f, -0.07565769f, -0.17136464f, -0.02619422f, -0.02477579f, 0.02679587f, 0.11621952f, 0.08788391f, 0.15520640f, 0.04709549f, 0.04504483f, -0.10214074f, -0.12293372f, -0.04820546f, -0.05484834f, 0.05473754f, 0.07346445f, 0.05577277f, -0.08209965f, 0.03462975f, -0.20962234f, -0.09324598f, 3.79481679e-003f, 0.03617633f, 0.16742408f, 0.07058107f, 0.10204960f, -0.06795346f, 3.22807301e-003f, -0.12589309f, -0.17496960f, 0.02078314f, -0.07694324f, 0.12184640f, 0.08997164f, 0.04793497f, -0.11383379f, -0.08046359f, -0.25716835f, -0.08080962f, 6.80711539e-003f, -0.02930280f, -3.04938294e-003f, -0.11106286f, -0.04628860f, -0.07821649f, 7.70127494e-003f, -0.10247706f, 1.21042714e-003f, 0.20573859f, -0.03241005f, 8.42972286e-003f, 0.01946464f, -0.01197973f, -0.14579976f, 0.04233614f, -4.14096704e-003f, -0.06866436f, -0.02431862f, -0.13529138f, 1.25891645e-003f, -0.11425111f, -0.04303651f, -0.01694815f, 0.05720210f, -0.16040207f, 0.02772896f, 0.05498345f, -0.15010567f, 0.01450866f, 0.02350303f, -0.04301004f, -0.04951802f, 0.21702233f, -0.03159155f, -0.01963303f, 0.18232647f, -0.03263875f, -2.88476888e-003f, 0.01587562f, -1.94303901e-003f, -0.07789494f, 0.04674156f, -6.25576358e-003f, 0.08925962f, 0.21353747f, 0.01254677f, -0.06999976f, -0.05931328f, -0.01884327f, -0.04306272f, 0.11794136f, 0.03842728f, -0.03907030f, 0.05636114f, -0.09766009f, -0.02104000f, 8.72711372e-003f, -0.02736877f, -0.05112274f, 0.16996814f, 0.02955785f, 0.02094014f, 0.08414304f, -0.03335762f, -0.03617457f, -0.05808248f, -0.08872101f, 0.02927705f, 0.27077839f, 0.06075108f, 0.07478261f, 0.15282831f, -0.03908454f, -0.05101782f, -9.51998029e-003f, -0.03272416f, -0.08735625f, 0.07633440f, -0.07185312f, 0.13841286f, 0.07812646f, -0.12901451f, -0.05488589f, -0.05644578f, -0.03290703f, -0.11184757f, 0.03751570f, -0.05978153f, -0.09155276f, 0.05657315f, -0.04328186f, -0.03047933f, -0.01413135f, -0.10181040f, -0.01384013f, 0.20132534f, -0.01536873f, -0.07641169f, 0.05906778f, -0.07833145f, -0.01523801f, -0.07502609f, -0.09461885f, -0.15013233f, 0.16050665f, 0.09021381f, 0.08473236f, 0.03386267f, -0.09147339f, -0.09170618f, -0.08498498f, -0.05119187f, -0.10431040f, 0.01041618f, -0.03064913f, 0.09340212f, 0.06448522f, -0.03881054f, -0.04985436f, -0.14794017f, -0.05200112f, -0.02144495f, 0.04000821f, 0.12420804f, -0.01851651f, -0.04116732f, -0.11951703f, -0.04879033f, -0.08722515f, -0.08454733f, -0.10549165f, 0.11251976f, 0.10766345f, 0.19201984f, 0.06128913f, -0.02734615f, -0.08834923f, -0.16999826f, -0.03548348f, -5.36092324e-003f, 0.08297954f, 0.07226378f, 0.04194529f, 0.04668673f, 8.73902347e-003f, 0.06980139f, 0.05652480f, 0.05879445f, 0.02477076f, 0.02451423f, 0.12433673f, 0.05600227f, 0.06886370f, 0.03863076f, 0.07459056f, 0.02264139f, 0.01495469f, 0.06344220f, 0.06945208f, 0.02931899f, 0.11719371f, 0.04527427f, 0.03248192f, 2.08271481e-003f, 0.02044626f, 0.11403449f, 0.04303892f, 0.06444661f, 0.04959024f, 0.08174094f, 0.09240247f, 0.04894639f, 0.02252937f, -0.01652530f, 0.07587013f, 0.06064249f, 0.13954395f, 0.02772832f, 0.07093039f, 0.08501238f, 0.01701301f, 0.09055722f, 0.33421436f, 0.20163782f, 0.09821030f, 0.07951369f, 0.08695120f, -0.12757730f, -0.13865978f, -0.06610068f, -0.10985506f, 0.03406816f, -0.01116336f, -0.07281768f, -0.13525715f, -0.12844718f, 0.08956250f, 0.09171610f, 0.10092317f, 0.23385370f, 0.34489515f, 0.09901748f, 0.02002922f, 0.12335990f, 0.07606190f, -0.14899330f, -0.15634622f, -0.06494618f, -0.01760547f, 0.03404277f, -0.13208845f, -0.12101169f, -0.18294574f, -0.16560709f, 0.02183887f, -0.02752613f, 0.01813638f, 0.02000757f, 0.01319924f, 0.08030242f, 0.01220535f, 2.98233377e-003f, -0.01307070f, 0.05970297f, -0.05345284f, -0.03381982f, -9.87543724e-003f, -0.06869387f, 0.03956730f, -0.03108176f, -0.05732809f, 0.02172386f, 0.04159765f, 2.62783933e-003f, 0.04813229f, 0.09358983f, -8.18389002e-003f, 0.01724574f, -0.02547474f, -0.04967288f, -0.02390376f, 0.06640504f, -0.06306566f, 0.01137518f, 0.05589378f, -0.08237787f, 0.02455001f, -0.03059422f, -0.08953978f, 0.06851497f, 0.07190268f, -0.07610799f, 7.87237938e-003f, -7.85830803e-003f, 0.06006952f, -0.01126728f, -2.85743061e-003f, -0.04772895f, 0.01884944f, 0.15005857f, -0.06268821f, -0.01989072f, 0.01138399f, 0.08760451f, 0.03879007f, -9.66926850e-003f, -0.08012961f, 0.06414555f, -0.01362950f, -0.09135523f, 0.01755159f, 0.04459474f, 0.09650917f, 0.05219948f, -2.19440833e-003f, -0.07037939f, -0.01599054f, 0.13103317f, -0.02492603f, -0.01032540f, -0.02903307f, 0.04489160f, 0.05148086f, 0.01858173f, -0.02919228f, 0.08299296f, -0.04590359f, -0.15745632f, -0.09068198f, -0.02972453f, 0.12985018f, 0.22320485f, 0.24261914f, 0.03642650f, -0.05506422f, 2.67413049e-003f, -0.03834032f, 0.06449424f, 0.03834866f, 0.03816991f, 0.25039271f, 0.34212017f, 0.32433882f, 0.18824573f, -0.08599839f, -0.17599408f, -0.15317015f, -0.09913155f, -0.02856072f, -0.05304699f, -1.06437842e-003f, -0.06641813f, -0.07509298f, 0.01463361f, -0.07551918f, -0.04510373f, -8.44620075e-003f, 0.01772176f, 0.04068235f, 0.20295307f, 0.15719447f, 0.05712103f, 0.26296997f, 0.14657754f, 0.01547317f, -0.05052776f, -0.03881342f, -0.01437883f, -0.04930177f, 0.11719568f, 0.24098417f, 0.26468599f, 0.31698579f, 0.10103608f, -0.01096375f, -0.01367013f, 0.17104232f, 0.20065314f, 2.67622480e-003f, -0.01190034f, 0.18301608f, 0.09459770f, -0.06357619f, -0.06473801f, 0.01377906f, -0.10032775f, -0.06388740f, 3.80393048e-003f, 0.06206078f, 0.10349120f, 0.26804337f, 8.17918684e-003f, -0.02314351f, 9.34422202e-003f, 0.09198381f, 0.03681326f, -8.77339672e-003f, -0.09662418f, -0.02715708f, 0.13503517f, 0.08962728f, -6.57071499e-003f, -0.03201199f, 0.28510824f, 0.32095715f, 0.18512695f, -0.14230858f, -0.14048551f, -0.07181299f, -0.08575408f, -0.08661680f, -0.17416079f, 7.54326640e-004f, 0.05601677f, 0.13585392f, -0.04960437f, -0.07708392f, 0.10676333f, -0.04407546f, -0.07209078f, 0.03663663f, 0.28949317f, 0.41127121f, 0.27431169f, -0.06900328f, -0.21474190f, -0.15578632f, -0.19555484f, -0.15209621f, -0.11269179f, 0.07416003f, 0.18991330f, 0.26858172f, 0.01952259f, 0.01017922f, 0.02159843f, -4.95165400e-003f, -0.04368168f, -0.12721671f, -0.06673957f, -0.11275250f, 0.04413409f, 0.05578312f, 0.03896771f, 0.03566417f, -0.05871816f, -0.07388090f, -0.17965563f, -0.08570268f, -0.15273231f, -0.06022318f, -0.06999847f, -6.81510568e-003f, 0.06294262f, -6.54901436e-004f, -0.01128654f, -0.02289657f, 0.04849290f, 0.04140804f, 0.23681939f, 0.14545733f, 0.01989965f, 0.12032662f, 3.87463090e-003f, -6.02597650e-003f, -0.05919775f, -0.03067224f, -0.07787777f, 0.10834727f, 0.02153730f, 0.02765649f, 0.03975543f, -0.12182906f, -0.04900113f, -0.09940100f, -0.06453611f, -0.13757215f, -0.03721382f, 0.02827376f, -0.04351249f, 0.01907038f, -0.10284120f, -0.05671160f, -0.10760647f, -0.09624009f, -0.09565596f, -0.01303654f, 0.03080539f, 0.01416511f, 0.05846142f, -5.42971538e-003f, 0.06221476f, -0.03320325f, -0.06791797f, -0.05791342f, 0.12851369f, 0.14990346f, 0.03634374f, 0.14262885f, 0.04330391f, 0.05032569f, -0.05631914f, 0.01606137f, 0.04387223f, 0.22344995f, 0.15722635f, -0.04693628f, 0.03006579f, -2.52882647e-003f, 0.05717621f, -0.07529724f, -0.02848588f, -0.06868757f, -4.51729307e-003f, 0.06466042f, -0.05935378f, -0.04704857f, -0.07363959f, 0.04843248f, -0.13421375f, -0.09789340f, -0.10255270f, 0.03509852f, 0.04751543f, -0.03822323f, 0.09740467f, 0.04762916f, 0.03940146f, -0.08283259f, 0.09552965f, 0.05038739f, 0.21258622f, 0.09646992f, 0.03241193f, 0.05167701f, 0.04614570f, 0.04330090f, -0.02671840f, -0.06259909f, -0.02301898f, 0.18829170f, 0.10522786f, 0.04313190f, 0.01670948f, -0.08421925f, 0.05911417f, -0.10582602f, -0.04855484f, -0.08373898f, 0.07775915f, 0.03723533f, -0.12047344f, 4.86345543e-003f, -0.10520902f, 0.06571782f, -0.07528137f, -0.03245651f, -0.09869066f, -0.02917477f, -0.18293270f, 0.14810945f, 9.24033765e-003f, -0.04354914f, 0.02266885f, -0.11872729f, -0.04016589f, 0.02830229f, 0.22539048f, 0.20565644f, 0.16701797f, 0.09019924f, 0.01300652f, 0.09760600f, -0.03675831f, -0.01935448f, -0.06894835f, 0.08077277f, 0.19047537f, 0.11312226f, 0.04106043f, -0.11187182f, 0.04312806f, -0.18548580f, -0.11287174f, -0.08794551f, 0.02078281f, -0.15295486f, 0.11806386f, -0.01103218f, -0.15971117f, 0.02153538f, -0.05232147f, -0.10835317f, -0.13910367f, 0.05920752f, -0.10122602f, 0.20174250f, 0.09105796f, -0.01881348f, 0.09559010f, -0.03725745f, -0.09442931f, -0.09763174f, 0.05854454f, 0.08287182f, 0.12919849f, 0.08594352f, -2.49806582e-003f, 0.02398440f, 5.67950122e-003f, -0.06296340f, -0.12993270f, 0.03855852f, 0.05186560f, 0.10839908f, -0.03380463f, -0.12654832f, -0.05399339f, -0.07456800f, -0.04736232f, -0.10164231f, 0.07496139f, 0.08125214f, 0.07656177f, -0.04999603f, -0.12823077f, -0.07692395f, -0.11317524f, -0.09118655f, -0.05695669f, 0.10477209f, 0.07468581f, 0.01630048f, -8.00961629e-003f, -0.06582128f, -0.04019095f, -0.04682907f, -0.01907842f, -0.10997720f, 0.04911406f, 0.02931030f, 0.04197735f, -0.05773980f, -0.09670641f, -0.03594951f, -0.03402121f, -0.07149299f, -0.10566200f, 0.10601286f, 0.06340689f, -0.01518632f, -5.96402306e-003f, -0.07628012f, -3.52779147e-003f, -0.02683854f, -0.10265494f, -0.02680815f, 0.16338381f, 0.03103515f, 0.02296976f, 0.01624348f, -0.10831620f, -0.02314233f, -0.04789969f, -0.05530700f, -0.06461314f, 0.10494506f, 0.04642856f, -0.07592955f, -0.06197905f, -0.09042154f, -0.01445521f, -0.04297818f, -0.11262015f, -0.11430512f, 0.03174541f, -0.03677487f, -0.02963996f, -0.06610169f, -0.13292049f, -0.07059067f, -0.08444111f, -0.02640536f, -0.07136250f, 0.04559967f, 0.01459980f, 0.17989251f, 0.04435328f, -0.12464730f, -0.02871115f, -0.10752209f, -0.03393742f, -0.03791408f, 0.02548251f, 0.01956050f, 0.19245651f, 0.13963254f, -0.05904696f, -0.07424626f, -0.10411884f, 1.54176133e-003f, 0.01797429f, 0.13025844f, 0.04547642f, -0.05710349f, -0.10697161f, -0.13489437f, -0.06515755f, -0.06406886f, -4.08572936e-003f, -0.01336483f, 0.04368737f, -0.11259720f, -0.05701635f, -0.06469971f, -0.08346602f, -0.04166770f, -0.05795543f, -0.08247511f, -0.05742628f, 0.08452254f, -0.03350224f, 0.13980860f, 0.13252275f, 0.07589617f, 0.07539988f, 0.12155797f, 0.19087289f, 0.15050751f, 0.21250245f, 0.14206800f, 0.01298489f, 0.07450245f, 0.06559097f, 0.01700557f, 0.04512971f, 0.16950700f, 0.10261577f, 0.16389982f, 0.05505059f, -0.03453077f, 0.08622462f, 0.07935954f, 0.03976260f, 0.02036091f, 3.95744899e-003f, 0.03267065f, 0.15235919f, 0.01297494f, -0.08109194f, 0.01407558f, 4.40693414e-003f, -0.15157418f, -0.11390478f, -0.07487597f, -7.81322457e-003f, -0.02749545f, -0.10181408f, 0.13755716f, 0.14007211f, 0.13482562f, 0.27517235f, 0.34251109f, 0.07639657f, 0.07268607f, 0.19823882f, 0.16135791f, -0.04186463f, -0.12784107f, -0.09846287f, 0.03169041f, 0.10974082f, -0.15051922f, -0.08916726f, -0.07138767f, -0.04153349f, 6.25418453e-003f, 0.01266654f, 0.10533249f, 0.12749144f, 0.15148053f, 0.01498513f, 0.06305949f, -0.01247123f, -0.08778401f, -0.08551880f, -0.11955146f, -0.08493572f, -0.02901620f, -0.02394859f, -0.13427313f, -0.11053200f, -0.14413260f, -0.15203285f, 0.03972760f, -3.72127310e-004f, -0.04200919f, 0.06105104f, 0.01904975f, -0.01106191f, -7.27445772e-003f, -0.01520341f, 1.10228511e-003f, -0.04949187f, -0.08013099f, 5.72071038e-003f, 0.08415454f, -0.06523152f, 0.03664081f, -0.02673042f, -0.12066154f, -0.03702074f, 0.06006580f, 0.01628682f, -6.17772620e-003f, 0.08192339f, -3.41629819e-003f, 0.02870512f, 0.05807141f, 0.04959986f, 0.04618251f, -0.04901629f, -0.10579574f, 0.02274442f, 0.12070961f, 2.23597488e-003f, 0.09831765f, -0.03019848f, -0.11181970f, -0.04961075f, 0.02498928f, -0.03714991f, -0.01619653f, 0.02643486f, -7.62964319e-003f, -0.02882290f, -0.06242594f, -0.08439861f, 0.07220893f, 0.07263952f, 0.01561574f, 0.03091968f, 0.01708712f, -0.03797151f, -3.18561122e-003f, 0.01624021f, -0.02828573f, 0.11284444f, -1.32280716e-003f, -0.07784860f, -0.07209100f, 0.03372242f, 0.12154529f, 0.02278104f, -0.05275500f, -0.01918484f, 0.12989293f, 0.05424401f, 0.02333086f, 0.04029022f, 0.12392918f, 0.09495489f, 0.09190340f, 0.07935889f, 8.76816828e-003f, 0.17148446f, -8.51302687e-003f, -0.08011249f, -0.06796283f, 0.04884845f, 0.01112272f, -0.07835306f, -1.14811445e-003f, -0.03440760f, 0.02845243f, 0.07695542f, -0.07069533f, -0.01151784f, -8.53884313e-003f, -0.01662786f, -0.04163864f, 0.05400505f, 0.02859163f, 0.02921852f, 0.05003135f, -6.85718050e-003f, -0.01632611f, 0.07780217f, 0.04042810f, -0.01216440f, 3.60914599e-003f, -0.06322435f, 0.09516726f, 0.12877031f, -9.69162490e-003f, 0.01031179f, 0.05180895f, -9.34659224e-003f, -0.01644533f, -0.04849347f, -0.04343236f, 0.10514783f, 0.08046635f, -0.04615205f, -0.03975486f, -0.01485525f, 0.13096830f, -0.01517950f, -0.06571898f, -0.04016372f, 0.01849786f, 0.02439670f, 0.08067258f, 1.74824719e-003f, 0.07053747f, 0.08819518f, -5.08352555e-003f, -0.06550863f, -0.08266170f, -0.07780605f, 0.01453450f, -0.08756890f, 0.01096501f, -8.71319138e-003f, 0.10110464f, 0.02420769f, -0.06708383f, 0.02007811f, 5.93133038e-003f, 0.05398923f, 0.07538138f, 0.02049227f, 0.02242589f, 0.04011070f, -1.44875818e-003f, -4.19115182e-003f, 0.06367654f, 0.02506934f, 0.02434536f, 0.05879405f, -8.22952855e-003f, -0.01242441f, 0.04224926f, -0.01754923f, 0.05958161f, 0.03818886f, -0.01830363f, -0.04308917f, -0.04422197f, -0.02432721f, 0.02264866f, 2.03751423e-003f, 0.01197031f, 0.04439203f, 0.12169247f, 0.03602713f, -0.02599251f, -1.98226492e-003f, 0.02046336f, -0.02639058f, -1.91242550e-003f, -0.09334669f, -0.03595153f, -9.88179818e-003f, -0.06848445f, -0.04666303f, -0.09955736f, -0.04206430f, 0.02609075f, 9.09005292e-003f, -0.07138551f, -4.22313227e-004f, 0.01766645f, 0.02756404f, 0.01308276f, 0.04052891f, 0.02387515f, 0.05337298f, 0.02500631f, -0.04970853f, -0.12467445f, 0.17604403f, 0.12256411f, -0.07512254f, 8.70451052e-003f, -0.05697548f, -0.03626474f, -8.76623299e-003f, -0.01210897f, -0.09451522f, 0.07490732f, -0.02008001f, -0.02681278f, -0.06463405f, -0.01517507f, 7.33757764e-003f, 6.07147906e-003f, -0.09316964f, -0.04575328f, 0.13261597f, 0.15424870f, -0.01655918f, -0.02772390f, -0.05243644f, -0.02356456f, -0.02351753f, -0.10211615f, -0.12873036f, 0.14549787f, 0.12519856f, 4.38762689e-003f, 0.02795992f, 0.05170322f, 0.09223596f, 0.05890015f, 0.02376701f, -0.02777346f, 0.09506908f, 0.02328936f, -0.02319928f, -0.03218696f, -0.01527841f, -0.01016694f, -0.02674719f, 0.05137179f, 0.01980666f, 0.06544447f, -0.01746171f, 0.01026380f, 0.01561806f, 7.97004555e-004f, 0.07601810f, 0.01907250f, -0.03083035f, -0.05987392f, 0.09242783f, 0.14555025f, 0.01035827f, 0.03092401f, -0.09562709f, -0.03802354f, 0.02531144f, 0.03079449f, -0.07100715f, 0.03330721f, -2.69116857e-003f, 0.03167490f, 0.05744999f, 0.03259895f, 1.91266940e-003f, 0.03194578f, 0.07389776f, 0.02198060f, 0.07633314f, 0.03293105f, -0.09103648f, 0.04718142f, 0.06102672f, -0.01003063f, 5.85481385e-003f, -0.01522574f, 0.02323526f, 0.10584345f, 4.35879454e-003f, 0.06107873f, 0.05868603f, -0.03115531f, 0.01214679f, 0.08567052f, 3.93926632e-003f, -0.02521488f, -1.88425183e-003f, 0.02038053f, -6.26854831e-004f, 0.04897438f, -0.04280585f, -0.04819689f, -0.04812867f, -0.01451186f, 0.05101469f, -9.01125465e-003f, -0.03333859f, 0.03917955f, 0.04196448f, 0.04292135f, 0.02809529f, 0.02999715f, 0.04081348f, 9.10039060e-003f, 0.09703232f, 0.10379741f, 0.02348725f, -4.72756615e-003f, 0.01027325f, 0.10402658f, 0.12071823f, 0.09817299f, -0.02612033f, 0.03638414f, 0.05896405f, 0.04865025f, 0.04793910f, -0.03882321f, -0.02962117f, -0.01222268f, 0.04071597f, 0.01922777f, -0.02287866f, 0.03328381f, 0.01859092f, 0.09024994f, 0.03804455f, -0.01424510f, 0.01953739f, 0.02509617f, -0.03390914f, -0.05663941f, -0.01641979f, 0.05848591f, 0.04639670f, 0.02092116f, 0.12911791f, 0.19918139f, 0.07739855f, -7.25806039e-003f, 0.04074838f, 0.03183993f, 1.39251316e-003f, -0.01428625f, 0.01865480f, 0.08529541f, 0.13547510f, 0.11189661f, 0.03998901f, 0.09575938f, -0.02631102f, -0.03458253f, -0.04749985f, -0.06070716f, 4.71884012e-003f, 0.06445789f, -0.02450038f, -0.05483776f, -0.04657237f, -0.02030717f, -0.03480766f, -0.09397731f, -0.06399718f, -0.01804585f, 5.62348310e-003f, -6.64811488e-003f, -0.06517869f, 6.96210237e-003f, -0.01860148f, -0.04245830f, -0.05850367f, -3.24417115e-003f, 0.07700698f, 0.11290991f, 0.09923030f, -0.02970599f, 0.05592411f, 0.04813979f, -0.09811195f, -0.09357996f, -0.03276114f, 0.05218338f, 0.04141375f, 3.92977800e-003f, -0.05047480f, 0.15960084f, 0.04612800f, -0.03114098f, -0.04650044f, -0.03249795f, -0.02425641f, -0.04311355f, 0.04307659f, -0.09401883f, -0.04742785f, -0.01254499f, -0.06598741f, 3.41369561e-003f, -0.05620445f, -7.28127593e-003f, -0.05998361f, -0.03274450f, -0.07376868f, 3.19015374e-003f, -0.07733069f, 0.05815864f, -0.02471071f, 0.03850617f, 0.13838784f, 0.15399861f, 0.01731321f, -0.01477586f, 0.10393341f, 0.05159833f, -0.01945555f, -0.03427503f, -0.04867341f, 0.09237480f, 0.10732719f, 0.06071450f, -0.01355071f, 0.01844356f, -0.03480803f, -0.03796671f, 2.15628621e-004f, -0.05440186f, 0.01889855f, -0.01443413f, -0.02607902f, -0.02938001f, 0.02720689f, -0.06228397f, -0.02970936f, -0.03426210f, -0.10280876f, -0.06739304f, -0.05227850f, 0.03360292f, -0.11278441f, -0.06966180f, -0.13937433f, 9.10932291e-003f, 2.52020749e-004f, -4.07359656e-003f, 0.12310639f, 0.09343060f, 0.07302511f, 0.03222093f, 0.07532879f, 0.03792387f, -0.04985180f, 0.01804602f, 0.02694195f, 0.13481498f, 0.04601225f, 0.04106982f, 0.08511057f, 0.12314661f, 0.01320830f, 0.05044121f, -5.52943908e-003f, -0.08992624f, -0.02249301f, -0.08181777f, 0.06165213f, -0.03256603f, -0.01068920f, -0.01323473f, -0.11970232f, -0.04616347f, -0.12088681f, -0.06762606f, -0.08676834f, -0.06434575f, 0.01772529f, 0.03469615f, -0.10926618f, 0.03013873f, 0.14030397f, 0.16130108f, 0.17985588f, 0.11281928f, 0.10530639f, 0.08905948f, 0.07733764f, 0.06695238f, 0.02142088f, 0.06438877f, 0.09794453f, 0.05745072f, 0.02788557f, 0.02632830f, 0.07985807f, 4.24902979e-003f, 8.47890321e-003f, -0.02679466f, -5.28812688e-003f, -0.02162580f, -0.07490715f, -0.08251337f, -0.02056576f, -0.01026194f, -1.15492963e-003f, -5.75720915e-004f, -0.07210591f, -0.07320981f, -0.04883312f, -0.10897151f, -0.07477258f, -0.08867134f, -0.09222437f, -0.10924666f, -0.10430276f, 0.07953499f, 0.02767959f, 0.11393359f, 0.18779543f, 0.03313421f, 0.02143700f, 0.05852016f, -2.12067598e-003f, -3.76984011e-003f, 0.02774167f, -0.03124610f, 0.01465141f, 0.01616004f, -0.01391913f, -0.04404102f, -0.05444227f, -0.14684731f, -0.15016587f, 0.04509468f, 1.29563001e-003f, 0.01398350f, 0.05610404f, -0.04868806f, -0.04776716f, -8.16873740e-003f, -2.30126386e-003f, -0.02286313f, 0.11983398f, -0.04703261f, -0.08814441f, -0.07585249f, -0.10799607f, -0.03232087f, 0.01509786f, -0.04843464f, -0.03967846f, 0.09589416f, 0.01352560f, -0.01458119f, 0.01050829f, -0.03038946f, 0.01608388f, 1.11975556e-003f, -0.01250656f, 2.86211423e-003f, 0.04333691f, -0.14603497f, -0.01946543f, -0.02327525f, -0.01973944f, 0.07944400f, -0.02224544f, -0.06701808f, 0.03476532f, 0.11505594f, -0.02712801f, -0.01665113f, 0.06315716f, -0.08205860f, 0.07431999f, 0.04915778f, -0.04468752f, -0.01490402f, 0.07400476f, -0.11650901f, 0.05102430f, 0.04559118f, -0.05916039f, 0.08840760f, -0.01587902f, -0.14890194f, 0.07857784f, 0.04710254f, -0.05381983f, -0.07331945f, -0.03604643f, 0.15611970f, 0.07649943f, -0.05959348f, -0.02776607f, 0.11098688f, 0.03758875f, -0.04446875f, 0.04933187f, 0.01345535f, 0.06921103f, 0.07364785f, 0.05518956f, 0.02899585f, 0.09375840f, 0.10518434f, -0.04420241f, 0.01915282f, -3.56386811e-003f, 0.14586878f, 0.10286101f, -0.04360626f, -0.12723237f, 0.09076386f, 0.11119842f, -0.06035013f, 0.09674817f, 0.08938243f, 0.07065924f, 0.02603180f, 5.84815582e-003f, -0.05922065f, 0.12360309f, 3.59695964e-003f, 2.99844006e-003f, 0.03697936f, 0.02043072f, 0.04168725f, 0.01025975f, -0.01359980f, -0.01600920f, 0.02581056f, 0.02329250f, 2.98100687e-003f, 0.01629762f, 0.06652115f, 0.05855627f, 0.01237463f, -0.01297135f, 0.01761587f, 0.05090865f, 0.06549342f, -0.04425945f, 2.43203156e-003f, 3.07327788e-003f, 0.06678630f, -0.04303836f, 0.01082393f, -0.06476044f, 0.04077786f, 0.12441979f, 0.08237778f, 0.07424165f, 0.04065890f, 0.06905543f, 0.09556347f, 0.12724875f, -0.02132082f, 0.08514154f, -0.04175328f, -0.02666954f, 0.01897836f, 0.03317382f, 9.45465732e-003f, -0.01238974f, -0.04242500f, -0.01419479f, -0.03545213f, -0.02440874f, 0.08684119f, 0.04212951f, 0.02462858f, -0.01104825f, -5.01706870e-003f, 0.02968982f, 0.02597476f, -0.01568939f, 0.04514892f, 0.06974549f, 0.08670278f, 0.06828108f, 0.10238872f, 0.05405957f, 0.06548470f, -0.03763957f, 0.01366090f, 0.07069602f, 0.05363748f, 0.04798120f, 0.11706422f, 0.05466456f, -0.01869259f, 0.06344382f, 0.03106543f, 0.08432506f, -0.02061096f, 0.03821088f, -6.92190882e-003f, 6.40467042e-003f, -0.01271779f, 6.89014705e-005f, 0.04541415f, -0.01899539f, -0.05020239f, 0.03000903f, 0.01090422f, 4.52452758e-003f, 0.02573632f, -0.02388454f, -0.04200457f, 1.72783900e-003f, -0.05978370f, -0.02720562f, 0.06573715f, 0.01154317f, 0.01265615f, 0.07375994f, -9.19828378e-003f, -0.04914120f, 0.02124831f, 0.06455322f, 0.04372910f, -0.03310043f, 0.03605788f, -6.78055827e-003f, 9.36202332e-003f, 0.01747596f, -0.06406314f, -0.06812935f, 0.08080816f, -0.02778088f, 0.02735260f, 0.06393493f, 0.06652229f, 0.05676993f, 0.08640018f, -7.59188086e-003f, -0.02012847f, -0.04741159f, -0.01657069f, -0.01624399f, 0.05547778f, -2.33309763e-003f, 0.01120033f, 0.06141156f, -0.06285004f, -0.08732341f, -0.09313398f, -0.04267832f, 5.57443965e-003f, 0.04809862f, 0.01773641f, 5.37361018e-003f, 0.14842421f, -0.06298012f, -0.02935147f, 0.11443478f, -0.05034208f, 5.65494271e-003f, 0.02076526f, -0.04577984f, -0.04735741f, 0.02961071f, -0.09307127f, -0.04417921f, -0.04990027f, -0.03940028f, 0.01306016f, 0.06267900f, 0.03758737f, 0.08460117f, 0.13858789f, 0.04862388f, -0.06319809f, -0.05655516f, 0.01885816f, -0.03285607f, 0.03371567f, -0.07040928f, -0.04514049f, 0.01392166f, 0.08184422f, -0.07230316f, 0.02386871f, 0.02184591f, 0.02605764f, -0.01033954f, 9.29878280e-003f, 7.67351175e-003f, 0.15189242f, 0.02069071f, -0.09738296f, -0.08894105f, -0.07768748f, 0.02332268f, -0.01778995f, -0.03258888f, -0.08180822f, -0.08492987f, 0.02290156f, -0.11368170f, -0.03554465f, -0.04533844f, -0.02861580f, 0.06782424f, 0.01113123f, 0.02453644f, 0.12721945f, 0.08084814f, -0.03607795f, 0.01109122f, 0.04803548f, -0.03489929f, 0.03399536f, -0.05682014f, 8.59533902e-003f, -4.27904585e-003f, 0.03230887f, -0.01300198f, -0.01038137f, -0.07930113f, 8.33097473e-003f, 0.02296994f, -0.01306500f, -0.01881626f, 0.04413369f, 0.05729880f, -0.03761553f, 0.01942326f, 1.64540811e-003f, -0.03811319f, 0.04190650f, -0.14978096f, -0.04514487f, 0.01209545f, -5.46460645e-003f, -0.01647195f, 7.63064111e-003f, -0.07494587f, 0.08415288f, 0.10020141f, -0.01228561f, 0.06553826f, 0.04554005f, 0.07890417f, 0.03041138f, 0.01752007f, 0.09208256f, -3.74419295e-004f, 0.10549527f, 0.04686913f, 0.01894833f, -0.02651412f, -4.34682379e-003f, 5.44942822e-003f, 0.01444484f, 0.05882156f, -0.03336544f, 0.04603891f, -0.10432546f, 0.01923928f, 0.01842845f, -0.01712168f, -0.02222766f, 0.04693324f, -0.06202956f, -0.01422159f, 0.08732220f, -0.07706107f, 0.02661049f, -0.04300238f, -0.03092422f, -0.03552184f, -0.01886088f, -0.04979934f, 0.03906401f, 0.04608644f, 0.04966111f, 0.04275464f, -0.04621769f, -0.02653212f, 8.57011229e-003f, 0.03839684f, 0.05818764f, 0.03880796f, -2.76100676e-004f, 0.03076511f, -0.03266929f, -0.05374557f, 0.04986527f, -9.45429131e-003f, 0.03582499f, -2.64564669e-003f, -1.07461517e-003f, 0.02962313f, -0.01483363f, 0.03060869f, 0.02448327f, 0.01845641f, 0.03282966f, -0.03534438f, -0.01084059f, -0.01119136f, -1.85360224e-003f, -5.94652840e-004f, -0.04451817f, 2.98327743e-003f, 0.06272484f, -0.02152076f, -3.05971340e-003f, -0.05070828f, 0.01531762f, 0.01282815f, 0.05167150f, 9.46266949e-003f, -3.34558333e-003f, 0.11442288f, -0.03906701f, -2.67325155e-003f, 0.03069184f, -0.01134165f, 0.02949462f, 0.02879886f, 0.03855566f, -0.03450781f, 0.09142872f, -0.02156654f, 0.06075062f, -0.06220816f, 0.01944680f, 6.68372354e-003f, -0.06656796f, 8.70784000e-003f, 0.03456013f, 0.02434320f, -0.13236357f, -0.04177035f, -0.02069627f, 0.01068112f, 0.01505432f, -0.07517391f, -3.83571628e-003f, -0.06298508f, -0.02881260f, -0.13101046f, -0.07221562f, -5.79945277e-003f, -8.57300125e-003f, 0.03782469f, 0.02762164f, 0.04942456f, -0.02936396f, 0.09597211f, 0.01921411f, 0.06101191f, -0.04787507f, -0.01379578f, -7.40224449e-003f, -0.02220136f, -0.01313756f, 7.77558051e-003f, 0.12296968f, 0.02939998f, 0.03594062f, -0.07788624f, -0.01133144f, 3.99316690e-004f, -0.06090347f, -0.01122066f, -4.68682544e-003f, 0.07633100f, -0.06748922f, -0.05640298f, -0.05265681f, -0.01139122f, -0.01624347f, -0.04715714f, -0.01099092f, 0.01048561f, 3.28499987e-003f, -0.05810167f, -0.07699911f, -0.03330683f, 0.04185145f, 0.03478536f, 0.02275165f, 0.02304766f, 6.66040834e-003f, 0.10968148f, -5.93013782e-003f, -0.04858336f, -0.04203213f, -0.09316786f, -6.13074889e-003f, -0.02544625f, 0.01366201f, 9.18555818e-003f, -0.01846578f, -0.05622401f, -0.03989377f, -0.07810296f, 6.91275718e-003f, 0.05957597f, -0.03901334f, 0.01572002f, -0.01193903f, -6.89400872e-003f, -0.03093356f, -0.04136098f, -0.01562869f, -0.04604580f, 0.02865234f, -0.08678447f, -0.03232484f, -0.05364593f, -0.01445016f, -0.07003860f, -0.08669746f, -0.04520775f, 0.04274122f, 0.03117515f, 0.08175703f, 0.01081109f, 0.06379741f, 0.06199206f, 0.02865988f, 0.02360346f, 0.06725410f, -0.03248780f, -9.37702879e-003f, 0.08265898f, -0.02245839f, 0.05125763f, -0.01862395f, 0.01973453f, -0.01994494f, -0.10770868f, 0.03180375f, 3.23935156e-003f, -0.02142080f, -0.04256190f, 0.04760900f, 0.04282863f, 0.05635953f, -0.01870849f, 0.05540622f, -0.03042666f, 0.01455277f, -0.06630179f, -0.05843807f, -0.03739681f, -0.09739155f, -0.03220233f, -0.05620182f, -0.10381401f, 0.07400211f, 4.20676917e-003f, 0.03258535f, 2.14308966e-003f, 0.05121966f, -0.01274337f, 0.02384761f, 0.06335578f, -0.07905591f, 0.08375625f, -0.07898903f, -0.06508528f, -0.02498444f, 0.06535810f, 0.03970535f, 0.04895468f, -0.01169566f, -0.03980601f, 0.05682293f, 0.05925463f, -0.01165808f, -0.07936699f, -0.04208954f, 0.01333987f, 0.09051196f, 0.10098671f, -0.03974256f, 0.01238771f, -0.07501741f, -0.03655440f, -0.04301528f, 0.09216860f, 4.63579083e-004f, 0.02851115f, 0.02142735f, 1.28244064e-004f, 0.02879687f, -0.08554889f, -0.04838862f, 0.08135369f, -0.05756533f, 0.01413900f, 0.03451880f, -0.06619488f, -0.03053130f, 0.02961676f, -0.07384635f, 0.01135692f, 0.05283910f, -0.07778034f, -0.02107482f, -0.05511716f, -0.13473752f, 0.03030157f, 0.06722020f, -0.06218817f, -0.05826827f, 0.06254654f, 0.02895772f, -0.01664000f, -0.03620280f, -0.01612278f, -1.46097376e-003f, 0.14013411f, -8.96181818e-003f, -0.03250246f, 3.38630192e-003f, 2.64779478e-003f, 0.03359732f, -0.02411991f, -0.04229729f, 0.10666174f, -6.66579151f }; return std::vector<float>(detector, detector + sizeof(detector)/sizeof(detector[0])); } #endif
#include<pcl/common/file_io.h> #include<pcl/point_cloud.h> #include<vector> #include<ctime> #include<fstream> #include<iostream> #include<utility> #include<Eigen/Dense> #include<Eigen/Geometry> #include <pcl/common/common_headers.h> #include <pcl/kdtree/kdtree_flann.h> using namespace std; namespace map3d{ /** * \brief vanilla-R iterative closest point algorithm * \example * map3d::ICP icp(k,search_r_up,d_threshold,step_degrade); * icp.setInputCloud(src,dst); * icp.setParamsConvergence(); * icp.solve(R,t) */ class ICP{ public: string Options; /** * \member k , algorithm ask number of the eligable pairs to be up to k, or the algorithm will be unstable, and then the flag wiil be set as flase */ int k; /** * \memberof search_r_low normally is zero, don't change it */ float search_r_low; float search_r_up; //Because search raduis must be a positive value, so the floor_r set a min upper bound float floor_r; float step_degrade; float d_threshold; //In this programm, a search time for matching points in different point cloud is used to determine whether ICP can continue to run, if search timeout, flag is false bool flag; float timeout; //the very closest point to origin usually is noise point, so the bounds is used to filter those nosie points. float filter_low_bounds; /** * \member final_pairs store the final index of point pairs used to solve transform. That are useful for compute InformationMatrix for pose graph */ vector< pair<int, int> > final_pairs; /** * @brief ICP constructor function, there are huge amounts of parameters need to be set. * All parameters has a default value. normally the four parameters in left are especially important for user to adpat their situations. */ ICP(int k_=500,float search_r_up_=1010, float d_threshold_=10,float step_degrade_=25,float floor_r_=5,float search_r_low_=0, float filter_low_bounds_=40, float timeout_=0.5, bool flag_=true) { k=k_; search_r_low=search_r_low_; search_r_up=search_r_up_; d_threshold=d_threshold_; step_degrade=step_degrade_; floor_r=floor_r_; flag=flag_; filter_low_bounds=filter_low_bounds_; timeout=timeout_; } /** * @brief setInputCloud for registering. * @param SCP is source point cloud * @param TCP is target point cloud */ void setInputCloud(pcl::PointCloud<pcl::PointXYZ>::Ptr SCP, pcl::PointCloud<pcl::PointXYZ>::Ptr TCP) { sourceCloudPtr=SCP; targetCloudPtr=TCP; } /** *\brief *\param[in] iter_maxnum *\param[out] */ void setParamsConvergence( int iter_maxnum_=80, int convergence_counter_max_=2, float sigma_=2.1,float error_belta_=0.2) { iter_maxnum=iter_maxnum_; convergence_counter_max=convergence_counter_max_; error_sigma=sigma_; error_belta=error_belta_; } //************************************************************************************************** bool Vanllia_R(int index, int &pairIndex, pcl::PointCloud<pcl::PointXYZ>::ConstPtr middle_cloud_ptr,const pcl::KdTreeFLANN<pcl::PointXYZ> &kdtree , const pcl::KdTreeFLANN<pcl::PointXYZ> &kdtree1) const { size_t K=1; vector<int> pointIdxNKNSearch(K);//用来存放搜索到的点的index vector<int> pointIdxNKNSearch1(K); vector<float> pointNKNSquaredDistance(K);//存放搜索到的点到当前的欧式距离 vector<float> pointNKNSquaredDistance1(K); kdtree.nearestKSearch (middle_cloud_ptr->points[index], K, pointIdxNKNSearch, pointNKNSquaredDistance); pairIndex=pointIdxNKNSearch[0]; //ICRP if((pointNKNSquaredDistance[0]<=search_r_up)&&(pointNKNSquaredDistance[0]>=search_r_low)) { kdtree1.nearestKSearch(targetCloudPtr->points[pointIdxNKNSearch[0]],K,pointIdxNKNSearch1, pointNKNSquaredDistance1); double d; d=pow(abs(middle_cloud_ptr->points[pointIdxNKNSearch1[0]].x-middle_cloud_ptr->points[index].x),2) +pow(abs(middle_cloud_ptr->points[pointIdxNKNSearch1[0]].y-middle_cloud_ptr->points[index].y),2) +pow(abs(middle_cloud_ptr->points[pointIdxNKNSearch1[0]].z-middle_cloud_ptr->points[index].z),2); d=sqrt(d); if(d<d_threshold) { return true; } else { return false; } } else { return false; } } /** *\brief SVD decompostion is used to solve the transform between two point cloud while the pair relation is knowned. This function can be improved using index of pairs instead of pairs themselves * \param[in] * \param[in] * \param[out] * \param[out] */ void registration(pcl::PointCloud<pcl::PointXYZ>::Ptr filter_initPoints,pcl::PointCloud<pcl::PointXYZ>::Ptr filter_matchedPoints,Eigen::Matrix3f &R_svd,Eigen::Vector3f &t_translate) { Eigen::Vector3f centriod_initPoints(0,0,0);//初始点云中心,当向量维数小于4的时候,这样的初始化也是被允许的 Eigen::Vector3f centriod_matchedPoints(0,0,0);//匹配到的点云中心 Eigen::Matrix3f U,V,S; size_t filter_k;//经过ICRP过滤后的点对数目 filter_k=filter_initPoints->points.size(); Eigen::MatrixXf W; for(int i=0;i<filter_k;i++) { Eigen::Vector3f temV; temV<<filter_initPoints->points[i].x,filter_initPoints->points[i].y,filter_initPoints->points[i].z;//p centriod_initPoints+=temV; temV<<filter_matchedPoints->points[i].x,filter_matchedPoints->points[i].y,filter_matchedPoints->points[i].z;//y centriod_matchedPoints+=temV; } centriod_initPoints/=(float)filter_k; centriod_matchedPoints/=(float)filter_k; for(int i=0;i<filter_k;i++) { Eigen::Vector3f temV1; Eigen::Vector3f temV2; temV1<<filter_initPoints->points[i].x,filter_initPoints->points[i].y,filter_initPoints->points[i].z; temV1-=centriod_initPoints; temV2<<filter_matchedPoints->points[i].x,filter_matchedPoints->points[i].y,filter_matchedPoints->points[i].z; temV2-=centriod_matchedPoints; if (i==0) {W=temV2*temV1.transpose();} else {W+=temV2*temV1.transpose();}//y*p' } W/=(float)filter_k; Eigen::JacobiSVD<Eigen::MatrixXf> svd(W,Eigen::ComputeFullU|Eigen::ComputeFullV); U=svd.matrixU();//不建议写成Eigen::Matrix3f U=svd.matrixU(); V=svd.matrixV(); S<<1,0,0, 0,1,0, 0,0,U.determinant()*V.determinant(); R_svd=U*S*V.transpose(); //y-R*p.求出的是initPoints点所在坐标系到matchedPoints点所在坐标系位移,注意这个位移是表示在matchedPoints坐标系下的,这里也就是global坐标系下 t_translate=centriod_matchedPoints-R_svd*centriod_initPoints; cout<<"find the rotation Matrix using SVD method:"<<endl <<R_svd<<endl <<"平移:"<<endl <<t_translate<<endl; } /** *@brief set a initial pose esimation, and then this function will solve a optimazition for registration. * If icp failed to match points, member flag will be set as false, and this funtion will return initial estimation as final result. \brief * *\param[in] R_0 *\param[in] t_0 * \param[out] R_k * \param[out] t_k */ void solve(Eigen::Matrix3f &R_k, Eigen::Vector3f &t_k) { R_update=R_k;//不应该再转置了,数据中的意思就是第二次到第一次的位姿 t_update=t_k; pcl::PointXYZ initPoints[k];//随机找出k个点云并存放在这个类数组中 pcl::PointXYZ points_transformed;//并应用初始旋转 pcl::PointXYZ matchedPoints[k];//匹配得到的点 pcl::PointXYZ matchedPoints1[k]; pcl::KdTreeFLANN<pcl::PointXYZ> kdtree; kdtree.setInputCloud(targetCloudPtr);//把点云按照kdtree形式存储 float error_current; float error_last=0; int convergence_counter=0; int iterative_counter=0; while(convergence_counter<=convergence_counter_max&&iterative_counter<iter_maxnum) { pcl::PointCloud<pcl::PointXYZ>::Ptr filter_initPoints(new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>::Ptr filter_matchedPoints(new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>::Ptr middle_cloud_ptr (new pcl::PointCloud<pcl::PointXYZ>); //store index of pairs. for example (j, k) represent that jth point in source point cloud is assicated with kth point in Targetcloud vector<pair<int, int> > index_pairs; Eigen::Vector3f v1; Eigen::Vector3f v2; for(int i=0;i<sourceCloudPtr->points.size();i++) { v1(0)=sourceCloudPtr->points[i].x; v1(1)=sourceCloudPtr->points[i].y; v1(2)=sourceCloudPtr->points[i].z; v2=R_update*v1;//应用初始的旋转 points_transformed.x=v2(0)+t_update(0); points_transformed.y=v2(1)+t_update(1); points_transformed.z=v2(2)+t_update(2); middle_cloud_ptr->points.push_back(points_transformed); } pcl::KdTreeFLANN<pcl::PointXYZ> kdtree_midCloudPtr; kdtree_midCloudPtr.setInputCloud(middle_cloud_ptr); int nPoint_current=sourceCloudPtr->points.size(); int *p=new int; int i=0; int counter=0; time_t begin_search=clock(); while(i<k) { int j; unsigned int R; unsigned int t; time_t search_t=clock(); if(float(search_t-begin_search)/CLOCKS_PER_SEC>timeout) { flag=false; break; } L1: R = RAND_MAX-(RAND_MAX+1)%nPoint_current; //去除尾数 t = rand(); while( t > R ) t = rand(); j = t % nPoint_current; if (counter==0) p[counter]=j; else { for(int m=0;m<counter;m++) { if(p[m]==j) { cout<<"back"; goto L1; } } p[++counter]=j; } float filter_r;//激光近距离点是用来标记的,不用于匹配 filter_r=sqrt(pow(sourceCloudPtr->points[j].x,2)+pow(sourceCloudPtr->points[j].y,2)+pow(sourceCloudPtr->points[j].y,2)); if(filter_r>filter_low_bounds) { int pairIndex; bool flag_vanllia_R=Vanllia_R(j,pairIndex,middle_cloud_ptr,kdtree,kdtree_midCloudPtr); if(flag_vanllia_R) { filter_initPoints->points.push_back(sourceCloudPtr->points[j]); filter_matchedPoints->points.push_back(targetCloudPtr->points[pairIndex]); pair<int,int> tempair(j,pairIndex); index_pairs.push_back(tempair); i++; } } } if(flag==true) { final_pairs=index_pairs; // final_pairs.assign(index_pairs.begin(),index_pairs.end()); registration(filter_initPoints,filter_matchedPoints,R_update,t_update); //****************************************************************************************** //用于配准的内部点对误差统计 //****************************************************************************************** error_current=0; for(int j=0;j<filter_initPoints->size();++j) { Eigen::Vector3f temV1; Eigen::Vector3f temV2; temV1<<filter_initPoints->points[j].x,filter_initPoints->points[j].y,filter_initPoints->points[j].z; temV2<<filter_matchedPoints->points[j].x,filter_matchedPoints->points[j].y,filter_matchedPoints->points[j].z; temV1=R_update*temV1+t_update-temV2; error_current+=sqrt(temV1.dot(temV1)); } //note that error_final should satisfy following equation rather than "error_final=error_current" error_final=pow(error_current,2); /*******************************************************************************************/ //******************************************************************************************* //收敛准则 //******************************************************************************************* int filter_num=filter_initPoints->points.size(); if(abs(error_current-error_last)/filter_num<error_belta&&(error_current/(float)filter_num<error_sigma)) convergence_counter+=1; error_last=error_current; if(search_r_up>(step_degrade+floor_r)) search_r_up-=step_degrade; else { search_r_up=floor_r;} cout<<"the cureent error is equal to:"<<error_current<<endl; iterative_counter++; cout<<"the number of iterative:"<<iterative_counter<<endl; } else { break; } } R_k=R_update; t_k=t_update; } /** * \brief compute infromation matrix for pose graph. Of course, it is not necessary for the situation where registering only two point cloud * InformationMatrix was detemined by registration error and registration residual. The smaller current registration error, the more important the constraints. *one term of registeration residual represents the influence of individual variables on registeration. The bigger it, the more important the variable. * */ void getInformationMatrix(Eigen::Matrix<float,6,6> &InformationMatrix) { InformationMatrix.setZero(); if(flag==true) { // cout<<final_pairs.size(); for(int i=0;i<final_pairs.size();i++) { Eigen::Vector3f temV1; Eigen::Vector3f temV2; /** * temV1<<sourceCloudPtr->points[final_pairs[i].first].x,sourceCloudPtr->points[final_pairs[i].first].y,sourceCloudPtr->points[final_pairs[i].first].z; //temV2<<targetCloudPtr->points[final_pairs[i].second].x,targetCloudPtr->points[final_pairs[i].second].y,targetCloudPtr->points[final_pairs[i].second].z; //temV1=R_update*temV1+t_update-temV2; temV1=R_update*temV1+t_update; //cout<<temV1; Eigen::Matrix<float,3,6> Mk; Mk.block(0,0,3,3).setIdentity(); cout<<Mk.block(0,0,3,3); Mk.block(0,3,3,3)<<0, -temV1[1],-temV1[2], temV1[2],temV1[0],0, -temV1[1], 0,temV1[0]; //cout<<Mk; */ temV1<<sourceCloudPtr->points[final_pairs[i].first].x,sourceCloudPtr->points[final_pairs[i].first].y,sourceCloudPtr->points[final_pairs[i].first].z; temV1=R_update*temV1+t_update; Eigen::Matrix<float,3,6> Mk; Mk.block(0,0,3,3).setIdentity(); Mk.block(0,3,3,3)<<0, -temV1[2],temV1[1], temV1[2],0,-temV1[0], -temV1[1], temV1[0],0; InformationMatrix+=Mk.transpose()*Mk; } InformationMatrix=(3*final_pairs.size()-3)*InformationMatrix/error_final; } else { cout<<"error request for InformationMatrix, Because ICP has failed to register two point cloud"<<endl; } } private: pcl::PointCloud<pcl::PointXYZ>::Ptr sourceCloudPtr; pcl::PointCloud<pcl::PointXYZ>::Ptr targetCloudPtr; /** * \memberof iter_maxnum protect algorithm from infinite loop once the iterative_counter exceed it. */ int iter_maxnum; /** * \memberof convergence_counter_max protect algorithm from decetive convergence, only the times convergence criterion has been satified exceed it, the loop will end */ int convergence_counter_max; /** * \memberof error_sigma is the average registration error that algorithm must reach at least. */ float error_sigma; /** * \memberof error_belta is the error change threshold for each point. Only change small the average error of registration, the algorithm is treated as convergence. */ float error_belta; double error_final; Eigen::Matrix3f R_update; Eigen::Vector3f t_update; }; }
// Copyright 2021 Apex.AI, 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. // Co-developed by Tier IV, Inc. and Apex.AI, Inc. #include <gtest/gtest.h> #include <geometry/intersection.hpp> #include <geometry/convex_hull.hpp> #include <list> struct TestPoint { autoware::common::types::float32_t x; autoware::common::types::float32_t y; }; struct IntersectionTestParams { std::list<TestPoint> polygon1_pts; std::list<TestPoint> polygon2_pts; std::list<TestPoint> expected_intersection_pts; }; void order_ccw(std::list<TestPoint> & points) { const auto end_it = autoware::common::geometry::convex_hull(points); ASSERT_EQ(end_it, points.end()); // Points should have represent a shape } class IntersectionTest : public ::testing::TestWithParam<IntersectionTestParams> { }; TEST_P(IntersectionTest, Basic) { const auto get_ordered_polygon = [](auto polygon) { order_ccw(polygon); return polygon; }; const auto polygon1 = get_ordered_polygon(GetParam().polygon1_pts); const auto polygon2 = get_ordered_polygon(GetParam().polygon2_pts); const auto expected_intersection = get_ordered_polygon(GetParam().expected_intersection_pts); const auto result = autoware::common::geometry::convex_polygon_intersection2d(polygon1, polygon2); ASSERT_EQ(result.size(), expected_intersection.size()); auto expected_shape_it = expected_intersection.begin(); for (auto result_it = result.begin(); result_it != result.end(); ++result_it) { EXPECT_FLOAT_EQ(result_it->x, expected_shape_it->x); EXPECT_FLOAT_EQ(result_it->y, expected_shape_it->y); ++expected_shape_it; } } INSTANTIATE_TEST_SUITE_P( Basic, IntersectionTest, ::testing::Values( IntersectionTestParams{ {}, {}, {} }, IntersectionTestParams{ // Partial intersection {{0.0F, 0.0F}, {10.0F, 0.0F}, {0.0F, 10.0F}, {10.0F, 10.0F}}, {{5.0F, 5.0F}, {15.0F, 5.0F}, {5.0F, 15.0F}, {15.0F, 15.0F}}, {{5.0F, 5.0F}, {10.0F, 5.0F}, {5.0F, 10.0F}, {10.0F, 10.0F}} }, // Full intersection with overlapping edges // TODO(yunus.caliskan): enable after #1231 // IntersectionTestParams{ // {{0.0F, 0.0F}, {10.0F, 0.0F}, {0.0F, 10.0F}, {10.0F, 10.0F}}, // {{5.0F, 5.0F}, {10.0F, 5.0F}, {5.0F, 10.0F}, {10.0F, 10.0F}}, // {{5.0F, 5.0F}, {10.0F, 5.0F}, {5.0F, 10.0F}, {10.0F, 10.0F}}, // }, IntersectionTestParams{ // Fully contained {{0.0F, 0.0F}, {10.0F, 0.0F}, {0.0F, 10.0F}, {10.0F, 10.0F}}, {{5.0F, 5.0F}, {6.0F, 5.0F}, {5.0F, 7.0F}, {8.0F, 8.0F}}, {{5.0F, 5.0F}, {6.0F, 5.0F}, {5.0F, 7.0F}, {8.0F, 8.0F}}, }, IntersectionTestParams{ // Fully contained triangle {{0.0F, 0.0F}, {10.0F, 0.0F}, {0.0F, 10.0F}, {10.0F, 10.0F}}, {{5.0F, 5.0F}, {6.0F, 5.0F}, {5.0F, 7.0F}}, {{5.0F, 5.0F}, {6.0F, 5.0F}, {5.0F, 7.0F}}, }, IntersectionTestParams{ // Triangle rectangle intersection. {{0.0F, 0.0F}, {10.0F, 0.0F}, {0.0F, 10.0F}, {10.0F, 10.0F}}, {{5.0F, 1.0F}, {5.0F, 9.0F}, {15.0F, 5.0F}}, {{5.0F, 1.0F}, {5.0F, 9.0F}, {10.0F, 3.0F}, {10.0F, 7.0F}} }, IntersectionTestParams{ // No intersection {{0.0F, 0.0F}, {10.0F, 0.0F}, {0.0F, 10.0F}, {10.0F, 10.0F}}, {{15.0F, 15.0F}, {20.0F, 15.0F}, {15.0F, 20.0F}, {20.0F, 20.0F}}, {} } // cppcheck-suppress syntaxError )); TEST(PolygonPointTest, Basic) { GTEST_SKIP(); // TODO(yunus.caliskan): enable after #1231 std::list<TestPoint> polygon{{5.0F, 5.0F}, {10.0F, 5.0F}, {5.0F, 10.0F}, {10.0F, 10.0F}}; order_ccw(polygon); EXPECT_FALSE( autoware::common::geometry::is_point_inside_polygon_2d( polygon.begin(), polygon.end(), TestPoint{0.0F, 10.0F})); } // IoU of two intersecting shapes: a pentagon and a square. The test includes pen and paper // computations for the intermediate steps as assertions. TEST(IoUTest, PentagonRectangleIntersection) { std::list<TestPoint> polygon1{ {0.0F, 3.0F}, {3.0F, 4.0F}, {6.0F, 3.0F}, {4.0F, 1.0F}, {2.0F, 1.0F} }; std::list<TestPoint> polygon2{ {3.0F, 0.0F}, {3.0F, 2.0F}, {5.0F, 2.0F}, {5.0F, 0.0F} }; order_ccw(polygon1); order_ccw(polygon2); const auto intersection = autoware::common::geometry::convex_polygon_intersection2d(polygon1, polygon2); const auto expected_intersection_area = autoware::common::geometry::area_2d(intersection.begin(), intersection.end()); ASSERT_FLOAT_EQ(expected_intersection_area, 1.5F); // Pen & paper proof. const auto expected_union_area = autoware::common::geometry::area_2d(polygon1.begin(), polygon1.end()) + autoware::common::geometry::area_2d(polygon2.begin(), polygon2.end()) - expected_intersection_area; ASSERT_FLOAT_EQ(expected_union_area, (11.0F + 4.0F - 1.5F)); // Pen & paper proof. const auto computed_iou = autoware::common::geometry::convex_intersection_over_union_2d(polygon1, polygon2); EXPECT_FLOAT_EQ(computed_iou, expected_intersection_area / expected_union_area); } // IoU of two non-intersecting rectangles. TEST(IoUTest, NoIntersection) { std::list<TestPoint> polygon1{ {0.0F, 0.0F}, {0.0F, 1.0F}, {1.0F, 1.0F}, {1.0F, 0.0F} }; std::list<TestPoint> polygon2{ {3.0F, 0.0F}, {3.0F, 2.0F}, {5.0F, 2.0F}, {5.0F, 0.0F} }; order_ccw(polygon1); order_ccw(polygon2); EXPECT_FLOAT_EQ( autoware::common::geometry::convex_intersection_over_union_2d(polygon1, polygon2), 0.0F); }
// Crc32.cpp created on 2020-06-07 as part of xcikit project // https://github.com/rbrich/xcikit // // Copyright 2020 Radek Brich // Licensed under the Apache License, Version 2.0 (see LICENSE file) #include "Crc32.h" #include <zlib.h> namespace xci::data { inline uint32_t init_crc() { return (uint32_t) crc32_z(0L, Z_NULL, 0); } Crc32::Crc32() : m_crc(init_crc()) {} void Crc32::reset() { m_crc = init_crc(); } void Crc32::feed(const std::byte* data, size_t size) { m_crc = (uint32_t) crc32_z(m_crc, (const Bytef*) data, size); } } // namespace xci::data
// A llvm backend helper #include "taichi/llvm/llvm_context.h" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/STLExtras.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Instructions.h" #include "llvm/ExecutionEngine/Orc/ThreadSafeModule.h" #include "llvm/IR/Module.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/IntrinsicsNVPTX.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/Type.h" #include "llvm/IR/Verifier.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/InstCombine/InstCombine.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Scalar/GVN.h" #include "llvm/Transforms/Utils.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/Internalize.h" #include "llvm/Transforms/IPO/GlobalDCE.h" #include "llvm/Pass.h" #include "llvm/Passes/PassBuilder.h" #include "llvm/Bitcode/BitcodeReader.h" #include "llvm/Linker/Linker.h" #include "llvm/Demangle/Demangle.h" #include "llvm/Bitcode/BitcodeWriter.h" #include "taichi/lang_util.h" #include "taichi/jit/jit_session.h" #include "taichi/common/task.h" #include "taichi/util/environ_config.h" #include "llvm_context.h" #ifdef _WIN32 // Travis CI seems doesn't support <filesystem>... #include <filesystem> #else #include <unistd.h> #endif #if defined(TI_WITH_CUDA) #include "taichi/backends/cuda/cuda_context.h" #endif namespace taichi { namespace lang { using namespace llvm; TaichiLLVMContext::TaichiLLVMContext(LlvmProgramImpl *llvm_prog, Arch arch) : arch_(arch) { TI_TRACE("Creating Taichi llvm context for arch: {}", arch_name(arch)); main_thread_id_ = std::this_thread::get_id(); main_thread_data_ = get_this_thread_data(); llvm::remove_fatal_error_handler(); llvm::install_fatal_error_handler( [](void *user_data, const std::string &reason, bool gen_crash_diag) { TI_ERROR("LLVM Fatal Error: {}", reason); }, nullptr); if (arch_is_cpu(arch)) { #if defined(TI_PLATFORM_OSX) and defined(TI_ARCH_ARM) // Note that on Apple Silicon (M1), "native" seems to mean arm instead of // arm64 (aka AArch64). LLVMInitializeAArch64Target(); LLVMInitializeAArch64TargetMC(); LLVMInitializeAArch64TargetInfo(); LLVMInitializeAArch64AsmPrinter(); #else llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::InitializeNativeTargetAsmParser(); #endif } else { #if defined(TI_WITH_CUDA) LLVMInitializeNVPTXTarget(); LLVMInitializeNVPTXTargetMC(); LLVMInitializeNVPTXTargetInfo(); LLVMInitializeNVPTXAsmPrinter(); #else TI_NOT_IMPLEMENTED #endif } jit = JITSession::create(llvm_prog, arch); TI_TRACE("Taichi llvm context created."); } TaichiLLVMContext::~TaichiLLVMContext() { } llvm::Type *TaichiLLVMContext::get_data_type(DataType dt) { auto ctx = get_this_thread_context(); if (dt->is_primitive(PrimitiveTypeID::i32)) { return llvm::Type::getInt32Ty(*ctx); } else if (dt->is_primitive(PrimitiveTypeID::i8)) { return llvm::Type::getInt8Ty(*ctx); } else if (dt->is_primitive(PrimitiveTypeID::i16)) { return llvm::Type::getInt16Ty(*ctx); } else if (dt->is_primitive(PrimitiveTypeID::i64)) { return llvm::Type::getInt64Ty(*ctx); } else if (dt->is_primitive(PrimitiveTypeID::f32)) { return llvm::Type::getFloatTy(*ctx); } else if (dt->is_primitive(PrimitiveTypeID::f64)) { return llvm::Type::getDoubleTy(*ctx); } else if (dt->is_primitive(PrimitiveTypeID::u8)) { return llvm::Type::getInt8Ty(*ctx); } else if (dt->is_primitive(PrimitiveTypeID::u16)) { return llvm::Type::getInt16Ty(*ctx); } else if (dt->is_primitive(PrimitiveTypeID::u32)) { return llvm::Type::getInt32Ty(*ctx); } else if (dt->is_primitive(PrimitiveTypeID::u64)) { return llvm::Type::getInt64Ty(*ctx); } else if (dt->is_primitive(PrimitiveTypeID::f16)) { return llvm::Type::getHalfTy(*ctx); } else { TI_INFO(data_type_name(dt)); TI_NOT_IMPLEMENTED } } std::string find_existing_command(const std::vector<std::string> &commands) { for (auto &cmd : commands) { if (command_exist(cmd)) { return cmd; } } for (const auto &cmd : commands) { TI_WARN("Potential command {}", cmd); } TI_ERROR("None command found."); } std::string get_runtime_fn(Arch arch) { return fmt::format("runtime_{}.bc", arch_name(arch)); } std::string libdevice_path() { std::string folder; folder = runtime_lib_dir(); auto cuda_version_string = get_cuda_version_string(); auto cuda_version_major = int(std::atof(cuda_version_string.c_str())); return fmt::format("{}/slim_libdevice.{}.bc", folder, cuda_version_major); } std::unique_ptr<llvm::Module> TaichiLLVMContext::clone_module_to_context( llvm::Module *module, llvm::LLVMContext *target_context) { // Dump a module from one context to bitcode and then parse the bitcode in a // different context std::string bitcode; { std::lock_guard<std::mutex> _(mut_); llvm::raw_string_ostream sos(bitcode); // Use a scope to make sure sos flushes on destruction llvm::WriteBitcodeToFile(*module, sos); } auto cloned = parseBitcodeFile( llvm::MemoryBufferRef(bitcode, "runtime_bitcode"), *target_context); if (!cloned) { auto error = cloned.takeError(); TI_ERROR("Bitcode cloned failed."); } return std::move(cloned.get()); } std::unique_ptr<llvm::Module> TaichiLLVMContext::clone_module_to_this_thread_context(llvm::Module *module) { TI_TRACE("Cloning struct module"); TI_ASSERT(module); auto this_context = get_this_thread_context(); return clone_module_to_context(module, this_context); } std::unique_ptr<llvm::Module> module_from_bitcode_file(std::string bitcode_path, llvm::LLVMContext *ctx) { TI_AUTO_PROF std::ifstream ifs(bitcode_path, std::ios::binary); TI_ERROR_IF(!ifs, "Bitcode file ({}) not found.", bitcode_path); std::string bitcode(std::istreambuf_iterator<char>(ifs), (std::istreambuf_iterator<char>())); auto runtime = parseBitcodeFile(llvm::MemoryBufferRef(bitcode, "runtime_bitcode"), *ctx); if (!runtime) { auto error = runtime.takeError(); TI_WARN("Bitcode loading error message:"); llvm::errs() << error << "\n"; TI_ERROR("Bitcode {} load failure.", bitcode_path); } for (auto &f : *(runtime.get())) TaichiLLVMContext::mark_inline(&f); bool module_broken = llvm::verifyModule(*runtime.get(), &llvm::errs()); TI_ERROR_IF(module_broken, "Module broken"); return std::move(runtime.get()); } // The goal of this function is to rip off huge libdevice functions that are not // going to be used later, at an early stage. Although the LLVM optimizer will // ultimately remove unused functions during a global DCE pass, we don't even // want these functions to waste clock cycles during module cloning and linking. static void remove_useless_cuda_libdevice_functions(llvm::Module *module) { std::vector<std::string> function_name_list = { "rnorm3df", "norm4df", "rnorm4df", "normf", "rnormf", "j0f", "j1f", "y0f", "y1f", "ynf", "jnf", "cyl_bessel_i0f", "cyl_bessel_i1f", "j0", "j1", "y0", "y1", "yn", "jn", "cyl_bessel_i0", "cyl_bessel_i1", "tgammaf", "lgammaf", "tgamma", "lgamma", "erff", "erfinvf", "erfcf", "erfcxf", "erfcinvf", "erf", "erfinv", "erfcx", "erfcinv", "erfc", }; for (auto fn : function_name_list) { module->getFunction("__nv_" + fn)->eraseFromParent(); } module->getFunction("__internal_lgamma_pos")->eraseFromParent(); } void TaichiLLVMContext::init_runtime_jit_module() { update_runtime_jit_module(clone_runtime_module()); } // Note: runtime_module = init_module < struct_module std::unique_ptr<llvm::Module> TaichiLLVMContext::clone_runtime_module() { TI_AUTO_PROF TI_ASSERT(std::this_thread::get_id() == main_thread_id_); auto data = get_this_thread_data(); if (!data->runtime_module) { data->runtime_module = clone_module(get_runtime_fn(arch_)); } std::unique_ptr<llvm::Module> cloned; { TI_PROFILER("clone module"); cloned = llvm::CloneModule(*data->runtime_module); } TI_ASSERT(cloned != nullptr); return cloned; } std::unique_ptr<llvm::Module> TaichiLLVMContext::clone_module( const std::string &file) { auto ctx = get_this_thread_context(); std::unique_ptr<llvm::Module> module = module_from_bitcode_file( fmt::format("{}/{}", runtime_lib_dir(), file), ctx); if (arch_ == Arch::cuda) { module->setTargetTriple("nvptx64-nvidia-cuda"); #if defined(TI_WITH_CUDA) auto func = module->getFunction("cuda_compute_capability"); if (func) { func->deleteBody(); auto bb = llvm::BasicBlock::Create(*ctx, "entry", func); IRBuilder<> builder(*ctx); builder.SetInsertPoint(bb); builder.CreateRet( get_constant(CUDAContext::get_instance().get_compute_capability())); TaichiLLVMContext::mark_inline(func); } #endif auto patch_intrinsic = [&](std::string name, Intrinsic::ID intrin, bool ret = true, std::vector<llvm::Type *> types = {}, std::vector<llvm::Value *> extra_args = {}) { auto func = module->getFunction(name); if (!func) { return; } func->deleteBody(); auto bb = llvm::BasicBlock::Create(*ctx, "entry", func); IRBuilder<> builder(*ctx); builder.SetInsertPoint(bb); std::vector<llvm::Value *> args; for (auto &arg : func->args()) args.push_back(&arg); args.insert(args.end(), extra_args.begin(), extra_args.end()); if (ret) { builder.CreateRet(builder.CreateIntrinsic(intrin, types, args)); } else { builder.CreateIntrinsic(intrin, types, args); builder.CreateRetVoid(); } TaichiLLVMContext::mark_inline(func); }; auto patch_atomic_add = [&](std::string name, llvm::AtomicRMWInst::BinOp op) { auto func = module->getFunction(name); if (!func) { return; } func->deleteBody(); auto bb = llvm::BasicBlock::Create(*ctx, "entry", func); IRBuilder<> builder(*ctx); builder.SetInsertPoint(bb); std::vector<llvm::Value *> args; for (auto &arg : func->args()) args.push_back(&arg); builder.CreateRet(builder.CreateAtomicRMW( op, args[0], args[1], llvm::AtomicOrdering::SequentiallyConsistent)); TaichiLLVMContext::mark_inline(func); }; patch_intrinsic("thread_idx", Intrinsic::nvvm_read_ptx_sreg_tid_x); patch_intrinsic("cuda_clock_i64", Intrinsic::nvvm_read_ptx_sreg_clock64); patch_intrinsic("block_idx", Intrinsic::nvvm_read_ptx_sreg_ctaid_x); patch_intrinsic("block_dim", Intrinsic::nvvm_read_ptx_sreg_ntid_x); patch_intrinsic("grid_dim", Intrinsic::nvvm_read_ptx_sreg_nctaid_x); patch_intrinsic("block_barrier", Intrinsic::nvvm_barrier0, false); patch_intrinsic("warp_barrier", Intrinsic::nvvm_bar_warp_sync, false); patch_intrinsic("block_memfence", Intrinsic::nvvm_membar_cta, false); patch_intrinsic("grid_memfence", Intrinsic::nvvm_membar_gl, false); patch_intrinsic("system_memfence", Intrinsic::nvvm_membar_sys, false); patch_intrinsic("cuda_all", Intrinsic::nvvm_vote_all); patch_intrinsic("cuda_all_sync", Intrinsic::nvvm_vote_all_sync); patch_intrinsic("cuda_any", Intrinsic::nvvm_vote_any); patch_intrinsic("cuda_any_sync", Intrinsic::nvvm_vote_any_sync); patch_intrinsic("cuda_uni", Intrinsic::nvvm_vote_uni); patch_intrinsic("cuda_uni_sync", Intrinsic::nvvm_vote_uni_sync); patch_intrinsic("cuda_ballot", Intrinsic::nvvm_vote_ballot); patch_intrinsic("cuda_ballot_sync", Intrinsic::nvvm_vote_ballot_sync); patch_intrinsic("cuda_shfl_down_sync_i32", Intrinsic::nvvm_shfl_sync_down_i32); patch_intrinsic("cuda_shfl_down_sync_f32", Intrinsic::nvvm_shfl_sync_down_f32); patch_intrinsic("cuda_shfl_up_sync_i32", Intrinsic::nvvm_shfl_sync_up_i32); patch_intrinsic("cuda_shfl_up_sync_f32", Intrinsic::nvvm_shfl_sync_up_f32); patch_intrinsic("cuda_shfl_sync_i32", Intrinsic::nvvm_shfl_sync_idx_i32); patch_intrinsic("cuda_shfl_sync_f32", Intrinsic::nvvm_shfl_sync_idx_f32); patch_intrinsic("cuda_shfl_xor_sync_i32", Intrinsic::nvvm_shfl_sync_bfly_i32); patch_intrinsic("cuda_match_any_sync_i32", Intrinsic::nvvm_match_any_sync_i32); // LLVM 10.0.0 seems to have a bug on this intrinsic function /* patch_intrinsic("cuda_match_any_sync_i64", Intrinsic::nvvm_match_any_sync_i64); */ patch_intrinsic("ctlz_i32", Intrinsic::ctlz, true, {llvm::Type::getInt32Ty(*ctx)}, {get_constant(false)}); patch_intrinsic("cttz_i32", Intrinsic::cttz, true, {llvm::Type::getInt32Ty(*ctx)}, {get_constant(false)}); patch_atomic_add("atomic_add_i32", llvm::AtomicRMWInst::Add); patch_atomic_add("atomic_add_i64", llvm::AtomicRMWInst::Add); patch_atomic_add("atomic_add_f32", llvm::AtomicRMWInst::FAdd); patch_atomic_add("atomic_add_f64", llvm::AtomicRMWInst::FAdd); patch_intrinsic("block_memfence", Intrinsic::nvvm_membar_cta, false); link_module_with_cuda_libdevice(module); // To prevent potential symbol name conflicts, we use "cuda_vprintf" // instead of "vprintf" in llvm/runtime.cpp. Now we change it back for // linking for (auto &f : *module) { if (f.getName() == "cuda_vprintf") { f.setName("vprintf"); } } // runtime_module->print(llvm::errs(), nullptr); } return module; } void TaichiLLVMContext::link_module_with_cuda_libdevice( std::unique_ptr<llvm::Module> &module) { TI_AUTO_PROF TI_ASSERT(arch_ == Arch::cuda); auto libdevice_module = module_from_bitcode_file(libdevice_path(), get_this_thread_context()); std::vector<std::string> libdevice_function_names; for (auto &f : *libdevice_module) { if (!f.isDeclaration()) { libdevice_function_names.push_back(f.getName()); } } libdevice_module->setTargetTriple("nvptx64-nvidia-cuda"); module->setDataLayout(libdevice_module->getDataLayout()); bool failed = llvm::Linker::linkModules(*module, std::move(libdevice_module)); if (failed) { TI_ERROR("CUDA libdevice linking failure."); } // Make sure all libdevice functions are linked, and set their linkage to // internal for (auto func_name : libdevice_function_names) { auto func = module->getFunction(func_name); if (!func) { TI_INFO("Function {} not found", func_name); } else func->setLinkage(llvm::Function::InternalLinkage); } } std::unique_ptr<llvm::Module> TaichiLLVMContext::clone_struct_module() { TI_AUTO_PROF auto struct_module = get_this_thread_struct_module(); TI_ASSERT(struct_module); return llvm::CloneModule(*struct_module); } void TaichiLLVMContext::set_struct_module( const std::unique_ptr<llvm::Module> &module) { auto data = get_this_thread_data(); TI_ASSERT(module); if (llvm::verifyModule(*module, &llvm::errs())) { module->print(llvm::errs(), nullptr); TI_ERROR("module broken"); } // TODO: Move this after ``if (!arch_is_cpu(arch))``. data->struct_module = llvm::CloneModule(*module); } template <typename T> llvm::Value *TaichiLLVMContext::get_constant(DataType dt, T t) { auto ctx = get_this_thread_context(); if (dt->is_primitive(PrimitiveTypeID::f32)) { return llvm::ConstantFP::get(*ctx, llvm::APFloat((float32)t)); } else if (dt->is_primitive(PrimitiveTypeID::f16)) { return llvm::ConstantFP::get(llvm::Type::getHalfTy(*ctx), (float32)t); } else if (dt->is_primitive(PrimitiveTypeID::f64)) { return llvm::ConstantFP::get(*ctx, llvm::APFloat((float64)t)); } else if (is_integral(dt)) { if (is_signed(dt)) { return llvm::ConstantInt::get( *ctx, llvm::APInt(data_type_bits(dt), (uint64_t)t, true)); } else { return llvm::ConstantInt::get( *ctx, llvm::APInt(data_type_bits(dt), (uint64_t)t, false)); } } else { TI_NOT_IMPLEMENTED } } template llvm::Value *TaichiLLVMContext::get_constant(DataType dt, int32 t); template llvm::Value *TaichiLLVMContext::get_constant(DataType dt, int64 t); template llvm::Value *TaichiLLVMContext::get_constant(DataType dt, uint32 t); template llvm::Value *TaichiLLVMContext::get_constant(DataType dt, uint64 t); template llvm::Value *TaichiLLVMContext::get_constant(DataType dt, float32 t); template llvm::Value *TaichiLLVMContext::get_constant(DataType dt, float64 t); template <typename T> llvm::Value *TaichiLLVMContext::get_constant(T t) { auto ctx = get_this_thread_context(); TI_ASSERT(ctx != nullptr); using TargetType = T; if constexpr (std::is_same_v<TargetType, float32> || std::is_same_v<TargetType, float64>) { return llvm::ConstantFP::get(*ctx, llvm::APFloat(t)); } else if (std::is_same_v<TargetType, bool>) { return llvm::ConstantInt::get(*ctx, llvm::APInt(1, (uint64)t, true)); } else if (std::is_same_v<TargetType, int32> || std::is_same_v<TargetType, uint32>) { return llvm::ConstantInt::get(*ctx, llvm::APInt(32, (uint64)t, true)); } else if (std::is_same_v<TargetType, int64> || std::is_same_v<TargetType, std::size_t> || std::is_same_v<TargetType, uint64>) { static_assert(sizeof(std::size_t) == sizeof(uint64)); return llvm::ConstantInt::get(*ctx, llvm::APInt(64, (uint64)t, true)); } else { TI_NOT_IMPLEMENTED } } std::string TaichiLLVMContext::type_name(llvm::Type *type) { std::string type_name; llvm::raw_string_ostream rso(type_name); type->print(rso); return rso.str(); } std::size_t TaichiLLVMContext::get_type_size(llvm::Type *type) { return get_data_layout().getTypeAllocSize(type); } std::size_t TaichiLLVMContext::get_struct_element_offset(llvm::StructType *type, int idx) { return get_data_layout().getStructLayout(type)->getElementOffset(idx); } void TaichiLLVMContext::mark_inline(llvm::Function *f) { for (auto &B : *f) for (auto &I : B) { if (auto *call = llvm::dyn_cast<llvm::CallInst>(&I)) { if (auto func = call->getCalledFunction(); func && func->getName() == "mark_force_no_inline") { // Found "mark_force_no_inline". Do not inline. return; } } } f->removeAttribute(llvm::AttributeList::FunctionIndex, llvm::Attribute::OptimizeNone); f->removeAttribute(llvm::AttributeList::FunctionIndex, llvm::Attribute::NoInline); f->addAttribute(llvm::AttributeList::FunctionIndex, llvm::Attribute::AlwaysInline); } int TaichiLLVMContext::num_instructions(llvm::Function *func) { int counter = 0; for (BasicBlock &bb : *func) counter += std::distance(bb.begin(), bb.end()); return counter; } void TaichiLLVMContext::print_huge_functions(llvm::Module *module) { int total_inst = 0; int total_big_inst = 0; for (auto &f : *module) { int c = num_instructions(&f); if (c > 100) { total_big_inst += c; TI_INFO("{}: {} inst.", std::string(f.getName()), c); } total_inst += c; } TI_P(total_inst); TI_P(total_big_inst); } llvm::DataLayout TaichiLLVMContext::get_data_layout() { return jit->get_data_layout(); } JITModule *TaichiLLVMContext::add_module(std::unique_ptr<llvm::Module> module) { return jit->add_module(std::move(module)); } void TaichiLLVMContext::insert_nvvm_annotation(llvm::Function *func, std::string key, int val) { /******************************************************************* Example annotation from llvm PTX doc: define void @kernel(float addrspace(1)* %A, float addrspace(1)* %B, float addrspace(1)* %C); !nvvm.annotations = !{!0} !0 = !{void (float addrspace(1)*, float addrspace(1)*, float addrspace(1)*)* @kernel, !"kernel", i32 1} *******************************************************************/ auto ctx = get_this_thread_context(); llvm::Metadata *md_args[] = {llvm::ValueAsMetadata::get(func), MDString::get(*ctx, key), llvm::ValueAsMetadata::get(get_constant(val))}; MDNode *md_node = MDNode::get(*ctx, md_args); func->getParent() ->getOrInsertNamedMetadata("nvvm.annotations") ->addOperand(md_node); } void TaichiLLVMContext::mark_function_as_cuda_kernel(llvm::Function *func, int block_dim) { // Mark kernel function as a CUDA __global__ function // Add the nvvm annotation that it is considered a kernel function. insert_nvvm_annotation(func, "kernel", 1); if (block_dim != 0) { // CUDA launch bounds insert_nvvm_annotation(func, "maxntidx", block_dim); insert_nvvm_annotation(func, "minctasm", 2); } } void TaichiLLVMContext::eliminate_unused_functions( llvm::Module *module, std::function<bool(const std::string &)> export_indicator) { TI_AUTO_PROF using namespace llvm; TI_ASSERT(module); if (false) { // temporary fix for now to make LLVM 8 work with CUDA // TODO: recover this when it's time if (llvm::verifyModule(*module, &llvm::errs())) { TI_ERROR("Module broken\n"); } } llvm::ModulePassManager manager; llvm::ModuleAnalysisManager ana; llvm::PassBuilder pb; pb.registerModuleAnalyses(ana); manager.addPass(llvm::InternalizePass([&](const GlobalValue &val) -> bool { return export_indicator(val.getName()); })); manager.addPass(GlobalDCEPass()); manager.run(*module, ana); } TaichiLLVMContext::ThreadLocalData *TaichiLLVMContext::get_this_thread_data() { std::lock_guard<std::mutex> _(thread_map_mut_); auto tid = std::this_thread::get_id(); if (per_thread_data_.find(tid) == per_thread_data_.end()) { std::stringstream ss; ss << tid; TI_TRACE("Creating thread local data for thread {}", ss.str()); per_thread_data_[tid] = std::make_unique<ThreadLocalData>(); } return per_thread_data_[tid].get(); } llvm::LLVMContext *TaichiLLVMContext::get_this_thread_context() { ThreadLocalData *data = get_this_thread_data(); if (!data->llvm_context) { auto ctx = std::make_unique<llvm::LLVMContext>(); data->llvm_context = ctx.get(); data->thread_safe_llvm_context = std::make_unique<llvm::orc::ThreadSafeContext>(std::move(ctx)); } return data->llvm_context; } llvm::orc::ThreadSafeContext * TaichiLLVMContext::get_this_thread_thread_safe_context() { get_this_thread_context(); // make sure the context is created ThreadLocalData *data = get_this_thread_data(); return data->thread_safe_llvm_context.get(); } llvm::Module *TaichiLLVMContext::get_this_thread_struct_module() { ThreadLocalData *data = get_this_thread_data(); if (!data->struct_module) { data->struct_module = clone_module_to_this_thread_context( main_thread_data_->struct_module.get()); } return data->struct_module.get(); } template llvm::Value *TaichiLLVMContext::get_constant(float32 t); template llvm::Value *TaichiLLVMContext::get_constant(float64 t); template llvm::Value *TaichiLLVMContext::get_constant(bool t); template llvm::Value *TaichiLLVMContext::get_constant(int32 t); template llvm::Value *TaichiLLVMContext::get_constant(uint32 t); template llvm::Value *TaichiLLVMContext::get_constant(int64 t); template llvm::Value *TaichiLLVMContext::get_constant(uint64 t); #ifdef TI_PLATFORM_OSX template llvm::Value *TaichiLLVMContext::get_constant(unsigned long t); #endif auto make_slim_libdevice = [](const std::vector<std::string> &args) { TI_ASSERT_INFO(args.size() == 1, "Usage: ti task make_slim_libdevice [libdevice.X.bc file]"); auto ctx = std::make_unique<llvm::LLVMContext>(); auto libdevice_module = module_from_bitcode_file(args[0], ctx.get()); remove_useless_cuda_libdevice_functions(libdevice_module.get()); std::error_code ec; auto output_fn = "slim_" + args[0]; llvm::raw_fd_ostream os(output_fn, ec, llvm::sys::fs::F_None); llvm::WriteBitcodeToFile(*libdevice_module, os); os.flush(); TI_INFO("Slimmed libdevice written to {}", output_fn); }; void TaichiLLVMContext::update_runtime_jit_module( std::unique_ptr<llvm::Module> module) { if (arch_ == Arch::cuda) { for (auto &f : *module) { bool is_kernel = false; const std::string func_name = f.getName(); if (starts_with(func_name, "runtime_")) { mark_function_as_cuda_kernel(&f); is_kernel = true; } if (!is_kernel && !f.isDeclaration()) // set declaration-only functions as internal linking to avoid // duplicated symbols and to remove external symbol dependencies such as // std::sin f.setLinkage(llvm::Function::PrivateLinkage); } } eliminate_unused_functions(module.get(), [](std::string func_name) { return starts_with(func_name, "runtime_") || starts_with(func_name, "LLVMRuntime_"); }); runtime_jit_module = add_module(std::move(module)); } void TaichiLLVMContext::delete_functions_of_snode_tree(int id) { if (!snode_tree_funcs_.count(id)) { return; } llvm::Module *module = get_this_thread_struct_module(); for (auto str : snode_tree_funcs_[id]) { auto *func = module->getFunction(str); func->eraseFromParent(); } snode_tree_funcs_.erase(id); } void TaichiLLVMContext::add_function_to_snode_tree(int id, std::string func) { snode_tree_funcs_[id].push_back(func); } TI_REGISTER_TASK(make_slim_libdevice); } // namespace lang } // namespace taichi
// Copyright 2013 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 Google 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. #include "v8.h" #if defined(V8_TARGET_ARCH_X64) #include "x64/lithium-codegen-x64.h" #include "code-stubs.h" #include "stub-cache.h" namespace v8 { namespace internal { // When invoking builtins, we need to record the safepoint in the middle of // the invoke instruction sequence generated by the macro assembler. class SafepointGenerator : public CallWrapper { public: SafepointGenerator(LCodeGen* codegen, LPointerMap* pointers, Safepoint::DeoptMode mode) : codegen_(codegen), pointers_(pointers), deopt_mode_(mode) { } virtual ~SafepointGenerator() { } virtual void BeforeCall(int call_size) const { codegen_->EnsureSpaceForLazyDeopt(Deoptimizer::patch_size() - call_size); } virtual void AfterCall() const { codegen_->RecordSafepoint(pointers_, deopt_mode_); } private: LCodeGen* codegen_; LPointerMap* pointers_; Safepoint::DeoptMode deopt_mode_; }; #define __ masm()-> bool LCodeGen::GenerateCode() { HPhase phase("Z_Code generation", chunk()); ASSERT(is_unused()); status_ = GENERATING; // Open a frame scope to indicate that there is a frame on the stack. The // MANUAL indicates that the scope shouldn't actually generate code to set up // the frame (that is done in GeneratePrologue). FrameScope frame_scope(masm_, StackFrame::MANUAL); return GeneratePrologue() && GenerateBody() && GenerateDeferredCode() && GenerateJumpTable() && GenerateSafepointTable(); } void LCodeGen::FinishCode(Handle<Code> code) { ASSERT(is_done()); code->set_stack_slots(GetStackSlotCount()); code->set_safepoint_table_offset(safepoints_.GetCodeOffset()); PopulateDeoptimizationData(code); } void LChunkBuilder::Abort(const char* reason) { info()->set_bailout_reason(reason); status_ = ABORTED; } void LCodeGen::Comment(const char* format, ...) { if (!FLAG_code_comments) return; char buffer[4 * KB]; StringBuilder builder(buffer, ARRAY_SIZE(buffer)); va_list arguments; va_start(arguments, format); builder.AddFormattedList(format, arguments); va_end(arguments); // Copy the string before recording it in the assembler to avoid // issues when the stack allocated buffer goes out of scope. int length = builder.position(); Vector<char> copy = Vector<char>::New(length + 1); memcpy(copy.start(), builder.Finalize(), copy.length()); masm()->RecordComment(copy.start()); } bool LCodeGen::GeneratePrologue() { ASSERT(is_generating()); if (info()->IsOptimizing()) { ProfileEntryHookStub::MaybeCallEntryHook(masm_); #ifdef DEBUG if (strlen(FLAG_stop_at) > 0 && info_->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) { __ int3(); } #endif // Strict mode functions need to replace the receiver with undefined // when called as functions (without an explicit receiver // object). rcx is zero for method calls and non-zero for function // calls. if (!info_->is_classic_mode() || info_->is_native()) { Label ok; __ testq(rcx, rcx); __ j(zero, &ok, Label::kNear); // +1 for return address. int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize; __ LoadRoot(kScratchRegister, Heap::kUndefinedValueRootIndex); __ movq(Operand(rsp, receiver_offset), kScratchRegister); __ bind(&ok); } } info()->set_prologue_offset(masm_->pc_offset()); if (NeedsEagerFrame()) { ASSERT(!frame_is_built_); frame_is_built_ = true; __ push(rbp); // Caller's frame pointer. __ movq(rbp, rsp); __ push(rsi); // Callee's context. if (info()->IsStub()) { __ Push(Smi::FromInt(StackFrame::STUB)); } else { __ push(rdi); // Callee's JS function. } } // Reserve space for the stack slots needed by the code. int slots = GetStackSlotCount(); if (slots > 0) { if (FLAG_debug_code) { __ subq(rsp, Immediate(slots * kPointerSize)); __ push(rax); __ Set(rax, slots); __ movq(kScratchRegister, kSlotsZapValue, RelocInfo::NONE64); Label loop; __ bind(&loop); __ movq(MemOperand(rsp, rax, times_pointer_size, 0), kScratchRegister); __ decl(rax); __ j(not_zero, &loop); __ pop(rax); } else { __ subq(rsp, Immediate(slots * kPointerSize)); #ifdef _MSC_VER // On windows, you may not access the stack more than one page below // the most recently mapped page. To make the allocated area randomly // accessible, we write to each page in turn (the value is irrelevant). const int kPageSize = 4 * KB; for (int offset = slots * kPointerSize - kPageSize; offset > 0; offset -= kPageSize) { __ movq(Operand(rsp, offset), rax); } #endif } if (info()->saves_caller_doubles()) { Comment(";;; Save clobbered callee double registers"); int count = 0; BitVector* doubles = chunk()->allocated_double_registers(); BitVector::Iterator save_iterator(doubles); while (!save_iterator.Done()) { __ movsd(MemOperand(rsp, count * kDoubleSize), XMMRegister::FromAllocationIndex(save_iterator.Current())); save_iterator.Advance(); count++; } } } // Possibly allocate a local context. int heap_slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS; if (heap_slots > 0) { Comment(";;; Allocate local context"); // Argument to NewContext is the function, which is still in rdi. __ push(rdi); if (heap_slots <= FastNewContextStub::kMaximumSlots) { FastNewContextStub stub(heap_slots); __ CallStub(&stub); } else { __ CallRuntime(Runtime::kNewFunctionContext, 1); } RecordSafepoint(Safepoint::kNoLazyDeopt); // Context is returned in both rax and rsi. It replaces the context // passed to us. It's saved in the stack and kept live in rsi. __ movq(Operand(rbp, StandardFrameConstants::kContextOffset), rsi); // Copy any necessary parameters into the context. int num_parameters = scope()->num_parameters(); for (int i = 0; i < num_parameters; i++) { Variable* var = scope()->parameter(i); if (var->IsContextSlot()) { int parameter_offset = StandardFrameConstants::kCallerSPOffset + (num_parameters - 1 - i) * kPointerSize; // Load parameter from stack. __ movq(rax, Operand(rbp, parameter_offset)); // Store it in the context. int context_offset = Context::SlotOffset(var->index()); __ movq(Operand(rsi, context_offset), rax); // Update the write barrier. This clobbers rax and rbx. __ RecordWriteContextSlot(rsi, context_offset, rax, rbx, kSaveFPRegs); } } Comment(";;; End allocate local context"); } // Trace the call. if (FLAG_trace && info()->IsOptimizing()) { __ CallRuntime(Runtime::kTraceEnter, 0); } return !is_aborted(); } bool LCodeGen::GenerateBody() { ASSERT(is_generating()); bool emit_instructions = true; for (current_instruction_ = 0; !is_aborted() && current_instruction_ < instructions_->length(); current_instruction_++) { LInstruction* instr = instructions_->at(current_instruction_); if (instr->IsLabel()) { LLabel* label = LLabel::cast(instr); emit_instructions = !label->HasReplacement(); } if (emit_instructions) { if (FLAG_code_comments) { HValue* hydrogen = instr->hydrogen_value(); if (hydrogen != NULL) { if (hydrogen->IsChange()) { HValue* changed_value = HChange::cast(hydrogen)->value(); int use_id = 0; const char* use_mnemo = "dead"; if (hydrogen->UseCount() >= 1) { HValue* use_value = hydrogen->uses().value(); use_id = use_value->id(); use_mnemo = use_value->Mnemonic(); } Comment(";;; @%d: %s. <of #%d %s for #%d %s>", current_instruction_, instr->Mnemonic(), changed_value->id(), changed_value->Mnemonic(), use_id, use_mnemo); } else { Comment(";;; @%d: %s. <#%d>", current_instruction_, instr->Mnemonic(), hydrogen->id()); } } else { Comment(";;; @%d: %s.", current_instruction_, instr->Mnemonic()); } } instr->CompileToNative(this); } } EnsureSpaceForLazyDeopt(Deoptimizer::patch_size()); return !is_aborted(); } bool LCodeGen::GenerateJumpTable() { Label needs_frame_not_call; Label needs_frame_is_call; for (int i = 0; i < jump_table_.length(); i++) { __ bind(&jump_table_[i].label); Address entry = jump_table_[i].address; bool is_lazy_deopt = jump_table_[i].is_lazy_deopt; Deoptimizer::BailoutType type = is_lazy_deopt ? Deoptimizer::LAZY : Deoptimizer::EAGER; int id = Deoptimizer::GetDeoptimizationId(entry, type); if (id == Deoptimizer::kNotDeoptimizationEntry) { Comment(";;; jump table entry %d.", i); } else { Comment(";;; jump table entry %d: deoptimization bailout %d.", i, id); } if (jump_table_[i].needs_frame) { __ movq(kScratchRegister, ExternalReference::ForDeoptEntry(entry)); if (is_lazy_deopt) { if (needs_frame_is_call.is_bound()) { __ jmp(&needs_frame_is_call); } else { __ bind(&needs_frame_is_call); __ push(rbp); __ movq(rbp, rsp); __ push(rsi); // This variant of deopt can only be used with stubs. Since we don't // have a function pointer to install in the stack frame that we're // building, install a special marker there instead. ASSERT(info()->IsStub()); __ Move(rsi, Smi::FromInt(StackFrame::STUB)); __ push(rsi); __ movq(rsi, MemOperand(rsp, kPointerSize)); __ call(kScratchRegister); } } else { if (needs_frame_not_call.is_bound()) { __ jmp(&needs_frame_not_call); } else { __ bind(&needs_frame_not_call); __ push(rbp); __ movq(rbp, rsp); __ push(rsi); // This variant of deopt can only be used with stubs. Since we don't // have a function pointer to install in the stack frame that we're // building, install a special marker there instead. ASSERT(info()->IsStub()); __ Move(rsi, Smi::FromInt(StackFrame::STUB)); __ push(rsi); __ movq(rsi, MemOperand(rsp, kPointerSize)); __ jmp(kScratchRegister); } } } else { if (is_lazy_deopt) { __ Call(entry, RelocInfo::RUNTIME_ENTRY); } else { __ Jump(entry, RelocInfo::RUNTIME_ENTRY); } } } return !is_aborted(); } bool LCodeGen::GenerateDeferredCode() { ASSERT(is_generating()); if (deferred_.length() > 0) { for (int i = 0; !is_aborted() && i < deferred_.length(); i++) { LDeferredCode* code = deferred_[i]; __ bind(code->entry()); if (NeedsDeferredFrame()) { Comment(";;; Deferred build frame", code->instruction_index(), code->instr()->Mnemonic()); ASSERT(!frame_is_built_); ASSERT(info()->IsStub()); frame_is_built_ = true; // Build the frame in such a way that esi isn't trashed. __ push(rbp); // Caller's frame pointer. __ push(Operand(rbp, StandardFrameConstants::kContextOffset)); __ Push(Smi::FromInt(StackFrame::STUB)); __ lea(rbp, Operand(rsp, 2 * kPointerSize)); } Comment(";;; Deferred code @%d: %s.", code->instruction_index(), code->instr()->Mnemonic()); code->Generate(); if (NeedsDeferredFrame()) { Comment(";;; Deferred destroy frame", code->instruction_index(), code->instr()->Mnemonic()); ASSERT(frame_is_built_); frame_is_built_ = false; __ movq(rsp, rbp); __ pop(rbp); } __ jmp(code->exit()); } } // Deferred code is the last part of the instruction sequence. Mark // the generated code as done unless we bailed out. if (!is_aborted()) status_ = DONE; return !is_aborted(); } bool LCodeGen::GenerateSafepointTable() { ASSERT(is_done()); safepoints_.Emit(masm(), GetStackSlotCount()); return !is_aborted(); } Register LCodeGen::ToRegister(int index) const { return Register::FromAllocationIndex(index); } XMMRegister LCodeGen::ToDoubleRegister(int index) const { return XMMRegister::FromAllocationIndex(index); } Register LCodeGen::ToRegister(LOperand* op) const { ASSERT(op->IsRegister()); return ToRegister(op->index()); } XMMRegister LCodeGen::ToDoubleRegister(LOperand* op) const { ASSERT(op->IsDoubleRegister()); return ToDoubleRegister(op->index()); } bool LCodeGen::IsInteger32Constant(LConstantOperand* op) const { return op->IsConstantOperand() && chunk_->LookupLiteralRepresentation(op).IsInteger32(); } bool LCodeGen::IsTaggedConstant(LConstantOperand* op) const { return op->IsConstantOperand() && chunk_->LookupLiteralRepresentation(op).IsTagged(); } int LCodeGen::ToInteger32(LConstantOperand* op) const { HConstant* constant = chunk_->LookupConstant(op); return constant->Integer32Value(); } double LCodeGen::ToDouble(LConstantOperand* op) const { HConstant* constant = chunk_->LookupConstant(op); ASSERT(constant->HasDoubleValue()); return constant->DoubleValue(); } Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const { HConstant* constant = chunk_->LookupConstant(op); ASSERT(chunk_->LookupLiteralRepresentation(op).IsTagged()); return constant->handle(); } Operand LCodeGen::ToOperand(LOperand* op) const { // Does not handle registers. In X64 assembler, plain registers are not // representable as an Operand. ASSERT(op->IsStackSlot() || op->IsDoubleStackSlot()); int index = op->index(); if (index >= 0) { // Local or spill slot. Skip the frame pointer, function, and // context in the fixed part of the frame. return Operand(rbp, -(index + 3) * kPointerSize); } else { // Incoming parameter. Skip the return address. return Operand(rbp, -(index - 1) * kPointerSize); } } void LCodeGen::WriteTranslation(LEnvironment* environment, Translation* translation, int* arguments_index, int* arguments_count) { if (environment == NULL) return; // The translation includes one command per value in the environment. int translation_size = environment->values()->length(); // The output frame height does not include the parameters. int height = translation_size - environment->parameter_count(); // Function parameters are arguments to the outermost environment. The // arguments index points to the first element of a sequence of tagged // values on the stack that represent the arguments. This needs to be // kept in sync with the LArgumentsElements implementation. *arguments_index = -environment->parameter_count(); *arguments_count = environment->parameter_count(); WriteTranslation(environment->outer(), translation, arguments_index, arguments_count); bool has_closure_id = !info()->closure().is_null() && *info()->closure() != *environment->closure(); int closure_id = has_closure_id ? DefineDeoptimizationLiteral(environment->closure()) : Translation::kSelfLiteralId; switch (environment->frame_type()) { case JS_FUNCTION: translation->BeginJSFrame(environment->ast_id(), closure_id, height); break; case JS_CONSTRUCT: translation->BeginConstructStubFrame(closure_id, translation_size); break; case JS_GETTER: ASSERT(translation_size == 1); ASSERT(height == 0); translation->BeginGetterStubFrame(closure_id); break; case JS_SETTER: ASSERT(translation_size == 2); ASSERT(height == 0); translation->BeginSetterStubFrame(closure_id); break; case ARGUMENTS_ADAPTOR: translation->BeginArgumentsAdaptorFrame(closure_id, translation_size); break; case STUB: translation->BeginCompiledStubFrame(); break; } // Inlined frames which push their arguments cause the index to be // bumped and a new stack area to be used for materialization. if (environment->entry() != NULL && environment->entry()->arguments_pushed()) { *arguments_index = *arguments_index < 0 ? GetStackSlotCount() : *arguments_index + *arguments_count; *arguments_count = environment->entry()->arguments_count() + 1; } for (int i = 0; i < translation_size; ++i) { LOperand* value = environment->values()->at(i); // spilled_registers_ and spilled_double_registers_ are either // both NULL or both set. if (environment->spilled_registers() != NULL && value != NULL) { if (value->IsRegister() && environment->spilled_registers()[value->index()] != NULL) { translation->MarkDuplicate(); AddToTranslation(translation, environment->spilled_registers()[value->index()], environment->HasTaggedValueAt(i), environment->HasUint32ValueAt(i), *arguments_index, *arguments_count); } else if ( value->IsDoubleRegister() && environment->spilled_double_registers()[value->index()] != NULL) { translation->MarkDuplicate(); AddToTranslation( translation, environment->spilled_double_registers()[value->index()], false, false, *arguments_index, *arguments_count); } } AddToTranslation(translation, value, environment->HasTaggedValueAt(i), environment->HasUint32ValueAt(i), *arguments_index, *arguments_count); } } void LCodeGen::AddToTranslation(Translation* translation, LOperand* op, bool is_tagged, bool is_uint32, int arguments_index, int arguments_count) { if (op == NULL) { // TODO(twuerthinger): Introduce marker operands to indicate that this value // is not present and must be reconstructed from the deoptimizer. Currently // this is only used for the arguments object. translation->StoreArgumentsObject(arguments_index, arguments_count); } else if (op->IsStackSlot()) { if (is_tagged) { translation->StoreStackSlot(op->index()); } else if (is_uint32) { translation->StoreUint32StackSlot(op->index()); } else { translation->StoreInt32StackSlot(op->index()); } } else if (op->IsDoubleStackSlot()) { translation->StoreDoubleStackSlot(op->index()); } else if (op->IsArgument()) { ASSERT(is_tagged); int src_index = GetStackSlotCount() + op->index(); translation->StoreStackSlot(src_index); } else if (op->IsRegister()) { Register reg = ToRegister(op); if (is_tagged) { translation->StoreRegister(reg); } else if (is_uint32) { translation->StoreUint32Register(reg); } else { translation->StoreInt32Register(reg); } } else if (op->IsDoubleRegister()) { XMMRegister reg = ToDoubleRegister(op); translation->StoreDoubleRegister(reg); } else if (op->IsConstantOperand()) { HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op)); int src_index = DefineDeoptimizationLiteral(constant->handle()); translation->StoreLiteral(src_index); } else { UNREACHABLE(); } } void LCodeGen::CallCodeGeneric(Handle<Code> code, RelocInfo::Mode mode, LInstruction* instr, SafepointMode safepoint_mode, int argc) { EnsureSpaceForLazyDeopt(Deoptimizer::patch_size() - masm()->CallSize(code)); ASSERT(instr != NULL); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); __ call(code, mode); RecordSafepointWithLazyDeopt(instr, safepoint_mode, argc); // Signal that we don't inline smi code before these stubs in the // optimizing code generator. if (code->kind() == Code::BINARY_OP_IC || code->kind() == Code::COMPARE_IC) { __ nop(); } } void LCodeGen::CallCode(Handle<Code> code, RelocInfo::Mode mode, LInstruction* instr) { CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT, 0); } void LCodeGen::CallRuntime(const Runtime::Function* function, int num_arguments, LInstruction* instr) { ASSERT(instr != NULL); ASSERT(instr->HasPointerMap()); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); __ CallRuntime(function, num_arguments); RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT, 0); } void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id, int argc, LInstruction* instr) { __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); __ CallRuntimeSaveDoubles(id); RecordSafepointWithRegisters( instr->pointer_map(), argc, Safepoint::kNoLazyDeopt); } void LCodeGen::RegisterEnvironmentForDeoptimization(LEnvironment* environment, Safepoint::DeoptMode mode) { if (!environment->HasBeenRegistered()) { // Physical stack frame layout: // -x ............. -4 0 ..................................... y // [incoming arguments] [spill slots] [pushed outgoing arguments] // Layout of the environment: // 0 ..................................................... size-1 // [parameters] [locals] [expression stack including arguments] // Layout of the translation: // 0 ........................................................ size - 1 + 4 // [expression stack including arguments] [locals] [4 words] [parameters] // |>------------ translation_size ------------<| int frame_count = 0; int jsframe_count = 0; int args_index = 0; int args_count = 0; for (LEnvironment* e = environment; e != NULL; e = e->outer()) { ++frame_count; if (e->frame_type() == JS_FUNCTION) { ++jsframe_count; } } Translation translation(&translations_, frame_count, jsframe_count, zone()); WriteTranslation(environment, &translation, &args_index, &args_count); int deoptimization_index = deoptimizations_.length(); int pc_offset = masm()->pc_offset(); environment->Register(deoptimization_index, translation.index(), (mode == Safepoint::kLazyDeopt) ? pc_offset : -1); deoptimizations_.Add(environment, environment->zone()); } } void LCodeGen::DeoptimizeIf(Condition cc, LEnvironment* environment) { RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt); ASSERT(environment->HasBeenRegistered()); int id = environment->deoptimization_index(); ASSERT(info()->IsOptimizing() || info()->IsStub()); Deoptimizer::BailoutType bailout_type = info()->IsStub() ? Deoptimizer::LAZY : Deoptimizer::EAGER; Address entry = Deoptimizer::GetDeoptimizationEntry(id, bailout_type); if (entry == NULL) { Abort("bailout was not prepared"); return; } ASSERT(info()->IsStub() || frame_is_built_); bool lazy_deopt = info()->IsStub(); if (cc == no_condition) { if (lazy_deopt) { __ Call(entry, RelocInfo::RUNTIME_ENTRY); } else { __ Jump(entry, RelocInfo::RUNTIME_ENTRY); } } else { // We often have several deopts to the same entry, reuse the last // jump entry if this is the case. if (jump_table_.is_empty() || jump_table_.last().address != entry || jump_table_.last().needs_frame != !frame_is_built_ || jump_table_.last().is_lazy_deopt != lazy_deopt) { JumpTableEntry table_entry(entry, !frame_is_built_, lazy_deopt); jump_table_.Add(table_entry, zone()); } __ j(cc, &jump_table_.last().label); } } void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) { int length = deoptimizations_.length(); if (length == 0) return; Handle<DeoptimizationInputData> data = factory()->NewDeoptimizationInputData(length, TENURED); Handle<ByteArray> translations = translations_.CreateByteArray(); data->SetTranslationByteArray(*translations); data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_)); Handle<FixedArray> literals = factory()->NewFixedArray(deoptimization_literals_.length(), TENURED); for (int i = 0; i < deoptimization_literals_.length(); i++) { literals->set(i, *deoptimization_literals_[i]); } data->SetLiteralArray(*literals); data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt())); data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_)); // Populate the deoptimization entries. for (int i = 0; i < length; i++) { LEnvironment* env = deoptimizations_[i]; data->SetAstId(i, env->ast_id()); data->SetTranslationIndex(i, Smi::FromInt(env->translation_index())); data->SetArgumentsStackHeight(i, Smi::FromInt(env->arguments_stack_height())); data->SetPc(i, Smi::FromInt(env->pc_offset())); } code->set_deoptimization_data(*data); } int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) { int result = deoptimization_literals_.length(); for (int i = 0; i < deoptimization_literals_.length(); ++i) { if (deoptimization_literals_[i].is_identical_to(literal)) return i; } deoptimization_literals_.Add(literal, zone()); return result; } void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() { ASSERT(deoptimization_literals_.length() == 0); const ZoneList<Handle<JSFunction> >* inlined_closures = chunk()->inlined_closures(); for (int i = 0, length = inlined_closures->length(); i < length; i++) { DefineDeoptimizationLiteral(inlined_closures->at(i)); } inlined_function_count_ = deoptimization_literals_.length(); } void LCodeGen::RecordSafepointWithLazyDeopt( LInstruction* instr, SafepointMode safepoint_mode, int argc) { if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) { RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt); } else { ASSERT(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS); RecordSafepointWithRegisters( instr->pointer_map(), argc, Safepoint::kLazyDeopt); } } void LCodeGen::RecordSafepoint( LPointerMap* pointers, Safepoint::Kind kind, int arguments, Safepoint::DeoptMode deopt_mode) { ASSERT(kind == expected_safepoint_kind_); const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands(); Safepoint safepoint = safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode); for (int i = 0; i < operands->length(); i++) { LOperand* pointer = operands->at(i); if (pointer->IsStackSlot()) { safepoint.DefinePointerSlot(pointer->index(), zone()); } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) { safepoint.DefinePointerRegister(ToRegister(pointer), zone()); } } if (kind & Safepoint::kWithRegisters) { // Register rsi always contains a pointer to the context. safepoint.DefinePointerRegister(rsi, zone()); } } void LCodeGen::RecordSafepoint(LPointerMap* pointers, Safepoint::DeoptMode deopt_mode) { RecordSafepoint(pointers, Safepoint::kSimple, 0, deopt_mode); } void LCodeGen::RecordSafepoint(Safepoint::DeoptMode deopt_mode) { LPointerMap empty_pointers(RelocInfo::kNoPosition, zone()); RecordSafepoint(&empty_pointers, deopt_mode); } void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers, int arguments, Safepoint::DeoptMode deopt_mode) { RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, deopt_mode); } void LCodeGen::RecordPosition(int position) { if (position == RelocInfo::kNoPosition) return; masm()->positions_recorder()->RecordPosition(position); } void LCodeGen::DoLabel(LLabel* label) { if (label->is_loop_header()) { Comment(";;; B%d - LOOP entry", label->block_id()); } else { Comment(";;; B%d", label->block_id()); } __ bind(label->label()); current_block_ = label->block_id(); DoGap(label); } void LCodeGen::DoParallelMove(LParallelMove* move) { resolver_.Resolve(move); } void LCodeGen::DoGap(LGap* gap) { for (int i = LGap::FIRST_INNER_POSITION; i <= LGap::LAST_INNER_POSITION; i++) { LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i); LParallelMove* move = gap->GetParallelMove(inner_pos); if (move != NULL) DoParallelMove(move); } } void LCodeGen::DoInstructionGap(LInstructionGap* instr) { DoGap(instr); } void LCodeGen::DoParameter(LParameter* instr) { // Nothing to do. } void LCodeGen::DoCallStub(LCallStub* instr) { ASSERT(ToRegister(instr->result()).is(rax)); switch (instr->hydrogen()->major_key()) { case CodeStub::RegExpConstructResult: { RegExpConstructResultStub stub; CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::RegExpExec: { RegExpExecStub stub; CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::SubString: { SubStringStub stub; CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::NumberToString: { NumberToStringStub stub; CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::StringAdd: { StringAddStub stub(NO_STRING_ADD_FLAGS); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::StringCompare: { StringCompareStub stub; CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::TranscendentalCache: { TranscendentalCacheStub stub(instr->transcendental_type(), TranscendentalCacheStub::TAGGED); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } default: UNREACHABLE(); } } void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) { // Nothing to do. } void LCodeGen::DoModI(LModI* instr) { if (instr->hydrogen()->HasPowerOf2Divisor()) { Register dividend = ToRegister(instr->left()); int32_t divisor = HConstant::cast(instr->hydrogen()->right())->Integer32Value(); if (divisor < 0) divisor = -divisor; Label positive_dividend, done; __ testl(dividend, dividend); __ j(not_sign, &positive_dividend, Label::kNear); __ negl(dividend); __ andl(dividend, Immediate(divisor - 1)); __ negl(dividend); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ j(not_zero, &done, Label::kNear); DeoptimizeIf(no_condition, instr->environment()); } else { __ jmp(&done, Label::kNear); } __ bind(&positive_dividend); __ andl(dividend, Immediate(divisor - 1)); __ bind(&done); } else { Label done, remainder_eq_dividend, slow, do_subtraction, both_positive; Register left_reg = ToRegister(instr->left()); Register right_reg = ToRegister(instr->right()); Register result_reg = ToRegister(instr->result()); ASSERT(left_reg.is(rax)); ASSERT(result_reg.is(rdx)); ASSERT(!right_reg.is(rax)); ASSERT(!right_reg.is(rdx)); // Check for x % 0. if (instr->hydrogen()->CheckFlag(HValue::kCanBeDivByZero)) { __ testl(right_reg, right_reg); DeoptimizeIf(zero, instr->environment()); } __ testl(left_reg, left_reg); __ j(zero, &remainder_eq_dividend, Label::kNear); __ j(sign, &slow, Label::kNear); __ testl(right_reg, right_reg); __ j(not_sign, &both_positive, Label::kNear); // The sign of the divisor doesn't matter. __ neg(right_reg); __ bind(&both_positive); // If the dividend is smaller than the nonnegative // divisor, the dividend is the result. __ cmpl(left_reg, right_reg); __ j(less, &remainder_eq_dividend, Label::kNear); // Check if the divisor is a PowerOfTwo integer. Register scratch = ToRegister(instr->temp()); __ movl(scratch, right_reg); __ subl(scratch, Immediate(1)); __ testl(scratch, right_reg); __ j(not_zero, &do_subtraction, Label::kNear); __ andl(left_reg, scratch); __ jmp(&remainder_eq_dividend, Label::kNear); __ bind(&do_subtraction); const int kUnfolds = 3; // Try a few subtractions of the dividend. __ movl(scratch, left_reg); for (int i = 0; i < kUnfolds; i++) { // Reduce the dividend by the divisor. __ subl(left_reg, right_reg); // Check if the dividend is less than the divisor. __ cmpl(left_reg, right_reg); __ j(less, &remainder_eq_dividend, Label::kNear); } __ movl(left_reg, scratch); // Slow case, using idiv instruction. __ bind(&slow); // Check for (kMinInt % -1). if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) { Label left_not_min_int; __ cmpl(left_reg, Immediate(kMinInt)); __ j(not_zero, &left_not_min_int, Label::kNear); __ cmpl(right_reg, Immediate(-1)); DeoptimizeIf(zero, instr->environment()); __ bind(&left_not_min_int); } // Sign extend eax to edx. // (We are using only the low 32 bits of the values.) __ cdq(); // Check for (0 % -x) that will produce negative zero. if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { Label positive_left; Label done; __ testl(left_reg, left_reg); __ j(not_sign, &positive_left, Label::kNear); __ idivl(right_reg); // Test the remainder for 0, because then the result would be -0. __ testl(result_reg, result_reg); __ j(not_zero, &done, Label::kNear); DeoptimizeIf(no_condition, instr->environment()); __ bind(&positive_left); __ idivl(right_reg); __ bind(&done); } else { __ idivl(right_reg); } __ jmp(&done, Label::kNear); __ bind(&remainder_eq_dividend); __ movl(result_reg, left_reg); __ bind(&done); } } void LCodeGen::DoMathFloorOfDiv(LMathFloorOfDiv* instr) { ASSERT(instr->right()->IsConstantOperand()); const Register dividend = ToRegister(instr->left()); int32_t divisor = ToInteger32(LConstantOperand::cast(instr->right())); const Register result = ToRegister(instr->result()); switch (divisor) { case 0: DeoptimizeIf(no_condition, instr->environment()); return; case 1: if (!result.is(dividend)) { __ movl(result, dividend); } return; case -1: if (!result.is(dividend)) { __ movl(result, dividend); } __ negl(result); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { DeoptimizeIf(zero, instr->environment()); } if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) { DeoptimizeIf(overflow, instr->environment()); } return; } uint32_t divisor_abs = abs(divisor); if (IsPowerOf2(divisor_abs)) { int32_t power = WhichPowerOf2(divisor_abs); if (divisor < 0) { __ movsxlq(result, dividend); __ neg(result); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { DeoptimizeIf(zero, instr->environment()); } __ sar(result, Immediate(power)); } else { if (!result.is(dividend)) { __ movl(result, dividend); } __ sarl(result, Immediate(power)); } } else { Register reg1 = ToRegister(instr->temp()); Register reg2 = ToRegister(instr->result()); // Find b which: 2^b < divisor_abs < 2^(b+1). unsigned b = 31 - CompilerIntrinsics::CountLeadingZeros(divisor_abs); unsigned shift = 32 + b; // Precision +1bit (effectively). double multiplier_f = static_cast<double>(static_cast<uint64_t>(1) << shift) / divisor_abs; int64_t multiplier; if (multiplier_f - floor(multiplier_f) < 0.5) { multiplier = static_cast<int64_t>(floor(multiplier_f)); } else { multiplier = static_cast<int64_t>(floor(multiplier_f)) + 1; } // The multiplier is a uint32. ASSERT(multiplier > 0 && multiplier < (static_cast<int64_t>(1) << 32)); // The multiply is int64, so sign-extend to r64. __ movsxlq(reg1, dividend); if (divisor < 0 && instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ neg(reg1); DeoptimizeIf(zero, instr->environment()); } __ movq(reg2, multiplier, RelocInfo::NONE64); // Result just fit in r64, because it's int32 * uint32. __ imul(reg2, reg1); __ addq(reg2, Immediate(1 << 30)); __ sar(reg2, Immediate(shift)); } } void LCodeGen::DoDivI(LDivI* instr) { if (!instr->is_flooring() && instr->hydrogen()->HasPowerOf2Divisor()) { Register dividend = ToRegister(instr->left()); int32_t divisor = HConstant::cast(instr->hydrogen()->right())->Integer32Value(); int32_t test_value = 0; int32_t power = 0; if (divisor > 0) { test_value = divisor - 1; power = WhichPowerOf2(divisor); } else { // Check for (0 / -x) that will produce negative zero. if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ testl(dividend, dividend); DeoptimizeIf(zero, instr->environment()); } // Check for (kMinInt / -1). if (divisor == -1 && instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) { __ cmpl(dividend, Immediate(kMinInt)); DeoptimizeIf(zero, instr->environment()); } test_value = - divisor - 1; power = WhichPowerOf2(-divisor); } if (test_value != 0) { // Deoptimize if remainder is not 0. __ testl(dividend, Immediate(test_value)); DeoptimizeIf(not_zero, instr->environment()); __ sarl(dividend, Immediate(power)); } if (divisor < 0) __ negl(dividend); return; } LOperand* right = instr->right(); ASSERT(ToRegister(instr->result()).is(rax)); ASSERT(ToRegister(instr->left()).is(rax)); ASSERT(!ToRegister(instr->right()).is(rax)); ASSERT(!ToRegister(instr->right()).is(rdx)); Register left_reg = rax; // Check for x / 0. Register right_reg = ToRegister(right); if (instr->hydrogen_value()->CheckFlag(HValue::kCanBeDivByZero)) { __ testl(right_reg, right_reg); DeoptimizeIf(zero, instr->environment()); } // Check for (0 / -x) that will produce negative zero. if (instr->hydrogen_value()->CheckFlag(HValue::kBailoutOnMinusZero)) { Label left_not_zero; __ testl(left_reg, left_reg); __ j(not_zero, &left_not_zero, Label::kNear); __ testl(right_reg, right_reg); DeoptimizeIf(sign, instr->environment()); __ bind(&left_not_zero); } // Check for (kMinInt / -1). if (instr->hydrogen_value()->CheckFlag(HValue::kCanOverflow)) { Label left_not_min_int; __ cmpl(left_reg, Immediate(kMinInt)); __ j(not_zero, &left_not_min_int, Label::kNear); __ cmpl(right_reg, Immediate(-1)); DeoptimizeIf(zero, instr->environment()); __ bind(&left_not_min_int); } // Sign extend to rdx. __ cdq(); __ idivl(right_reg); if (!instr->is_flooring()) { // Deoptimize if remainder is not 0. __ testl(rdx, rdx); DeoptimizeIf(not_zero, instr->environment()); } else { Label done; __ testl(rdx, rdx); __ j(zero, &done, Label::kNear); __ xorl(rdx, right_reg); __ sarl(rdx, Immediate(31)); __ addl(rax, rdx); __ bind(&done); } } void LCodeGen::DoMulI(LMulI* instr) { Register left = ToRegister(instr->left()); LOperand* right = instr->right(); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ movl(kScratchRegister, left); } bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow); if (right->IsConstantOperand()) { int right_value = ToInteger32(LConstantOperand::cast(right)); if (right_value == -1) { __ negl(left); } else if (right_value == 0) { __ xorl(left, left); } else if (right_value == 2) { __ addl(left, left); } else if (!can_overflow) { // If the multiplication is known to not overflow, we // can use operations that don't set the overflow flag // correctly. switch (right_value) { case 1: // Do nothing. break; case 3: __ leal(left, Operand(left, left, times_2, 0)); break; case 4: __ shll(left, Immediate(2)); break; case 5: __ leal(left, Operand(left, left, times_4, 0)); break; case 8: __ shll(left, Immediate(3)); break; case 9: __ leal(left, Operand(left, left, times_8, 0)); break; case 16: __ shll(left, Immediate(4)); break; default: __ imull(left, left, Immediate(right_value)); break; } } else { __ imull(left, left, Immediate(right_value)); } } else if (right->IsStackSlot()) { __ imull(left, ToOperand(right)); } else { __ imull(left, ToRegister(right)); } if (can_overflow) { DeoptimizeIf(overflow, instr->environment()); } if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { // Bail out if the result is supposed to be negative zero. Label done; __ testl(left, left); __ j(not_zero, &done, Label::kNear); if (right->IsConstantOperand()) { if (ToInteger32(LConstantOperand::cast(right)) < 0) { DeoptimizeIf(no_condition, instr->environment()); } else if (ToInteger32(LConstantOperand::cast(right)) == 0) { __ cmpl(kScratchRegister, Immediate(0)); DeoptimizeIf(less, instr->environment()); } } else if (right->IsStackSlot()) { __ orl(kScratchRegister, ToOperand(right)); DeoptimizeIf(sign, instr->environment()); } else { // Test the non-zero operand for negative sign. __ orl(kScratchRegister, ToRegister(right)); DeoptimizeIf(sign, instr->environment()); } __ bind(&done); } } void LCodeGen::DoBitI(LBitI* instr) { LOperand* left = instr->left(); LOperand* right = instr->right(); ASSERT(left->Equals(instr->result())); ASSERT(left->IsRegister()); if (right->IsConstantOperand()) { int right_operand = ToInteger32(LConstantOperand::cast(right)); switch (instr->op()) { case Token::BIT_AND: __ andl(ToRegister(left), Immediate(right_operand)); break; case Token::BIT_OR: __ orl(ToRegister(left), Immediate(right_operand)); break; case Token::BIT_XOR: __ xorl(ToRegister(left), Immediate(right_operand)); break; default: UNREACHABLE(); break; } } else if (right->IsStackSlot()) { switch (instr->op()) { case Token::BIT_AND: __ andl(ToRegister(left), ToOperand(right)); break; case Token::BIT_OR: __ orl(ToRegister(left), ToOperand(right)); break; case Token::BIT_XOR: __ xorl(ToRegister(left), ToOperand(right)); break; default: UNREACHABLE(); break; } } else { ASSERT(right->IsRegister()); switch (instr->op()) { case Token::BIT_AND: __ andl(ToRegister(left), ToRegister(right)); break; case Token::BIT_OR: __ orl(ToRegister(left), ToRegister(right)); break; case Token::BIT_XOR: __ xorl(ToRegister(left), ToRegister(right)); break; default: UNREACHABLE(); break; } } } void LCodeGen::DoShiftI(LShiftI* instr) { LOperand* left = instr->left(); LOperand* right = instr->right(); ASSERT(left->Equals(instr->result())); ASSERT(left->IsRegister()); if (right->IsRegister()) { ASSERT(ToRegister(right).is(rcx)); switch (instr->op()) { case Token::ROR: __ rorl_cl(ToRegister(left)); break; case Token::SAR: __ sarl_cl(ToRegister(left)); break; case Token::SHR: __ shrl_cl(ToRegister(left)); if (instr->can_deopt()) { __ testl(ToRegister(left), ToRegister(left)); DeoptimizeIf(negative, instr->environment()); } break; case Token::SHL: __ shll_cl(ToRegister(left)); break; default: UNREACHABLE(); break; } } else { int value = ToInteger32(LConstantOperand::cast(right)); uint8_t shift_count = static_cast<uint8_t>(value & 0x1F); switch (instr->op()) { case Token::ROR: if (shift_count != 0) { __ rorl(ToRegister(left), Immediate(shift_count)); } break; case Token::SAR: if (shift_count != 0) { __ sarl(ToRegister(left), Immediate(shift_count)); } break; case Token::SHR: if (shift_count == 0 && instr->can_deopt()) { __ testl(ToRegister(left), ToRegister(left)); DeoptimizeIf(negative, instr->environment()); } else { __ shrl(ToRegister(left), Immediate(shift_count)); } break; case Token::SHL: if (shift_count != 0) { __ shll(ToRegister(left), Immediate(shift_count)); } break; default: UNREACHABLE(); break; } } } void LCodeGen::DoSubI(LSubI* instr) { LOperand* left = instr->left(); LOperand* right = instr->right(); ASSERT(left->Equals(instr->result())); if (right->IsConstantOperand()) { __ subl(ToRegister(left), Immediate(ToInteger32(LConstantOperand::cast(right)))); } else if (right->IsRegister()) { __ subl(ToRegister(left), ToRegister(right)); } else { __ subl(ToRegister(left), ToOperand(right)); } if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) { DeoptimizeIf(overflow, instr->environment()); } } void LCodeGen::DoConstantI(LConstantI* instr) { ASSERT(instr->result()->IsRegister()); __ Set(ToRegister(instr->result()), instr->value()); } void LCodeGen::DoConstantD(LConstantD* instr) { ASSERT(instr->result()->IsDoubleRegister()); XMMRegister res = ToDoubleRegister(instr->result()); double v = instr->value(); uint64_t int_val = BitCast<uint64_t, double>(v); // Use xor to produce +0.0 in a fast and compact way, but avoid to // do so if the constant is -0.0. if (int_val == 0) { __ xorps(res, res); } else { Register tmp = ToRegister(instr->temp()); __ Set(tmp, int_val); __ movq(res, tmp); } } void LCodeGen::DoConstantT(LConstantT* instr) { Handle<Object> value = instr->value(); if (value->IsSmi()) { __ Move(ToRegister(instr->result()), value); } else { __ LoadHeapObject(ToRegister(instr->result()), Handle<HeapObject>::cast(value)); } } void LCodeGen::DoJSArrayLength(LJSArrayLength* instr) { Register result = ToRegister(instr->result()); Register array = ToRegister(instr->value()); __ movq(result, FieldOperand(array, JSArray::kLengthOffset)); } void LCodeGen::DoFixedArrayBaseLength(LFixedArrayBaseLength* instr) { Register result = ToRegister(instr->result()); Register array = ToRegister(instr->value()); __ movq(result, FieldOperand(array, FixedArrayBase::kLengthOffset)); } void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) { Register result = ToRegister(instr->result()); Register map = ToRegister(instr->value()); __ EnumLength(result, map); } void LCodeGen::DoElementsKind(LElementsKind* instr) { Register result = ToRegister(instr->result()); Register input = ToRegister(instr->value()); // Load map into |result|. __ movq(result, FieldOperand(input, HeapObject::kMapOffset)); // Load the map's "bit field 2" into |result|. We only need the first byte. __ movzxbq(result, FieldOperand(result, Map::kBitField2Offset)); // Retrieve elements_kind from bit field 2. __ and_(result, Immediate(Map::kElementsKindMask)); __ shr(result, Immediate(Map::kElementsKindShift)); } void LCodeGen::DoValueOf(LValueOf* instr) { Register input = ToRegister(instr->value()); Register result = ToRegister(instr->result()); ASSERT(input.is(result)); Label done; // If the object is a smi return the object. __ JumpIfSmi(input, &done, Label::kNear); // If the object is not a value type, return the object. __ CmpObjectType(input, JS_VALUE_TYPE, kScratchRegister); __ j(not_equal, &done, Label::kNear); __ movq(result, FieldOperand(input, JSValue::kValueOffset)); __ bind(&done); } void LCodeGen::DoDateField(LDateField* instr) { Register object = ToRegister(instr->date()); Register result = ToRegister(instr->result()); Smi* index = instr->index(); Label runtime, done, not_date_object; ASSERT(object.is(result)); ASSERT(object.is(rax)); Condition cc = masm()->CheckSmi(object); DeoptimizeIf(cc, instr->environment()); __ CmpObjectType(object, JS_DATE_TYPE, kScratchRegister); DeoptimizeIf(not_equal, instr->environment()); if (index->value() == 0) { __ movq(result, FieldOperand(object, JSDate::kValueOffset)); } else { if (index->value() < JSDate::kFirstUncachedField) { ExternalReference stamp = ExternalReference::date_cache_stamp(isolate()); __ movq(kScratchRegister, stamp); __ cmpq(kScratchRegister, FieldOperand(object, JSDate::kCacheStampOffset)); __ j(not_equal, &runtime, Label::kNear); __ movq(result, FieldOperand(object, JSDate::kValueOffset + kPointerSize * index->value())); __ jmp(&done); } __ bind(&runtime); __ PrepareCallCFunction(2); #ifdef _WIN64 __ movq(rcx, object); __ movq(rdx, index, RelocInfo::NONE64); #else __ movq(rdi, object); __ movq(rsi, index, RelocInfo::NONE64); #endif __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); __ bind(&done); } } void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) { SeqStringSetCharGenerator::Generate(masm(), instr->encoding(), ToRegister(instr->string()), ToRegister(instr->index()), ToRegister(instr->value())); } void LCodeGen::DoBitNotI(LBitNotI* instr) { LOperand* input = instr->value(); ASSERT(input->Equals(instr->result())); __ not_(ToRegister(input)); } void LCodeGen::DoThrow(LThrow* instr) { __ push(ToRegister(instr->value())); CallRuntime(Runtime::kThrow, 1, instr); if (FLAG_debug_code) { Comment("Unreachable code."); __ int3(); } } void LCodeGen::DoAddI(LAddI* instr) { LOperand* left = instr->left(); LOperand* right = instr->right(); ASSERT(left->Equals(instr->result())); if (right->IsConstantOperand()) { __ addl(ToRegister(left), Immediate(ToInteger32(LConstantOperand::cast(right)))); } else if (right->IsRegister()) { __ addl(ToRegister(left), ToRegister(right)); } else { __ addl(ToRegister(left), ToOperand(right)); } if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) { DeoptimizeIf(overflow, instr->environment()); } } void LCodeGen::DoMathMinMax(LMathMinMax* instr) { LOperand* left = instr->left(); LOperand* right = instr->right(); ASSERT(left->Equals(instr->result())); HMathMinMax::Operation operation = instr->hydrogen()->operation(); if (instr->hydrogen()->representation().IsInteger32()) { Label return_left; Condition condition = (operation == HMathMinMax::kMathMin) ? less_equal : greater_equal; Register left_reg = ToRegister(left); if (right->IsConstantOperand()) { Immediate right_imm = Immediate(ToInteger32(LConstantOperand::cast(right))); __ cmpl(left_reg, right_imm); __ j(condition, &return_left, Label::kNear); __ movq(left_reg, right_imm); } else if (right->IsRegister()) { Register right_reg = ToRegister(right); __ cmpl(left_reg, right_reg); __ j(condition, &return_left, Label::kNear); __ movq(left_reg, right_reg); } else { Operand right_op = ToOperand(right); __ cmpl(left_reg, right_op); __ j(condition, &return_left, Label::kNear); __ movq(left_reg, right_op); } __ bind(&return_left); } else { ASSERT(instr->hydrogen()->representation().IsDouble()); Label check_nan_left, check_zero, return_left, return_right; Condition condition = (operation == HMathMinMax::kMathMin) ? below : above; XMMRegister left_reg = ToDoubleRegister(left); XMMRegister right_reg = ToDoubleRegister(right); __ ucomisd(left_reg, right_reg); __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN. __ j(equal, &check_zero, Label::kNear); // left == right. __ j(condition, &return_left, Label::kNear); __ jmp(&return_right, Label::kNear); __ bind(&check_zero); XMMRegister xmm_scratch = xmm0; __ xorps(xmm_scratch, xmm_scratch); __ ucomisd(left_reg, xmm_scratch); __ j(not_equal, &return_left, Label::kNear); // left == right != 0. // At this point, both left and right are either 0 or -0. if (operation == HMathMinMax::kMathMin) { __ orpd(left_reg, right_reg); } else { // Since we operate on +0 and/or -0, addsd and andsd have the same effect. __ addsd(left_reg, right_reg); } __ jmp(&return_left, Label::kNear); __ bind(&check_nan_left); __ ucomisd(left_reg, left_reg); // NaN check. __ j(parity_even, &return_left, Label::kNear); __ bind(&return_right); __ movsd(left_reg, right_reg); __ bind(&return_left); } } void LCodeGen::DoArithmeticD(LArithmeticD* instr) { XMMRegister left = ToDoubleRegister(instr->left()); XMMRegister right = ToDoubleRegister(instr->right()); XMMRegister result = ToDoubleRegister(instr->result()); // All operations except MOD are computed in-place. ASSERT(instr->op() == Token::MOD || left.is(result)); switch (instr->op()) { case Token::ADD: __ addsd(left, right); break; case Token::SUB: __ subsd(left, right); break; case Token::MUL: __ mulsd(left, right); break; case Token::DIV: __ divsd(left, right); __ movaps(left, left); break; case Token::MOD: __ PrepareCallCFunction(2); __ movaps(xmm0, left); ASSERT(right.is(xmm1)); __ CallCFunction( ExternalReference::double_fp_operation(Token::MOD, isolate()), 2); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); __ movaps(result, xmm0); break; default: UNREACHABLE(); break; } } void LCodeGen::DoArithmeticT(LArithmeticT* instr) { ASSERT(ToRegister(instr->left()).is(rdx)); ASSERT(ToRegister(instr->right()).is(rax)); ASSERT(ToRegister(instr->result()).is(rax)); BinaryOpStub stub(instr->op(), NO_OVERWRITE); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); __ nop(); // Signals no inlined code. } int LCodeGen::GetNextEmittedBlock(int block) { for (int i = block + 1; i < graph()->blocks()->length(); ++i) { LLabel* label = chunk_->GetLabel(i); if (!label->HasReplacement()) return i; } return -1; } void LCodeGen::EmitBranch(int left_block, int right_block, Condition cc) { int next_block = GetNextEmittedBlock(current_block_); right_block = chunk_->LookupDestination(right_block); left_block = chunk_->LookupDestination(left_block); if (right_block == left_block) { EmitGoto(left_block); } else if (left_block == next_block) { __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block)); } else if (right_block == next_block) { __ j(cc, chunk_->GetAssemblyLabel(left_block)); } else { __ j(cc, chunk_->GetAssemblyLabel(left_block)); if (cc != always) { __ jmp(chunk_->GetAssemblyLabel(right_block)); } } } void LCodeGen::DoBranch(LBranch* instr) { int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Representation r = instr->hydrogen()->value()->representation(); if (r.IsInteger32()) { Register reg = ToRegister(instr->value()); __ testl(reg, reg); EmitBranch(true_block, false_block, not_zero); } else if (r.IsDouble()) { XMMRegister reg = ToDoubleRegister(instr->value()); __ xorps(xmm0, xmm0); __ ucomisd(reg, xmm0); EmitBranch(true_block, false_block, not_equal); } else { ASSERT(r.IsTagged()); Register reg = ToRegister(instr->value()); HType type = instr->hydrogen()->value()->type(); if (type.IsBoolean()) { __ CompareRoot(reg, Heap::kTrueValueRootIndex); EmitBranch(true_block, false_block, equal); } else if (type.IsSmi()) { __ SmiCompare(reg, Smi::FromInt(0)); EmitBranch(true_block, false_block, not_equal); } else { Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types(); // Avoid deopts in the case where we've never executed this path before. if (expected.IsEmpty()) expected = ToBooleanStub::all_types(); if (expected.Contains(ToBooleanStub::UNDEFINED)) { // undefined -> false. __ CompareRoot(reg, Heap::kUndefinedValueRootIndex); __ j(equal, false_label); } if (expected.Contains(ToBooleanStub::BOOLEAN)) { // true -> true. __ CompareRoot(reg, Heap::kTrueValueRootIndex); __ j(equal, true_label); // false -> false. __ CompareRoot(reg, Heap::kFalseValueRootIndex); __ j(equal, false_label); } if (expected.Contains(ToBooleanStub::NULL_TYPE)) { // 'null' -> false. __ CompareRoot(reg, Heap::kNullValueRootIndex); __ j(equal, false_label); } if (expected.Contains(ToBooleanStub::SMI)) { // Smis: 0 -> false, all other -> true. __ Cmp(reg, Smi::FromInt(0)); __ j(equal, false_label); __ JumpIfSmi(reg, true_label); } else if (expected.NeedsMap()) { // If we need a map later and have a Smi -> deopt. __ testb(reg, Immediate(kSmiTagMask)); DeoptimizeIf(zero, instr->environment()); } const Register map = kScratchRegister; if (expected.NeedsMap()) { __ movq(map, FieldOperand(reg, HeapObject::kMapOffset)); if (expected.CanBeUndetectable()) { // Undetectable -> false. __ testb(FieldOperand(map, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); __ j(not_zero, false_label); } } if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) { // spec object -> true. __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE); __ j(above_equal, true_label); } if (expected.Contains(ToBooleanStub::STRING)) { // String value -> false iff empty. Label not_string; __ CmpInstanceType(map, FIRST_NONSTRING_TYPE); __ j(above_equal, &not_string, Label::kNear); __ cmpq(FieldOperand(reg, String::kLengthOffset), Immediate(0)); __ j(not_zero, true_label); __ jmp(false_label); __ bind(&not_string); } if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) { // heap number -> false iff +0, -0, or NaN. Label not_heap_number; __ CompareRoot(map, Heap::kHeapNumberMapRootIndex); __ j(not_equal, &not_heap_number, Label::kNear); __ xorps(xmm0, xmm0); __ ucomisd(xmm0, FieldOperand(reg, HeapNumber::kValueOffset)); __ j(zero, false_label); __ jmp(true_label); __ bind(&not_heap_number); } // We've seen something for the first time -> deopt. DeoptimizeIf(no_condition, instr->environment()); } } } void LCodeGen::EmitGoto(int block) { block = chunk_->LookupDestination(block); int next_block = GetNextEmittedBlock(current_block_); if (block != next_block) { __ jmp(chunk_->GetAssemblyLabel(block)); } } void LCodeGen::DoGoto(LGoto* instr) { EmitGoto(instr->block_id()); } inline Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) { Condition cond = no_condition; switch (op) { case Token::EQ: case Token::EQ_STRICT: cond = equal; break; case Token::LT: cond = is_unsigned ? below : less; break; case Token::GT: cond = is_unsigned ? above : greater; break; case Token::LTE: cond = is_unsigned ? below_equal : less_equal; break; case Token::GTE: cond = is_unsigned ? above_equal : greater_equal; break; case Token::IN: case Token::INSTANCEOF: default: UNREACHABLE(); } return cond; } void LCodeGen::DoCmpIDAndBranch(LCmpIDAndBranch* instr) { LOperand* left = instr->left(); LOperand* right = instr->right(); int false_block = chunk_->LookupDestination(instr->false_block_id()); int true_block = chunk_->LookupDestination(instr->true_block_id()); Condition cc = TokenToCondition(instr->op(), instr->is_double()); if (left->IsConstantOperand() && right->IsConstantOperand()) { // We can statically evaluate the comparison. double left_val = ToDouble(LConstantOperand::cast(left)); double right_val = ToDouble(LConstantOperand::cast(right)); int next_block = EvalComparison(instr->op(), left_val, right_val) ? true_block : false_block; EmitGoto(next_block); } else { if (instr->is_double()) { // Don't base result on EFLAGS when a NaN is involved. Instead // jump to the false block. __ ucomisd(ToDoubleRegister(left), ToDoubleRegister(right)); __ j(parity_even, chunk_->GetAssemblyLabel(false_block)); } else { int32_t value; if (right->IsConstantOperand()) { value = ToInteger32(LConstantOperand::cast(right)); __ cmpl(ToRegister(left), Immediate(value)); } else if (left->IsConstantOperand()) { value = ToInteger32(LConstantOperand::cast(left)); if (right->IsRegister()) { __ cmpl(ToRegister(right), Immediate(value)); } else { __ cmpl(ToOperand(right), Immediate(value)); } // We transposed the operands. Reverse the condition. cc = ReverseCondition(cc); } else { if (right->IsRegister()) { __ cmpl(ToRegister(left), ToRegister(right)); } else { __ cmpl(ToRegister(left), ToOperand(right)); } } } EmitBranch(true_block, false_block, cc); } } void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) { Register left = ToRegister(instr->left()); Register right = ToRegister(instr->right()); int false_block = chunk_->LookupDestination(instr->false_block_id()); int true_block = chunk_->LookupDestination(instr->true_block_id()); __ cmpq(left, right); EmitBranch(true_block, false_block, equal); } void LCodeGen::DoCmpConstantEqAndBranch(LCmpConstantEqAndBranch* instr) { Register left = ToRegister(instr->left()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); __ cmpq(left, Immediate(instr->hydrogen()->right())); EmitBranch(true_block, false_block, equal); } void LCodeGen::DoIsNilAndBranch(LIsNilAndBranch* instr) { Register reg = ToRegister(instr->value()); int false_block = chunk_->LookupDestination(instr->false_block_id()); // If the expression is known to be untagged or a smi, then it's definitely // not null, and it can't be a an undetectable object. if (instr->hydrogen()->representation().IsSpecialization() || instr->hydrogen()->type().IsSmi()) { EmitGoto(false_block); return; } int true_block = chunk_->LookupDestination(instr->true_block_id()); Heap::RootListIndex nil_value = instr->nil() == kNullValue ? Heap::kNullValueRootIndex : Heap::kUndefinedValueRootIndex; __ CompareRoot(reg, nil_value); if (instr->kind() == kStrictEquality) { EmitBranch(true_block, false_block, equal); } else { Heap::RootListIndex other_nil_value = instr->nil() == kNullValue ? Heap::kUndefinedValueRootIndex : Heap::kNullValueRootIndex; Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); __ j(equal, true_label); __ CompareRoot(reg, other_nil_value); __ j(equal, true_label); __ JumpIfSmi(reg, false_label); // Check for undetectable objects by looking in the bit field in // the map. The object has already been smi checked. Register scratch = ToRegister(instr->temp()); __ movq(scratch, FieldOperand(reg, HeapObject::kMapOffset)); __ testb(FieldOperand(scratch, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); EmitBranch(true_block, false_block, not_zero); } } Condition LCodeGen::EmitIsObject(Register input, Label* is_not_object, Label* is_object) { ASSERT(!input.is(kScratchRegister)); __ JumpIfSmi(input, is_not_object); __ CompareRoot(input, Heap::kNullValueRootIndex); __ j(equal, is_object); __ movq(kScratchRegister, FieldOperand(input, HeapObject::kMapOffset)); // Undetectable objects behave like undefined. __ testb(FieldOperand(kScratchRegister, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); __ j(not_zero, is_not_object); __ movzxbl(kScratchRegister, FieldOperand(kScratchRegister, Map::kInstanceTypeOffset)); __ cmpb(kScratchRegister, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE)); __ j(below, is_not_object); __ cmpb(kScratchRegister, Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE)); return below_equal; } void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) { Register reg = ToRegister(instr->value()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); Condition true_cond = EmitIsObject(reg, false_label, true_label); EmitBranch(true_block, false_block, true_cond); } Condition LCodeGen::EmitIsString(Register input, Register temp1, Label* is_not_string) { __ JumpIfSmi(input, is_not_string); Condition cond = masm_->IsObjectStringType(input, temp1, temp1); return cond; } void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) { Register reg = ToRegister(instr->value()); Register temp = ToRegister(instr->temp()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* false_label = chunk_->GetAssemblyLabel(false_block); Condition true_cond = EmitIsString(reg, temp, false_label); EmitBranch(true_block, false_block, true_cond); } void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) { int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Condition is_smi; if (instr->value()->IsRegister()) { Register input = ToRegister(instr->value()); is_smi = masm()->CheckSmi(input); } else { Operand input = ToOperand(instr->value()); is_smi = masm()->CheckSmi(input); } EmitBranch(true_block, false_block, is_smi); } void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) { Register input = ToRegister(instr->value()); Register temp = ToRegister(instr->temp()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); __ JumpIfSmi(input, chunk_->GetAssemblyLabel(false_block)); __ movq(temp, FieldOperand(input, HeapObject::kMapOffset)); __ testb(FieldOperand(temp, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); EmitBranch(true_block, false_block, not_zero); } void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) { Token::Value op = instr->op(); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Handle<Code> ic = CompareIC::GetUninitialized(op); CallCode(ic, RelocInfo::CODE_TARGET, instr); Condition condition = TokenToCondition(op, false); __ testq(rax, rax); EmitBranch(true_block, false_block, condition); } static InstanceType TestType(HHasInstanceTypeAndBranch* instr) { InstanceType from = instr->from(); InstanceType to = instr->to(); if (from == FIRST_TYPE) return to; ASSERT(from == to || to == LAST_TYPE); return from; } static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) { InstanceType from = instr->from(); InstanceType to = instr->to(); if (from == to) return equal; if (to == LAST_TYPE) return above_equal; if (from == FIRST_TYPE) return below_equal; UNREACHABLE(); return equal; } void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) { Register input = ToRegister(instr->value()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* false_label = chunk_->GetAssemblyLabel(false_block); __ JumpIfSmi(input, false_label); __ CmpObjectType(input, TestType(instr->hydrogen()), kScratchRegister); EmitBranch(true_block, false_block, BranchCondition(instr->hydrogen())); } void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) { Register input = ToRegister(instr->value()); Register result = ToRegister(instr->result()); __ AssertString(input); __ movl(result, FieldOperand(input, String::kHashFieldOffset)); ASSERT(String::kHashShift >= kSmiTagSize); __ IndexFromHash(result, result); } void LCodeGen::DoHasCachedArrayIndexAndBranch( LHasCachedArrayIndexAndBranch* instr) { Register input = ToRegister(instr->value()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); __ testl(FieldOperand(input, String::kHashFieldOffset), Immediate(String::kContainsCachedArrayIndexMask)); EmitBranch(true_block, false_block, equal); } // Branches to a label or falls through with the answer in the z flag. // Trashes the temp register. void LCodeGen::EmitClassOfTest(Label* is_true, Label* is_false, Handle<String> class_name, Register input, Register temp, Register temp2) { ASSERT(!input.is(temp)); ASSERT(!input.is(temp2)); ASSERT(!temp.is(temp2)); __ JumpIfSmi(input, is_false); if (class_name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("Function"))) { // Assuming the following assertions, we can use the same compares to test // for both being a function type and being in the object type range. STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2); STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE == FIRST_SPEC_OBJECT_TYPE + 1); STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_SPEC_OBJECT_TYPE - 1); STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE); __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp); __ j(below, is_false); __ j(equal, is_true); __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE); __ j(equal, is_true); } else { // Faster code path to avoid two compares: subtract lower bound from the // actual type and do a signed compare with the width of the type range. __ movq(temp, FieldOperand(input, HeapObject::kMapOffset)); __ movzxbl(temp2, FieldOperand(temp, Map::kInstanceTypeOffset)); __ subq(temp2, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE)); __ cmpq(temp2, Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE - FIRST_NONCALLABLE_SPEC_OBJECT_TYPE)); __ j(above, is_false); } // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range. // Check if the constructor in the map is a function. __ movq(temp, FieldOperand(temp, Map::kConstructorOffset)); // Objects with a non-function constructor have class 'Object'. __ CmpObjectType(temp, JS_FUNCTION_TYPE, kScratchRegister); if (class_name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("Object"))) { __ j(not_equal, is_true); } else { __ j(not_equal, is_false); } // temp now contains the constructor function. Grab the // instance class name from there. __ movq(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset)); __ movq(temp, FieldOperand(temp, SharedFunctionInfo::kInstanceClassNameOffset)); // The class name we are testing against is a symbol because it's a literal. // The name in the constructor is a symbol because of the way the context is // booted. This routine isn't expected to work for random API-created // classes and it doesn't have to because you can't access it with natives // syntax. Since both sides are symbols it is sufficient to use an identity // comparison. ASSERT(class_name->IsSymbol()); __ Cmp(temp, class_name); // End with the answer in the z flag. } void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) { Register input = ToRegister(instr->value()); Register temp = ToRegister(instr->temp()); Register temp2 = ToRegister(instr->temp2()); Handle<String> class_name = instr->hydrogen()->class_name(); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); EmitClassOfTest(true_label, false_label, class_name, input, temp, temp2); EmitBranch(true_block, false_block, equal); } void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) { Register reg = ToRegister(instr->value()); int true_block = instr->true_block_id(); int false_block = instr->false_block_id(); __ Cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map()); EmitBranch(true_block, false_block, equal); } void LCodeGen::DoInstanceOf(LInstanceOf* instr) { InstanceofStub stub(InstanceofStub::kNoFlags); __ push(ToRegister(instr->left())); __ push(ToRegister(instr->right())); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); Label true_value, done; __ testq(rax, rax); __ j(zero, &true_value, Label::kNear); __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex); __ jmp(&done, Label::kNear); __ bind(&true_value); __ LoadRoot(ToRegister(instr->result()), Heap::kTrueValueRootIndex); __ bind(&done); } void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) { class DeferredInstanceOfKnownGlobal: public LDeferredCode { public: DeferredInstanceOfKnownGlobal(LCodeGen* codegen, LInstanceOfKnownGlobal* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_); } virtual LInstruction* instr() { return instr_; } Label* map_check() { return &map_check_; } private: LInstanceOfKnownGlobal* instr_; Label map_check_; }; DeferredInstanceOfKnownGlobal* deferred; deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr); Label done, false_result; Register object = ToRegister(instr->value()); // A Smi is not an instance of anything. __ JumpIfSmi(object, &false_result); // This is the inlined call site instanceof cache. The two occurences of the // hole value will be patched to the last map/result pair generated by the // instanceof stub. Label cache_miss; // Use a temp register to avoid memory operands with variable lengths. Register map = ToRegister(instr->temp()); __ movq(map, FieldOperand(object, HeapObject::kMapOffset)); __ bind(deferred->map_check()); // Label for calculating code patching. Handle<JSGlobalPropertyCell> cache_cell = factory()->NewJSGlobalPropertyCell(factory()->the_hole_value()); __ movq(kScratchRegister, cache_cell, RelocInfo::GLOBAL_PROPERTY_CELL); __ cmpq(map, Operand(kScratchRegister, 0)); __ j(not_equal, &cache_miss, Label::kNear); // Patched to load either true or false. __ LoadRoot(ToRegister(instr->result()), Heap::kTheHoleValueRootIndex); #ifdef DEBUG // Check that the code size between patch label and patch sites is invariant. Label end_of_patched_code; __ bind(&end_of_patched_code); ASSERT(true); #endif __ jmp(&done); // The inlined call site cache did not match. Check for null and string // before calling the deferred code. __ bind(&cache_miss); // Null is not an instance of anything. __ CompareRoot(object, Heap::kNullValueRootIndex); __ j(equal, &false_result, Label::kNear); // String values are not instances of anything. __ JumpIfNotString(object, kScratchRegister, deferred->entry()); __ bind(&false_result); __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex); __ bind(deferred->exit()); __ bind(&done); } void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr, Label* map_check) { { PushSafepointRegistersScope scope(this); InstanceofStub::Flags flags = static_cast<InstanceofStub::Flags>( InstanceofStub::kNoFlags | InstanceofStub::kCallSiteInlineCheck); InstanceofStub stub(flags); __ push(ToRegister(instr->value())); __ PushHeapObject(instr->function()); static const int kAdditionalDelta = 10; int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta; ASSERT(delta >= 0); __ push_imm32(delta); // We are pushing three values on the stack but recording a // safepoint with two arguments because stub is going to // remove the third argument from the stack before jumping // to instanceof builtin on the slow path. CallCodeGeneric(stub.GetCode(), RelocInfo::CODE_TARGET, instr, RECORD_SAFEPOINT_WITH_REGISTERS, 2); ASSERT(delta == masm_->SizeOfCodeGeneratedSince(map_check)); LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment(); safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index()); // Move result to a register that survives the end of the // PushSafepointRegisterScope. __ movq(kScratchRegister, rax); } __ testq(kScratchRegister, kScratchRegister); Label load_false; Label done; __ j(not_zero, &load_false); __ LoadRoot(rax, Heap::kTrueValueRootIndex); __ jmp(&done); __ bind(&load_false); __ LoadRoot(rax, Heap::kFalseValueRootIndex); __ bind(&done); } void LCodeGen::DoCmpT(LCmpT* instr) { Token::Value op = instr->op(); Handle<Code> ic = CompareIC::GetUninitialized(op); CallCode(ic, RelocInfo::CODE_TARGET, instr); Condition condition = TokenToCondition(op, false); Label true_value, done; __ testq(rax, rax); __ j(condition, &true_value, Label::kNear); __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex); __ jmp(&done, Label::kNear); __ bind(&true_value); __ LoadRoot(ToRegister(instr->result()), Heap::kTrueValueRootIndex); __ bind(&done); } void LCodeGen::DoReturn(LReturn* instr) { if (FLAG_trace && info()->IsOptimizing()) { // Preserve the return value on the stack and rely on the runtime // call to return the value in the same register. __ push(rax); __ CallRuntime(Runtime::kTraceExit, 1); } if (info()->saves_caller_doubles()) { ASSERT(NeedsEagerFrame()); BitVector* doubles = chunk()->allocated_double_registers(); BitVector::Iterator save_iterator(doubles); int count = 0; while (!save_iterator.Done()) { __ movsd(XMMRegister::FromAllocationIndex(save_iterator.Current()), MemOperand(rsp, count * kDoubleSize)); save_iterator.Advance(); count++; } } if (NeedsEagerFrame()) { __ movq(rsp, rbp); __ pop(rbp); } if (info()->IsStub()) { __ Ret(0, r10); } else { __ Ret((GetParameterCount() + 1) * kPointerSize, rcx); } } void LCodeGen::DoLoadGlobalCell(LLoadGlobalCell* instr) { Register result = ToRegister(instr->result()); __ LoadGlobalCell(result, instr->hydrogen()->cell()); if (instr->hydrogen()->RequiresHoleCheck()) { __ CompareRoot(result, Heap::kTheHoleValueRootIndex); DeoptimizeIf(equal, instr->environment()); } } void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) { ASSERT(ToRegister(instr->global_object()).is(rax)); ASSERT(ToRegister(instr->result()).is(rax)); __ Move(rcx, instr->name()); RelocInfo::Mode mode = instr->for_typeof() ? RelocInfo::CODE_TARGET : RelocInfo::CODE_TARGET_CONTEXT; Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); CallCode(ic, mode, instr); } void LCodeGen::DoStoreGlobalCell(LStoreGlobalCell* instr) { Register value = ToRegister(instr->value()); Handle<JSGlobalPropertyCell> cell_handle = instr->hydrogen()->cell(); // If the cell we are storing to contains the hole it could have // been deleted from the property dictionary. In that case, we need // to update the property details in the property dictionary to mark // it as no longer deleted. We deoptimize in that case. if (instr->hydrogen()->RequiresHoleCheck()) { // We have a temp because CompareRoot might clobber kScratchRegister. Register cell = ToRegister(instr->temp()); ASSERT(!value.is(cell)); __ movq(cell, cell_handle, RelocInfo::GLOBAL_PROPERTY_CELL); __ CompareRoot(Operand(cell, 0), Heap::kTheHoleValueRootIndex); DeoptimizeIf(equal, instr->environment()); // Store the value. __ movq(Operand(cell, 0), value); } else { // Store the value. __ movq(kScratchRegister, cell_handle, RelocInfo::GLOBAL_PROPERTY_CELL); __ movq(Operand(kScratchRegister, 0), value); } // Cells are always rescanned, so no write barrier here. } void LCodeGen::DoStoreGlobalGeneric(LStoreGlobalGeneric* instr) { ASSERT(ToRegister(instr->global_object()).is(rdx)); ASSERT(ToRegister(instr->value()).is(rax)); __ Move(rcx, instr->name()); Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode) ? isolate()->builtins()->StoreIC_Initialize_Strict() : isolate()->builtins()->StoreIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET_CONTEXT, instr); } void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) { Register context = ToRegister(instr->context()); Register result = ToRegister(instr->result()); __ movq(result, ContextOperand(context, instr->slot_index())); if (instr->hydrogen()->RequiresHoleCheck()) { __ CompareRoot(result, Heap::kTheHoleValueRootIndex); if (instr->hydrogen()->DeoptimizesOnHole()) { DeoptimizeIf(equal, instr->environment()); } else { Label is_not_hole; __ j(not_equal, &is_not_hole, Label::kNear); __ LoadRoot(result, Heap::kUndefinedValueRootIndex); __ bind(&is_not_hole); } } } void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) { Register context = ToRegister(instr->context()); Register value = ToRegister(instr->value()); Operand target = ContextOperand(context, instr->slot_index()); Label skip_assignment; if (instr->hydrogen()->RequiresHoleCheck()) { __ CompareRoot(target, Heap::kTheHoleValueRootIndex); if (instr->hydrogen()->DeoptimizesOnHole()) { DeoptimizeIf(equal, instr->environment()); } else { __ j(not_equal, &skip_assignment); } } __ movq(target, value); if (instr->hydrogen()->NeedsWriteBarrier()) { HType type = instr->hydrogen()->value()->type(); SmiCheck check_needed = type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK; int offset = Context::SlotOffset(instr->slot_index()); Register scratch = ToRegister(instr->temp()); __ RecordWriteContextSlot(context, offset, value, scratch, kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed); } __ bind(&skip_assignment); } void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) { Register object = ToRegister(instr->object()); Register result = ToRegister(instr->result()); if (instr->hydrogen()->is_in_object()) { __ movq(result, FieldOperand(object, instr->hydrogen()->offset())); } else { __ movq(result, FieldOperand(object, JSObject::kPropertiesOffset)); __ movq(result, FieldOperand(result, instr->hydrogen()->offset())); } } void LCodeGen::EmitLoadFieldOrConstantFunction(Register result, Register object, Handle<Map> type, Handle<String> name, LEnvironment* env) { LookupResult lookup(isolate()); type->LookupDescriptor(NULL, *name, &lookup); ASSERT(lookup.IsFound() || lookup.IsCacheable()); if (lookup.IsField()) { int index = lookup.GetLocalFieldIndexFromMap(*type); int offset = index * kPointerSize; if (index < 0) { // Negative property indices are in-object properties, indexed // from the end of the fixed part of the object. __ movq(result, FieldOperand(object, offset + type->instance_size())); } else { // Non-negative property indices are in the properties array. __ movq(result, FieldOperand(object, JSObject::kPropertiesOffset)); __ movq(result, FieldOperand(result, offset + FixedArray::kHeaderSize)); } } else if (lookup.IsConstantFunction()) { Handle<JSFunction> function(lookup.GetConstantFunctionFromMap(*type)); __ LoadHeapObject(result, function); } else { // Negative lookup. // Check prototypes. Handle<HeapObject> current(HeapObject::cast((*type)->prototype())); Heap* heap = type->GetHeap(); while (*current != heap->null_value()) { __ LoadHeapObject(result, current); __ Cmp(FieldOperand(result, HeapObject::kMapOffset), Handle<Map>(current->map())); DeoptimizeIf(not_equal, env); current = Handle<HeapObject>(HeapObject::cast(current->map()->prototype())); } __ LoadRoot(result, Heap::kUndefinedValueRootIndex); } } // Check for cases where EmitLoadFieldOrConstantFunction needs to walk the // prototype chain, which causes unbounded code generation. static bool CompactEmit(SmallMapList* list, Handle<String> name, int i, Isolate* isolate) { Handle<Map> map = list->at(i); // If the map has ElementsKind transitions, we will generate map checks // for each kind in __ CompareMap(..., ALLOW_ELEMENTS_TRANSITION_MAPS). if (map->HasElementsTransition()) return false; LookupResult lookup(isolate); map->LookupDescriptor(NULL, *name, &lookup); return lookup.IsField() || lookup.IsConstantFunction(); } void LCodeGen::DoLoadNamedFieldPolymorphic(LLoadNamedFieldPolymorphic* instr) { Register object = ToRegister(instr->object()); Register result = ToRegister(instr->result()); int map_count = instr->hydrogen()->types()->length(); bool need_generic = instr->hydrogen()->need_generic(); if (map_count == 0 && !need_generic) { DeoptimizeIf(no_condition, instr->environment()); return; } Handle<String> name = instr->hydrogen()->name(); Label done; bool all_are_compact = true; for (int i = 0; i < map_count; ++i) { if (!CompactEmit(instr->hydrogen()->types(), name, i, isolate())) { all_are_compact = false; break; } } for (int i = 0; i < map_count; ++i) { bool last = (i == map_count - 1); Handle<Map> map = instr->hydrogen()->types()->at(i); Label check_passed; __ CompareMap(object, map, &check_passed, ALLOW_ELEMENT_TRANSITION_MAPS); if (last && !need_generic) { DeoptimizeIf(not_equal, instr->environment()); __ bind(&check_passed); EmitLoadFieldOrConstantFunction( result, object, map, name, instr->environment()); } else { Label next; bool compact = all_are_compact ? true : CompactEmit(instr->hydrogen()->types(), name, i, isolate()); __ j(not_equal, &next, compact ? Label::kNear : Label::kFar); __ bind(&check_passed); EmitLoadFieldOrConstantFunction( result, object, map, name, instr->environment()); __ jmp(&done, all_are_compact ? Label::kNear : Label::kFar); __ bind(&next); } } if (need_generic) { __ Move(rcx, name); Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr); } __ bind(&done); } void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) { ASSERT(ToRegister(instr->object()).is(rax)); ASSERT(ToRegister(instr->result()).is(rax)); __ Move(rcx, instr->name()); Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) { Register function = ToRegister(instr->function()); Register result = ToRegister(instr->result()); // Check that the function really is a function. __ CmpObjectType(function, JS_FUNCTION_TYPE, result); DeoptimizeIf(not_equal, instr->environment()); // Check whether the function has an instance prototype. Label non_instance; __ testb(FieldOperand(result, Map::kBitFieldOffset), Immediate(1 << Map::kHasNonInstancePrototype)); __ j(not_zero, &non_instance, Label::kNear); // Get the prototype or initial map from the function. __ movq(result, FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset)); // Check that the function has a prototype or an initial map. __ CompareRoot(result, Heap::kTheHoleValueRootIndex); DeoptimizeIf(equal, instr->environment()); // If the function does not have an initial map, we're done. Label done; __ CmpObjectType(result, MAP_TYPE, kScratchRegister); __ j(not_equal, &done, Label::kNear); // Get the prototype from the initial map. __ movq(result, FieldOperand(result, Map::kPrototypeOffset)); __ jmp(&done, Label::kNear); // Non-instance prototype: Fetch prototype from constructor field // in the function's map. __ bind(&non_instance); __ movq(result, FieldOperand(result, Map::kConstructorOffset)); // All done. __ bind(&done); } void LCodeGen::DoLoadElements(LLoadElements* instr) { Register result = ToRegister(instr->result()); Register input = ToRegister(instr->object()); __ movq(result, FieldOperand(input, JSObject::kElementsOffset)); if (FLAG_debug_code) { Label done, ok, fail; __ CompareRoot(FieldOperand(result, HeapObject::kMapOffset), Heap::kFixedArrayMapRootIndex); __ j(equal, &done, Label::kNear); __ CompareRoot(FieldOperand(result, HeapObject::kMapOffset), Heap::kFixedCOWArrayMapRootIndex); __ j(equal, &done, Label::kNear); Register temp((result.is(rax)) ? rbx : rax); __ push(temp); __ movq(temp, FieldOperand(result, HeapObject::kMapOffset)); __ movzxbq(temp, FieldOperand(temp, Map::kBitField2Offset)); __ and_(temp, Immediate(Map::kElementsKindMask)); __ shr(temp, Immediate(Map::kElementsKindShift)); __ cmpl(temp, Immediate(GetInitialFastElementsKind())); __ j(less, &fail, Label::kNear); __ cmpl(temp, Immediate(TERMINAL_FAST_ELEMENTS_KIND)); __ j(less_equal, &ok, Label::kNear); __ cmpl(temp, Immediate(FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND)); __ j(less, &fail, Label::kNear); __ cmpl(temp, Immediate(LAST_EXTERNAL_ARRAY_ELEMENTS_KIND)); __ j(less_equal, &ok, Label::kNear); __ bind(&fail); __ Abort("Check for fast or external elements failed"); __ bind(&ok); __ pop(temp); __ bind(&done); } } void LCodeGen::DoLoadExternalArrayPointer( LLoadExternalArrayPointer* instr) { Register result = ToRegister(instr->result()); Register input = ToRegister(instr->object()); __ movq(result, FieldOperand(input, ExternalPixelArray::kExternalPointerOffset)); } void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) { Register arguments = ToRegister(instr->arguments()); Register length = ToRegister(instr->length()); Register result = ToRegister(instr->result()); // There are two words between the frame pointer and the last argument. // Subtracting from length accounts for one of them add one more. if (instr->index()->IsRegister()) { __ subl(length, ToRegister(instr->index())); } else { __ subl(length, ToOperand(instr->index())); } __ movq(result, Operand(arguments, length, times_pointer_size, kPointerSize)); } void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) { ElementsKind elements_kind = instr->elements_kind(); LOperand* key = instr->key(); if (!key->IsConstantOperand()) { Register key_reg = ToRegister(key); // Even though the HLoad/StoreKeyed (in this case) instructions force // the input representation for the key to be an integer, the input // gets replaced during bound check elimination with the index argument // to the bounds check, which can be tagged, so that case must be // handled here, too. if (instr->hydrogen()->key()->representation().IsTagged()) { __ SmiToInteger64(key_reg, key_reg); } else if (instr->hydrogen()->IsDehoisted()) { // Sign extend key because it could be a 32 bit negative value // and the dehoisted address computation happens in 64 bits __ movsxlq(key_reg, key_reg); } } Operand operand(BuildFastArrayOperand( instr->elements(), key, elements_kind, 0, instr->additional_index())); if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) { XMMRegister result(ToDoubleRegister(instr->result())); __ movss(result, operand); __ cvtss2sd(result, result); } else if (elements_kind == EXTERNAL_DOUBLE_ELEMENTS) { __ movsd(ToDoubleRegister(instr->result()), operand); } else { Register result(ToRegister(instr->result())); switch (elements_kind) { case EXTERNAL_BYTE_ELEMENTS: __ movsxbq(result, operand); break; case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: case EXTERNAL_PIXEL_ELEMENTS: __ movzxbq(result, operand); break; case EXTERNAL_SHORT_ELEMENTS: __ movsxwq(result, operand); break; case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: __ movzxwq(result, operand); break; case EXTERNAL_INT_ELEMENTS: __ movsxlq(result, operand); break; case EXTERNAL_UNSIGNED_INT_ELEMENTS: __ movl(result, operand); if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) { __ testl(result, result); DeoptimizeIf(negative, instr->environment()); } break; case EXTERNAL_FLOAT_ELEMENTS: case EXTERNAL_DOUBLE_ELEMENTS: case FAST_ELEMENTS: case FAST_SMI_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case FAST_HOLEY_ELEMENTS: case FAST_HOLEY_SMI_ELEMENTS: case FAST_HOLEY_DOUBLE_ELEMENTS: case DICTIONARY_ELEMENTS: case NON_STRICT_ARGUMENTS_ELEMENTS: UNREACHABLE(); break; } } } void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) { XMMRegister result(ToDoubleRegister(instr->result())); LOperand* key = instr->key(); if (!key->IsConstantOperand()) { Register key_reg = ToRegister(key); // Even though the HLoad/StoreKeyed instructions force the input // representation for the key to be an integer, the input gets replaced // during bound check elimination with the index argument to the bounds // check, which can be tagged, so that case must be handled here, too. if (instr->hydrogen()->key()->representation().IsTagged()) { __ SmiToInteger64(key_reg, key_reg); } else if (instr->hydrogen()->IsDehoisted()) { // Sign extend key because it could be a 32 bit negative value // and the dehoisted address computation happens in 64 bits __ movsxlq(key_reg, key_reg); } } if (instr->hydrogen()->RequiresHoleCheck()) { int offset = FixedDoubleArray::kHeaderSize - kHeapObjectTag + sizeof(kHoleNanLower32); Operand hole_check_operand = BuildFastArrayOperand( instr->elements(), key, FAST_DOUBLE_ELEMENTS, offset, instr->additional_index()); __ cmpl(hole_check_operand, Immediate(kHoleNanUpper32)); DeoptimizeIf(equal, instr->environment()); } Operand double_load_operand = BuildFastArrayOperand( instr->elements(), key, FAST_DOUBLE_ELEMENTS, FixedDoubleArray::kHeaderSize - kHeapObjectTag, instr->additional_index()); __ movsd(result, double_load_operand); } void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) { Register result = ToRegister(instr->result()); LOperand* key = instr->key(); if (!key->IsConstantOperand()) { Register key_reg = ToRegister(key); // Even though the HLoad/StoreKeyedFastElement instructions force // the input representation for the key to be an integer, the input // gets replaced during bound check elimination with the index // argument to the bounds check, which can be tagged, so that // case must be handled here, too. if (instr->hydrogen()->key()->representation().IsTagged()) { __ SmiToInteger64(key_reg, key_reg); } else if (instr->hydrogen()->IsDehoisted()) { // Sign extend key because it could be a 32 bit negative value // and the dehoisted address computation happens in 64 bits __ movsxlq(key_reg, key_reg); } } // Load the result. __ movq(result, BuildFastArrayOperand(instr->elements(), key, FAST_ELEMENTS, FixedArray::kHeaderSize - kHeapObjectTag, instr->additional_index())); // Check for the hole value. if (instr->hydrogen()->RequiresHoleCheck()) { if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) { Condition smi = __ CheckSmi(result); DeoptimizeIf(NegateCondition(smi), instr->environment()); } else { __ CompareRoot(result, Heap::kTheHoleValueRootIndex); DeoptimizeIf(equal, instr->environment()); } } } void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) { if (instr->is_external()) { DoLoadKeyedExternalArray(instr); } else if (instr->hydrogen()->representation().IsDouble()) { DoLoadKeyedFixedDoubleArray(instr); } else { DoLoadKeyedFixedArray(instr); } } Operand LCodeGen::BuildFastArrayOperand( LOperand* elements_pointer, LOperand* key, ElementsKind elements_kind, uint32_t offset, uint32_t additional_index) { Register elements_pointer_reg = ToRegister(elements_pointer); int shift_size = ElementsKindToShiftSize(elements_kind); if (key->IsConstantOperand()) { int constant_value = ToInteger32(LConstantOperand::cast(key)); if (constant_value & 0xF0000000) { Abort("array index constant value too big"); } return Operand(elements_pointer_reg, ((constant_value + additional_index) << shift_size) + offset); } else { ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size); return Operand(elements_pointer_reg, ToRegister(key), scale_factor, offset + (additional_index << shift_size)); } } void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) { ASSERT(ToRegister(instr->object()).is(rdx)); ASSERT(ToRegister(instr->key()).is(rax)); Handle<Code> ic = isolate()->builtins()->KeyedLoadIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) { Register result = ToRegister(instr->result()); if (instr->hydrogen()->from_inlined()) { __ lea(result, Operand(rsp, -2 * kPointerSize)); } else { // Check for arguments adapter frame. Label done, adapted; __ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset)); __ Cmp(Operand(result, StandardFrameConstants::kContextOffset), Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)); __ j(equal, &adapted, Label::kNear); // No arguments adaptor frame. __ movq(result, rbp); __ jmp(&done, Label::kNear); // Arguments adaptor frame present. __ bind(&adapted); __ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset)); // Result is the frame pointer for the frame if not adapted and for the real // frame below the adaptor frame if adapted. __ bind(&done); } } void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) { Register result = ToRegister(instr->result()); Label done; // If no arguments adaptor frame the number of arguments is fixed. if (instr->elements()->IsRegister()) { __ cmpq(rbp, ToRegister(instr->elements())); } else { __ cmpq(rbp, ToOperand(instr->elements())); } __ movl(result, Immediate(scope()->num_parameters())); __ j(equal, &done, Label::kNear); // Arguments adaptor frame present. Get argument length from there. __ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset)); __ SmiToInteger32(result, Operand(result, ArgumentsAdaptorFrameConstants::kLengthOffset)); // Argument length is in result register. __ bind(&done); } void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) { Register receiver = ToRegister(instr->receiver()); Register function = ToRegister(instr->function()); // If the receiver is null or undefined, we have to pass the global // object as a receiver to normal functions. Values have to be // passed unchanged to builtins and strict-mode functions. Label global_object, receiver_ok; // Do not transform the receiver to object for strict mode // functions. __ movq(kScratchRegister, FieldOperand(function, JSFunction::kSharedFunctionInfoOffset)); __ testb(FieldOperand(kScratchRegister, SharedFunctionInfo::kStrictModeByteOffset), Immediate(1 << SharedFunctionInfo::kStrictModeBitWithinByte)); __ j(not_equal, &receiver_ok, Label::kNear); // Do not transform the receiver to object for builtins. __ testb(FieldOperand(kScratchRegister, SharedFunctionInfo::kNativeByteOffset), Immediate(1 << SharedFunctionInfo::kNativeBitWithinByte)); __ j(not_equal, &receiver_ok, Label::kNear); // Normal function. Replace undefined or null with global receiver. __ CompareRoot(receiver, Heap::kNullValueRootIndex); __ j(equal, &global_object, Label::kNear); __ CompareRoot(receiver, Heap::kUndefinedValueRootIndex); __ j(equal, &global_object, Label::kNear); // The receiver should be a JS object. Condition is_smi = __ CheckSmi(receiver); DeoptimizeIf(is_smi, instr->environment()); __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, kScratchRegister); DeoptimizeIf(below, instr->environment()); __ jmp(&receiver_ok, Label::kNear); __ bind(&global_object); // TODO(kmillikin): We have a hydrogen value for the global object. See // if it's better to use it than to explicitly fetch it from the context // here. __ movq(receiver, ContextOperand(rsi, Context::GLOBAL_OBJECT_INDEX)); __ movq(receiver, FieldOperand(receiver, JSGlobalObject::kGlobalReceiverOffset)); __ bind(&receiver_ok); } void LCodeGen::DoApplyArguments(LApplyArguments* instr) { Register receiver = ToRegister(instr->receiver()); Register function = ToRegister(instr->function()); Register length = ToRegister(instr->length()); Register elements = ToRegister(instr->elements()); ASSERT(receiver.is(rax)); // Used for parameter count. ASSERT(function.is(rdi)); // Required by InvokeFunction. ASSERT(ToRegister(instr->result()).is(rax)); // Copy the arguments to this function possibly from the // adaptor frame below it. const uint32_t kArgumentsLimit = 1 * KB; __ cmpq(length, Immediate(kArgumentsLimit)); DeoptimizeIf(above, instr->environment()); __ push(receiver); __ movq(receiver, length); // Loop through the arguments pushing them onto the execution // stack. Label invoke, loop; // length is a small non-negative integer, due to the test above. __ testl(length, length); __ j(zero, &invoke, Label::kNear); __ bind(&loop); __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize)); __ decl(length); __ j(not_zero, &loop); // Invoke the function. __ bind(&invoke); ASSERT(instr->HasPointerMap()); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); SafepointGenerator safepoint_generator( this, pointers, Safepoint::kLazyDeopt); ParameterCount actual(rax); __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator, CALL_AS_METHOD); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoPushArgument(LPushArgument* instr) { LOperand* argument = instr->value(); EmitPushTaggedOperand(argument); } void LCodeGen::DoDrop(LDrop* instr) { __ Drop(instr->count()); } void LCodeGen::DoThisFunction(LThisFunction* instr) { Register result = ToRegister(instr->result()); __ movq(result, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); } void LCodeGen::DoContext(LContext* instr) { Register result = ToRegister(instr->result()); __ movq(result, rsi); } void LCodeGen::DoOuterContext(LOuterContext* instr) { Register context = ToRegister(instr->context()); Register result = ToRegister(instr->result()); __ movq(result, Operand(context, Context::SlotOffset(Context::PREVIOUS_INDEX))); } void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) { __ push(rsi); // The context is the first argument. __ PushHeapObject(instr->hydrogen()->pairs()); __ Push(Smi::FromInt(instr->hydrogen()->flags())); CallRuntime(Runtime::kDeclareGlobals, 3, instr); } void LCodeGen::DoGlobalObject(LGlobalObject* instr) { Register result = ToRegister(instr->result()); __ movq(result, GlobalObjectOperand()); } void LCodeGen::DoGlobalReceiver(LGlobalReceiver* instr) { Register global = ToRegister(instr->global()); Register result = ToRegister(instr->result()); __ movq(result, FieldOperand(global, GlobalObject::kGlobalReceiverOffset)); } void LCodeGen::CallKnownFunction(Handle<JSFunction> function, int arity, LInstruction* instr, CallKind call_kind, RDIState rdi_state) { bool can_invoke_directly = !function->NeedsArgumentsAdaption() || function->shared()->formal_parameter_count() == arity; LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); if (can_invoke_directly) { if (rdi_state == RDI_UNINITIALIZED) { __ LoadHeapObject(rdi, function); } // Change context. __ movq(rsi, FieldOperand(rdi, JSFunction::kContextOffset)); // Set rax to arguments count if adaption is not needed. Assumes that rax // is available to write to at this point. if (!function->NeedsArgumentsAdaption()) { __ Set(rax, arity); } // Invoke function. __ SetCallKind(rcx, call_kind); if (*function == *info()->closure()) { __ CallSelf(); } else { __ call(FieldOperand(rdi, JSFunction::kCodeEntryOffset)); } // Set up deoptimization. RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT, 0); } else { // We need to adapt arguments. SafepointGenerator generator( this, pointers, Safepoint::kLazyDeopt); ParameterCount count(arity); __ InvokeFunction(function, count, CALL_FUNCTION, generator, call_kind); } // Restore context. __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallConstantFunction(LCallConstantFunction* instr) { ASSERT(ToRegister(instr->result()).is(rax)); CallKnownFunction(instr->function(), instr->arity(), instr, CALL_AS_METHOD, RDI_UNINITIALIZED); } void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LUnaryMathOperation* instr) { Register input_reg = ToRegister(instr->value()); __ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset), Heap::kHeapNumberMapRootIndex); DeoptimizeIf(not_equal, instr->environment()); Label done; Register tmp = input_reg.is(rax) ? rcx : rax; Register tmp2 = tmp.is(rcx) ? rdx : input_reg.is(rcx) ? rdx : rcx; // Preserve the value of all registers. PushSafepointRegistersScope scope(this); Label negative; __ movl(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset)); // Check the sign of the argument. If the argument is positive, just // return it. We do not need to patch the stack since |input| and // |result| are the same register and |input| will be restored // unchanged by popping safepoint registers. __ testl(tmp, Immediate(HeapNumber::kSignMask)); __ j(not_zero, &negative); __ jmp(&done); __ bind(&negative); Label allocated, slow; __ AllocateHeapNumber(tmp, tmp2, &slow); __ jmp(&allocated); // Slow case: Call the runtime system to do the number allocation. __ bind(&slow); CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr); // Set the pointer to the new heap number in tmp. if (!tmp.is(rax)) { __ movq(tmp, rax); } // Restore input_reg after call to runtime. __ LoadFromSafepointRegisterSlot(input_reg, input_reg); __ bind(&allocated); __ movq(tmp2, FieldOperand(input_reg, HeapNumber::kValueOffset)); __ shl(tmp2, Immediate(1)); __ shr(tmp2, Immediate(1)); __ movq(FieldOperand(tmp, HeapNumber::kValueOffset), tmp2); __ StoreToSafepointRegisterSlot(input_reg, tmp); __ bind(&done); } void LCodeGen::EmitIntegerMathAbs(LUnaryMathOperation* instr) { Register input_reg = ToRegister(instr->value()); __ testl(input_reg, input_reg); Label is_positive; __ j(not_sign, &is_positive); __ negl(input_reg); // Sets flags. DeoptimizeIf(negative, instr->environment()); __ bind(&is_positive); } void LCodeGen::DoMathAbs(LUnaryMathOperation* instr) { // Class for deferred case. class DeferredMathAbsTaggedHeapNumber: public LDeferredCode { public: DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen, LUnaryMathOperation* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_); } virtual LInstruction* instr() { return instr_; } private: LUnaryMathOperation* instr_; }; ASSERT(instr->value()->Equals(instr->result())); Representation r = instr->hydrogen()->value()->representation(); if (r.IsDouble()) { XMMRegister scratch = xmm0; XMMRegister input_reg = ToDoubleRegister(instr->value()); __ xorps(scratch, scratch); __ subsd(scratch, input_reg); __ andpd(input_reg, scratch); } else if (r.IsInteger32()) { EmitIntegerMathAbs(instr); } else { // Tagged case. DeferredMathAbsTaggedHeapNumber* deferred = new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr); Register input_reg = ToRegister(instr->value()); // Smi check. __ JumpIfNotSmi(input_reg, deferred->entry()); __ SmiToInteger32(input_reg, input_reg); EmitIntegerMathAbs(instr); __ Integer32ToSmi(input_reg, input_reg); __ bind(deferred->exit()); } } void LCodeGen::DoMathFloor(LUnaryMathOperation* instr) { XMMRegister xmm_scratch = xmm0; Register output_reg = ToRegister(instr->result()); XMMRegister input_reg = ToDoubleRegister(instr->value()); if (CpuFeatures::IsSupported(SSE4_1)) { CpuFeatures::Scope scope(SSE4_1); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { // Deoptimize if minus zero. __ movq(output_reg, input_reg); __ subq(output_reg, Immediate(1)); DeoptimizeIf(overflow, instr->environment()); } __ roundsd(xmm_scratch, input_reg, Assembler::kRoundDown); __ cvttsd2si(output_reg, xmm_scratch); __ cmpl(output_reg, Immediate(0x80000000)); DeoptimizeIf(equal, instr->environment()); } else { Label negative_sign, done; // Deoptimize on negative inputs. __ xorps(xmm_scratch, xmm_scratch); // Zero the register. __ ucomisd(input_reg, xmm_scratch); DeoptimizeIf(parity_even, instr->environment()); __ j(below, &negative_sign, Label::kNear); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { // Check for negative zero. Label positive_sign; __ j(above, &positive_sign, Label::kNear); __ movmskpd(output_reg, input_reg); __ testq(output_reg, Immediate(1)); DeoptimizeIf(not_zero, instr->environment()); __ Set(output_reg, 0); __ jmp(&done); __ bind(&positive_sign); } // Use truncating instruction (OK because input is positive). __ cvttsd2si(output_reg, input_reg); // Overflow is signalled with minint. __ cmpl(output_reg, Immediate(0x80000000)); DeoptimizeIf(equal, instr->environment()); __ jmp(&done, Label::kNear); // Non-zero negative reaches here. __ bind(&negative_sign); // Truncate, then compare and compensate. __ cvttsd2si(output_reg, input_reg); __ cvtlsi2sd(xmm_scratch, output_reg); __ ucomisd(input_reg, xmm_scratch); __ j(equal, &done, Label::kNear); __ subl(output_reg, Immediate(1)); DeoptimizeIf(overflow, instr->environment()); __ bind(&done); } } void LCodeGen::DoMathRound(LUnaryMathOperation* instr) { const XMMRegister xmm_scratch = xmm0; Register output_reg = ToRegister(instr->result()); XMMRegister input_reg = ToDoubleRegister(instr->value()); Label done; // xmm_scratch = 0.5 __ movq(kScratchRegister, V8_INT64_C(0x3FE0000000000000), RelocInfo::NONE64); __ movq(xmm_scratch, kScratchRegister); Label below_half; __ ucomisd(xmm_scratch, input_reg); // If input_reg is NaN, this doesn't jump. __ j(above, &below_half, Label::kNear); // input = input + 0.5 // This addition might give a result that isn't the correct for // rounding, due to loss of precision, but only for a number that's // so big that the conversion below will overflow anyway. __ addsd(xmm_scratch, input_reg); // Compute Math.floor(input). // Use truncating instruction (OK because input is positive). __ cvttsd2si(output_reg, xmm_scratch); // Overflow is signalled with minint. __ cmpl(output_reg, Immediate(0x80000000)); DeoptimizeIf(equal, instr->environment()); __ jmp(&done); __ bind(&below_half); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { // Bailout if negative (including -0). __ movq(output_reg, input_reg); __ testq(output_reg, output_reg); DeoptimizeIf(negative, instr->environment()); } else { // Bailout if below -0.5, otherwise round to (positive) zero, even // if negative. // xmm_scrach = -0.5 __ movq(kScratchRegister, V8_INT64_C(0xBFE0000000000000), RelocInfo::NONE64); __ movq(xmm_scratch, kScratchRegister); __ ucomisd(input_reg, xmm_scratch); DeoptimizeIf(below, instr->environment()); } __ xorl(output_reg, output_reg); __ bind(&done); } void LCodeGen::DoMathSqrt(LUnaryMathOperation* instr) { XMMRegister input_reg = ToDoubleRegister(instr->value()); ASSERT(ToDoubleRegister(instr->result()).is(input_reg)); __ sqrtsd(input_reg, input_reg); } void LCodeGen::DoMathPowHalf(LUnaryMathOperation* instr) { XMMRegister xmm_scratch = xmm0; XMMRegister input_reg = ToDoubleRegister(instr->value()); ASSERT(ToDoubleRegister(instr->result()).is(input_reg)); // Note that according to ECMA-262 15.8.2.13: // Math.pow(-Infinity, 0.5) == Infinity // Math.sqrt(-Infinity) == NaN Label done, sqrt; // Check base for -Infinity. According to IEEE-754, double-precision // -Infinity has the highest 12 bits set and the lowest 52 bits cleared. __ movq(kScratchRegister, V8_INT64_C(0xFFF0000000000000), RelocInfo::NONE64); __ movq(xmm_scratch, kScratchRegister); __ ucomisd(xmm_scratch, input_reg); // Comparing -Infinity with NaN results in "unordered", which sets the // zero flag as if both were equal. However, it also sets the carry flag. __ j(not_equal, &sqrt, Label::kNear); __ j(carry, &sqrt, Label::kNear); // If input is -Infinity, return Infinity. __ xorps(input_reg, input_reg); __ subsd(input_reg, xmm_scratch); __ jmp(&done, Label::kNear); // Square root. __ bind(&sqrt); __ xorps(xmm_scratch, xmm_scratch); __ addsd(input_reg, xmm_scratch); // Convert -0 to +0. __ sqrtsd(input_reg, input_reg); __ bind(&done); } void LCodeGen::DoPower(LPower* instr) { Representation exponent_type = instr->hydrogen()->right()->representation(); // Having marked this as a call, we can use any registers. // Just make sure that the input/output registers are the expected ones. // Choose register conforming to calling convention (when bailing out). #ifdef _WIN64 Register exponent = rdx; #else Register exponent = rdi; #endif ASSERT(!instr->right()->IsRegister() || ToRegister(instr->right()).is(exponent)); ASSERT(!instr->right()->IsDoubleRegister() || ToDoubleRegister(instr->right()).is(xmm1)); ASSERT(ToDoubleRegister(instr->left()).is(xmm2)); ASSERT(ToDoubleRegister(instr->result()).is(xmm3)); if (exponent_type.IsTagged()) { Label no_deopt; __ JumpIfSmi(exponent, &no_deopt); __ CmpObjectType(exponent, HEAP_NUMBER_TYPE, rcx); DeoptimizeIf(not_equal, instr->environment()); __ bind(&no_deopt); MathPowStub stub(MathPowStub::TAGGED); __ CallStub(&stub); } else if (exponent_type.IsInteger32()) { MathPowStub stub(MathPowStub::INTEGER); __ CallStub(&stub); } else { ASSERT(exponent_type.IsDouble()); MathPowStub stub(MathPowStub::DOUBLE); __ CallStub(&stub); } } void LCodeGen::DoRandom(LRandom* instr) { class DeferredDoRandom: public LDeferredCode { public: DeferredDoRandom(LCodeGen* codegen, LRandom* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredRandom(instr_); } virtual LInstruction* instr() { return instr_; } private: LRandom* instr_; }; DeferredDoRandom* deferred = new(zone()) DeferredDoRandom(this, instr); // Having marked this instruction as a call we can use any // registers. ASSERT(ToDoubleRegister(instr->result()).is(xmm1)); // Choose the right register for the first argument depending on // calling convention. #ifdef _WIN64 ASSERT(ToRegister(instr->global_object()).is(rcx)); Register global_object = rcx; #else ASSERT(ToRegister(instr->global_object()).is(rdi)); Register global_object = rdi; #endif static const int kSeedSize = sizeof(uint32_t); STATIC_ASSERT(kPointerSize == 2 * kSeedSize); __ movq(global_object, FieldOperand(global_object, GlobalObject::kNativeContextOffset)); static const int kRandomSeedOffset = FixedArray::kHeaderSize + Context::RANDOM_SEED_INDEX * kPointerSize; __ movq(rbx, FieldOperand(global_object, kRandomSeedOffset)); // rbx: FixedArray of the native context's random seeds // Load state[0]. __ movl(rax, FieldOperand(rbx, ByteArray::kHeaderSize)); // If state[0] == 0, call runtime to initialize seeds. __ testl(rax, rax); __ j(zero, deferred->entry()); // Load state[1]. __ movl(rcx, FieldOperand(rbx, ByteArray::kHeaderSize + kSeedSize)); // state[0] = 18273 * (state[0] & 0xFFFF) + (state[0] >> 16) // Only operate on the lower 32 bit of rax. __ movzxwl(rdx, rax); __ imull(rdx, rdx, Immediate(18273)); __ shrl(rax, Immediate(16)); __ addl(rax, rdx); // Save state[0]. __ movl(FieldOperand(rbx, ByteArray::kHeaderSize), rax); // state[1] = 36969 * (state[1] & 0xFFFF) + (state[1] >> 16) __ movzxwl(rdx, rcx); __ imull(rdx, rdx, Immediate(36969)); __ shrl(rcx, Immediate(16)); __ addl(rcx, rdx); // Save state[1]. __ movl(FieldOperand(rbx, ByteArray::kHeaderSize + kSeedSize), rcx); // Random bit pattern = (state[0] << 14) + (state[1] & 0x3FFFF) __ shll(rax, Immediate(14)); __ andl(rcx, Immediate(0x3FFFF)); __ addl(rax, rcx); __ bind(deferred->exit()); // Convert 32 random bits in rax to 0.(32 random bits) in a double // by computing: // ( 1.(20 0s)(32 random bits) x 2^20 ) - (1.0 x 2^20)). __ movq(rcx, V8_INT64_C(0x4130000000000000), RelocInfo::NONE64); // 1.0 x 2^20 as double __ movq(xmm2, rcx); __ movd(xmm1, rax); __ xorps(xmm1, xmm2); __ subsd(xmm1, xmm2); } void LCodeGen::DoDeferredRandom(LRandom* instr) { __ PrepareCallCFunction(1); __ CallCFunction(ExternalReference::random_uint32_function(isolate()), 1); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); // Return value is in rax. } void LCodeGen::DoMathExp(LMathExp* instr) { XMMRegister input = ToDoubleRegister(instr->value()); XMMRegister result = ToDoubleRegister(instr->result()); Register temp1 = ToRegister(instr->temp1()); Register temp2 = ToRegister(instr->temp2()); MathExpGenerator::EmitMathExp(masm(), input, result, xmm0, temp1, temp2); } void LCodeGen::DoMathLog(LUnaryMathOperation* instr) { ASSERT(ToDoubleRegister(instr->result()).is(xmm1)); TranscendentalCacheStub stub(TranscendentalCache::LOG, TranscendentalCacheStub::UNTAGGED); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoMathTan(LUnaryMathOperation* instr) { ASSERT(ToDoubleRegister(instr->result()).is(xmm1)); TranscendentalCacheStub stub(TranscendentalCache::TAN, TranscendentalCacheStub::UNTAGGED); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoMathCos(LUnaryMathOperation* instr) { ASSERT(ToDoubleRegister(instr->result()).is(xmm1)); TranscendentalCacheStub stub(TranscendentalCache::COS, TranscendentalCacheStub::UNTAGGED); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoMathSin(LUnaryMathOperation* instr) { ASSERT(ToDoubleRegister(instr->result()).is(xmm1)); TranscendentalCacheStub stub(TranscendentalCache::SIN, TranscendentalCacheStub::UNTAGGED); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoUnaryMathOperation(LUnaryMathOperation* instr) { switch (instr->op()) { case kMathAbs: DoMathAbs(instr); break; case kMathFloor: DoMathFloor(instr); break; case kMathRound: DoMathRound(instr); break; case kMathSqrt: DoMathSqrt(instr); break; case kMathPowHalf: DoMathPowHalf(instr); break; case kMathCos: DoMathCos(instr); break; case kMathSin: DoMathSin(instr); break; case kMathTan: DoMathTan(instr); break; case kMathLog: DoMathLog(instr); break; default: UNREACHABLE(); } } void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) { ASSERT(ToRegister(instr->function()).is(rdi)); ASSERT(instr->HasPointerMap()); if (instr->known_function().is_null()) { LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt); ParameterCount count(instr->arity()); __ InvokeFunction(rdi, count, CALL_FUNCTION, generator, CALL_AS_METHOD); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } else { CallKnownFunction(instr->known_function(), instr->arity(), instr, CALL_AS_METHOD, RDI_CONTAINS_TARGET); } } void LCodeGen::DoCallKeyed(LCallKeyed* instr) { ASSERT(ToRegister(instr->key()).is(rcx)); ASSERT(ToRegister(instr->result()).is(rax)); int arity = instr->arity(); Handle<Code> ic = isolate()->stub_cache()->ComputeKeyedCallInitialize(arity); CallCode(ic, RelocInfo::CODE_TARGET, instr); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallNamed(LCallNamed* instr) { ASSERT(ToRegister(instr->result()).is(rax)); int arity = instr->arity(); RelocInfo::Mode mode = RelocInfo::CODE_TARGET; Handle<Code> ic = isolate()->stub_cache()->ComputeCallInitialize(arity, mode); __ Move(rcx, instr->name()); CallCode(ic, mode, instr); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallFunction(LCallFunction* instr) { ASSERT(ToRegister(instr->function()).is(rdi)); ASSERT(ToRegister(instr->result()).is(rax)); int arity = instr->arity(); CallFunctionStub stub(arity, NO_CALL_FUNCTION_FLAGS); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallGlobal(LCallGlobal* instr) { ASSERT(ToRegister(instr->result()).is(rax)); int arity = instr->arity(); RelocInfo::Mode mode = RelocInfo::CODE_TARGET_CONTEXT; Handle<Code> ic = isolate()->stub_cache()->ComputeCallInitialize(arity, mode); __ Move(rcx, instr->name()); CallCode(ic, mode, instr); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallKnownGlobal(LCallKnownGlobal* instr) { ASSERT(ToRegister(instr->result()).is(rax)); CallKnownFunction(instr->target(), instr->arity(), instr, CALL_AS_FUNCTION, RDI_UNINITIALIZED); } void LCodeGen::DoCallNew(LCallNew* instr) { ASSERT(ToRegister(instr->constructor()).is(rdi)); ASSERT(ToRegister(instr->result()).is(rax)); CallConstructStub stub(NO_CALL_FUNCTION_FLAGS); __ Set(rax, instr->arity()); CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr); } void LCodeGen::DoCallRuntime(LCallRuntime* instr) { CallRuntime(instr->function(), instr->arity(), instr); } void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) { Register object = ToRegister(instr->object()); Register value = ToRegister(instr->value()); int offset = instr->offset(); if (!instr->transition().is_null()) { if (!instr->hydrogen()->NeedsWriteBarrierForMap()) { __ Move(FieldOperand(object, HeapObject::kMapOffset), instr->transition()); } else { Register temp = ToRegister(instr->temp()); __ Move(kScratchRegister, instr->transition()); __ movq(FieldOperand(object, HeapObject::kMapOffset), kScratchRegister); // Update the write barrier for the map field. __ RecordWriteField(object, HeapObject::kMapOffset, kScratchRegister, temp, kSaveFPRegs, OMIT_REMEMBERED_SET, OMIT_SMI_CHECK); } } // Do the store. HType type = instr->hydrogen()->value()->type(); SmiCheck check_needed = type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK; if (instr->is_in_object()) { __ movq(FieldOperand(object, offset), value); if (instr->hydrogen()->NeedsWriteBarrier()) { Register temp = ToRegister(instr->temp()); // Update the write barrier for the object for in-object properties. __ RecordWriteField(object, offset, value, temp, kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed); } } else { Register temp = ToRegister(instr->temp()); __ movq(temp, FieldOperand(object, JSObject::kPropertiesOffset)); __ movq(FieldOperand(temp, offset), value); if (instr->hydrogen()->NeedsWriteBarrier()) { // Update the write barrier for the properties array. // object is used as a scratch register. __ RecordWriteField(temp, offset, value, object, kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed); } } } void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) { ASSERT(ToRegister(instr->object()).is(rdx)); ASSERT(ToRegister(instr->value()).is(rax)); __ Move(rcx, instr->hydrogen()->name()); Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode) ? isolate()->builtins()->StoreIC_Initialize_Strict() : isolate()->builtins()->StoreIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr); } void LCodeGen::DeoptIfTaggedButNotSmi(LEnvironment* environment, HValue* value, LOperand* operand) { if (value->representation().IsTagged() && !value->type().IsSmi()) { Condition cc; if (operand->IsRegister()) { cc = masm()->CheckSmi(ToRegister(operand)); } else { cc = masm()->CheckSmi(ToOperand(operand)); } DeoptimizeIf(NegateCondition(cc), environment); } } void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) { DeoptIfTaggedButNotSmi(instr->environment(), instr->hydrogen()->length(), instr->length()); DeoptIfTaggedButNotSmi(instr->environment(), instr->hydrogen()->index(), instr->index()); if (instr->length()->IsRegister()) { Register reg = ToRegister(instr->length()); if (!instr->hydrogen()->length()->representation().IsTagged()) { __ AssertZeroExtended(reg); } if (instr->index()->IsConstantOperand()) { int constant_index = ToInteger32(LConstantOperand::cast(instr->index())); if (instr->hydrogen()->length()->representation().IsTagged()) { __ Cmp(reg, Smi::FromInt(constant_index)); } else { __ cmpq(reg, Immediate(constant_index)); } } else { Register reg2 = ToRegister(instr->index()); if (!instr->hydrogen()->index()->representation().IsTagged()) { __ AssertZeroExtended(reg2); } __ cmpq(reg, reg2); } } else { Operand length = ToOperand(instr->length()); if (instr->index()->IsConstantOperand()) { int constant_index = ToInteger32(LConstantOperand::cast(instr->index())); if (instr->hydrogen()->length()->representation().IsTagged()) { __ Cmp(length, Smi::FromInt(constant_index)); } else { __ cmpq(length, Immediate(constant_index)); } } else { __ cmpq(length, ToRegister(instr->index())); } } DeoptimizeIf(below_equal, instr->environment()); } void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) { ElementsKind elements_kind = instr->elements_kind(); LOperand* key = instr->key(); if (!key->IsConstantOperand()) { Register key_reg = ToRegister(key); // Even though the HLoad/StoreKeyedFastElement instructions force // the input representation for the key to be an integer, the input // gets replaced during bound check elimination with the index // argument to the bounds check, which can be tagged, so that case // must be handled here, too. if (instr->hydrogen()->key()->representation().IsTagged()) { __ SmiToInteger64(key_reg, key_reg); } else if (instr->hydrogen()->IsDehoisted()) { // Sign extend key because it could be a 32 bit negative value // and the dehoisted address computation happens in 64 bits __ movsxlq(key_reg, key_reg); } } Operand operand(BuildFastArrayOperand( instr->elements(), key, elements_kind, 0, instr->additional_index())); if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) { XMMRegister value(ToDoubleRegister(instr->value())); __ cvtsd2ss(value, value); __ movss(operand, value); } else if (elements_kind == EXTERNAL_DOUBLE_ELEMENTS) { __ movsd(operand, ToDoubleRegister(instr->value())); } else { Register value(ToRegister(instr->value())); switch (elements_kind) { case EXTERNAL_PIXEL_ELEMENTS: case EXTERNAL_BYTE_ELEMENTS: case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: __ movb(operand, value); break; case EXTERNAL_SHORT_ELEMENTS: case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: __ movw(operand, value); break; case EXTERNAL_INT_ELEMENTS: case EXTERNAL_UNSIGNED_INT_ELEMENTS: __ movl(operand, value); break; case EXTERNAL_FLOAT_ELEMENTS: case EXTERNAL_DOUBLE_ELEMENTS: case FAST_ELEMENTS: case FAST_SMI_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case FAST_HOLEY_ELEMENTS: case FAST_HOLEY_SMI_ELEMENTS: case FAST_HOLEY_DOUBLE_ELEMENTS: case DICTIONARY_ELEMENTS: case NON_STRICT_ARGUMENTS_ELEMENTS: UNREACHABLE(); break; } } } void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) { XMMRegister value = ToDoubleRegister(instr->value()); LOperand* key = instr->key(); if (!key->IsConstantOperand()) { Register key_reg = ToRegister(key); // Even though the HLoad/StoreKeyedFastElement instructions force // the input representation for the key to be an integer, the // input gets replaced during bound check elimination with the index // argument to the bounds check, which can be tagged, so that case // must be handled here, too. if (instr->hydrogen()->key()->representation().IsTagged()) { __ SmiToInteger64(key_reg, key_reg); } else if (instr->hydrogen()->IsDehoisted()) { // Sign extend key because it could be a 32 bit negative value // and the dehoisted address computation happens in 64 bits __ movsxlq(key_reg, key_reg); } } if (instr->NeedsCanonicalization()) { Label have_value; __ ucomisd(value, value); __ j(parity_odd, &have_value); // NaN. __ Set(kScratchRegister, BitCast<uint64_t>( FixedDoubleArray::canonical_not_the_hole_nan_as_double())); __ movq(value, kScratchRegister); __ bind(&have_value); } Operand double_store_operand = BuildFastArrayOperand( instr->elements(), key, FAST_DOUBLE_ELEMENTS, FixedDoubleArray::kHeaderSize - kHeapObjectTag, instr->additional_index()); __ movsd(double_store_operand, value); } void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) { Register value = ToRegister(instr->value()); Register elements = ToRegister(instr->elements()); LOperand* key = instr->key(); if (!key->IsConstantOperand()) { Register key_reg = ToRegister(key); // Even though the HLoad/StoreKeyedFastElement instructions force // the input representation for the key to be an integer, the // input gets replaced during bound check elimination with the index // argument to the bounds check, which can be tagged, so that case // must be handled here, too. if (instr->hydrogen()->key()->representation().IsTagged()) { __ SmiToInteger64(key_reg, key_reg); } else if (instr->hydrogen()->IsDehoisted()) { // Sign extend key because it could be a 32 bit negative value // and the dehoisted address computation happens in 64 bits __ movsxlq(key_reg, key_reg); } } Operand operand = BuildFastArrayOperand(instr->elements(), key, FAST_ELEMENTS, FixedArray::kHeaderSize - kHeapObjectTag, instr->additional_index()); if (instr->hydrogen()->NeedsWriteBarrier()) { ASSERT(!instr->key()->IsConstantOperand()); HType type = instr->hydrogen()->value()->type(); SmiCheck check_needed = type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK; // Compute address of modified element and store it into key register. Register key_reg(ToRegister(key)); __ lea(key_reg, operand); __ movq(Operand(key_reg, 0), value); __ RecordWrite(elements, key_reg, value, kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed); } else { __ movq(operand, value); } } void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) { if (instr->is_external()) { DoStoreKeyedExternalArray(instr); } else if (instr->hydrogen()->value()->representation().IsDouble()) { DoStoreKeyedFixedDoubleArray(instr); } else { DoStoreKeyedFixedArray(instr); } } void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) { ASSERT(ToRegister(instr->object()).is(rdx)); ASSERT(ToRegister(instr->key()).is(rcx)); ASSERT(ToRegister(instr->value()).is(rax)); Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode) ? isolate()->builtins()->KeyedStoreIC_Initialize_Strict() : isolate()->builtins()->KeyedStoreIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) { Register object_reg = ToRegister(instr->object()); Handle<Map> from_map = instr->original_map(); Handle<Map> to_map = instr->transitioned_map(); ElementsKind from_kind = instr->from_kind(); ElementsKind to_kind = instr->to_kind(); Label not_applicable; __ Cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map); __ j(not_equal, &not_applicable); if (IsSimpleMapChangeTransition(from_kind, to_kind)) { Register new_map_reg = ToRegister(instr->new_map_temp()); __ movq(new_map_reg, to_map, RelocInfo::EMBEDDED_OBJECT); __ movq(FieldOperand(object_reg, HeapObject::kMapOffset), new_map_reg); // Write barrier. ASSERT_NE(instr->temp(), NULL); __ RecordWriteField(object_reg, HeapObject::kMapOffset, new_map_reg, ToRegister(instr->temp()), kDontSaveFPRegs); } else if (FLAG_compiled_transitions) { PushSafepointRegistersScope scope(this); if (!object_reg.is(rax)) { __ movq(rax, object_reg); } __ Move(rbx, to_map); TransitionElementsKindStub stub(from_kind, to_kind); __ CallStub(&stub); RecordSafepointWithRegisters( instr->pointer_map(), 0, Safepoint::kNoLazyDeopt); } else if (IsFastSmiElementsKind(from_kind) && IsFastDoubleElementsKind(to_kind)) { Register fixed_object_reg = ToRegister(instr->temp()); ASSERT(fixed_object_reg.is(rdx)); Register new_map_reg = ToRegister(instr->new_map_temp()); ASSERT(new_map_reg.is(rbx)); __ movq(new_map_reg, to_map, RelocInfo::EMBEDDED_OBJECT); __ movq(fixed_object_reg, object_reg); CallCode(isolate()->builtins()->TransitionElementsSmiToDouble(), RelocInfo::CODE_TARGET, instr); } else if (IsFastDoubleElementsKind(from_kind) && IsFastObjectElementsKind(to_kind)) { Register fixed_object_reg = ToRegister(instr->temp()); ASSERT(fixed_object_reg.is(rdx)); Register new_map_reg = ToRegister(instr->new_map_temp()); ASSERT(new_map_reg.is(rbx)); __ movq(new_map_reg, to_map, RelocInfo::EMBEDDED_OBJECT); __ movq(fixed_object_reg, object_reg); CallCode(isolate()->builtins()->TransitionElementsDoubleToObject(), RelocInfo::CODE_TARGET, instr); } else { UNREACHABLE(); } __ bind(&not_applicable); } void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) { Register object = ToRegister(instr->object()); Register temp = ToRegister(instr->temp()); __ TestJSArrayForAllocationSiteInfo(object, temp); DeoptimizeIf(equal, instr->environment()); } void LCodeGen::DoStringAdd(LStringAdd* instr) { EmitPushTaggedOperand(instr->left()); EmitPushTaggedOperand(instr->right()); StringAddStub stub(NO_STRING_CHECK_IN_STUB); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) { class DeferredStringCharCodeAt: public LDeferredCode { public: DeferredStringCharCodeAt(LCodeGen* codegen, LStringCharCodeAt* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredStringCharCodeAt(instr_); } virtual LInstruction* instr() { return instr_; } private: LStringCharCodeAt* instr_; }; DeferredStringCharCodeAt* deferred = new(zone()) DeferredStringCharCodeAt(this, instr); StringCharLoadGenerator::Generate(masm(), ToRegister(instr->string()), ToRegister(instr->index()), ToRegister(instr->result()), deferred->entry()); __ bind(deferred->exit()); } void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) { Register string = ToRegister(instr->string()); Register result = ToRegister(instr->result()); // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. __ Set(result, 0); PushSafepointRegistersScope scope(this); __ push(string); // Push the index as a smi. This is safe because of the checks in // DoStringCharCodeAt above. STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue); if (instr->index()->IsConstantOperand()) { int const_index = ToInteger32(LConstantOperand::cast(instr->index())); __ Push(Smi::FromInt(const_index)); } else { Register index = ToRegister(instr->index()); __ Integer32ToSmi(index, index); __ push(index); } CallRuntimeFromDeferred(Runtime::kStringCharCodeAt, 2, instr); __ AssertSmi(rax); __ SmiToInteger32(rax, rax); __ StoreToSafepointRegisterSlot(result, rax); } void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) { class DeferredStringCharFromCode: public LDeferredCode { public: DeferredStringCharFromCode(LCodeGen* codegen, LStringCharFromCode* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredStringCharFromCode(instr_); } virtual LInstruction* instr() { return instr_; } private: LStringCharFromCode* instr_; }; DeferredStringCharFromCode* deferred = new(zone()) DeferredStringCharFromCode(this, instr); ASSERT(instr->hydrogen()->value()->representation().IsInteger32()); Register char_code = ToRegister(instr->char_code()); Register result = ToRegister(instr->result()); ASSERT(!char_code.is(result)); __ cmpl(char_code, Immediate(String::kMaxOneByteCharCode)); __ j(above, deferred->entry()); __ LoadRoot(result, Heap::kSingleCharacterStringCacheRootIndex); __ movq(result, FieldOperand(result, char_code, times_pointer_size, FixedArray::kHeaderSize)); __ CompareRoot(result, Heap::kUndefinedValueRootIndex); __ j(equal, deferred->entry()); __ bind(deferred->exit()); } void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) { Register char_code = ToRegister(instr->char_code()); Register result = ToRegister(instr->result()); // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. __ Set(result, 0); PushSafepointRegistersScope scope(this); __ Integer32ToSmi(char_code, char_code); __ push(char_code); CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr); __ StoreToSafepointRegisterSlot(result, rax); } void LCodeGen::DoStringLength(LStringLength* instr) { Register string = ToRegister(instr->string()); Register result = ToRegister(instr->result()); __ movq(result, FieldOperand(string, String::kLengthOffset)); } void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) { LOperand* input = instr->value(); ASSERT(input->IsRegister() || input->IsStackSlot()); LOperand* output = instr->result(); ASSERT(output->IsDoubleRegister()); if (input->IsRegister()) { __ cvtlsi2sd(ToDoubleRegister(output), ToRegister(input)); } else { __ cvtlsi2sd(ToDoubleRegister(output), ToOperand(input)); } } void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) { LOperand* input = instr->value(); LOperand* output = instr->result(); LOperand* temp = instr->temp(); __ LoadUint32(ToDoubleRegister(output), ToRegister(input), ToDoubleRegister(temp)); } void LCodeGen::DoNumberTagI(LNumberTagI* instr) { LOperand* input = instr->value(); ASSERT(input->IsRegister() && input->Equals(instr->result())); Register reg = ToRegister(input); __ Integer32ToSmi(reg, reg); } void LCodeGen::DoNumberTagU(LNumberTagU* instr) { class DeferredNumberTagU: public LDeferredCode { public: DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredNumberTagU(instr_); } virtual LInstruction* instr() { return instr_; } private: LNumberTagU* instr_; }; LOperand* input = instr->value(); ASSERT(input->IsRegister() && input->Equals(instr->result())); Register reg = ToRegister(input); DeferredNumberTagU* deferred = new(zone()) DeferredNumberTagU(this, instr); __ cmpl(reg, Immediate(Smi::kMaxValue)); __ j(above, deferred->entry()); __ Integer32ToSmi(reg, reg); __ bind(deferred->exit()); } void LCodeGen::DoDeferredNumberTagU(LNumberTagU* instr) { Label slow; Register reg = ToRegister(instr->value()); Register tmp = reg.is(rax) ? rcx : rax; // Preserve the value of all registers. PushSafepointRegistersScope scope(this); Label done; // Load value into xmm1 which will be preserved across potential call to // runtime (MacroAssembler::EnterExitFrameEpilogue preserves only allocatable // XMM registers on x64). __ LoadUint32(xmm1, reg, xmm0); if (FLAG_inline_new) { __ AllocateHeapNumber(reg, tmp, &slow); __ jmp(&done, Label::kNear); } // Slow case: Call the runtime system to do the number allocation. __ bind(&slow); // Put a valid pointer value in the stack slot where the result // register is stored, as this register is in the pointer map, but contains an // integer value. __ StoreToSafepointRegisterSlot(reg, Immediate(0)); CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr); if (!reg.is(rax)) __ movq(reg, rax); // Done. Put the value in xmm1 into the value of the allocated heap // number. __ bind(&done); __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), xmm1); __ StoreToSafepointRegisterSlot(reg, reg); } void LCodeGen::DoNumberTagD(LNumberTagD* instr) { class DeferredNumberTagD: public LDeferredCode { public: DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredNumberTagD(instr_); } virtual LInstruction* instr() { return instr_; } private: LNumberTagD* instr_; }; XMMRegister input_reg = ToDoubleRegister(instr->value()); Register reg = ToRegister(instr->result()); Register tmp = ToRegister(instr->temp()); bool convert_hole = false; HValue* change_input = instr->hydrogen()->value(); if (change_input->IsLoadKeyed()) { HLoadKeyed* load = HLoadKeyed::cast(change_input); convert_hole = load->UsesMustHandleHole(); } Label no_special_nan_handling; Label done; if (convert_hole) { XMMRegister input_reg = ToDoubleRegister(instr->value()); __ ucomisd(input_reg, input_reg); __ j(parity_odd, &no_special_nan_handling); __ subq(rsp, Immediate(kDoubleSize)); __ movsd(MemOperand(rsp, 0), input_reg); __ cmpl(MemOperand(rsp, sizeof(kHoleNanLower32)), Immediate(kHoleNanUpper32)); Label canonicalize; __ j(not_equal, &canonicalize); __ addq(rsp, Immediate(kDoubleSize)); __ Move(reg, factory()->the_hole_value()); __ jmp(&done); __ bind(&canonicalize); __ addq(rsp, Immediate(kDoubleSize)); __ Set(kScratchRegister, BitCast<uint64_t>( FixedDoubleArray::canonical_not_the_hole_nan_as_double())); __ movq(input_reg, kScratchRegister); } __ bind(&no_special_nan_handling); DeferredNumberTagD* deferred = new(zone()) DeferredNumberTagD(this, instr); if (FLAG_inline_new) { __ AllocateHeapNumber(reg, tmp, deferred->entry()); } else { __ jmp(deferred->entry()); } __ bind(deferred->exit()); __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg); __ bind(&done); } void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) { // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. Register reg = ToRegister(instr->result()); __ Move(reg, Smi::FromInt(0)); { PushSafepointRegistersScope scope(this); CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr); // Ensure that value in rax survives popping registers. __ movq(kScratchRegister, rax); } __ movq(reg, kScratchRegister); } void LCodeGen::DoSmiTag(LSmiTag* instr) { ASSERT(instr->value()->Equals(instr->result())); Register input = ToRegister(instr->value()); ASSERT(!instr->hydrogen_value()->CheckFlag(HValue::kCanOverflow)); __ Integer32ToSmi(input, input); } void LCodeGen::DoSmiUntag(LSmiUntag* instr) { ASSERT(instr->value()->Equals(instr->result())); Register input = ToRegister(instr->value()); if (instr->needs_check()) { Condition is_smi = __ CheckSmi(input); DeoptimizeIf(NegateCondition(is_smi), instr->environment()); } else { __ AssertSmi(input); } __ SmiToInteger32(input, input); } void LCodeGen::EmitNumberUntagD(Register input_reg, XMMRegister result_reg, bool deoptimize_on_undefined, bool deoptimize_on_minus_zero, LEnvironment* env, NumberUntagDMode mode) { Label load_smi, done; if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) { // Smi check. __ JumpIfSmi(input_reg, &load_smi, Label::kNear); // Heap number map check. __ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset), Heap::kHeapNumberMapRootIndex); if (deoptimize_on_undefined) { DeoptimizeIf(not_equal, env); } else { Label heap_number; __ j(equal, &heap_number, Label::kNear); __ CompareRoot(input_reg, Heap::kUndefinedValueRootIndex); DeoptimizeIf(not_equal, env); // Convert undefined to NaN. Compute NaN as 0/0. __ xorps(result_reg, result_reg); __ divsd(result_reg, result_reg); __ jmp(&done, Label::kNear); __ bind(&heap_number); } // Heap number to XMM conversion. __ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset)); if (deoptimize_on_minus_zero) { XMMRegister xmm_scratch = xmm0; __ xorps(xmm_scratch, xmm_scratch); __ ucomisd(xmm_scratch, result_reg); __ j(not_equal, &done, Label::kNear); __ movmskpd(kScratchRegister, result_reg); __ testq(kScratchRegister, Immediate(1)); DeoptimizeIf(not_zero, env); } __ jmp(&done, Label::kNear); } else if (mode == NUMBER_CANDIDATE_IS_SMI_OR_HOLE) { __ testq(input_reg, Immediate(kSmiTagMask)); DeoptimizeIf(not_equal, env); } else if (mode == NUMBER_CANDIDATE_IS_SMI_CONVERT_HOLE) { __ testq(input_reg, Immediate(kSmiTagMask)); __ j(zero, &load_smi); __ Set(kScratchRegister, BitCast<uint64_t>( FixedDoubleArray::hole_nan_as_double())); __ movq(result_reg, kScratchRegister); __ jmp(&done, Label::kNear); } else { ASSERT(mode == NUMBER_CANDIDATE_IS_SMI); } // Smi to XMM conversion __ bind(&load_smi); __ SmiToInteger32(kScratchRegister, input_reg); __ cvtlsi2sd(result_reg, kScratchRegister); __ bind(&done); } void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr) { Label done, heap_number; Register input_reg = ToRegister(instr->value()); // Heap number map check. __ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset), Heap::kHeapNumberMapRootIndex); if (instr->truncating()) { __ j(equal, &heap_number, Label::kNear); // Check for undefined. Undefined is converted to zero for truncating // conversions. __ CompareRoot(input_reg, Heap::kUndefinedValueRootIndex); DeoptimizeIf(not_equal, instr->environment()); __ Set(input_reg, 0); __ jmp(&done, Label::kNear); __ bind(&heap_number); __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset)); __ cvttsd2siq(input_reg, xmm0); __ Set(kScratchRegister, V8_UINT64_C(0x8000000000000000)); __ cmpq(input_reg, kScratchRegister); DeoptimizeIf(equal, instr->environment()); } else { // Deoptimize if we don't have a heap number. DeoptimizeIf(not_equal, instr->environment()); XMMRegister xmm_temp = ToDoubleRegister(instr->temp()); __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset)); __ cvttsd2si(input_reg, xmm0); __ cvtlsi2sd(xmm_temp, input_reg); __ ucomisd(xmm0, xmm_temp); DeoptimizeIf(not_equal, instr->environment()); DeoptimizeIf(parity_even, instr->environment()); // NaN. if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ testl(input_reg, input_reg); __ j(not_zero, &done); __ movmskpd(input_reg, xmm0); __ andl(input_reg, Immediate(1)); DeoptimizeIf(not_zero, instr->environment()); } } __ bind(&done); } void LCodeGen::DoTaggedToI(LTaggedToI* instr) { class DeferredTaggedToI: public LDeferredCode { public: DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredTaggedToI(instr_); } virtual LInstruction* instr() { return instr_; } private: LTaggedToI* instr_; }; LOperand* input = instr->value(); ASSERT(input->IsRegister()); ASSERT(input->Equals(instr->result())); Register input_reg = ToRegister(input); DeferredTaggedToI* deferred = new(zone()) DeferredTaggedToI(this, instr); __ JumpIfNotSmi(input_reg, deferred->entry()); __ SmiToInteger32(input_reg, input_reg); __ bind(deferred->exit()); } void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) { LOperand* input = instr->value(); ASSERT(input->IsRegister()); LOperand* result = instr->result(); ASSERT(result->IsDoubleRegister()); Register input_reg = ToRegister(input); XMMRegister result_reg = ToDoubleRegister(result); NumberUntagDMode mode = NUMBER_CANDIDATE_IS_ANY_TAGGED; HValue* value = instr->hydrogen()->value(); if (value->type().IsSmi()) { if (value->IsLoadKeyed()) { HLoadKeyed* load = HLoadKeyed::cast(value); if (load->UsesMustHandleHole()) { if (load->hole_mode() == ALLOW_RETURN_HOLE) { mode = NUMBER_CANDIDATE_IS_SMI_CONVERT_HOLE; } else { mode = NUMBER_CANDIDATE_IS_SMI_OR_HOLE; } } else { mode = NUMBER_CANDIDATE_IS_SMI; } } } EmitNumberUntagD(input_reg, result_reg, instr->hydrogen()->deoptimize_on_undefined(), instr->hydrogen()->deoptimize_on_minus_zero(), instr->environment(), mode); } void LCodeGen::DoDoubleToI(LDoubleToI* instr) { LOperand* input = instr->value(); ASSERT(input->IsDoubleRegister()); LOperand* result = instr->result(); ASSERT(result->IsRegister()); XMMRegister input_reg = ToDoubleRegister(input); Register result_reg = ToRegister(result); if (instr->truncating()) { // Performs a truncating conversion of a floating point number as used by // the JS bitwise operations. __ cvttsd2siq(result_reg, input_reg); __ movq(kScratchRegister, V8_INT64_C(0x8000000000000000), RelocInfo::NONE64); __ cmpq(result_reg, kScratchRegister); DeoptimizeIf(equal, instr->environment()); } else { __ cvttsd2si(result_reg, input_reg); __ cvtlsi2sd(xmm0, result_reg); __ ucomisd(xmm0, input_reg); DeoptimizeIf(not_equal, instr->environment()); DeoptimizeIf(parity_even, instr->environment()); // NaN. if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { Label done; // The integer converted back is equal to the original. We // only have to test if we got -0 as an input. __ testl(result_reg, result_reg); __ j(not_zero, &done, Label::kNear); __ movmskpd(result_reg, input_reg); // Bit 0 contains the sign of the double in input_reg. // If input was positive, we are ok and return 0, otherwise // deoptimize. __ andl(result_reg, Immediate(1)); DeoptimizeIf(not_zero, instr->environment()); __ bind(&done); } } } void LCodeGen::DoCheckSmi(LCheckSmi* instr) { LOperand* input = instr->value(); Condition cc = masm()->CheckSmi(ToRegister(input)); DeoptimizeIf(NegateCondition(cc), instr->environment()); } void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) { LOperand* input = instr->value(); Condition cc = masm()->CheckSmi(ToRegister(input)); DeoptimizeIf(cc, instr->environment()); } void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) { Register input = ToRegister(instr->value()); __ movq(kScratchRegister, FieldOperand(input, HeapObject::kMapOffset)); if (instr->hydrogen()->is_interval_check()) { InstanceType first; InstanceType last; instr->hydrogen()->GetCheckInterval(&first, &last); __ cmpb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset), Immediate(static_cast<int8_t>(first))); // If there is only one type in the interval check for equality. if (first == last) { DeoptimizeIf(not_equal, instr->environment()); } else { DeoptimizeIf(below, instr->environment()); // Omit check for the last type. if (last != LAST_TYPE) { __ cmpb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset), Immediate(static_cast<int8_t>(last))); DeoptimizeIf(above, instr->environment()); } } } else { uint8_t mask; uint8_t tag; instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag); if (IsPowerOf2(mask)) { ASSERT(tag == 0 || IsPowerOf2(tag)); __ testb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset), Immediate(mask)); DeoptimizeIf(tag == 0 ? not_zero : zero, instr->environment()); } else { __ movzxbl(kScratchRegister, FieldOperand(kScratchRegister, Map::kInstanceTypeOffset)); __ andb(kScratchRegister, Immediate(mask)); __ cmpb(kScratchRegister, Immediate(tag)); DeoptimizeIf(not_equal, instr->environment()); } } } void LCodeGen::DoCheckFunction(LCheckFunction* instr) { Register reg = ToRegister(instr->value()); Handle<JSFunction> target = instr->hydrogen()->target(); if (isolate()->heap()->InNewSpace(*target)) { Handle<JSGlobalPropertyCell> cell = isolate()->factory()->NewJSGlobalPropertyCell(target); __ movq(kScratchRegister, cell, RelocInfo::GLOBAL_PROPERTY_CELL); __ cmpq(reg, Operand(kScratchRegister, 0)); } else { __ Cmp(reg, target); } DeoptimizeIf(not_equal, instr->environment()); } void LCodeGen::DoCheckMapCommon(Register reg, Handle<Map> map, CompareMapMode mode, LInstruction* instr) { Label success; __ CompareMap(reg, map, &success, mode); DeoptimizeIf(not_equal, instr->environment()); __ bind(&success); } void LCodeGen::DoCheckMaps(LCheckMaps* instr) { LOperand* input = instr->value(); ASSERT(input->IsRegister()); Register reg = ToRegister(input); Label success; SmallMapList* map_set = instr->hydrogen()->map_set(); for (int i = 0; i < map_set->length() - 1; i++) { Handle<Map> map = map_set->at(i); __ CompareMap(reg, map, &success, REQUIRE_EXACT_MAP); __ j(equal, &success); } Handle<Map> map = map_set->last(); DoCheckMapCommon(reg, map, REQUIRE_EXACT_MAP, instr); __ bind(&success); } void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) { XMMRegister value_reg = ToDoubleRegister(instr->unclamped()); Register result_reg = ToRegister(instr->result()); __ ClampDoubleToUint8(value_reg, xmm0, result_reg); } void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) { ASSERT(instr->unclamped()->Equals(instr->result())); Register value_reg = ToRegister(instr->result()); __ ClampUint8(value_reg); } void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) { ASSERT(instr->unclamped()->Equals(instr->result())); Register input_reg = ToRegister(instr->unclamped()); XMMRegister temp_xmm_reg = ToDoubleRegister(instr->temp_xmm()); Label is_smi, done, heap_number; __ JumpIfSmi(input_reg, &is_smi); // Check for heap number __ Cmp(FieldOperand(input_reg, HeapObject::kMapOffset), factory()->heap_number_map()); __ j(equal, &heap_number, Label::kNear); // Check for undefined. Undefined is converted to zero for clamping // conversions. __ Cmp(input_reg, factory()->undefined_value()); DeoptimizeIf(not_equal, instr->environment()); __ movq(input_reg, Immediate(0)); __ jmp(&done, Label::kNear); // Heap number __ bind(&heap_number); __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset)); __ ClampDoubleToUint8(xmm0, temp_xmm_reg, input_reg); __ jmp(&done, Label::kNear); // smi __ bind(&is_smi); __ SmiToInteger32(input_reg, input_reg); __ ClampUint8(input_reg); __ bind(&done); } void LCodeGen::DoCheckPrototypeMaps(LCheckPrototypeMaps* instr) { ASSERT(instr->temp()->Equals(instr->result())); Register reg = ToRegister(instr->temp()); ZoneList<Handle<JSObject> >* prototypes = instr->prototypes(); ZoneList<Handle<Map> >* maps = instr->maps(); ASSERT(prototypes->length() == maps->length()); for (int i = 0; i < prototypes->length(); i++) { __ LoadHeapObject(reg, prototypes->at(i)); DoCheckMapCommon(reg, maps->at(i), ALLOW_ELEMENT_TRANSITION_MAPS, instr); } } void LCodeGen::DoAllocateObject(LAllocateObject* instr) { class DeferredAllocateObject: public LDeferredCode { public: DeferredAllocateObject(LCodeGen* codegen, LAllocateObject* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredAllocateObject(instr_); } virtual LInstruction* instr() { return instr_; } private: LAllocateObject* instr_; }; DeferredAllocateObject* deferred = new(zone()) DeferredAllocateObject(this, instr); Register result = ToRegister(instr->result()); Register scratch = ToRegister(instr->temp()); Handle<JSFunction> constructor = instr->hydrogen()->constructor(); Handle<Map> initial_map(constructor->initial_map()); int instance_size = initial_map->instance_size(); ASSERT(initial_map->pre_allocated_property_fields() + initial_map->unused_property_fields() - initial_map->inobject_properties() == 0); // Allocate memory for the object. The initial map might change when // the constructor's prototype changes, but instance size and property // counts remain unchanged (if slack tracking finished). ASSERT(!constructor->shared()->IsInobjectSlackTrackingInProgress()); __ AllocateInNewSpace(instance_size, result, no_reg, scratch, deferred->entry(), TAG_OBJECT); __ bind(deferred->exit()); if (FLAG_debug_code) { Label is_in_new_space; __ JumpIfInNewSpace(result, scratch, &is_in_new_space); __ Abort("Allocated object is not in new-space"); __ bind(&is_in_new_space); } // Load the initial map. Register map = scratch; __ LoadHeapObject(scratch, constructor); __ movq(map, FieldOperand(scratch, JSFunction::kPrototypeOrInitialMapOffset)); if (FLAG_debug_code) { __ AssertNotSmi(map); __ cmpb(FieldOperand(map, Map::kInstanceSizeOffset), Immediate(instance_size >> kPointerSizeLog2)); __ Assert(equal, "Unexpected instance size"); __ cmpb(FieldOperand(map, Map::kPreAllocatedPropertyFieldsOffset), Immediate(initial_map->pre_allocated_property_fields())); __ Assert(equal, "Unexpected pre-allocated property fields count"); __ cmpb(FieldOperand(map, Map::kUnusedPropertyFieldsOffset), Immediate(initial_map->unused_property_fields())); __ Assert(equal, "Unexpected unused property fields count"); __ cmpb(FieldOperand(map, Map::kInObjectPropertiesOffset), Immediate(initial_map->inobject_properties())); __ Assert(equal, "Unexpected in-object property fields count"); } // Initialize map and fields of the newly allocated object. ASSERT(initial_map->instance_type() == JS_OBJECT_TYPE); __ movq(FieldOperand(result, JSObject::kMapOffset), map); __ LoadRoot(scratch, Heap::kEmptyFixedArrayRootIndex); __ movq(FieldOperand(result, JSObject::kElementsOffset), scratch); __ movq(FieldOperand(result, JSObject::kPropertiesOffset), scratch); if (initial_map->inobject_properties() != 0) { __ LoadRoot(scratch, Heap::kUndefinedValueRootIndex); for (int i = 0; i < initial_map->inobject_properties(); i++) { int property_offset = JSObject::kHeaderSize + i * kPointerSize; __ movq(FieldOperand(result, property_offset), scratch); } } } void LCodeGen::DoDeferredAllocateObject(LAllocateObject* instr) { Register result = ToRegister(instr->result()); Handle<JSFunction> constructor = instr->hydrogen()->constructor(); Handle<Map> initial_map(constructor->initial_map()); int instance_size = initial_map->instance_size(); // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. __ Set(result, 0); PushSafepointRegistersScope scope(this); __ Push(Smi::FromInt(instance_size)); CallRuntimeFromDeferred(Runtime::kAllocateInNewSpace, 1, instr); __ StoreToSafepointRegisterSlot(result, rax); } void LCodeGen::DoAllocate(LAllocate* instr) { class DeferredAllocate: public LDeferredCode { public: DeferredAllocate(LCodeGen* codegen, LAllocate* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredAllocate(instr_); } virtual LInstruction* instr() { return instr_; } private: LAllocate* instr_; }; DeferredAllocate* deferred = new(zone()) DeferredAllocate(this, instr); Register size = ToRegister(instr->size()); Register result = ToRegister(instr->result()); Register temp = ToRegister(instr->temp()); HAllocate* original_instr = instr->hydrogen(); if (original_instr->size()->IsConstant()) { UNREACHABLE(); } else { // Allocate memory for the object. AllocationFlags flags = TAG_OBJECT; if (original_instr->MustAllocateDoubleAligned()) { flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT); } __ AllocateInNewSpace(size, result, temp, no_reg, deferred->entry(), flags); } __ bind(deferred->exit()); } void LCodeGen::DoDeferredAllocate(LAllocate* instr) { Register size = ToRegister(instr->size()); Register result = ToRegister(instr->result()); // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. __ Set(result, 0); PushSafepointRegistersScope scope(this); __ Integer32ToSmi(size, size); __ push(size); CallRuntimeFromDeferred(Runtime::kAllocateInNewSpace, 1, instr); __ StoreToSafepointRegisterSlot(result, rax); } void LCodeGen::DoArrayLiteral(LArrayLiteral* instr) { Handle<FixedArray> literals(instr->environment()->closure()->literals()); ElementsKind boilerplate_elements_kind = instr->hydrogen()->boilerplate_elements_kind(); AllocationSiteMode allocation_site_mode = instr->hydrogen()->allocation_site_mode(); // Deopt if the array literal boilerplate ElementsKind is of a type different // than the expected one. The check isn't necessary if the boilerplate has // already been converted to TERMINAL_FAST_ELEMENTS_KIND. if (CanTransitionToMoreGeneralFastElementsKind( boilerplate_elements_kind, true)) { __ LoadHeapObject(rax, instr->hydrogen()->boilerplate_object()); __ movq(rbx, FieldOperand(rax, HeapObject::kMapOffset)); // Load the map's "bit field 2". __ movb(rbx, FieldOperand(rbx, Map::kBitField2Offset)); // Retrieve elements_kind from bit field 2. __ and_(rbx, Immediate(Map::kElementsKindMask)); __ cmpb(rbx, Immediate(boilerplate_elements_kind << Map::kElementsKindShift)); DeoptimizeIf(not_equal, instr->environment()); } // Set up the parameters to the stub/runtime call. __ PushHeapObject(literals); __ Push(Smi::FromInt(instr->hydrogen()->literal_index())); // Boilerplate already exists, constant elements are never accessed. // Pass an empty fixed array. __ Push(isolate()->factory()->empty_fixed_array()); // Pick the right runtime function or stub to call. int length = instr->hydrogen()->length(); if (instr->hydrogen()->IsCopyOnWrite()) { ASSERT(instr->hydrogen()->depth() == 1); FastCloneShallowArrayStub::Mode mode = FastCloneShallowArrayStub::COPY_ON_WRITE_ELEMENTS; FastCloneShallowArrayStub stub(mode, DONT_TRACK_ALLOCATION_SITE, length); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } else if (instr->hydrogen()->depth() > 1) { CallRuntime(Runtime::kCreateArrayLiteral, 3, instr); } else if (length > FastCloneShallowArrayStub::kMaximumClonedLength) { CallRuntime(Runtime::kCreateArrayLiteralShallow, 3, instr); } else { FastCloneShallowArrayStub::Mode mode = boilerplate_elements_kind == FAST_DOUBLE_ELEMENTS ? FastCloneShallowArrayStub::CLONE_DOUBLE_ELEMENTS : FastCloneShallowArrayStub::CLONE_ELEMENTS; FastCloneShallowArrayStub stub(mode, allocation_site_mode, length); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } } void LCodeGen::EmitDeepCopy(Handle<JSObject> object, Register result, Register source, int* offset, AllocationSiteMode mode) { ASSERT(!source.is(rcx)); ASSERT(!result.is(rcx)); bool create_allocation_site_info = mode == TRACK_ALLOCATION_SITE && object->map()->CanTrackAllocationSite(); // Only elements backing stores for non-COW arrays need to be copied. Handle<FixedArrayBase> elements(object->elements()); bool has_elements = elements->length() > 0 && elements->map() != isolate()->heap()->fixed_cow_array_map(); // Increase the offset so that subsequent objects end up right after // this object and its backing store. int object_offset = *offset; int object_size = object->map()->instance_size(); int elements_size = has_elements ? elements->Size() : 0; int elements_offset = *offset + object_size; if (create_allocation_site_info) { elements_offset += AllocationSiteInfo::kSize; *offset += AllocationSiteInfo::kSize; } *offset += object_size + elements_size; // Copy object header. ASSERT(object->properties()->length() == 0); int inobject_properties = object->map()->inobject_properties(); int header_size = object_size - inobject_properties * kPointerSize; for (int i = 0; i < header_size; i += kPointerSize) { if (has_elements && i == JSObject::kElementsOffset) { __ lea(rcx, Operand(result, elements_offset)); } else { __ movq(rcx, FieldOperand(source, i)); } __ movq(FieldOperand(result, object_offset + i), rcx); } // Copy in-object properties. for (int i = 0; i < inobject_properties; i++) { int total_offset = object_offset + object->GetInObjectPropertyOffset(i); Handle<Object> value = Handle<Object>(object->InObjectPropertyAt(i)); if (value->IsJSObject()) { Handle<JSObject> value_object = Handle<JSObject>::cast(value); __ lea(rcx, Operand(result, *offset)); __ movq(FieldOperand(result, total_offset), rcx); __ LoadHeapObject(source, value_object); EmitDeepCopy(value_object, result, source, offset, DONT_TRACK_ALLOCATION_SITE); } else if (value->IsHeapObject()) { __ LoadHeapObject(rcx, Handle<HeapObject>::cast(value)); __ movq(FieldOperand(result, total_offset), rcx); } else { __ movq(rcx, value, RelocInfo::NONE64); __ movq(FieldOperand(result, total_offset), rcx); } } // Build Allocation Site Info if desired if (create_allocation_site_info) { __ LoadRoot(kScratchRegister, Heap::kAllocationSiteInfoMapRootIndex); __ movq(FieldOperand(result, object_size), kScratchRegister); __ movq(FieldOperand(result, object_size + kPointerSize), source); } if (has_elements) { // Copy elements backing store header. __ LoadHeapObject(source, elements); for (int i = 0; i < FixedArray::kHeaderSize; i += kPointerSize) { __ movq(rcx, FieldOperand(source, i)); __ movq(FieldOperand(result, elements_offset + i), rcx); } // Copy elements backing store content. int elements_length = elements->length(); if (elements->IsFixedDoubleArray()) { Handle<FixedDoubleArray> double_array = Handle<FixedDoubleArray>::cast(elements); for (int i = 0; i < elements_length; i++) { int64_t value = double_array->get_representation(i); int total_offset = elements_offset + FixedDoubleArray::OffsetOfElementAt(i); __ movq(rcx, value, RelocInfo::NONE64); __ movq(FieldOperand(result, total_offset), rcx); } } else if (elements->IsFixedArray()) { Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements); for (int i = 0; i < elements_length; i++) { int total_offset = elements_offset + FixedArray::OffsetOfElementAt(i); Handle<Object> value(fast_elements->get(i)); if (value->IsJSObject()) { Handle<JSObject> value_object = Handle<JSObject>::cast(value); __ lea(rcx, Operand(result, *offset)); __ movq(FieldOperand(result, total_offset), rcx); __ LoadHeapObject(source, value_object); EmitDeepCopy(value_object, result, source, offset, DONT_TRACK_ALLOCATION_SITE); } else if (value->IsHeapObject()) { __ LoadHeapObject(rcx, Handle<HeapObject>::cast(value)); __ movq(FieldOperand(result, total_offset), rcx); } else { __ movq(rcx, value, RelocInfo::NONE64); __ movq(FieldOperand(result, total_offset), rcx); } } } else { UNREACHABLE(); } } } void LCodeGen::DoFastLiteral(LFastLiteral* instr) { int size = instr->hydrogen()->total_size(); ElementsKind boilerplate_elements_kind = instr->hydrogen()->boilerplate()->GetElementsKind(); // Deopt if the array literal boilerplate ElementsKind is of a type different // than the expected one. The check isn't necessary if the boilerplate has // already been converted to TERMINAL_FAST_ELEMENTS_KIND. if (CanTransitionToMoreGeneralFastElementsKind( boilerplate_elements_kind, true)) { __ LoadHeapObject(rbx, instr->hydrogen()->boilerplate()); __ movq(rcx, FieldOperand(rbx, HeapObject::kMapOffset)); // Load the map's "bit field 2". __ movb(rcx, FieldOperand(rcx, Map::kBitField2Offset)); // Retrieve elements_kind from bit field 2. __ and_(rcx, Immediate(Map::kElementsKindMask)); __ cmpb(rcx, Immediate(boilerplate_elements_kind << Map::kElementsKindShift)); DeoptimizeIf(not_equal, instr->environment()); } // Allocate all objects that are part of the literal in one big // allocation. This avoids multiple limit checks. Label allocated, runtime_allocate; __ AllocateInNewSpace(size, rax, rcx, rdx, &runtime_allocate, TAG_OBJECT); __ jmp(&allocated); __ bind(&runtime_allocate); __ Push(Smi::FromInt(size)); CallRuntime(Runtime::kAllocateInNewSpace, 1, instr); __ bind(&allocated); int offset = 0; __ LoadHeapObject(rbx, instr->hydrogen()->boilerplate()); EmitDeepCopy(instr->hydrogen()->boilerplate(), rax, rbx, &offset, instr->hydrogen()->allocation_site_mode()); ASSERT_EQ(size, offset); } void LCodeGen::DoObjectLiteral(LObjectLiteral* instr) { Handle<FixedArray> literals(instr->environment()->closure()->literals()); Handle<FixedArray> constant_properties = instr->hydrogen()->constant_properties(); // Set up the parameters to the stub/runtime call. __ PushHeapObject(literals); __ Push(Smi::FromInt(instr->hydrogen()->literal_index())); __ Push(constant_properties); int flags = instr->hydrogen()->fast_elements() ? ObjectLiteral::kFastElements : ObjectLiteral::kNoFlags; flags |= instr->hydrogen()->has_function() ? ObjectLiteral::kHasFunction : ObjectLiteral::kNoFlags; __ Push(Smi::FromInt(flags)); // Pick the right runtime function or stub to call. int properties_count = constant_properties->length() / 2; if (instr->hydrogen()->depth() > 1) { CallRuntime(Runtime::kCreateObjectLiteral, 4, instr); } else if (flags != ObjectLiteral::kFastElements || properties_count > FastCloneShallowObjectStub::kMaximumClonedProperties) { CallRuntime(Runtime::kCreateObjectLiteralShallow, 4, instr); } else { FastCloneShallowObjectStub stub(properties_count); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } } void LCodeGen::DoToFastProperties(LToFastProperties* instr) { ASSERT(ToRegister(instr->value()).is(rax)); __ push(rax); CallRuntime(Runtime::kToFastProperties, 1, instr); } void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) { Label materialized; // Registers will be used as follows: // rcx = literals array. // rbx = regexp literal. // rax = regexp literal clone. int literal_offset = FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index()); __ LoadHeapObject(rcx, instr->hydrogen()->literals()); __ movq(rbx, FieldOperand(rcx, literal_offset)); __ CompareRoot(rbx, Heap::kUndefinedValueRootIndex); __ j(not_equal, &materialized, Label::kNear); // Create regexp literal using runtime function // Result will be in rax. __ push(rcx); __ Push(Smi::FromInt(instr->hydrogen()->literal_index())); __ Push(instr->hydrogen()->pattern()); __ Push(instr->hydrogen()->flags()); CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr); __ movq(rbx, rax); __ bind(&materialized); int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize; Label allocated, runtime_allocate; __ AllocateInNewSpace(size, rax, rcx, rdx, &runtime_allocate, TAG_OBJECT); __ jmp(&allocated); __ bind(&runtime_allocate); __ push(rbx); __ Push(Smi::FromInt(size)); CallRuntime(Runtime::kAllocateInNewSpace, 1, instr); __ pop(rbx); __ bind(&allocated); // Copy the content into the newly allocated memory. // (Unroll copy loop once for better throughput). for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) { __ movq(rdx, FieldOperand(rbx, i)); __ movq(rcx, FieldOperand(rbx, i + kPointerSize)); __ movq(FieldOperand(rax, i), rdx); __ movq(FieldOperand(rax, i + kPointerSize), rcx); } if ((size % (2 * kPointerSize)) != 0) { __ movq(rdx, FieldOperand(rbx, size - kPointerSize)); __ movq(FieldOperand(rax, size - kPointerSize), rdx); } } void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) { // Use the fast case closure allocation code that allocates in new // space for nested functions that don't need literals cloning. Handle<SharedFunctionInfo> shared_info = instr->shared_info(); bool pretenure = instr->hydrogen()->pretenure(); if (!pretenure && shared_info->num_literals() == 0) { FastNewClosureStub stub(shared_info->language_mode()); __ Push(shared_info); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } else { __ push(rsi); __ Push(shared_info); __ PushRoot(pretenure ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex); CallRuntime(Runtime::kNewClosure, 3, instr); } } void LCodeGen::DoTypeof(LTypeof* instr) { LOperand* input = instr->value(); EmitPushTaggedOperand(input); CallRuntime(Runtime::kTypeof, 1, instr); } void LCodeGen::EmitPushTaggedOperand(LOperand* operand) { ASSERT(!operand->IsDoubleRegister()); if (operand->IsConstantOperand()) { Handle<Object> object = ToHandle(LConstantOperand::cast(operand)); if (object->IsSmi()) { __ Push(Handle<Smi>::cast(object)); } else { __ PushHeapObject(Handle<HeapObject>::cast(object)); } } else if (operand->IsRegister()) { __ push(ToRegister(operand)); } else { __ push(ToOperand(operand)); } } void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) { Register input = ToRegister(instr->value()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); Condition final_branch_condition = EmitTypeofIs(true_label, false_label, input, instr->type_literal()); if (final_branch_condition != no_condition) { EmitBranch(true_block, false_block, final_branch_condition); } } Condition LCodeGen::EmitTypeofIs(Label* true_label, Label* false_label, Register input, Handle<String> type_name) { Condition final_branch_condition = no_condition; if (type_name->Equals(heap()->number_symbol())) { __ JumpIfSmi(input, true_label); __ CompareRoot(FieldOperand(input, HeapObject::kMapOffset), Heap::kHeapNumberMapRootIndex); final_branch_condition = equal; } else if (type_name->Equals(heap()->string_symbol())) { __ JumpIfSmi(input, false_label); __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input); __ j(above_equal, false_label); __ testb(FieldOperand(input, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); final_branch_condition = zero; } else if (type_name->Equals(heap()->boolean_symbol())) { __ CompareRoot(input, Heap::kTrueValueRootIndex); __ j(equal, true_label); __ CompareRoot(input, Heap::kFalseValueRootIndex); final_branch_condition = equal; } else if (FLAG_harmony_typeof && type_name->Equals(heap()->null_symbol())) { __ CompareRoot(input, Heap::kNullValueRootIndex); final_branch_condition = equal; } else if (type_name->Equals(heap()->undefined_symbol())) { __ CompareRoot(input, Heap::kUndefinedValueRootIndex); __ j(equal, true_label); __ JumpIfSmi(input, false_label); // Check for undetectable objects => true. __ movq(input, FieldOperand(input, HeapObject::kMapOffset)); __ testb(FieldOperand(input, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); final_branch_condition = not_zero; } else if (type_name->Equals(heap()->function_symbol())) { STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2); __ JumpIfSmi(input, false_label); __ CmpObjectType(input, JS_FUNCTION_TYPE, input); __ j(equal, true_label); __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE); final_branch_condition = equal; } else if (type_name->Equals(heap()->object_symbol())) { __ JumpIfSmi(input, false_label); if (!FLAG_harmony_typeof) { __ CompareRoot(input, Heap::kNullValueRootIndex); __ j(equal, true_label); } __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input); __ j(below, false_label); __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE); __ j(above, false_label); // Check for undetectable objects => false. __ testb(FieldOperand(input, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); final_branch_condition = zero; } else { __ jmp(false_label); } return final_branch_condition; } void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) { Register temp = ToRegister(instr->temp()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); EmitIsConstructCall(temp); EmitBranch(true_block, false_block, equal); } void LCodeGen::EmitIsConstructCall(Register temp) { // Get the frame pointer for the calling frame. __ movq(temp, Operand(rbp, StandardFrameConstants::kCallerFPOffset)); // Skip the arguments adaptor frame if it exists. Label check_frame_marker; __ Cmp(Operand(temp, StandardFrameConstants::kContextOffset), Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)); __ j(not_equal, &check_frame_marker, Label::kNear); __ movq(temp, Operand(rax, StandardFrameConstants::kCallerFPOffset)); // Check the marker in the calling frame. __ bind(&check_frame_marker); __ Cmp(Operand(temp, StandardFrameConstants::kMarkerOffset), Smi::FromInt(StackFrame::CONSTRUCT)); } void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) { if (info()->IsStub()) return; // Ensure that we have enough space after the previous lazy-bailout // instruction for patching the code here. int current_pc = masm()->pc_offset(); if (current_pc < last_lazy_deopt_pc_ + space_needed) { int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc; __ Nop(padding_size); } } void LCodeGen::DoLazyBailout(LLazyBailout* instr) { EnsureSpaceForLazyDeopt(Deoptimizer::patch_size()); last_lazy_deopt_pc_ = masm()->pc_offset(); ASSERT(instr->HasEnvironment()); LEnvironment* env = instr->environment(); RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt); safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index()); } void LCodeGen::DoDeoptimize(LDeoptimize* instr) { DeoptimizeIf(no_condition, instr->environment()); } void LCodeGen::DoDummyUse(LDummyUse* instr) { // Nothing to see here, move on! } void LCodeGen::DoDeleteProperty(LDeleteProperty* instr) { LOperand* obj = instr->object(); LOperand* key = instr->key(); EmitPushTaggedOperand(obj); EmitPushTaggedOperand(key); ASSERT(instr->HasPointerMap()); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); // Create safepoint generator that will also ensure enough space in the // reloc info for patching in deoptimization (since this is invoking a // builtin) SafepointGenerator safepoint_generator( this, pointers, Safepoint::kLazyDeopt); __ Push(Smi::FromInt(strict_mode_flag())); __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION, safepoint_generator); } void LCodeGen::DoIn(LIn* instr) { LOperand* obj = instr->object(); LOperand* key = instr->key(); EmitPushTaggedOperand(key); EmitPushTaggedOperand(obj); ASSERT(instr->HasPointerMap()); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); SafepointGenerator safepoint_generator( this, pointers, Safepoint::kLazyDeopt); __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION, safepoint_generator); } void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) { PushSafepointRegistersScope scope(this); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); __ CallRuntimeSaveDoubles(Runtime::kStackGuard); RecordSafepointWithLazyDeopt(instr, RECORD_SAFEPOINT_WITH_REGISTERS, 0); ASSERT(instr->HasEnvironment()); LEnvironment* env = instr->environment(); safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index()); } void LCodeGen::DoStackCheck(LStackCheck* instr) { class DeferredStackCheck: public LDeferredCode { public: DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredStackCheck(instr_); } virtual LInstruction* instr() { return instr_; } private: LStackCheck* instr_; }; ASSERT(instr->HasEnvironment()); LEnvironment* env = instr->environment(); // There is no LLazyBailout instruction for stack-checks. We have to // prepare for lazy deoptimization explicitly here. if (instr->hydrogen()->is_function_entry()) { // Perform stack overflow check. Label done; __ CompareRoot(rsp, Heap::kStackLimitRootIndex); __ j(above_equal, &done, Label::kNear); StackCheckStub stub; CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); EnsureSpaceForLazyDeopt(Deoptimizer::patch_size()); last_lazy_deopt_pc_ = masm()->pc_offset(); __ bind(&done); RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt); safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index()); } else { ASSERT(instr->hydrogen()->is_backwards_branch()); // Perform stack overflow check if this goto needs it before jumping. DeferredStackCheck* deferred_stack_check = new(zone()) DeferredStackCheck(this, instr); __ CompareRoot(rsp, Heap::kStackLimitRootIndex); __ j(below, deferred_stack_check->entry()); EnsureSpaceForLazyDeopt(Deoptimizer::patch_size()); last_lazy_deopt_pc_ = masm()->pc_offset(); __ bind(instr->done_label()); deferred_stack_check->SetExit(instr->done_label()); RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt); // Don't record a deoptimization index for the safepoint here. // This will be done explicitly when emitting call and the safepoint in // the deferred code. } } void LCodeGen::DoOsrEntry(LOsrEntry* instr) { // This is a pseudo-instruction that ensures that the environment here is // properly registered for deoptimization and records the assembler's PC // offset. LEnvironment* environment = instr->environment(); environment->SetSpilledRegisters(instr->SpilledRegisterArray(), instr->SpilledDoubleRegisterArray()); // If the environment were already registered, we would have no way of // backpatching it with the spill slot operands. ASSERT(!environment->HasBeenRegistered()); RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt); ASSERT(osr_pc_offset_ == -1); osr_pc_offset_ = masm()->pc_offset(); } void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) { __ CompareRoot(rax, Heap::kUndefinedValueRootIndex); DeoptimizeIf(equal, instr->environment()); Register null_value = rdi; __ LoadRoot(null_value, Heap::kNullValueRootIndex); __ cmpq(rax, null_value); DeoptimizeIf(equal, instr->environment()); Condition cc = masm()->CheckSmi(rax); DeoptimizeIf(cc, instr->environment()); STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE); __ CmpObjectType(rax, LAST_JS_PROXY_TYPE, rcx); DeoptimizeIf(below_equal, instr->environment()); Label use_cache, call_runtime; __ CheckEnumCache(null_value, &call_runtime); __ movq(rax, FieldOperand(rax, HeapObject::kMapOffset)); __ jmp(&use_cache, Label::kNear); // Get the set of properties to enumerate. __ bind(&call_runtime); __ push(rax); CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr); __ CompareRoot(FieldOperand(rax, HeapObject::kMapOffset), Heap::kMetaMapRootIndex); DeoptimizeIf(not_equal, instr->environment()); __ bind(&use_cache); } void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) { Register map = ToRegister(instr->map()); Register result = ToRegister(instr->result()); Label load_cache, done; __ EnumLength(result, map); __ Cmp(result, Smi::FromInt(0)); __ j(not_equal, &load_cache); __ LoadRoot(result, Heap::kEmptyFixedArrayRootIndex); __ jmp(&done); __ bind(&load_cache); __ LoadInstanceDescriptors(map, result); __ movq(result, FieldOperand(result, DescriptorArray::kEnumCacheOffset)); __ movq(result, FieldOperand(result, FixedArray::SizeFor(instr->idx()))); __ bind(&done); Condition cc = masm()->CheckSmi(result); DeoptimizeIf(cc, instr->environment()); } void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) { Register object = ToRegister(instr->value()); __ cmpq(ToRegister(instr->map()), FieldOperand(object, HeapObject::kMapOffset)); DeoptimizeIf(not_equal, instr->environment()); } void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) { Register object = ToRegister(instr->object()); Register index = ToRegister(instr->index()); Label out_of_object, done; __ SmiToInteger32(index, index); __ cmpl(index, Immediate(0)); __ j(less, &out_of_object); __ movq(object, FieldOperand(object, index, times_pointer_size, JSObject::kHeaderSize)); __ jmp(&done, Label::kNear); __ bind(&out_of_object); __ movq(object, FieldOperand(object, JSObject::kPropertiesOffset)); __ negl(index); // Index is now equal to out of object property index plus 1. __ movq(object, FieldOperand(object, index, times_pointer_size, FixedArray::kHeaderSize - kPointerSize)); __ bind(&done); } #undef __ } } // namespace v8::internal #endif // V8_TARGET_ARCH_X64
//Data Structure includes #include<vector> #include<stack> #include<set> #include<map> #include<queue> #include<deque> #include<string> //Other Includes #include<iostream> #include<algorithm> #include<cstring> #include<cassert> #include<cstdlib> #include<cstdio> #include<cmath> #include<sstream> //some common functionn #define maX(a,b) ( (a) > (b) ? (a) : (b)) #define miN(a,b) ( (a) < (b) ? (a) : (b)) #define FOR(i,a,b) for(int i=a;i<b;i++) #define FORs(i,a,b) for(int i=a;i>=b;i--) #define fill(a,v) memset(a,v,sizeof a) #define abS(x) ((x)<0?-(x):(x)) #define mP make_pair #define pB push_back #define error(x) cout << #x << " : " << (x) << endl #define all(c) (c).begin(),(c).end() // Input macros #define s(n) scanf("%d",&n) #define sc(n) scanf("%c",&n) #define sl(n) scanf("%lld",&n) #define sf(n) scanf("%lf",&n) #define ss(n) scanf("%s",n) // Output macros #define p(n) printf("%d",n) #define pc(n) printf("%c",n) #define pl(n) printf("%lld",n) #define pf(n) printf("%lf",n) #define ps(n) printf("%s",n) using namespace std; typedef long long LL; typedef pair<int,int> PII; typedef pair<LL,LL> PLL; typedef pair<int,PII> TRI; typedef vector<int> VI; typedef vector<LL> VL; typedef vector<PII> VII; typedef vector<PLL> VLL; typedef vector<TRI> VT; typedef vector<VI> VVI; typedef vector<VL> VVL; typedef vector<VII> VVII; typedef vector<VLL> VVLL; typedef vector<VT> VVT; using namespace std; void chekarre(int * arr,int n) { cout<<"["; for(int i=0;i<n;i++) cout<<arr[i]<<" "; cout<<"]"<<endl; } int n, m ; long long row[314999]={0}, col[314999]={0}; int solve() { long long mc=0, mr=0; FOR(i,0,n+1) { if(mc<row[i]) mc=row[i]; if(mr<col[i]) mr=col[i]; } cout<<mr+mc; return 1; } bool input() { s(n);s(m); string s; int a, b; FOR(i,0,m) { cin>>s; cin>>a>>b; if(s[0]=='R') { row[a]+=b; } else { col[a]+=b; } } return true; } int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); int T=1; //s(T); for(int testnum=1;testnum<=T;testnum++) { if(!input()) break; solve(); //printf("\n"); } // system("pause"); return 0; }
// no-networkit-format #include <cmath> #include <networkit/auxiliary/Log.hpp> #include <networkit/community/GraphClusteringTools.hpp> namespace NetworKit { namespace GraphClusteringTools { float getImbalance(const Partition &zeta) { float avg = std::ceil( (float)zeta.numberOfElements() / (float)zeta.numberOfSubsets()); // TODO number of nodes and not number of elements std::vector<count> clusterSizes = zeta.subsetSizes(); float maxClusterSize = (float) *std::max_element(clusterSizes.begin(), clusterSizes.end()); float imbalance = maxClusterSize / avg; return imbalance; } Graph communicationGraph(const Graph& graph, Partition &zeta) { zeta.compact(); count n = zeta.numberOfSubsets(); Graph commGraph(n); if (graph.isWeighted()) { DEBUG("weighted"); graph.forEdges([&](node u, node v, edgeweight w) { if (zeta[u] != zeta[v]) { commGraph.increaseWeight(zeta[u], zeta[v], w); TRACE("increase weight of " , zeta[u] , " and " , zeta[v] , " by " , w); } }); } else { DEBUG("not weighted"); graph.forEdges([&](node u, node v) { if (zeta[u] != zeta[v]) { commGraph.increaseWeight(zeta[u], zeta[v], 1); TRACE("increase weight of " , zeta[u] , " and " , zeta[v] , " by 1"); } }); } return commGraph; } count weightedDegreeWithCluster(const Graph& graph, const Partition &zeta, node u, index cid) { //const // TRACE("start wdeg with cluster..."); count wdeg = 0; if (graph.isWeighted()) { graph.forEdgesOf(u, [&](node, node v, edgeweight w) { if (zeta[v] == cid) { wdeg += w; } }); } else { graph.forEdgesOf(u, [&](node, node v) { if (zeta[v] == cid) { wdeg += 1; } }); } return wdeg; } bool isProperClustering(const Graph &G, const Partition &zeta) { // test whether each node has been assigned to a cluster bool success = true; G.forNodes([&](node v) { bool contained = zeta.contains(v); if (!contained) { ERROR("Clustering does not contain node " , v); success = false; } }); return success; } bool isOneClustering(const Graph &, const Partition &zeta) { return (zeta.numberOfSubsets() == 1); /* index one = data[0]; // first subset id should be equal to all others // TODO: use iterator forEntries and pair-wise comparison? for (index e = 0; e < this->z; ++e) { // FIXME constructor initializes data with z+1, so <= is necessary. if (data[e] != one) { return false; } } return true;*/ } bool isSingletonClustering(const Graph& G, const Partition& zeta) { return (zeta.numberOfSubsets() == G.numberOfNodes()); } bool equalClusterings(const Partition& zeta, const Partition& eta, Graph& G) { bool eq = true; G.parallelForEdges([&](node u, node v) { if (zeta.inSameSubset(u, v)) { if (!eta.inSameSubset(u, v)) { eq = false; } } else { if (eta.inSameSubset(u, v)) { eq = false; } } }); return eq; } } // namespace GCT } // namespace NetworKit
/* Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "trp_buffer.hpp" bool TFPool::init(size_t mem, size_t reserved_mem, size_t page_sz) { m_pagesize = page_sz; assert(m_pagesize == sizeof(TFPage)); m_tot_send_buffer_pages = mem/page_sz; size_t tot_alloc = m_tot_send_buffer_pages * page_sz; assert(reserved_mem < mem); m_reserved_send_buffer_pages = reserved_mem / page_sz; unsigned char * ptr = (m_alloc_ptr = (unsigned char*)malloc(tot_alloc)); for (size_t i = 0; i + page_sz <= tot_alloc; i += page_sz) { TFPage * p = (TFPage*)(ptr + i); assert(((UintPtr)(&p->m_data[0]) & 3) == 0); p->init(); p->m_next = m_first_free; m_first_free = p; m_free_send_buffer_pages++; } assert(m_free_send_buffer_pages == m_tot_send_buffer_pages); assert(m_free_send_buffer_pages > m_reserved_send_buffer_pages); return true; } TFPool::~TFPool() { if (m_alloc_ptr) free (m_alloc_ptr); } TFMTPool::TFMTPool(const char * name) { NdbMutex_InitWithName(&m_mutex, name); } void TFBuffer::validate() const { if (m_bytes_in_buffer == 0) { assert(m_head == m_tail); if (m_head) { // Full pages should be release assert(m_head->m_start < m_head->max_data_bytes()); assert(m_head->m_bytes == 0); } return; } else { assert(m_head != 0); assert(m_tail != 0); } Uint32 sum = 0; TFPage * p = m_head; while (p) { assert(p->m_bytes <= p->max_data_bytes()); assert(p->m_start <= p->max_data_bytes()); assert(p->m_start + p->m_bytes <= p->max_data_bytes()); assert(p->m_bytes <= (int)m_bytes_in_buffer); assert(p->m_next != p); if (p == m_tail) { assert(p->m_next == 0); } else { assert(p->m_next != 0); } sum += p->m_bytes; p = p->m_next; } assert(sum == m_bytes_in_buffer); }
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS 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. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "CFCFaceToCellStencil.hpp" #include "syncTools.hpp" #include "emptyPolyPatch.hpp" #include "dummyTransform.hpp" // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // // Calculates per face the neighbour data (= faces of cell). Leaves out the // face itself since this is already in stencil. void CML::CFCFaceToCellStencil::calcFaceBoundaryData ( labelListList& neiGlobal ) const { const polyBoundaryMesh& patches = mesh().boundaryMesh(); const label nBnd = mesh().nFaces()-mesh().nInternalFaces(); const labelList& own = mesh().faceOwner(); neiGlobal.setSize(nBnd); forAll(patches, patchI) { const polyPatch& pp = patches[patchI]; label faceI = pp.start(); if (pp.coupled()) { // For coupled faces get the faces of the cell on the other side forAll(pp, i) { const labelList& cFaces = mesh().cells()[own[faceI]]; labelList& globFaces = neiGlobal[faceI-mesh().nInternalFaces()]; globFaces.setSize(cFaces.size()-1); label globI = 0; forAll(cFaces, j) { if (cFaces[j] != faceI) { globFaces[globI++] = globalNumbering().toGlobal ( cFaces[j] ); } } faceI++; } } else if (isA<emptyPolyPatch>(pp)) { // Do nothing. } else { // Do nothing since face itself already in stencil } } //syncTools::swapBoundaryFaceList(mesh(), neiGlobal); syncTools::syncBoundaryFaceList ( mesh(), neiGlobal, eqOp<labelList>(), dummyTransform() ); } // Calculates per cell the neighbour data (= cell or boundary in global // numbering). First element is always cell itself! void CML::CFCFaceToCellStencil::calcCellStencil(labelListList& globalCellFaces) const { const label nBnd = mesh().nFaces()-mesh().nInternalFaces(); const labelList& own = mesh().faceOwner(); const labelList& nei = mesh().faceNeighbour(); // Calculate faces of coupled neighbour (in global numbering) // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ labelListList neiGlobal(nBnd); calcFaceBoundaryData(neiGlobal); // Non-empty boundary faces boolList validBFace(mesh().nFaces()-mesh().nInternalFaces(), true); const polyBoundaryMesh& patches = mesh().boundaryMesh(); forAll(patches, patchI) { const polyPatch& pp = patches[patchI]; if (isA<emptyPolyPatch>(pp)) { label bFaceI = pp.start()-mesh().nInternalFaces(); forAll(pp, i) { validBFace[bFaceI++] = false; } } } // Determine faces of cellCells in global numbering // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DynamicList<label> allGlobalFaces(100); globalCellFaces.setSize(mesh().nCells()); forAll(globalCellFaces, cellI) { const cell& cFaces = mesh().cells()[cellI]; allGlobalFaces.clear(); // My faces first forAll(cFaces, i) { label faceI = cFaces[i]; if ( mesh().isInternalFace(faceI) || validBFace[faceI-mesh().nInternalFaces()] ) { allGlobalFaces.append(globalNumbering().toGlobal(faceI)); } } // faces of neighbouring cells second forAll(cFaces, i) { label faceI = cFaces[i]; if (mesh().isInternalFace(faceI)) { label nbrCellI = own[faceI]; if (nbrCellI == cellI) { nbrCellI = nei[faceI]; } const cell& nbrFaces = mesh().cells()[nbrCellI]; forAll(nbrFaces, j) { label nbrFaceI = nbrFaces[j]; if ( mesh().isInternalFace(nbrFaceI) || validBFace[nbrFaceI-mesh().nInternalFaces()] ) { label nbrGlobalI = globalNumbering().toGlobal(nbrFaceI); // Check if already there. Note:should use hashset? if (findIndex(allGlobalFaces, nbrGlobalI) == -1) { allGlobalFaces.append(nbrGlobalI); } } } } else { const labelList& nbrGlobalFaces = neiGlobal[faceI-mesh().nInternalFaces()]; forAll(nbrGlobalFaces, j) { label nbrGlobalI = nbrGlobalFaces[j]; // Check if already there. Note:should use hashset? if (findIndex(allGlobalFaces, nbrGlobalI) == -1) { allGlobalFaces.append(nbrGlobalI); } } } } globalCellFaces[cellI] = allGlobalFaces; //Pout<< "** cell:" << cellI // << " at:" << mesh().cellCentres()[cellI] // << endl; //const labelList& globalFaces = globalCellFaces[cellI]; //forAll(globalFaces, i) //{ // label faceI = globalNumbering().toLocal(globalFaces[i]); // Pout<< " face:" << faceI // << " at:" << mesh().faceCentres()[faceI] // << endl; //} } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // CML::CFCFaceToCellStencil::CFCFaceToCellStencil(const polyMesh& mesh) : faceToCellStencil(mesh) { // Calculate per cell the (face) connected cells (in global numbering) calcCellStencil(*this); } // ************************************************************************* //
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/toolbar/encoding_menu_controller.h" #include <string> #include "base/basictypes.h" #include "base/message_loop.h" #include "base/prefs/pref_service.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/testing_profile.h" #include "content/public/test/test_browser_thread.h" #include "testing/gtest/include/gtest/gtest.h" using content::BrowserThread; class EncodingMenuControllerTest : public testing::Test { public: EncodingMenuControllerTest() : ui_thread_(BrowserThread::UI, &message_loop_) {} private: MessageLoop message_loop_; content::TestBrowserThread ui_thread_; }; TEST_F(EncodingMenuControllerTest, EncodingIDsBelongTest) { EncodingMenuController controller; // Check some bogus ids to make sure they're never valid. ASSERT_FALSE(controller.DoesCommandBelongToEncodingMenu(0)); ASSERT_FALSE(controller.DoesCommandBelongToEncodingMenu(-1)); int num_valid_encoding_ids = controller.NumValidGUIEncodingIDs(); const int* valid_encodings = controller.ValidGUIEncodingIDs(); ASSERT_TRUE(controller.DoesCommandBelongToEncodingMenu( IDC_ENCODING_AUTO_DETECT)); // Check that all valid encodings are accepted. for (int i = 0; i < num_valid_encoding_ids; ++i) { ASSERT_TRUE(controller.DoesCommandBelongToEncodingMenu(valid_encodings[i])); } // This test asserts that we haven't added a new valid ID without including it // in the kValidEncodingIds test list above. // The premise is that new encodings will be added directly after the current // ones so we'll catch such cases. int one_past_largest_id = valid_encodings[num_valid_encoding_ids - 1] + 1; ASSERT_FALSE(controller.DoesCommandBelongToEncodingMenu(one_past_largest_id)); } TEST_F(EncodingMenuControllerTest, ListEncodingMenuItems) { typedef EncodingMenuController::EncodingMenuItemList EncodingMenuItemList; EncodingMenuController controller; EncodingMenuItemList english_items; TestingProfile profile_en; controller.GetEncodingMenuItems(&profile_en, &english_items); // Make sure there are items in the lists. ASSERT_FALSE(english_items.empty()); // Make sure that autodetect is the first item on both menus ASSERT_EQ(english_items[0].first, IDC_ENCODING_AUTO_DETECT); } TEST_F(EncodingMenuControllerTest, IsItemChecked) { TestingProfile profile_en; std::string encoding("UTF-8"); // Check that enabling and disabling autodetect works. bool autodetect_enabed[] = {true, false}; PrefService* prefs = profile_en.GetPrefs(); EncodingMenuController controller; for (size_t i = 0; i < arraysize(autodetect_enabed); ++i) { bool enabled = autodetect_enabed[i]; prefs->SetBoolean(prefs::kWebKitUsesUniversalDetector, enabled); ASSERT_TRUE(controller.IsItemChecked(&profile_en, encoding, IDC_ENCODING_AUTO_DETECT) == enabled); } // Check all valid encodings, make sure only one is enabled when autodetection // is turned off. prefs->SetBoolean(prefs::kWebKitUsesUniversalDetector, false); bool encoding_is_enabled = false; size_t num_valid_encoding_ids = controller.NumValidGUIEncodingIDs(); const int* valid_encodings = controller.ValidGUIEncodingIDs(); for (size_t i = 0; i < num_valid_encoding_ids; ++i) { bool on = controller.IsItemChecked(&profile_en, encoding, valid_encodings[i]); // Only one item in the encoding menu can be selected at a time. ASSERT_FALSE(on && encoding_is_enabled); encoding_is_enabled |= on; } // Make sure at least one encoding is enabled. ASSERT_TRUE(encoding_is_enabled); }
/* Copyright 2017 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/layout_util.h" #include <stddef.h> #include <algorithm> #include <functional> #include <random> #include <string> #include <unordered_map> #include <vector> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "tensorflow/compiler/xla/protobuf_util.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/hash/hash.h" #include "tensorflow/core/lib/strings/numbers.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/protobuf.h" namespace xla { namespace { // Internal helper for GetDefaultLayoutForShape and SetToDefaultLayout. Sets // minor_to_major to the value that represents the default layout. void SetDefaultLayoutToContainer( tensorflow::protobuf::RepeatedField<tensorflow::protobuf_int64>* minor_to_major) { // The default XLA layout is major-to-minor (dim 0 is major). // For more information on XLA layouts, see: // https://www.tensorflow.org/performance/xla/shapes const int64 size = minor_to_major->size(); for (int64 i = 0; i < size; ++i) { minor_to_major->Set(i, size - 1 - i); } } } // namespace /* static */ Layout LayoutUtil::MakeLayout( absl::Span<const int64> minor_to_major, absl::Span<const Tile> tiles, int64 element_size_in_bits) { Layout layout; layout.set_format(DENSE); for (int64 dimension_number : minor_to_major) { layout.add_minor_to_major(dimension_number); } for (Tile tile : tiles) { for (int64 dim : tile.dimensions()) { if (dim < 0 && dim != Tile::kCombineDimension) { LOG(FATAL) << "Tile dimension size needs to be mininum int64 value if " "it's negative. Value is " << dim; } } *layout.add_tiles() = tile; } layout.set_element_size_in_bits(element_size_in_bits); return layout; } /* static */ Layout LayoutUtil::MakeDescendingLayout(int64 rank) { std::vector<int64> layout(rank); std::iota(layout.rbegin(), layout.rend(), static_cast<int64>(0)); return MakeLayout(layout); } /* static */ Layout LayoutUtil::MakeLayoutFromMajorToMinor( absl::Span<const int64> major_to_minor) { Layout layout; layout.set_format(DENSE); for (int i = major_to_minor.size() - 1; i >= 0; i--) { layout.add_minor_to_major(major_to_minor[i]); } return layout; } /* static */ Layout LayoutUtil::MakeSparseLayout(int64 max_sparse_elements) { Layout layout; layout.set_format(SPARSE); layout.set_max_sparse_elements(max_sparse_elements); return layout; } namespace { // Internal helper that creates a default layout for an array of the given rank. Layout CreateDefaultLayoutForRank(int64 rank) { Layout layout; layout.set_format(DENSE); tensorflow::protobuf::RepeatedField<tensorflow::protobuf_int64>* minor_to_major = layout.mutable_minor_to_major(); minor_to_major->Resize(rank, 0); SetDefaultLayoutToContainer(minor_to_major); return layout; } } // namespace /* static */ Layout LayoutUtil::GetDefaultLayoutForShape(const Shape& shape) { if (shape.IsOpaque() || shape.IsToken()) { // Opaque and token types have empty layouts. return Layout(); } // A Layout proto corresponds to a single array, not a tuple. CHECK(shape.IsArray()); return CreateDefaultLayoutForRank(shape.dimensions_size()); } /* static */ Layout LayoutUtil::GetDefaultLayoutForRank(int64 rank) { return CreateDefaultLayoutForRank(rank); } /* static */ Layout LayoutUtil::GetDefaultLayoutForR2() { return CreateDefaultLayoutForRank(2); } /* static */ Layout LayoutUtil::GetDefaultLayoutForR3() { return CreateDefaultLayoutForRank(3); } /* static */ Layout LayoutUtil::GetDefaultLayoutForR4() { return CreateDefaultLayoutForRank(4); } /* static */ void LayoutUtil::SetToDefaultLayout(Shape* shape) { if (shape->IsTuple()) { // Tuple shape. for (auto& element_shape : *shape->mutable_tuple_shapes()) { SetToDefaultLayout(&element_shape); } shape->clear_layout(); } else if (shape->IsArray()) { shape->mutable_layout()->set_format(DENSE); tensorflow::protobuf::RepeatedField<tensorflow::protobuf_int64>* minor_to_major = shape->mutable_layout()->mutable_minor_to_major(); minor_to_major->Resize(shape->dimensions_size(), 0); SetDefaultLayoutToContainer(minor_to_major); } else { // Opaque, token types etc. have no layout. shape->clear_layout(); } } /* static */ Shape LayoutUtil::GetWithDefaultLayout(const Shape& shape) { Shape copy(shape); LayoutUtil::SetToDefaultLayout(&copy); return copy; } /* static */ void LayoutUtil::SetToDefaultLayout(ProgramShape* program_shape) { for (auto& parameter_shape : *program_shape->mutable_parameters()) { LayoutUtil::SetToDefaultLayout(&parameter_shape); } LayoutUtil::SetToDefaultLayout(program_shape->mutable_result()); } /* static */ Status LayoutUtil::ValidateLayoutInShape( const Shape& shape, bool allow_missing_layouts) { if (shape.IsTuple()) { // Tuple shape. if (shape.has_layout()) { return InvalidArgument("tuple should not have a layout field"); } for (auto& element_shape : shape.tuple_shapes()) { TF_RETURN_IF_ERROR( ValidateLayoutInShape(element_shape, allow_missing_layouts)); } return Status::OK(); } else if (shape.IsArray()) { if (!shape.has_layout()) { if (allow_missing_layouts) { return Status::OK(); } return InvalidArgument("shape %s does not have a layout", ShapeUtil::HumanString(shape)); } return ValidateLayoutForShape(shape.layout(), shape); } else { // Token, opaque, etc. shape. if (shape.has_layout()) { return InvalidArgument( "shape of primitive type %s should not have a layout", PrimitiveType_Name(shape.element_type())); } return Status::OK(); } } /* static */ Status LayoutUtil::ValidateLayoutForShape(const Layout& layout, const Shape& shape) { if (shape.IsTuple()) { return InvalidArgument("a single Layout is not valid for tuple shapes"); } if (!shape.IsArray()) { if (layout.minor_to_major_size() != 0) { return InvalidArgument( "shape of primitive type %s should not have a non-trivial layout", PrimitiveType_Name(shape.element_type())); } return Status::OK(); } if (layout.format() == INVALID_FORMAT || !Format_IsValid(layout.format())) { return InvalidArgument( "Layout has an invalid format (%d) in layout {%s}, shape {%s}", layout.format(), layout.ShortDebugString(), shape.ShortDebugString()); } if (layout.format() == DENSE) { if (layout.minor_to_major_size() != shape.rank()) { return InvalidArgument( "layout minor_to_major field contains %d elements, " "but shape is rank %d: {%s}; shape: %s", layout.minor_to_major_size(), shape.rank(), absl::StrJoin(layout.minor_to_major(), ", "), shape.ShortDebugString()); } std::vector<bool> dimensions_in_layout(shape.rank(), false); for (int64 i = 0; i < shape.rank(); ++i) { int64 dim = layout.minor_to_major(i); if (dim < 0 || dim >= shape.rank()) { return InvalidArgument( "layout minor_to_major field has out-of-bounds value: %s", HumanString(layout)); } if (dimensions_in_layout[dim]) { return InvalidArgument( "layout minor_to_major field has duplicate values: {%s}", HumanString(layout)); } dimensions_in_layout[dim] = true; } } else { if (layout.tiles_size() != 0) { return InvalidArgument("Only dense layouts can be tiled."); } } return Status::OK(); } /* static */ void LayoutUtil::ClearLayout(Shape* shape) { shape->clear_layout(); for (auto& element_shape : *shape->mutable_tuple_shapes()) { ClearLayout(&element_shape); } } /* static */ void LayoutUtil::ClearLayout(ProgramShape* program_shape) { for (auto& parameter_shape : *program_shape->mutable_parameters()) { LayoutUtil::ClearLayout(&parameter_shape); } LayoutUtil::ClearLayout(program_shape->mutable_result()); } /* static */ bool LayoutUtil::IsDenseArray(const Shape& shape) { return shape.IsArray() && shape.has_layout() && IsDense(shape.layout()); } /* static */ bool LayoutUtil::IsDense(const Layout& layout) { return layout.format() == DENSE; } /* static */ bool LayoutUtil::IsMonotonicWithDim0Minor(const Layout& layout) { CHECK(layout.format() == DENSE); return std::is_sorted(layout.minor_to_major().begin(), layout.minor_to_major().end()); } /* static */ bool LayoutUtil::IsMonotonicWithDim0Major(const Layout& layout) { CHECK(layout.format() == DENSE); return std::is_sorted(layout.minor_to_major().begin(), layout.minor_to_major().end(), std::greater<int64>()); } /* static */ bool LayoutUtil::IsPadded(const Shape& shape) { if (!ShapeUtil::IsArray(shape) || !HasLayout(shape) || shape.layout().padded_dimensions_size() == 0) { return false; } CHECK(IsDenseArray(shape)) << shape.ShortDebugString(); CHECK_EQ(shape.dimensions_size(), shape.layout().padded_dimensions_size()); for (int64 i = 0; i < shape.dimensions_size(); ++i) { if (shape.layout().padded_dimensions(i) > shape.dimensions(i)) { return true; } } return false; } /* static */ absl::Span<const int64> LayoutUtil::PaddedDimensions( const Shape& shape) { CHECK(IsDenseArray(shape)); return AsInt64Slice(shape.layout().padded_dimensions()); } /* static */ int64 LayoutUtil::PaddedDimension(const Shape& shape, int64 index) { CHECK(IsDenseArray(shape)); return shape.layout().padded_dimensions(index); } /* static */ PaddingValue LayoutUtil::GetPaddingValue(const Shape& shape) { CHECK(IsDenseArray(shape)); return shape.layout().padding_value(); } /* static */ bool LayoutUtil::IsSparseArray(const Shape& shape) { return shape.IsArray() && shape.has_layout() && IsSparse(shape.layout()); } /* static */ bool LayoutUtil::IsSparse(const Layout& layout) { return layout.format() == SPARSE; } /* static */ int64 LayoutUtil::MaxSparseElements(const Layout& layout) { CHECK(IsSparse(layout)); return layout.max_sparse_elements(); } /* static */ bool LayoutUtil::HasLayout(const Shape& shape) { if (shape.IsTuple()) { // Tuple shape: all subshapes must have a layout. return absl::c_all_of(shape.tuple_shapes(), [](const Shape& s) { return HasLayout(s); }); } else if (!shape.IsArray()) { // Opaque, token types etc. ignore layout. return true; } return shape.has_layout() && shape.layout().format() != INVALID_FORMAT; } /* static */ bool LayoutUtil::HasLayout(const ProgramShape& program_shape) { for (auto& parameter_shape : program_shape.parameters()) { if (!LayoutUtil::HasLayout(parameter_shape)) { return false; } } return LayoutUtil::HasLayout(program_shape.result()); } /* static */ bool LayoutUtil::Equal(const Layout& lhs, const Layout& rhs) { return protobuf_util::ProtobufEquals(lhs, rhs); } /* static */ absl::Span<const int64> LayoutUtil::MinorToMajor( const Shape& shape) { CHECK(IsDenseArray(shape)); return AsInt64Slice(shape.layout().minor_to_major()); } /* static */ absl::Span<const int64> LayoutUtil::MinorToMajor( const Layout& layout) { CHECK(layout.format() == DENSE); return AsInt64Slice(layout.minor_to_major()); } /* static */ int64 LayoutUtil::Major(const Layout& layout, int64 physical_dimension_number) { CHECK_LE(0, physical_dimension_number); CHECK_LT(physical_dimension_number, layout.minor_to_major_size()); return Minor(layout, layout.minor_to_major_size() - 1 - physical_dimension_number); } /* static */ int64 LayoutUtil::Minor(const Layout& layout, int64 physical_dimension_number) { CHECK_EQ(layout.format(), DENSE); CHECK_LE(0, physical_dimension_number); CHECK_LT(physical_dimension_number, layout.minor_to_major_size()); return layout.minor_to_major(physical_dimension_number); } /* static */ std::vector<int64> LayoutUtil::MakeLogicalToPhysical( const Layout& layout) { std::vector<int64> logical_to_physical(layout.minor_to_major_size()); for (int64 physical = 0; physical < logical_to_physical.size(); ++physical) { const int64 logical = Major(layout, physical); logical_to_physical[logical] = physical; } return logical_to_physical; } /* static */ string LayoutUtil::HumanString(const Layout& layout) { if (IsSparse(layout)) { return absl::StrCat("sparse{", layout.max_sparse_elements(), "}"); } CHECK(IsDense(layout)); return absl::StrCat("{", absl::StrJoin(layout.minor_to_major(), ","), "}"); } namespace { // Internal helper for recursively copying layouts. Status CopyLayoutInternal(const Shape& src, Shape* dst) { if (src.IsTuple() != dst->IsTuple()) { return InvalidArgument( "cannot copy layout from shape: shape structure differs"); } if (src.IsTuple()) { if (ShapeUtil::TupleElementCount(src) != ShapeUtil::TupleElementCount(*dst)) { return InvalidArgument( "cannot copy layout from shape: tuple element count differs"); } for (int64 i = 0; i < ShapeUtil::TupleElementCount(src); ++i) { TF_RETURN_IF_ERROR(CopyLayoutInternal(src.tuple_shapes(i), dst->mutable_tuple_shapes(i))); } } else { if (src.has_layout()) { if (src.rank() != dst->rank()) { return InvalidArgument("cannot copy layout from shape: ranks differs"); } TF_RETURN_IF_ERROR( LayoutUtil::ValidateLayoutForShape(src.layout(), *dst)); *dst->mutable_layout() = src.layout(); } else { dst->clear_layout(); } } return Status::OK(); } } // namespace /* static */ Status LayoutUtil::CopyLayoutBetweenShapes(const Shape& src, Shape* dst) { return CopyLayoutInternal(src, dst); } /* static */ bool LayoutUtil::LayoutsInShapesEqual(const Shape& lhs, const Shape& rhs) { if (lhs.IsTuple()) { if (!rhs.IsTuple() || ShapeUtil::TupleElementCount(lhs) != ShapeUtil::TupleElementCount(rhs)) { return false; } for (int i = 0; i < ShapeUtil::TupleElementCount(lhs); ++i) { if (!LayoutsInShapesEqual(lhs.tuple_shapes(i), rhs.tuple_shapes(i))) { return false; } } return true; } else if (lhs.IsArray()) { return lhs.rank() == rhs.rank() && LayoutUtil::Equal(lhs.layout(), rhs.layout()); } else { // Layouts of non-array and non-tuple shapes is ignored. return true; } } /* static */ bool LayoutUtil::AreDimensionsConsecutive( const Layout& layout, absl::Span<const int64> dims) { CHECK(IsDense(layout)); std::vector<int64> positions_in_layout; for (int64 dim : dims) { positions_in_layout.push_back( PositionInContainer(layout.minor_to_major(), dim)); } absl::c_sort(positions_in_layout); for (size_t i = 1; i < positions_in_layout.size(); ++i) { if (1 != positions_in_layout[i] - positions_in_layout[i - 1]) { return false; } } return true; } std::ostream& operator<<(std::ostream& out, const Layout& layout) { out << LayoutUtil::HumanString(layout); return out; } /*static*/ size_t LayoutUtil::Hash(const Layout& layout) { using tensorflow::hash; using tensorflow::Hash64Combine; size_t hash_value = hash<Format>()(layout.format()); for (int64 minor_to_major : layout.minor_to_major()) { hash_value = Hash64Combine(hash_value, hash<int64>()(minor_to_major)); } for (int64 padded_dim : layout.padded_dimensions()) { hash_value = Hash64Combine(hash_value, hash<int64>()(padded_dim)); } hash_value = Hash64Combine(hash_value, hash<PaddingValue>()(layout.padding_value())); hash_value = Hash64Combine(hash_value, layout.max_sparse_elements()); return hash_value; } } // namespace xla
// // Copyright (c) 2008-2022 the Urho3D project. // // 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 <Urho3D/Core/Context.h> #include <Urho3D/Core/ProcessUtils.h> #include <Urho3D/Core/StringUtils.h> #include <Urho3D/IO/File.h> #include <Urho3D/IO/FileSystem.h> #include <Urho3D/IO/Log.h> #include <Urho3D/Resource/Image.h> #include <Urho3D/Resource/XMLElement.h> #include <Urho3D/Resource/XMLFile.h> #ifdef WIN32 #include <windows.h> #endif #define STBRP_LARGE_RECTS #if !URHO3D_STATIC # define STB_RECT_PACK_IMPLEMENTATION #endif #include <STB/stb_rect_pack.h> #include <Urho3D/DebugNew.h> using namespace Urho3D; // number of nodes allocated to each packer info. since this packer is not suited for real time purposes we can over allocate. const int PACKER_NUM_NODES = 4096; const int MAX_TEXTURE_SIZE = 2048; int main(int argc, char** argv); void Run(ea::vector<ea::string>& arguments); class PackerInfo : public RefCounted { public: ea::string path; ea::string name; int x{}; int y{}; int offsetX{}; int offsetY{}; int width{}; int height{}; int frameWidth{}; int frameHeight{}; PackerInfo(const ea::string& path_, const ea::string& name_) : path(path_), name(name_) { } ~PackerInfo() override = default; }; void Help() { ErrorExit("Usage: SpritePacker -options <input file> <input file> <output png file>\n" "\n" "Options:\n" "-h Shows this help message.\n" "-px Adds x pixels of padding per image to width.\n" "-py Adds y pixels of padding per image to height.\n" "-ox Adds x pixels to the horizontal position per image.\n" "-oy Adds y pixels to the horizontal position per image.\n" "-frameHeight Sets a fixed height for image and centers within frame.\n" "-frameWidth Sets a fixed width for image and centers within frame.\n" "-trim Trims excess transparent space from individual images offsets by frame size.\n" "-xml \'path\' Generates an SpriteSheet xml file at path.\n" "-debug Draws allocation boxes on sprite.\n"); } int main(int argc, char** argv) { ea::vector<ea::string> arguments; #ifdef WIN32 arguments = ParseArguments(GetCommandLineW()); #else arguments = ParseArguments(argc, argv); #endif Run(arguments); return 0; } void Run(ea::vector<ea::string>& arguments) { if (arguments.size() < 2) Help(); SharedPtr<Context> context(new Context()); context->RegisterSubsystem(new FileSystem(context)); context->RegisterSubsystem(new Log(context)); auto* fileSystem = context->GetSubsystem<FileSystem>(); ea::vector<ea::string> inputFiles; ea::string outputFile; ea::string spriteSheetFileName; bool debug = false; unsigned padX = 0; unsigned padY = 0; unsigned offsetX = 0; unsigned offsetY = 0; unsigned frameWidth = 0; unsigned frameHeight = 0; bool help = false; bool trim = false; while (arguments.size() > 0) { ea::string arg = arguments[0]; arguments.pop_front(); if (arg.empty()) continue; if (arg.starts_with("-")) { if (arg == "-px") { padX = ToUInt(arguments[0]); arguments.pop_front(); } else if (arg == "-py") { padY = ToUInt(arguments[0]); arguments.pop_front(); } else if (arg == "-ox") { offsetX = ToUInt(arguments[0]); arguments.pop_front(); } else if (arg == "-oy") { offsetY = ToUInt(arguments[0]); arguments.pop_front(); } else if (arg == "-frameWidth") { frameWidth = ToUInt(arguments[0]); arguments.pop_front(); } else if (arg == "-frameHeight") { frameHeight = ToUInt(arguments[0]); arguments.pop_front(); } else if (arg == "-trim") { trim = true; } else if (arg == "-xml") { spriteSheetFileName = arguments[0]; arguments.pop_front(); } else if (arg == "-h") { help = true; break; } else if (arg == "-debug") { debug = true; } } else inputFiles.push_back(arg); } if (help) Help(); if (inputFiles.size() < 2) ErrorExit("An input and output file must be specified."); if (frameWidth ^ frameHeight) ErrorExit("Both frameHeight and frameWidth must be omitted or specified."); // take last input file as output if (inputFiles.size() > 1) { outputFile = inputFiles[inputFiles.size() - 1]; URHO3D_LOGINFO("Output file set to " + outputFile + "."); inputFiles.erase_at(inputFiles.size() - 1); } // set spritesheet name to outputfile.xml if not specified if (spriteSheetFileName.empty()) spriteSheetFileName = ReplaceExtension(outputFile, ".xml"); if (GetParentPath(spriteSheetFileName) != GetParentPath(outputFile)) ErrorExit("Both output xml and png must be in the same folder"); // check all input files exist for (unsigned i = 0; i < inputFiles.size(); ++i) { URHO3D_LOGINFO("Checking " + inputFiles[i] + " to see if file exists."); if (!fileSystem->FileExists(inputFiles[i])) ErrorExit("File " + inputFiles[i] + " does not exist."); } // Set the max offset equal to padding to prevent images from going out of bounds offsetX = Min((int)offsetX, (int)padX); offsetY = Min((int)offsetY, (int)padY); ea::vector<SharedPtr<PackerInfo > > packerInfos; for (unsigned i = 0; i < inputFiles.size(); ++i) { ea::string path = inputFiles[i]; ea::string name = ReplaceExtension(GetFileName(path), ""); File file(context, path); Image image(context); if (!image.Load(file)) ErrorExit("Could not load image " + path + "."); if (image.IsCompressed()) ErrorExit(path + " is compressed. Compressed images are not allowed."); SharedPtr<PackerInfo> packerInfo(new PackerInfo(path, name)); int imageWidth = image.GetWidth(); int imageHeight = image.GetHeight(); int trimOffsetX = 0; int trimOffsetY = 0; int adjustedWidth = imageWidth; int adjustedHeight = imageHeight; if (trim) { int minX = imageWidth; int minY = imageHeight; int maxX = 0; int maxY = 0; for (int y = 0; y < imageHeight; ++y) { for (int x = 0; x < imageWidth; ++x) { bool found = (image.GetPixelInt(x, y) & 0x000000ffu) != 0; if (found) { minX = Min(minX, x); minY = Min(minY, y); maxX = Max(maxX, x); maxY = Max(maxY, y); } } } trimOffsetX = minX; trimOffsetY = minY; adjustedWidth = maxX - minX + 1; adjustedHeight = maxY - minY + 1; } if (trim) { packerInfo->frameWidth = imageWidth; packerInfo->frameHeight = imageHeight; } else if (frameWidth || frameHeight) { packerInfo->frameWidth = frameWidth; packerInfo->frameHeight = frameHeight; } packerInfo->width = adjustedWidth; packerInfo->height = adjustedHeight; packerInfo->offsetX -= trimOffsetX; packerInfo->offsetY -= trimOffsetY; packerInfos.push_back(packerInfo); } int packedWidth = MAX_TEXTURE_SIZE; int packedHeight = MAX_TEXTURE_SIZE; { // fill up an list of tries in increasing size and take the first win ea::vector<IntVector2> tries; for(unsigned x=2; x<11; ++x) { for(unsigned y=2; y<11; ++y) tries.push_back(IntVector2((1u << x), (1u << y))); } // load rectangles auto* packerRects = new stbrp_rect[packerInfos.size()]; for (unsigned i = 0; i < packerInfos.size(); ++i) { PackerInfo* packerInfo = packerInfos[i]; stbrp_rect* packerRect = &packerRects[i]; packerRect->id = i; packerRect->h = packerInfo->height + padY; packerRect->w = packerInfo->width + padX; } bool success = false; while (tries.size() > 0) { IntVector2 size = tries[0]; tries.pop_front(); bool fit = true; int textureHeight = size.y_; int textureWidth = size.x_; if (success && textureHeight * textureWidth > packedWidth * packedHeight) continue; stbrp_context packerContext; stbrp_node packerMemory[PACKER_NUM_NODES]; stbrp_init_target(&packerContext, textureWidth, textureHeight, packerMemory, PACKER_NUM_NODES); if (!stbrp_pack_rects(&packerContext, packerRects, packerInfos.size())) { // check to see if everything fit fit = false; } if (fit) { success = true; // distribute values to packer info for (unsigned i = 0; i < packerInfos.size(); ++i) { stbrp_rect* packerRect = &packerRects[i]; PackerInfo* packerInfo = packerInfos[packerRect->id]; packerInfo->x = packerRect->x; packerInfo->y = packerRect->y; } packedWidth = size.x_; packedHeight = size.y_; } } delete[] packerRects; if (!success) ErrorExit("Could not allocate for all images. The max sprite sheet texture size is " + ea::to_string(MAX_TEXTURE_SIZE) + "x" + ea::to_string(MAX_TEXTURE_SIZE) + "."); } // create image for spritesheet Image spriteSheetImage(context); spriteSheetImage.SetSize(packedWidth, packedHeight, 4); // zero out image spriteSheetImage.SetData(nullptr); XMLFile xml(context); XMLElement root = xml.CreateRoot("TextureAtlas"); root.SetAttribute("imagePath", GetFileNameAndExtension(outputFile)); for (unsigned i = 0; i < packerInfos.size(); ++i) { SharedPtr<PackerInfo> packerInfo = packerInfos[i]; XMLElement subTexture = root.CreateChild("SubTexture"); subTexture.SetString("name", packerInfo->name); subTexture.SetInt("x", packerInfo->x + offsetX); subTexture.SetInt("y", packerInfo->y + offsetY); subTexture.SetInt("width", packerInfo->width); subTexture.SetInt("height", packerInfo->height); if (packerInfo->frameWidth || packerInfo->frameHeight) { subTexture.SetInt("frameWidth", packerInfo->frameWidth); subTexture.SetInt("frameHeight", packerInfo->frameHeight); subTexture.SetInt("offsetX", packerInfo->offsetX); subTexture.SetInt("offsetY", packerInfo->offsetY); } URHO3D_LOGINFO("Transferring " + packerInfo->path + " to sprite sheet."); File file(context, packerInfo->path); Image image(context); if (!image.Load(file)) ErrorExit("Could not load image " + packerInfo->path + "."); for (int y = 0; y < packerInfo->height; ++y) { for (int x = 0; x < packerInfo->width; ++x) { unsigned color = image.GetPixelInt(x - packerInfo->offsetX, y - packerInfo->offsetY); spriteSheetImage.SetPixelInt( packerInfo->x + offsetX + x, packerInfo->y + offsetY + y, color); } } } if (debug) { unsigned OUTER_BOUNDS_DEBUG_COLOR = Color::BLUE.ToUInt(); unsigned INNER_BOUNDS_DEBUG_COLOR = Color::GREEN.ToUInt(); URHO3D_LOGINFO("Drawing debug information."); for (unsigned i = 0; i < packerInfos.size(); ++i) { SharedPtr<PackerInfo> packerInfo = packerInfos[i]; // Draw outer bounds for (int x = 0; x < packerInfo->frameWidth; ++x) { spriteSheetImage.SetPixelInt(packerInfo->x + x, packerInfo->y, OUTER_BOUNDS_DEBUG_COLOR); spriteSheetImage.SetPixelInt(packerInfo->x + x, packerInfo->y + packerInfo->frameHeight, OUTER_BOUNDS_DEBUG_COLOR); } for (int y = 0; y < packerInfo->frameHeight; ++y) { spriteSheetImage.SetPixelInt(packerInfo->x, packerInfo->y + y, OUTER_BOUNDS_DEBUG_COLOR); spriteSheetImage.SetPixelInt(packerInfo->x + packerInfo->frameWidth, packerInfo->y + y, OUTER_BOUNDS_DEBUG_COLOR); } // Draw inner bounds for (int x = 0; x < packerInfo->width; ++x) { spriteSheetImage.SetPixelInt(packerInfo->x + offsetX + x, packerInfo->y + offsetY, INNER_BOUNDS_DEBUG_COLOR); spriteSheetImage.SetPixelInt(packerInfo->x + offsetX + x, packerInfo->y + offsetY + packerInfo->height, INNER_BOUNDS_DEBUG_COLOR); } for (int y = 0; y < packerInfo->height; ++y) { spriteSheetImage.SetPixelInt(packerInfo->x + offsetX, packerInfo->y + offsetY + y, INNER_BOUNDS_DEBUG_COLOR); spriteSheetImage.SetPixelInt(packerInfo->x + offsetX + packerInfo->width, packerInfo->y + offsetY + y, INNER_BOUNDS_DEBUG_COLOR); } } } URHO3D_LOGINFO("Saving output image."); spriteSheetImage.SavePNG(outputFile); URHO3D_LOGINFO("Saving SpriteSheet xml file."); File spriteSheetFile(context); spriteSheetFile.Open(spriteSheetFileName, FILE_WRITE); xml.Save(spriteSheetFile); }
#include<cmath> #include"core/data/utility/Configuration.h" #include <sys/types.h> // For stat(). #include <sys/stat.h> // For stat(). #include <stdio.h> #include <fstream> #include <stdlib.h> #include <algorithm> #include "core/data/mat/MatN.h" #include"core/data/utility/BasicUtility.h" #if Pop_OS==2 #ifdef _MSC_VER #include"core/dependency/direntvc.h" #include <direct.h> #else #include <direct.h> #include <dirent.h> #endif #else #include <dirent.h> #endif namespace pop { std::string BasicUtility::IntFixedDigit2String(unsigned int value,int digitnumber) { long int number =std::pow (10.,digitnumber); long int tempvalue = value/number; value-=tempvalue*number; std::string s; for(int i =digitnumber-1;i>=0;i--) { long int number =std::pow (10.,i); long int tempvalue = value/number; value-=tempvalue*number; std::string str; Any2String(tempvalue,str); s+=str; } return s; } std::string BasicUtility::getline(std::istream& in,std::string del){ std::string str; std::string temp; int index=0; char c; while(index<(int)del.size()){ c = in.get(); if (in.good()){ if(c==del.operator [](index)) { temp+=c; index++; } else { if(index!=0){ str+=temp; temp.clear(); index=0; } if(c==del.operator [](index)) { temp+=c; index++; } else str+=c; } } } return str; } std::string BasicUtility::getExtension(std::string file){ int size =0, index = 0; do{ if(file[size] == '.') { index = size; } size ++; }while(size<(int)file.size()); if(size && index) return file.assign(file.begin()+index,file.end()); else return ""; //throw(pexception("BasicUtility::getExtension, no extension in your file :" +file)); } std::string BasicUtility::getBasefilename(std::string file){ int slash, dot; slash = -1; dot = file.size()-1; int size =0; while(size ++, file[size]) { if(file[size] == '.') { dot = size; } if(file[size] == '/'||file[size] == '\\') { slash = size; } } return file.assign(file.begin()+slash+1,file.begin()+dot); } std::string BasicUtility::getPath(std::string file){ int slash; slash = -1; int size =0; while(size ++, file[size]) { if(file[size] == '/'||file[size] == '\\') { slash = size; } } return file.assign(file.begin(),file.begin()+slash); } std::vector<std::string> BasicUtility::getFilesInDirectory(std::string dir) { DIR *dp; struct dirent *dirp; if((dp = opendir(dir.c_str())) == NULL) { return std::vector<std::string>(); // pexception("BasicUtility::getFilesInDirectory, Cannot open this directory"+dir); } std::vector<std::string> files; while ((dirp = readdir(dp)) != NULL) { std::string str = std::string(dirp->d_name); if(str!="."&&str!=".."&&*str.rbegin()!='~') files.push_back(str); } closedir(dp); std::sort(files.begin(),files.end()); return files; } bool BasicUtility::isFile( std::string filepath){ int status; struct stat st_buf; status = stat (filepath.c_str(), &st_buf); if (status != 0) { return false; } if (S_ISREG (st_buf.st_mode)) { return true; } else return false; } bool BasicUtility::isDirectory(std::string dirpath){ //#if Pop_OS==1 //// if ( access( dirpath.c_str(), 0 ) == 0 ) //#endif { struct stat status; stat( dirpath.c_str(), &status ); if ( status.st_mode & S_IFDIR ) { return true; } else { return false; } } //#if Pop_OS==1 // else //#endif // { // return false; // } } bool BasicUtility::makeDirectory(std::string dirpath){ if(isDirectory(dirpath)==false){ #if Pop_OS==1 mkdir(dirpath.c_str(),777); #endif #if Pop_OS==2 _mkdir(dirpath.c_str()); #endif return true; } else return false; } struct operatorReplaceSlashByAntiSlash { char operator()(char c){ if(c=='/') return '\\'; else return c; } }; std::string BasicUtility::replaceSlashByAntiSlash(std::string filepath){ std::transform(filepath.begin(),filepath.end(),filepath.begin(),operatorReplaceSlashByAntiSlash()); return filepath; } int BasicUtility::editDistance(std::string s1,std::string s2){ pop::Mat2F64 m(s1.size(),s2.size()); for(unsigned int i =0;i<m.sizeI();i++){ m(i,0)=i; } for(unsigned int j =0;j<m.sizeJ();j++){ m(0,j)=j; } int k =2; bool test=true; while(test==true){ test=false; for(int i=1;i<=k-1;i++){ int j=k-i; if(m.isValid(i,j)){ test =true; int v=1; if(s1[i-1]==s2[j-1]) v=0; int v1; if(m(i,j-1)+1<m(i-1,j)+1) v1 = m(i,j-1)+1; else v1 = m(i-1,j)+1; if(v1<m(i-1,j-1)+v) m(i,j)= v1; else m(i,j)= m(i-1,j-1)+v; } } k++; } return m(m.sizeI()-1,m.sizeJ()-1); } void BasicUtility::cryptOrDecryptFileXORKey(std::string inputfile,std::string outputfile, pop::UI32 key ){ std::ifstream infile(inputfile.c_str(), std::ios::binary); infile.seekg (0,infile.end); long size = infile.tellg(); infile.seekg (0); char * c = new char[size]; infile.seekg( 0, std::ios::beg); infile.read(c, size); pop::UI32 * ptrUI32 =reinterpret_cast<pop::UI32*>(c); for(unsigned int i =0;i<std::floor(size/4.);i++){ *ptrUI32 = (*ptrUI32)^(key); ptrUI32++; } std::ofstream outfile (outputfile.c_str(),std::ofstream::binary); outfile.write (c,size); delete[] c; outfile.close(); infile.close(); } } //namespace std{ //std::istream& operator >> (std::istream& in, unsigned char & c) //{ // int v; // in>>v; // c = (unsigned char)v; // return in; //} //std::ostream& operator << (std::ostream& out, unsigned char c) //{ // out<<(int)c; // return out; //} //}
// Copyright 2017 The Zeta Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ----------------------------------------------------------------------------- // File: [file_name] // ----------------------------------------------------------------------------- // // [file_descrition] // // Example: // // ... ... // // #include "src/server.h" #include "soil/log.h" namespace zeta { Server::Server(const rapidjson::Document& doc) { SOIL_FUNC_TRACE; options_.reset(new Options(doc)); if (!options_->speed_file.empty()) { speed_file_.reset( new MDataFile( options_->speed_file, options_->instrus_filter)); } // if (!config_->zetaOptions()->md_file.empty()) { // md_file_.reset( // new MDataFile( // options_->md_file, // options_->instrus_filter)); // } zebra_service_.reset(zebra::Service::create(doc, this)); } Server::~Server() { SOIL_FUNC_TRACE; } void Server::onReceiveMarketData( const ftdc::MarketDataField* md, const struct timeval& ts, const u_char* sp, uint32_t len) { SOIL_FUNC_TRACE; if (speed_file_.get()) { speed_file_->putData( toSpeedMData(md->updatetime_field.InstrumentID, md->updatetime_field.UpdateTime, md->updatetime_field.UpdateMillisec, ts)); } // if (md_file_.get()) { // md_file_->putData(toShfeMData(md)); // } } std::shared_ptr<SpeedMData> Server::toSpeedMData( const std::string& instru, const std::string& update_time, int update_millisec, const struct timeval& ts) { std::shared_ptr<SpeedMData> speed_data(new SpeedMData()); speed_data->instru = instru; speed_data->update_time = update_time; speed_data->update_millisec = update_millisec; speed_data->time_stamp = soil::DateTime(ts); return speed_data; } // ShfeMData* Server::toShfeMData(const ftdc::MarketDataField* md) { // std::unique_ptr<ShfeMData> shfe_data(new ShfeMData()); // shfe_data->TradingDay = md->base_field.TradingDay; // shfe_data->PreSettlementPrice = md->base_field.PreSettlementPrice; // shfe_data->PreClosePrice = md->base_field.PreClosePrice; // shfe_data->PreOpenInterest = md->base_field.PreOpenInterest; // shfe_data->PreDelta = md->base_field.PreDelta; // shfe_data->InstrumentID = md->updatetime_field.InstrumentID; // shfe_data->UpdateTime = md->updatetime_field.UpdateTime; // shfe_data->UpdateMillisec = md->updatetime_field.UpdateMillisec; // shfe_data->ActionDay = md->updatetime_field.ActionDay; // shfe_data->OpenPrice = md->static_field.OpenPrice; // shfe_data->HighestPrice = md->static_field.HighestPrice; // shfe_data->LowestPrice = md->static_field.LowestPrice; // shfe_data->ClosePrice = md->static_field.ClosePrice; // shfe_data->UpperLimitPrice = md->static_field.UpperLimitPrice; // shfe_data->LowerLimitPrice = md->static_field.LowerLimitPrice; // shfe_data->SettlementPrice = md->static_field.SettlementPrice; // shfe_data->CurrDelta = md->static_field.CurrDelta; // shfe_data->LastPrice = md->lastmatch_field.LastPrice; // shfe_data->Volume = md->lastmatch_field.Volume; // shfe_data->Turnover = md->lastmatch_field.Turnover; // shfe_data->OpenInterest = md->lastmatch_field.OpenInterest; // shfe_data->BidPrice1 = md->bestprice_field.BidPrice1; // shfe_data->BidVolume1 = md->bestprice_field.BidVolume1; // shfe_data->AskPrice1 = md->bestprice_field.AskPrice1; // shfe_data->AskVolume1 = md->bestprice_field.AskVolume1; // shfe_data->BidPrice2 = md->bid23_field.BidPrice2; // shfe_data->BidVolume2 = md->bid23_field.BidVolume2; // shfe_data->BidPrice3 = md->bid23_field.BidPrice3; // shfe_data->BidVolume3 = md->bid23_field.BidVolume3; // shfe_data->BidPrice4 = md->bid45_field.BidPrice4; // shfe_data->BidVolume4 = md->bid45_field.BidVolume4; // shfe_data->BidPrice5 = md->bid45_field.BidPrice5; // shfe_data->BidVolume5 = md->bid45_field.BidVolume5; // shfe_data->AskPrice2 = md->ask23_field.AskPrice2; // shfe_data->AskVolume2 = md->ask23_field.AskVolume2; // shfe_data->AskPrice3 = md->ask23_field.AskPrice3; // shfe_data->AskVolume3 = md->ask23_field.AskVolume3; // shfe_data->AskPrice4 = md->ask45_field.AskPrice4; // shfe_data->AskVolume4 = md->ask45_field.AskVolume4; // shfe_data->AskPrice5 = md->ask45_field.AskPrice5; // shfe_data->AskVolume5 = md->ask45_field.AskVolume5; // return shfe_data.release(); // } } // namespace zeta
#include "[command head file]" void [class name]::Init(ISessionService* session_service) { session_service_ = session_service; [do message logic init] PSS_LOGGER_DEBUG("[[class name]::Init]init."); } [command logic function achieve]
#include <Klein/Util/Gizmo.h> namespace Klein { Gizmo::Gizmo(QObject* parent) : QObject(parent) {} void Gizmo::update() { if (m_enabled) { ImGuizmo::BeginFrame(); const auto& io = ImGui::GetIO(); const auto viewMat = m_camera->viewMatrix(); const auto view = viewMat.constData(); const auto projMat = m_camera->projectionMatrix(); const auto proj = projMat.constData(); auto tranMat = m_transform->matrix(); auto tran = tranMat.data(); QMatrix4x4 idMat; idMat.setToIdentity(); ImGuizmo::SetRect(0.0f, 0.0f, io.DisplaySize.x, io.DisplaySize.y); ImGuizmo::Manipulate(view, proj, m_opration, m_mode, tran); if (ImGuizmo::IsUsing()) { m_transform->setMatrix(QMatrix4x4(tran).transposed()); } } } void Gizmo::setEnabled(bool value) { m_enabled = value; ImGuizmo::Enable(m_enabled); emit enabledChanged(value); } void Gizmo::setOperation(ImGuizmo::OPERATION operation) { m_opration = operation; } void Gizmo::setMode(ImGuizmo::MODE mode) { m_mode = mode; } void Gizmo::setTarget(Qt3DCore::QTransform* transform) { m_transform = transform; } void Gizmo::setCamera(Qt3DRender::QCamera* camera) { m_camera = camera; if (m_camera) { if (m_camera->projectionType() == Qt3DRender::QCameraLens::OrthographicProjection) { ImGuizmo::SetOrthographic(true); } else { ImGuizmo::SetOrthographic(false); } } } } // namespace Klein
/////////////////////////////////////////////////////////////////////////////// // // // OldVDCPlane // // // /////////////////////////////////////////////////////////////////////////////// // // // Here: // // Units of measurements: // // For cluster position (center) and size - wires; // // For X, Y, and Z coordinates of track - meters; // // For Theta and Phi angles of track - in tangents. // // // /////////////////////////////////////////////////////////////////////////////// #include "OldVDC.h" #include "OldVDCPlane.h" #include "OldVDCWire.h" #include "OldVDCUVPlane.h" #include "OldVDCCluster.h" #include "OldVDCHit.h" #include "THaDetMap.h" #include "OldVDCAnalyticTTDConv.h" #include "THaEvData.h" #include "TString.h" #include "TClass.h" #include "TMath.h" #include "VarDef.h" #include "THaApparatus.h" #include "THaTriggerTime.h" #include <cstring> #include <vector> #include <iostream> #include <iomanip> using namespace std; #define ALL(c) (c).begin(), (c).end() // Defaults for typical VDC operation. Can be overridden via set functions. // Configurable via database in version 1.6 and later. static const Int_t kDefaultNMaxGap = 1; static const Int_t kDefaultMinTime = 800; static const Int_t kDefaultMaxTime = 2200; static const Double_t kDefaultTDCRes = 5.0e-10; // 0.5 ns/chan = 5e-10 s /chan //_____________________________________________________________________________ OldVDCPlane::OldVDCPlane( const char* name, const char* description, THaDetectorBase* parent ) : THaSubDetector(name,description,parent), fNWiresHit(0), fNMaxGap(kDefaultNMaxGap), fMinTime(kDefaultMinTime), fMaxTime(kDefaultMaxTime), fFlags(0), fZ(0), fWBeg(0), fWSpac(0), fWAngle(0), fTDCRes(kDefaultTDCRes), fDriftVel(0), /*fTable(nullptr),*/ fTTDConv(0), fglTrg(0) { // Constructor // Since TCloneArrays can resize, the size here is fairly unimportant fWires = new TClonesArray("OldVDCWire", 368 ); fHits = new TClonesArray("OldVDCHit", 20 ); fClusters = new TClonesArray("OldVDCCluster", 5 ); fVDC = GetMainDetector(); ResetBit(kMaxGapSet); ResetBit(kMinTimeSet); ResetBit(kMaxTimeSet); ResetBit(kTDCResSet); } //_____________________________________________________________________________ void OldVDCPlane::MakePrefix() { // Special treatment of the prefix for VDC planes: We don't want variable // names such as "R.vdc.uv1.u.x", but rather "R.vdc.u1.x". TString basename; THaDetectorBase* uv_plane = GetParent(); if( fVDC ) basename = fVDC->GetPrefix(); if( fName.Contains("u") ) basename.Append("u"); else if ( fName.Contains("v") ) basename.Append("v"); if( uv_plane && strstr( uv_plane->GetName(), "uv1" )) basename.Append("1."); else if( uv_plane && strstr( uv_plane->GetName(), "uv2" )) basename.Append("2."); if( basename.Length() == 0 ) basename = fName + "."; delete [] fPrefix; fPrefix = new char[ basename.Length()+1 ]; strcpy( fPrefix, basename.Data() ); } //_____________________________________________________________________________ Int_t OldVDCPlane::DoReadDatabase( FILE* file, const TDatime& date ) { // Allocate TClonesArray objects and load plane parameters from database const char* const here = "ReadDatabase"; // Read fOrigin and fSize Int_t err = ReadGeometry( file, date ); if( err ) { return err; } fZ = fOrigin.Z(); // Read configuration parameters vector<Int_t> detmap, bad_wirelist; vector<Double_t> ttd_param; vector<Float_t> tdc_offsets; Int_t maxgap = kDefaultNMaxGap; Int_t mintime = kDefaultMinTime; Int_t maxtime = kDefaultMaxTime; Double_t tdcres = kDefaultTDCRes; DBRequest request[] = { { "detmap", &detmap, kIntV }, { "nwires", &fNelem, kInt, 0, 0, -1 }, { "wire.start", &fWBeg, kDouble }, { "wire.spacing", &fWSpac, kDouble, 0, 0, -1 }, { "wire.angle", &fWAngle, kDouble, 0, 0 }, { "wire.badlist", &bad_wirelist, kIntV, 0, 1 }, { "driftvel", &fDriftVel, kDouble, 0, 0, -1 }, { "maxgap", &maxgap, kInt, 0, 1, -1 }, { "tdc.min", &mintime, kInt, 0, 1, -1 }, { "tdc.max", &maxtime, kInt, 0, 1, -1 }, { "tdc.res", &tdcres, kDouble, 0, 0, -1 }, { "tdc.offsets", &tdc_offsets, kFloatV }, { "ttd.param", &ttd_param, kDoubleV, 0, 0, -1 }, { "description", &fTitle, kTString, 0, 1 }, { 0 } }; err = LoadDB( file, date, request, fPrefix ); if( err ) return err; if( FillDetMap(detmap, THaDetMap::kFillLogicalChannel, here) <= 0 ) return kInitError; // Error already printed by FillDetMap fWAngle *= TMath::DegToRad(); // Convert to radians set<Int_t> bad_wires( ALL(bad_wirelist) ); bad_wirelist.clear(); // Sanity checks if( fNelem <= 0 ) { Error( Here(here), "Invalid number of wires: %d", fNelem ); return kInitError; } Int_t nchan = fDetMap->GetTotNumChan(); if( nchan != fNelem ) { Error( Here(here), "Number of detector map channels (%d) " "disagrees with number of wires (%d)", nchan, fNelem ); return kInitError; } nchan = tdc_offsets.size(); if( nchan != fNelem ) { Error( Here(here), "Number of TDC offset values (%d) " "disagrees with number of wires (%d)", nchan, fNelem ); return kInitError; } // Values set via Set functions override database values if( !TestBit(kMaxGapSet) ) fNMaxGap = maxgap; if( !TestBit(kMinTimeSet) ) fMinTime = mintime; if( !TestBit(kMaxTimeSet) ) fMaxTime = maxtime; if( !TestBit(kTDCResSet) ) fTDCRes = tdcres; if( fNMaxGap < 0 || fNMaxGap > 2 ) { Error( Here(here), "Invalid max_gap = %d, must be between 0 and 2. " "Fix database.", fNMaxGap ); return kInitError; } if( fMinTime < 0 || fMinTime > 4095 ) { Error( Here(here), "Invalid min_time = %d, must be between 0 and 4095. " "Fix database.", fMinTime ); return kInitError; } if( fMaxTime < 1 || fMaxTime > 4096 || fMinTime >= fMaxTime ) { Error( Here(here), "Invalid max_time = %d. Must be between 1 and 4096 " "and >= min_time = %d. Fix database.", fMaxTime, fMinTime ); return kInitError; } if( fTDCRes < 0 || fTDCRes > 1e-6 ) { Error( Here(here), "Nonsense TDC resolution = %8.1le s/channel. " "Fix database.", fTDCRes ); return kInitError; } // Create time-to-distance converter delete fTTDConv; fTTDConv = new OldVDCAnalyticTTDConv(fDriftVel); // Initialize wires for (int i = 0; i < fNelem; i++) { OldVDCWire* wire = new((*fWires)[i]) OldVDCWire( i, fWBeg+i*fWSpac, tdc_offsets[i], fTTDConv ); if( bad_wires.find(i) != bad_wires.end() ) wire->SetFlag(1); } THaDetectorBase *sdet = GetParent(); if( sdet ) fOrigin += sdet->GetOrigin(); // finally, find the timing-offset to apply on an event-by-event basis //FIXME: time offset handling should go into the enclosing apparatus - //since not doing so leads to exactly this kind of mess: THaApparatus* app = GetApparatus(); const char* nm = "trg"; // inside an apparatus, the apparatus name is assumed if( !app || !(fglTrg = dynamic_cast<THaTriggerTime*>(app->GetDetector(nm))) ) { // Warning(Here(here),"Trigger-time detector \"%s\" not found. " // "Event-by-event time offsets will NOT be used!!",nm); } #ifdef WITH_DEBUG if( fDebug > 2 ) { Double_t pos[3]; fOrigin.GetXYZ(pos); Double_t angle = fWAngle*TMath::RadToDeg(); DBRequest list[] = { { "Number of wires", &fNelem, kInt }, { "Detector position", pos, kDouble, 3 }, { "Detector size", fSize, kFloat, 3 }, { "Wire angle (deg)", &angle }, { "Wire start pos (m)", &fWBeg }, { "Wire spacing (m)", &fWSpac }, { "TDC resolution (s/chan)", &fTDCRes }, { "Drift Velocity (m/s) ", &fDriftVel }, { "Max gap in cluster", &fNMaxGap, kInt }, { "Min TDC raw time", &fMinTime, kInt }, { "Max TDC raw time", &fMaxTime, kInt }, { 0 } }; DebugPrint( list ); } #endif fIsInit = true; return kOK; } //_____________________________________________________________________________ Int_t OldVDCPlane::ReadDatabase( const TDatime& date ) { // Wrapper around actual database reader. Using a wrapper makes it much // to close the input file in case of an error. FILE* fi = OpenFile( date ); if( !fi ) return kFileError; Int_t ret = DoReadDatabase( fi, date ); fclose(fi); return ret; } //_____________________________________________________________________________ Int_t OldVDCPlane::DefineVariables( EMode mode ) { // initialize global variables if( mode == kDefine && fIsSetup ) return kOK; fIsSetup = ( mode == kDefine ); // Register variables in global list RVarDef vars[] = { { "nhit", "Number of hits", "GetNHits()" }, { "wire", "Active wire numbers", "fHits.OldVDCHit.GetWireNum()" }, { "rawtime","Raw TDC values of wires", "fHits.OldVDCHit.fRawTime" }, { "time", "TDC values of active wires", "fHits.OldVDCHit.fTime" }, { "dist", "Drift distances", "fHits.OldVDCHit.fDist" }, { "ddist", "Drft dist uncertainty", "fHits.OldVDCHit.fdDist" }, { "trdist", "Dist. from track", "fHits.OldVDCHit.ftrDist" }, { "nclust", "Number of clusters", "GetNClusters()" }, { "clsiz", "Cluster sizes", "fClusters.OldVDCCluster.fSize" }, { "clpivot","Cluster pivot wire num", "fClusters.OldVDCCluster.GetPivotWireNum()" }, { "clpos", "Cluster intercepts (m)", "fClusters.OldVDCCluster.fInt" }, { "slope", "Cluster best slope", "fClusters.OldVDCCluster.fSlope" }, { "lslope", "Cluster local (fitted) slope","fClusters.OldVDCCluster.fLocalSlope" }, { "t0", "Timing offset (s)", "fClusters.OldVDCCluster.fT0" }, { "sigsl", "Cluster slope error", "fClusters.OldVDCCluster.fSigmaSlope" }, { "sigpos", "Cluster position error (m)", "fClusters.OldVDCCluster.fSigmaInt" }, { "sigt0", "Timing offset error (s)", "fClusters.OldVDCCluster.fSigmaT0" }, { "clchi2", "Cluster chi2", "fClusters.OldVDCCluster.fChi2" }, { "clndof", "Cluster NDoF", "fClusters.OldVDCCluster.fNDoF" }, { "cltcor", "Cluster Time correction", "fClusters.OldVDCCluster.fTimeCorrection" }, { 0 } }; return DefineVarsFromList( vars, mode ); } //_____________________________________________________________________________ OldVDCPlane::~OldVDCPlane() { // Destructor. if( fIsSetup ) RemoveVariables(); delete fWires; delete fHits; delete fClusters; delete fTTDConv; // delete [] fTable; } //_____________________________________________________________________________ void OldVDCPlane::Clear( Option_t* opt ) { // Clears the contents of the and hits and clusters THaSubDetector::Clear(opt); fNWiresHit = 0; fHits->Clear(); fClusters->Clear(); } //_____________________________________________________________________________ Int_t OldVDCPlane::Decode( const THaEvData& evData) { // Converts the raw data into hit information // Assumes channels & wires are numbered in order // TODO: Make sure the wires are numbered in order, even if the channels // aren't if (!evData.IsPhysicsTrigger()) return -1; // the event's T0-shift, due to the trigger-type // only an issue when adding in un-retimed trigger types Double_t evtT0=0; if ( fglTrg && fglTrg->Decode(evData)==kOK ) evtT0 = fglTrg->TimeOffset(); Int_t nextHit = 0; bool only_fastest_hit, no_negative; if( fVDC ) { // If true, add only the first (earliest) hit for each wire only_fastest_hit = fVDC->TestBit(OldVDC::kOnlyFastest); // If true, ignore negativ drift times completely no_negative = fVDC->TestBit(OldVDC::kIgnoreNegDrift); } else only_fastest_hit = no_negative = false; // Loop over all detector modules for this wire plane for (Int_t i = 0; i < fDetMap->GetSize(); i++) { THaDetMap::Module * d = fDetMap->GetModule(i); // Get number of channels with hits Int_t nChan = evData.GetNumChan(d->crate, d->slot); for (Int_t chNdx = 0; chNdx < nChan; chNdx++) { // Use channel index to loop through channels that have hits Int_t chan = evData.GetNextChan(d->crate, d->slot, chNdx); if (chan < d->lo || chan > d->hi) continue; //Not part of this detector // Wire numbers count up in the order in which channels are defined // in the detector map. That order may be forward or reverse, e.g. // forward: lo hi first = 0 95 1 --> channels 0..95 -> wire# = 1...96 // reverse: lo hi first = 95 0 1 --> channels 0..95 -> wire# = 96...1 Int_t wireNum = d->first + ((d->reverse) ? d->hi - chan : chan - d->lo); OldVDCWire* wire = GetWire(wireNum); if( !wire || wire->GetFlag() != 0 ) continue; // Get number of hits for this channel and loop through hits Int_t nHits = evData.GetNumHits(d->crate, d->slot, chan); Int_t max_data = -1; Double_t toff = wire->GetTOffset(); for (Int_t hit = 0; hit < nHits; hit++) { // Now get the TDC data for this hit Int_t data = evData.GetData(d->crate, d->slot, chan, hit); // Convert the TDC value to the drift time. // Being perfectionist, we apply a 1/2 channel correction to the raw // TDC data to compensate for the fact that the TDC truncates, not // rounds, the data. Double_t xdata = static_cast<Double_t>(data) + 0.5; Double_t time = fTDCRes * (toff - xdata) - evtT0; // If requested, ignore hits with negative drift times // (due to noise or miscalibration). Use with care. // If only fastest hit requested, find maximum TDC value and record the // hit after the hit loop is done (see below). // Otherwise just record all hits. if( !no_negative || time > 0.0 ) { if( only_fastest_hit ) { if( data > max_data ) max_data = data; } else new( (*fHits)[nextHit++] ) OldVDCHit( wire, data, time ); } } // End hit loop // If we are only interested in the hit with the largest TDC value // (shortest drift time), it is recorded here. if( only_fastest_hit && max_data>0 ) { Double_t xdata = static_cast<Double_t>(max_data) + 0.5; Double_t time = fTDCRes * (toff - xdata) - evtT0; new( (*fHits)[nextHit++] ) OldVDCHit( wire, max_data, time ); } } // End channel index loop } // End slot loop // Sort the hits in order of increasing wire number and (for the same wire // number) increasing time (NOT rawtime) fHits->Sort(); #ifdef WITH_DEBUG if ( fDebug > 3 ) { cout << endl << "VDC plane " << GetPrefix() << endl; int ncol=4; for (int i=0; i<ncol; i++) { cout << " Wire TDC "; } cout << endl; for (int i=0; i<(nextHit+ncol-1)/ncol; i++ ) { for (int c=0; c<ncol; c++) { int ind = c*nextHit/ncol+i; if (ind < nextHit) { OldVDCHit* hit = static_cast<OldVDCHit*>(fHits->At(ind)); cout << " " << setw(3) << hit->GetWireNum() << " " << setw(5) << hit->GetRawTime() << " "; } else { // cout << endl; break; } } cout << endl; } } #endif return 0; } //_____________________________________________________________________________ Int_t OldVDCPlane::FindClusters() { // Reconstruct clusters in a VDC plane // Assumes that the wires are numbered such that increasing wire numbers // correspond to decreasing physical position. // Ignores possibility of overlapping clusters bool hard_cut = false, soft_cut = false; if( fVDC ) { hard_cut = fVDC->TestBit(OldVDC::kHardTDCcut); soft_cut = fVDC->TestBit(OldVDC::kSoftTDCcut); } Double_t maxdist = 0.0; if( soft_cut ) { maxdist = 0.5*static_cast<OldVDCUVPlane*>(GetParent())->GetSpacing(); if( maxdist == 0.0 ) soft_cut = false; } Int_t pwireNum = -10; // Previous wire number Int_t wireNum = 0; // Current wire number Int_t ndif = 0; // Difference between wire numbers Int_t nHits = GetNHits(); // Number of hits in the plane OldVDCCluster* clust = nullptr; // Current cluster OldVDCHit* hit; // current hit // Int_t minTime = 0; // Smallest TDC time for a given cluster // OldVDCHit * minHit = nullptr; // Hit with the smallest TDC time for // a given cluster // const Double_t sqrt2 = 0.707106781186547462; Int_t nextClust = GetNClusters(); // Should be zero for ( int i = 0; i < nHits; i++ ) { //Loop through all TDC hits if( !(hit = GetHit(i))) continue; // Time within sanity cuts? if( hard_cut ) { Double_t rawtime = hit->GetRawTime(); if( rawtime < fMinTime || rawtime > fMaxTime) continue; } if( soft_cut ) { Double_t ratio = hit->GetTime() * fDriftVel / maxdist; if( ratio < -0.5 || ratio > 1.5 ) continue; } wireNum = hit->GetWire()->GetNum(); // Ignore multiple hits per wire if ( wireNum == pwireNum ) continue; // Keep track of how many wire were hit fNWiresHit++; ndif = wireNum - pwireNum; if (ndif < 0) { // Scream Bloody Murder Error(Here("FindCluster"),"Wire ordering error at wire numbers %d %d. " "Call expert.", pwireNum, wireNum ); fClusters->Remove(clust); return GetNClusters(); } pwireNum = wireNum; if ( ndif > fNMaxGap+1 ) { // Found a new cluster if (clust) // Estimate the track parameters for this cluster // (Pivot, intercept, and slope) clust->EstTrackParameters(); // Make a new OldVDCCluster (using space from fCluster array) clust = new ( (*fClusters)[nextClust++] ) OldVDCCluster(this); } //Add hit to the cluster clust->AddHit(hit); } // End looping through hits // Estimate track parameters for the last cluster found if (clust) clust->EstTrackParameters(); return GetNClusters(); // return the number of clusters found } //_____________________________________________________________________________ Int_t OldVDCPlane::FitTracks() { // Fit tracks to cluster positions and drift distances. OldVDCCluster* clust; Int_t nClust = GetNClusters(); for (int i = 0; i < nClust; i++) { if( !(clust = static_cast<OldVDCCluster*>( (*fClusters)[i] ))) continue; // Convert drift times to distances. // The conversion algorithm is determined at wire initialization time, // i.e. currently in the ReadDatabase() function of this class. // Current best estimates of the track parameters will be passed to // the converter. clust->ConvertTimeToDist(); // Fit drift distances to get intercept, slope. clust->FitTrack(); } return 0; } //_____________________________________________________________________________ void OldVDCPlane::SetNMaxGap( Int_t val ) { if( val < 0 || val > 2 ) { Error( Here("SetNMaxGap"), "Invalid max_gap = %d, must be betwwen 0 and 2.", val ); return; } fNMaxGap = val; SetBit(kMaxGapSet); } //_____________________________________________________________________________ void OldVDCPlane::SetMinTime( Int_t val ) { if( val < 0 || val > 4095 ) { Error( Here("SetMinTime"), "Invalid min_time = %d, must be betwwen 0 and 4095.", val ); return; } fMinTime = val; SetBit(kMinTimeSet); } //_____________________________________________________________________________ void OldVDCPlane::SetMaxTime( Int_t val ) { if( val < 1 || val > 4096 ) { Error( Here("SetMaxTime"), "Invalid max_time = %d. Must be between 1 and 4096.", val ); return; } fMaxTime = val; SetBit(kMaxTimeSet); } //_____________________________________________________________________________ void OldVDCPlane::SetTDCRes( Double_t val ) { if( val < 0 || val > 1e-6 ) { Error( Here("SetTDCRes"), "Nonsense TDC resolution = %8.1le s/channel.", val ); return; } fTDCRes = val; SetBit(kTDCResSet); } /////////////////////////////////////////////////////////////////////////////// ClassImp(OldVDCPlane)
#include "pch.h" #include "db.h" namespace fourdb { db::db(const std::string& filePath) : m_db(nullptr) { int rc = sqlite3_open(filePath.c_str(), &m_db); if (rc != SQLITE_OK) throw fourdberr(rc, m_db); } db::~db() { if (m_db != nullptr) { int rc = sqlite3_close(m_db); (void)rc; // release build assert(rc == SQLITE_OK); } } std::shared_ptr<dbreader> db::execReader(const std::wstring& sql, const paramap& params) { std::wstring fullSql = applyParams(sql, params); auto reader = std::make_shared<dbreader>(m_db, fullSql); return reader; } int db::execSql(const std::wstring& sql, const paramap& params) { int rowCount = 0; { auto reader = execReader(sql, params); while (reader->read()) { ++rowCount; } } return rowCount > 0 ? rowCount : execScalarInt32(L"SELECT changes()").value(); } std::optional<int> db::execScalarInt32(const std::wstring& sql, const paramap& params) { auto reader = execReader(sql, params); if (reader->read()) return reader->getInt32(0); else return std::nullopt; } std::optional<int64_t> db::execScalarInt64(const std::wstring& sql, const paramap& params) { auto reader = execReader(sql, params); if (reader->read()) return reader->getInt64(0); else return std::nullopt; } std::optional<std::wstring> db::execScalarString(const std::wstring& sql, const paramap& params) { auto reader = execReader(sql, params); if (reader->read()) return reader->getString(0); else return std::nullopt; } int64_t db::execInsert(const std::wstring& sql, const paramap& params) { execSql(sql, params); return execScalarInt64(L"select last_insert_rowid()").value(); } std::wstring db::applyParams(const std::wstring& sql, const paramap& params) { std::wstring retVal = sql; for (const auto& it : params) replace(retVal, it.first, it.second.toSqlLiteral()); return retVal; } }
#include <boost/test/unit_test.hpp> #include "init.h" #include "main.h" #include "uint256.h" #include "util.h" #include "wallet.h" extern void SHA256Transform(void* pstate, void* pinput, const void* pinit); BOOST_AUTO_TEST_SUITE(miner_tests) static struct { unsigned char extranonce; unsigned int nonce; } blockinfo[] = { {4, 0xa4ad9f65}, {2, 0x15cf2b27}, {1, 0x037620ac}, {1, 0x700d9c54}, {2, 0xce79f74f}, {2, 0x52d9c194}, {1, 0x77bc3efc}, {2, 0xbb62c5e8}, {2, 0x83ff997a}, {1, 0x48b984ee}, {1, 0xef925da0}, {2, 0x680d2979}, {2, 0x08953af7}, {1, 0x087dd553}, {2, 0x210e2818}, {2, 0xdfffcdef}, {1, 0xeea1b209}, {2, 0xba4a8943}, {1, 0xa7333e77}, {1, 0x344f3e2a}, {3, 0xd651f08e}, {2, 0xeca3957f}, {2, 0xca35aa49}, {1, 0x6bb2065d}, {2, 0x0170ee44}, {1, 0x6e12f4aa}, {2, 0x43f4f4db}, {2, 0x279c1c44}, {2, 0xb5a50f10}, {2, 0xb3902841}, {2, 0xd198647e}, {2, 0x6bc40d88}, {1, 0x633a9a1c}, {2, 0x9a722ed8}, {2, 0x55580d10}, {1, 0xd65022a1}, {2, 0xa12ffcc8}, {1, 0x75a6a9c7}, {2, 0xfb7c80b7}, {1, 0xe8403e6c}, {1, 0xe34017a0}, {3, 0x659e177b}, {2, 0xba5c40bf}, {5, 0x022f11ef}, {1, 0xa9ab516a}, {5, 0xd0999ed4}, {1, 0x37277cb3}, {1, 0x830f735f}, {1, 0xc6e3d947}, {2, 0x824a0c1b}, {1, 0x99962416}, {1, 0x75336f63}, {1, 0xaacf0fea}, {1, 0xd6531aec}, {5, 0x7afcf541}, {5, 0x9d6fac0d}, {1, 0x4cf5c4df}, {1, 0xabe0f2a0}, {6, 0x4a3dac18}, {2, 0xf265febe}, {2, 0x1bc9f23f}, {1, 0xad49ab71}, {1, 0x9f2d8923}, {1, 0x15acb65d}, {2, 0xd1cecb52}, {2, 0xf856808b}, {1, 0x0fa96e29}, {1, 0xe063ecbc}, {1, 0x78d926c6}, {5, 0x3e38ad35}, {5, 0x73901915}, {1, 0x63424be0}, {1, 0x6d6b0a1d}, {2, 0x888ba681}, {2, 0xe96b0714}, {1, 0xb7fcaa55}, {2, 0x19c106eb}, {1, 0x5aa13484}, {2, 0x5bf4c2f3}, {2, 0x94d401dd}, {1, 0xa9bc23d9}, {1, 0x3a69c375}, {1, 0x56ed2006}, {5, 0x85ba6dbd}, {1, 0xfd9b2000}, {1, 0x2b2be19a}, {1, 0xba724468}, {1, 0x717eb6e5}, {1, 0x70de86d9}, {1, 0x74e23a42}, {1, 0x49e92832}, {2, 0x6926dbb9}, {0, 0x64452497}, {1, 0x54306d6f}, {2, 0x97ebf052}, {2, 0x55198b70}, {2, 0x03fe61f0}, {1, 0x98f9e67f}, {1, 0xc0842a09}, {1, 0xdfed39c5}, {1, 0x3144223e}, {1, 0xb3d12f84}, {1, 0x7366ceb7}, {5, 0x6240691b}, {2, 0xd3529b57}, {1, 0xf4cae3b1}, {1, 0x5b1df222}, {1, 0xa16a5c70}, {2, 0xbbccedc6}, {2, 0xfe38d0ef}, }; // NOTE: These tests rely on CreateNewBlock doing its own self-validation! BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) { CReserveKey reservekey(pwalletMain); CBlockTemplate *pblocktemplate; CTransaction tx; CScript script; uint256 hash; // Simple block creation, nothing special yet: BOOST_CHECK(pblocktemplate = CreateNewBlockWithKey(reservekey)); // We can't make transactions until we have inputs // Therefore, load 100 blocks :) std::vector<CTransaction*>txFirst; for (unsigned int i = 0; i < sizeof(blockinfo)/sizeof(*blockinfo); ++i) { CBlock *pblock = &pblocktemplate->block; // pointer for convenience pblock->nVersion = 1; pblock->nTime = pindexBest->GetMedianTimePast()+1; pblock->vtx[0].vin[0].scriptSig = CScript(); pblock->vtx[0].vin[0].scriptSig.push_back(blockinfo[i].extranonce); pblock->vtx[0].vin[0].scriptSig.push_back(pindexBest->nHeight); pblock->vtx[0].vout[0].scriptPubKey = CScript(); if (txFirst.size() < 2) txFirst.push_back(new CTransaction(pblock->vtx[0])); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); pblock->nNonce = blockinfo[i].nonce; CValidationState state; BOOST_CHECK(ProcessBlock(state, NULL, pblock)); BOOST_CHECK(state.IsValid()); pblock->hashPrevBlock = pblock->GetHash(); } delete pblocktemplate; // Just to make sure we can still make simple blocks BOOST_CHECK(pblocktemplate = CreateNewBlockWithKey(reservekey)); // block sigops > limit: 1000 CHECKMULTISIG + 1 tx.vin.resize(1); // NOTE: OP_NOP is used to force 20 SigOps for the CHECKMULTISIG tx.vin[0].scriptSig = CScript() << OP_0 << OP_0 << OP_0 << OP_NOP << OP_CHECKMULTISIG << OP_1; tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vin[0].prevout.n = 0; tx.vout.resize(1); tx.vout[0].nValue = 5000000000LL; for (unsigned int i = 0; i < 1001; ++i) { tx.vout[0].nValue -= 1000000; hash = tx.GetHash(); mempool.addUnchecked(hash, tx); tx.vin[0].prevout.hash = hash; } BOOST_CHECK(pblocktemplate = CreateNewBlockWithKey(reservekey)); delete pblocktemplate; mempool.clear(); // block size > limit tx.vin[0].scriptSig = CScript(); // 18 * (520char + DROP) + OP_1 = 9433 bytes std::vector<unsigned char> vchData(520); for (unsigned int i = 0; i < 18; ++i) tx.vin[0].scriptSig << vchData << OP_DROP; tx.vin[0].scriptSig << OP_1; tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vout[0].nValue = 5000000000LL; for (unsigned int i = 0; i < 128; ++i) { tx.vout[0].nValue -= 10000000; hash = tx.GetHash(); mempool.addUnchecked(hash, tx); tx.vin[0].prevout.hash = hash; } BOOST_CHECK(pblocktemplate = CreateNewBlockWithKey(reservekey)); delete pblocktemplate; mempool.clear(); // orphan in mempool hash = tx.GetHash(); mempool.addUnchecked(hash, tx); BOOST_CHECK(pblocktemplate = CreateNewBlockWithKey(reservekey)); delete pblocktemplate; mempool.clear(); // child with higher priority than parent tx.vin[0].scriptSig = CScript() << OP_1; tx.vin[0].prevout.hash = txFirst[1]->GetHash(); tx.vout[0].nValue = 4900000000LL; hash = tx.GetHash(); mempool.addUnchecked(hash, tx); tx.vin[0].prevout.hash = hash; tx.vin.resize(2); tx.vin[1].scriptSig = CScript() << OP_1; tx.vin[1].prevout.hash = txFirst[0]->GetHash(); tx.vin[1].prevout.n = 0; tx.vout[0].nValue = 5900000000LL; hash = tx.GetHash(); mempool.addUnchecked(hash, tx); BOOST_CHECK(pblocktemplate = CreateNewBlockWithKey(reservekey)); delete pblocktemplate; mempool.clear(); // coinbase in mempool tx.vin.resize(1); tx.vin[0].prevout.SetNull(); tx.vin[0].scriptSig = CScript() << OP_0 << OP_1; tx.vout[0].nValue = 0; hash = tx.GetHash(); mempool.addUnchecked(hash, tx); BOOST_CHECK(pblocktemplate = CreateNewBlockWithKey(reservekey)); delete pblocktemplate; mempool.clear(); // invalid (pre-p2sh) txn in mempool tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vin[0].prevout.n = 0; tx.vin[0].scriptSig = CScript() << OP_1; tx.vout[0].nValue = 4900000000LL; script = CScript() << OP_0; tx.vout[0].scriptPubKey.SetDestination(script.GetID()); hash = tx.GetHash(); mempool.addUnchecked(hash, tx); tx.vin[0].prevout.hash = hash; tx.vin[0].scriptSig = CScript() << (std::vector<unsigned char>)script; tx.vout[0].nValue -= 1000000; hash = tx.GetHash(); mempool.addUnchecked(hash,tx); BOOST_CHECK(pblocktemplate = CreateNewBlockWithKey(reservekey)); delete pblocktemplate; mempool.clear(); // double spend txn pair in mempool tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vin[0].scriptSig = CScript() << OP_1; tx.vout[0].nValue = 4900000000LL; tx.vout[0].scriptPubKey = CScript() << OP_1; hash = tx.GetHash(); mempool.addUnchecked(hash, tx); tx.vout[0].scriptPubKey = CScript() << OP_2; hash = tx.GetHash(); mempool.addUnchecked(hash, tx); BOOST_CHECK(pblocktemplate = CreateNewBlockWithKey(reservekey)); delete pblocktemplate; mempool.clear(); // subsidy changing int nHeight = pindexBest->nHeight; pindexBest->nHeight = 209999; BOOST_CHECK(pblocktemplate = CreateNewBlockWithKey(reservekey)); delete pblocktemplate; pindexBest->nHeight = 500000; BOOST_CHECK(pblocktemplate = CreateNewBlockWithKey(reservekey)); delete pblocktemplate; pindexBest->nHeight = nHeight; } BOOST_AUTO_TEST_CASE(sha256transform_equality) { unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; // unsigned char pstate[32]; unsigned char pinput[64]; int i; for (i = 0; i < 32; i++) { pinput[i] = i; pinput[i+32] = 0; } uint256 hash; SHA256Transform(&hash, pinput, pSHA256InitState); BOOST_TEST_MESSAGE(hash.GetHex()); uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3"); BOOST_CHECK(hash == hash_reference); } BOOST_AUTO_TEST_SUITE_END()
// // OSDictionary.hpp // RealtekCardReader // // Created by FireWolf on 8/25/21. // #ifndef OSDictionary_hpp #define OSDictionary_hpp #include <libkern/c++/OSDictionary.h> static inline bool OSDictionaryAddStringToDictionary(OSDictionary* dictionary, const char* key, const char* value) { OSString* v = OSString::withCString(value); if (v == nullptr) { return false; } bool retVal = dictionary->setObject(key, v); v->release(); return retVal; } static inline bool OSDictionaryAddDataToDictionary(OSDictionary* dictionary, const char* key, const void* bytes, IOByteCount length) { OSData* data = OSData::withBytes(bytes, static_cast<UInt32>(length)); if (data == nullptr) { return false; } bool retVal = dictionary->setObject(key, data); data->release(); return retVal; } template <size_t N> static inline bool OSDictionaryAddDataToDictionary(OSDictionary* dictionary, const char* key, const UInt8 (&bytes)[N]) { return OSDictionaryAddDataToDictionary(dictionary, key, bytes, N); } template <typename T> static inline bool OSDictionaryAddIntegerToDictionary(OSDictionary* dictionary, const char* key, T interger) { OSNumber* number = OSNumber::withNumber(interger, sizeof(T) * 8); if (number == nullptr) { return false; } bool retVal = dictionary->setObject(key, number); number->release(); return retVal; } #endif /* OSDictionary_hpp */
// // time_t_timer.cpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <ctime> #include <iostream> struct time_t_traits { // The time type. typedef std::time_t time_type; // The duration type. struct duration_type { duration_type() : value(0) {} duration_type(std::time_t v) : value(v) {} std::time_t value; }; // Get the current time. static time_type now() { return std::time(0); } // Add a duration to a time. static time_type add(const time_type& t, const duration_type& d) { return t + d.value; } // Subtract one time from another. static duration_type subtract(const time_type& t1, const time_type& t2) { return duration_type(t1 - t2); } // Test whether one time is less than another. static bool less_than(const time_type& t1, const time_type& t2) { return t1 < t2; } // Convert to POSIX duration type. static boost::posix_time::time_duration to_posix_duration( const duration_type& d) { return boost::posix_time::seconds(d.value); } }; typedef boost::asio::basic_deadline_timer< std::time_t, time_t_traits> time_t_timer; void handle_timeout(const boost::system::error_code&) { std::cout << "handle_timeout\n"; } int main() { try { boost::asio::io_service io_service; time_t_timer timer(io_service); timer.expires_from_now(5); std::cout << "Starting synchronous wait\n"; timer.wait(); std::cout << "Finished synchronous wait\n"; timer.expires_from_now(5); std::cout << "Starting asynchronous wait\n"; timer.async_wait(&handle_timeout); io_service.run(); std::cout << "Finished asynchronous wait\n"; } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/callback_helpers.h" #include "base/message_loop/message_loop.h" #include "media/base/gmock_callback_support.h" #include "media/base/mock_filters.h" #include "media/base/test_helpers.h" #include "media/filters/decoder_stream.h" #include "media/filters/fake_demuxer_stream.h" #include "media/filters/fake_video_decoder.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; using ::testing::AnyNumber; using ::testing::Assign; using ::testing::Invoke; using ::testing::InvokeWithoutArgs; using ::testing::NiceMock; using ::testing::Return; using ::testing::SaveArg; static const int kNumConfigs = 4; static const int kNumBuffersInOneConfig = 5; // Use anonymous namespace here to prevent the actions to be defined multiple // times across multiple test files. Sadly we can't use static for them. namespace { ACTION_P3(ExecuteCallbackWithVerifier, decryptor, done_cb, verifier) { // verifier must be called first since |done_cb| call will invoke it as well. verifier->RecordACalled(); arg0.Run(decryptor, done_cb); } ACTION_P(ReportCallback, verifier) { verifier->RecordBCalled(); } } // namespace namespace media { struct VideoFrameStreamTestParams { VideoFrameStreamTestParams(bool is_encrypted, int decoding_delay, int parallel_decoding) : is_encrypted(is_encrypted), decoding_delay(decoding_delay), parallel_decoding(parallel_decoding) {} bool is_encrypted; int decoding_delay; int parallel_decoding; }; class VideoFrameStreamTest : public testing::Test, public testing::WithParamInterface<VideoFrameStreamTestParams> { public: VideoFrameStreamTest() : demuxer_stream_(new FakeDemuxerStream(kNumConfigs, kNumBuffersInOneConfig, GetParam().is_encrypted)), decryptor_(new NiceMock<MockDecryptor>()), decoder1_(new FakeVideoDecoder( GetParam().decoding_delay, GetParam().parallel_decoding, base::Bind(&VideoFrameStreamTest::OnBytesDecoded, base::Unretained(this)))), decoder2_(new FakeVideoDecoder( GetParam().decoding_delay, GetParam().parallel_decoding, base::Bind(&VideoFrameStreamTest::OnBytesDecoded, base::Unretained(this)))), decoder3_(new FakeVideoDecoder( GetParam().decoding_delay, GetParam().parallel_decoding, base::Bind(&VideoFrameStreamTest::OnBytesDecoded, base::Unretained(this)))), is_initialized_(false), num_decoded_frames_(0), pending_initialize_(false), pending_read_(false), pending_reset_(false), pending_stop_(false), num_decoded_bytes_unreported_(0), has_no_key_(false) { ScopedVector<VideoDecoder> decoders; decoders.push_back(decoder1_); decoders.push_back(decoder2_); decoders.push_back(decoder3_); video_frame_stream_.reset(new VideoFrameStream( message_loop_.message_loop_proxy(), decoders.Pass(), new MediaLog())); // Decryptor can only decrypt (not decrypt-and-decode) so that // DecryptingDemuxerStream will be used. EXPECT_CALL(*decryptor_, InitializeVideoDecoder(_, _)) .WillRepeatedly(RunCallback<1>(false)); EXPECT_CALL(*decryptor_, Decrypt(_, _, _)) .WillRepeatedly(Invoke(this, &VideoFrameStreamTest::Decrypt)); } ~VideoFrameStreamTest() { // Check that the pipeline statistics callback was fired correctly. EXPECT_EQ(num_decoded_bytes_unreported_, 0); is_initialized_ = false; decoder1_ = NULL; decoder2_ = NULL; decoder3_ = NULL; video_frame_stream_.reset(); message_loop_.RunUntilIdle(); DCHECK(!pending_initialize_); DCHECK(!pending_read_); DCHECK(!pending_reset_); DCHECK(!pending_stop_); } MOCK_METHOD1(OnNewSpliceBuffer, void(base::TimeDelta)); MOCK_METHOD1(SetDecryptorReadyCallback, void(const media::DecryptorReadyCB&)); MOCK_METHOD1(DecryptorSet, void(bool)); void OnStatistics(const PipelineStatistics& statistics) { num_decoded_bytes_unreported_ -= statistics.video_bytes_decoded; } void OnBytesDecoded(int count) { num_decoded_bytes_unreported_ += count; } void OnInitialized(bool success) { DCHECK(!pending_read_); DCHECK(!pending_reset_); DCHECK(pending_initialize_); pending_initialize_ = false; is_initialized_ = success; if (!success) { decoder1_ = NULL; decoder2_ = NULL; decoder3_ = NULL; } } void InitializeVideoFrameStream() { pending_initialize_ = true; video_frame_stream_->Initialize( demuxer_stream_.get(), base::Bind(&VideoFrameStreamTest::OnInitialized, base::Unretained(this)), base::Bind(&VideoFrameStreamTest::SetDecryptorReadyCallback, base::Unretained(this)), base::Bind(&VideoFrameStreamTest::OnStatistics, base::Unretained(this))); message_loop_.RunUntilIdle(); } // Fake Decrypt() function used by DecryptingDemuxerStream. It does nothing // but removes the DecryptConfig to make the buffer unencrypted. void Decrypt(Decryptor::StreamType stream_type, const scoped_refptr<DecoderBuffer>& encrypted, const Decryptor::DecryptCB& decrypt_cb) { DCHECK(encrypted->decrypt_config()); if (has_no_key_) { decrypt_cb.Run(Decryptor::kNoKey, NULL); return; } DCHECK_EQ(stream_type, Decryptor::kVideo); scoped_refptr<DecoderBuffer> decrypted = DecoderBuffer::CopyFrom(encrypted->data(), encrypted->data_size()); if (encrypted->is_key_frame()) decrypted->set_is_key_frame(true); decrypted->set_timestamp(encrypted->timestamp()); decrypted->set_duration(encrypted->duration()); decrypt_cb.Run(Decryptor::kSuccess, decrypted); } // Callback for VideoFrameStream::Read(). void FrameReady(VideoFrameStream::Status status, const scoped_refptr<VideoFrame>& frame) { DCHECK(pending_read_); frame_read_ = frame; last_read_status_ = status; if (frame.get() && !frame->end_of_stream()) num_decoded_frames_++; pending_read_ = false; } void FrameReadyHoldDemuxer(VideoFrameStream::Status status, const scoped_refptr<VideoFrame>& frame) { FrameReady(status, frame); } void OnReset() { DCHECK(!pending_read_); DCHECK(pending_reset_); pending_reset_ = false; } void ReadOneFrame() { frame_read_ = NULL; pending_read_ = true; video_frame_stream_->Read(base::Bind( &VideoFrameStreamTest::FrameReady, base::Unretained(this))); message_loop_.RunUntilIdle(); } void ReadUntilPending() { do { ReadOneFrame(); } while (!pending_read_); } void ReadAllFrames() { do { ReadOneFrame(); } while (frame_read_.get() && !frame_read_->end_of_stream()); const int total_num_frames = kNumConfigs * kNumBuffersInOneConfig; DCHECK_EQ(num_decoded_frames_, total_num_frames); } enum PendingState { NOT_PENDING, DEMUXER_READ_NORMAL, DEMUXER_READ_CONFIG_CHANGE, SET_DECRYPTOR, DECRYPTOR_NO_KEY, DECODER_INIT, DECODER_REINIT, DECODER_DECODE, DECODER_RESET }; void ExpectDecryptorNotification() { EXPECT_CALL(*this, SetDecryptorReadyCallback(_)) .WillRepeatedly(ExecuteCallbackWithVerifier( decryptor_.get(), base::Bind(&VideoFrameStreamTest::DecryptorSet, base::Unretained(this)), &verifier_)); EXPECT_CALL(*this, DecryptorSet(true)) .WillRepeatedly(ReportCallback(&verifier_)); } void EnterPendingState(PendingState state) { EnterPendingState(state, decoder1_); } void EnterPendingState(PendingState state, FakeVideoDecoder* decoder) { DCHECK_NE(state, NOT_PENDING); switch (state) { case DEMUXER_READ_NORMAL: demuxer_stream_->HoldNextRead(); ReadUntilPending(); break; case DEMUXER_READ_CONFIG_CHANGE: demuxer_stream_->HoldNextConfigChangeRead(); ReadUntilPending(); break; case SET_DECRYPTOR: // Hold DecryptorReadyCB. EXPECT_CALL(*this, SetDecryptorReadyCallback(_)) .Times(2); // Initialize will fail because no decryptor is available. InitializeVideoFrameStream(); break; case DECRYPTOR_NO_KEY: ExpectDecryptorNotification(); has_no_key_ = true; ReadOneFrame(); break; case DECODER_INIT: ExpectDecryptorNotification(); decoder->HoldNextInit(); InitializeVideoFrameStream(); break; case DECODER_REINIT: decoder->HoldNextInit(); ReadUntilPending(); break; case DECODER_DECODE: decoder->HoldDecode(); ReadUntilPending(); break; case DECODER_RESET: decoder->HoldNextReset(); pending_reset_ = true; video_frame_stream_->Reset(base::Bind(&VideoFrameStreamTest::OnReset, base::Unretained(this))); message_loop_.RunUntilIdle(); break; case NOT_PENDING: NOTREACHED(); break; } } void SatisfyPendingCallback(PendingState state) { SatisfyPendingCallback(state, decoder1_); } void SatisfyPendingCallback(PendingState state, FakeVideoDecoder* decoder) { DCHECK_NE(state, NOT_PENDING); switch (state) { case DEMUXER_READ_NORMAL: case DEMUXER_READ_CONFIG_CHANGE: demuxer_stream_->SatisfyRead(); break; // These two cases are only interesting to test during // VideoFrameStream destruction. There's no need to satisfy a callback. case SET_DECRYPTOR: case DECRYPTOR_NO_KEY: NOTREACHED(); break; case DECODER_INIT: decoder->SatisfyInit(); break; case DECODER_REINIT: decoder->SatisfyInit(); break; case DECODER_DECODE: decoder->SatisfyDecode(); break; case DECODER_RESET: decoder->SatisfyReset(); break; case NOT_PENDING: NOTREACHED(); break; } message_loop_.RunUntilIdle(); } void Initialize() { EnterPendingState(DECODER_INIT); SatisfyPendingCallback(DECODER_INIT); } void Read() { EnterPendingState(DECODER_DECODE); SatisfyPendingCallback(DECODER_DECODE); } void Reset() { EnterPendingState(DECODER_RESET); SatisfyPendingCallback(DECODER_RESET); } void ReadUntilDecoderReinitialized(FakeVideoDecoder* decoder) { EnterPendingState(DECODER_REINIT, decoder); SatisfyPendingCallback(DECODER_REINIT, decoder); } base::MessageLoop message_loop_; scoped_ptr<VideoFrameStream> video_frame_stream_; scoped_ptr<FakeDemuxerStream> demuxer_stream_; // Use NiceMock since we don't care about most of calls on the decryptor, // e.g. RegisterNewKeyCB(). scoped_ptr<NiceMock<MockDecryptor> > decryptor_; // Three decoders are needed to test that decoder fallback can occur more than // once on a config change. They are owned by |video_frame_stream_|. FakeVideoDecoder* decoder1_; FakeVideoDecoder* decoder2_; FakeVideoDecoder* decoder3_; bool is_initialized_; int num_decoded_frames_; bool pending_initialize_; bool pending_read_; bool pending_reset_; bool pending_stop_; int num_decoded_bytes_unreported_; scoped_refptr<VideoFrame> frame_read_; VideoFrameStream::Status last_read_status_; // Decryptor has no key to decrypt a frame. bool has_no_key_; CallbackPairChecker verifier_; private: DISALLOW_COPY_AND_ASSIGN(VideoFrameStreamTest); }; INSTANTIATE_TEST_CASE_P( Clear, VideoFrameStreamTest, ::testing::Values( VideoFrameStreamTestParams(false, 0, 1), VideoFrameStreamTestParams(false, 3, 1), VideoFrameStreamTestParams(false, 7, 1))); INSTANTIATE_TEST_CASE_P( Encrypted, VideoFrameStreamTest, ::testing::Values( VideoFrameStreamTestParams(true, 7, 1))); INSTANTIATE_TEST_CASE_P( Clear_Parallel, VideoFrameStreamTest, ::testing::Values( VideoFrameStreamTestParams(false, 0, 3), VideoFrameStreamTestParams(false, 2, 3))); TEST_P(VideoFrameStreamTest, Initialization) { Initialize(); } TEST_P(VideoFrameStreamTest, DecoderInitializationFails) { decoder1_->SimulateFailureToInit(); decoder2_->SimulateFailureToInit(); decoder3_->SimulateFailureToInit(); Initialize(); EXPECT_FALSE(is_initialized_); } TEST_P(VideoFrameStreamTest, ReadOneFrame) { Initialize(); Read(); } TEST_P(VideoFrameStreamTest, ReadAllFrames) { Initialize(); ReadAllFrames(); } TEST_P(VideoFrameStreamTest, Read_AfterReset) { Initialize(); Reset(); Read(); Reset(); Read(); } TEST_P(VideoFrameStreamTest, Read_BlockedDemuxer) { Initialize(); demuxer_stream_->HoldNextRead(); ReadOneFrame(); EXPECT_TRUE(pending_read_); int demuxed_buffers = 0; // Pass frames from the demuxer to the VideoFrameStream until the first read // request is satisfied. while (pending_read_) { ++demuxed_buffers; demuxer_stream_->SatisfyReadAndHoldNext(); message_loop_.RunUntilIdle(); } EXPECT_EQ(std::min(GetParam().decoding_delay + 1, kNumBuffersInOneConfig + 1), demuxed_buffers); // At this point the stream is waiting on read from the demuxer, but there is // no pending read from the stream. The stream should be blocked if we try // reading from it again. ReadUntilPending(); demuxer_stream_->SatisfyRead(); message_loop_.RunUntilIdle(); EXPECT_FALSE(pending_read_); } TEST_P(VideoFrameStreamTest, Read_BlockedDemuxerAndDecoder) { // Test applies only when the decoder allows multiple parallel requests. if (GetParam().parallel_decoding == 1) return; Initialize(); demuxer_stream_->HoldNextRead(); decoder1_->HoldDecode(); ReadOneFrame(); EXPECT_TRUE(pending_read_); int demuxed_buffers = 0; // Pass frames from the demuxer to the VideoFrameStream until the first read // request is satisfied, while always keeping one decode request pending. while (pending_read_) { ++demuxed_buffers; demuxer_stream_->SatisfyReadAndHoldNext(); message_loop_.RunUntilIdle(); // Always keep one decode request pending. if (demuxed_buffers > 1) { decoder1_->SatisfySingleDecode(); message_loop_.RunUntilIdle(); } } ReadUntilPending(); EXPECT_TRUE(pending_read_); // Unblocking one decode request should unblock read even when demuxer is // still blocked. decoder1_->SatisfySingleDecode(); message_loop_.RunUntilIdle(); EXPECT_FALSE(pending_read_); // Stream should still be blocked on the demuxer after unblocking the decoder. decoder1_->SatisfyDecode(); ReadUntilPending(); EXPECT_TRUE(pending_read_); // Verify that the stream has returned all frames that have been demuxed, // accounting for the decoder delay. EXPECT_EQ(demuxed_buffers - GetParam().decoding_delay, num_decoded_frames_); // Unblocking the demuxer will unblock the stream. demuxer_stream_->SatisfyRead(); message_loop_.RunUntilIdle(); EXPECT_FALSE(pending_read_); } TEST_P(VideoFrameStreamTest, Read_DuringEndOfStreamDecode) { // Test applies only when the decoder allows multiple parallel requests, and // they are not satisfied in a single batch. if (GetParam().parallel_decoding == 1 || GetParam().decoding_delay != 0) return; Initialize(); decoder1_->HoldDecode(); // Read all of the frames up to end of stream. Since parallel decoding is // enabled, the end of stream buffer will be sent to the decoder immediately, // but we don't satisfy it yet. for (int configuration = 0; configuration < kNumConfigs; configuration++) { for (int frame = 0; frame < kNumBuffersInOneConfig; frame++) { ReadOneFrame(); while (pending_read_) { decoder1_->SatisfySingleDecode(); message_loop_.RunUntilIdle(); } } } // Read() again. The callback must be delayed until the decode completes. ReadOneFrame(); ASSERT_TRUE(pending_read_); // Satisfy decoding of the end of stream buffer. The read should complete. decoder1_->SatisfySingleDecode(); message_loop_.RunUntilIdle(); ASSERT_FALSE(pending_read_); EXPECT_EQ(last_read_status_, VideoFrameStream::OK); // The read output should indicate end of stream. ASSERT_TRUE(frame_read_.get()); EXPECT_TRUE(frame_read_->end_of_stream()); } // No Reset() before initialization is successfully completed. TEST_P(VideoFrameStreamTest, Reset_AfterInitialization) { Initialize(); Reset(); Read(); } TEST_P(VideoFrameStreamTest, Reset_DuringReinitialization) { Initialize(); EnterPendingState(DECODER_REINIT); // VideoDecoder::Reset() is not called when we reset during reinitialization. pending_reset_ = true; video_frame_stream_->Reset( base::Bind(&VideoFrameStreamTest::OnReset, base::Unretained(this))); SatisfyPendingCallback(DECODER_REINIT); Read(); } TEST_P(VideoFrameStreamTest, Reset_AfterReinitialization) { Initialize(); EnterPendingState(DECODER_REINIT); SatisfyPendingCallback(DECODER_REINIT); Reset(); Read(); } TEST_P(VideoFrameStreamTest, Reset_DuringDemuxerRead_Normal) { Initialize(); EnterPendingState(DEMUXER_READ_NORMAL); EnterPendingState(DECODER_RESET); SatisfyPendingCallback(DEMUXER_READ_NORMAL); SatisfyPendingCallback(DECODER_RESET); Read(); } TEST_P(VideoFrameStreamTest, Reset_DuringDemuxerRead_ConfigChange) { Initialize(); EnterPendingState(DEMUXER_READ_CONFIG_CHANGE); EnterPendingState(DECODER_RESET); SatisfyPendingCallback(DEMUXER_READ_CONFIG_CHANGE); SatisfyPendingCallback(DECODER_RESET); Read(); } TEST_P(VideoFrameStreamTest, Reset_DuringNormalDecoderDecode) { Initialize(); EnterPendingState(DECODER_DECODE); EnterPendingState(DECODER_RESET); SatisfyPendingCallback(DECODER_DECODE); SatisfyPendingCallback(DECODER_RESET); Read(); } TEST_P(VideoFrameStreamTest, Reset_AfterNormalRead) { Initialize(); Read(); Reset(); Read(); } TEST_P(VideoFrameStreamTest, Reset_AfterNormalReadWithActiveSplice) { video_frame_stream_->set_splice_observer(base::Bind( &VideoFrameStreamTest::OnNewSpliceBuffer, base::Unretained(this))); Initialize(); // Send buffers with a splice timestamp, which sets the active splice flag. const base::TimeDelta splice_timestamp = base::TimeDelta(); demuxer_stream_->set_splice_timestamp(splice_timestamp); EXPECT_CALL(*this, OnNewSpliceBuffer(splice_timestamp)).Times(AnyNumber()); Read(); // Issue an explicit Reset() and clear the splice timestamp. Reset(); demuxer_stream_->set_splice_timestamp(kNoTimestamp()); // Ensure none of the upcoming calls indicate they have a splice timestamp. EXPECT_CALL(*this, OnNewSpliceBuffer(_)).Times(0); Read(); } TEST_P(VideoFrameStreamTest, Reset_AfterDemuxerRead_ConfigChange) { Initialize(); EnterPendingState(DEMUXER_READ_CONFIG_CHANGE); SatisfyPendingCallback(DEMUXER_READ_CONFIG_CHANGE); Reset(); Read(); } TEST_P(VideoFrameStreamTest, Reset_AfterEndOfStream) { Initialize(); ReadAllFrames(); Reset(); num_decoded_frames_ = 0; demuxer_stream_->SeekToStart(); ReadAllFrames(); } TEST_P(VideoFrameStreamTest, Reset_DuringNoKeyRead) { Initialize(); EnterPendingState(DECRYPTOR_NO_KEY); Reset(); } // In the following Destroy_* tests, |video_frame_stream_| is destroyed in // VideoFrameStreamTest dtor. TEST_P(VideoFrameStreamTest, Destroy_BeforeInitialization) { } TEST_P(VideoFrameStreamTest, Destroy_DuringSetDecryptor) { if (!GetParam().is_encrypted) { DVLOG(1) << "SetDecryptor test only runs when the stream is encrytped."; return; } EnterPendingState(SET_DECRYPTOR); } TEST_P(VideoFrameStreamTest, Destroy_DuringInitialization) { EnterPendingState(DECODER_INIT); } TEST_P(VideoFrameStreamTest, Destroy_AfterInitialization) { Initialize(); } TEST_P(VideoFrameStreamTest, Destroy_DuringReinitialization) { Initialize(); EnterPendingState(DECODER_REINIT); } TEST_P(VideoFrameStreamTest, Destroy_AfterReinitialization) { Initialize(); EnterPendingState(DECODER_REINIT); SatisfyPendingCallback(DECODER_REINIT); } TEST_P(VideoFrameStreamTest, Destroy_DuringDemuxerRead_Normal) { Initialize(); EnterPendingState(DEMUXER_READ_NORMAL); } TEST_P(VideoFrameStreamTest, Destroy_DuringDemuxerRead_ConfigChange) { Initialize(); EnterPendingState(DEMUXER_READ_CONFIG_CHANGE); } TEST_P(VideoFrameStreamTest, Destroy_DuringNormalDecoderDecode) { Initialize(); EnterPendingState(DECODER_DECODE); } TEST_P(VideoFrameStreamTest, Destroy_AfterNormalRead) { Initialize(); Read(); } TEST_P(VideoFrameStreamTest, Destroy_AfterConfigChangeRead) { Initialize(); EnterPendingState(DEMUXER_READ_CONFIG_CHANGE); SatisfyPendingCallback(DEMUXER_READ_CONFIG_CHANGE); } TEST_P(VideoFrameStreamTest, Destroy_DuringDecoderReinitialization) { Initialize(); EnterPendingState(DECODER_REINIT); } TEST_P(VideoFrameStreamTest, Destroy_DuringNoKeyRead) { Initialize(); EnterPendingState(DECRYPTOR_NO_KEY); } TEST_P(VideoFrameStreamTest, Destroy_DuringReset) { Initialize(); EnterPendingState(DECODER_RESET); } TEST_P(VideoFrameStreamTest, Destroy_AfterReset) { Initialize(); Reset(); } TEST_P(VideoFrameStreamTest, Destroy_DuringRead_DuringReset) { Initialize(); EnterPendingState(DECODER_DECODE); EnterPendingState(DECODER_RESET); } TEST_P(VideoFrameStreamTest, Destroy_AfterRead_DuringReset) { Initialize(); EnterPendingState(DECODER_DECODE); EnterPendingState(DECODER_RESET); SatisfyPendingCallback(DECODER_DECODE); } TEST_P(VideoFrameStreamTest, Destroy_AfterRead_AfterReset) { Initialize(); Read(); Reset(); } TEST_P(VideoFrameStreamTest, DecoderErrorWhenReading) { Initialize(); EnterPendingState(DECODER_DECODE); decoder1_->SimulateError(); message_loop_.RunUntilIdle(); ASSERT_FALSE(pending_read_); ASSERT_EQ(VideoFrameStream::DECODE_ERROR, last_read_status_); } TEST_P(VideoFrameStreamTest, DecoderErrorWhenNotReading) { Initialize(); decoder1_->HoldDecode(); ReadOneFrame(); EXPECT_TRUE(pending_read_); // Satisfy decode requests until we get the first frame out. while (pending_read_) { decoder1_->SatisfySingleDecode(); message_loop_.RunUntilIdle(); } // Trigger an error in the decoding. decoder1_->SimulateError(); // The error must surface from Read() as DECODE_ERROR. while (last_read_status_ == VideoFrameStream::OK) { ReadOneFrame(); message_loop_.RunUntilIdle(); EXPECT_FALSE(pending_read_); } EXPECT_EQ(VideoFrameStream::DECODE_ERROR, last_read_status_); } TEST_P(VideoFrameStreamTest, FallbackDecoderSelectedOnFailureToReinitialize) { Initialize(); decoder1_->SimulateFailureToInit(); ReadUntilDecoderReinitialized(decoder1_); ReadAllFrames(); } TEST_P(VideoFrameStreamTest, FallbackDecoderSelectedOnFailureToReinitialize_Twice) { Initialize(); decoder1_->SimulateFailureToInit(); ReadUntilDecoderReinitialized(decoder1_); ReadOneFrame(); decoder2_->SimulateFailureToInit(); ReadUntilDecoderReinitialized(decoder2_); ReadAllFrames(); } TEST_P(VideoFrameStreamTest, DecodeErrorAfterFallbackDecoderSelectionFails) { Initialize(); decoder1_->SimulateFailureToInit(); decoder2_->SimulateFailureToInit(); decoder3_->SimulateFailureToInit(); ReadUntilDecoderReinitialized(decoder1_); // The error will surface from Read() as DECODE_ERROR. while (last_read_status_ == VideoFrameStream::OK) { ReadOneFrame(); message_loop_.RunUntilIdle(); EXPECT_FALSE(pending_read_); } EXPECT_EQ(VideoFrameStream::DECODE_ERROR, last_read_status_); } TEST_P(VideoFrameStreamTest, Destroy_DuringFallbackDecoderSelection) { Initialize(); decoder1_->SimulateFailureToInit(); EnterPendingState(DECODER_REINIT); decoder2_->HoldNextInit(); SatisfyPendingCallback(DECODER_REINIT); } } // namespace media
#include "12.1string2.h" using namespace std; int main() { String s1(" and I am a C++ student."); String s2 = "Please enter your name: "; String s3; cout << s2; cin >> s3; s2 = "My name is " + s3; cout << s2 << ".\n"; s2 = s2 + s1; s2.stringup(); cout << "The string\n" << s2 << "\ncontains " << s2.has('A') << " 'A' characters in it.\n"; s1 = "red"; String rgb[3] = {String(s1), String("green"), String("blue")}; cout << "Enter the name of a primary color for mixing light: "; String ans; bool success = false; while(cin >> ans) { ans.stringlow(); for(int i=0; i< 3; i++) { if(ans == rgb[i]) { cout << "That's right!\n"; success = true; break; } } if (success) break; else cout << "Try again!\n"; } cout << "Bye\n"; return 0; }
#include "huffman.h" #include "ui_huffman.h" #define TR(str) (QString::fromLocal8Bit(str)) //解决中文乱码 huffman::huffman(QWidget *parent) : QWidget(parent), ui(new Ui::huffman) { ui->setupUi(this); setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint); // 禁止最大化按钮 this->setWindowTitle(TR("哈夫曼树")); this->setWindowIcon(QIcon(":/image/image/bg2.jpg")); static QMovie movie(":/image/image/huffman.png"); movie.start(); movie.resized(ui->label->size()); ui->label->setMovie(&movie); } huffman::~huffman() { delete ui; }
/** * Code for calling Quick entrypoints. These are runtime entrypoints * that already existed for supporting the Quick backend. * * Here we might also call some additional entrypoints we have implemented * for the LLVM backend. * * Copyright (C) 2021 Paschalis Mpeis (paschalis.mpeis-AT-gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "hgraph_to_llvm-inl.h" #include "hgraph_to_llvm.h" #include <llvm/Support/raw_ostream.h> #include "art_method.h" #include "asm_arm64.h" #include "asm_arm_thumb.h" #include "class_linker-inl.h" #include "hgraph_to_llvm.h" #include "mcr_cc/analyser.h" #include "mcr_cc/mcr_cc.h" #include "mirror/class_loader.h" #include "mirror/object.h" #include "mirror/string.h" #include "scoped_thread_state_change.h" #include "llvm_macros_irb_.h" using namespace ::llvm; namespace art { namespace LLVM { // llvm_verify_stack_frame_current void HGraphToLLVM::ArtCallVerifyStackFrameCurrent() { VERIFIED_; Type* retTy = irb_->getVoidTy(); artCall(kQuickLLVMVerifyStackFrameCurrent, retTy); } void HGraphToLLVM::ArtCallVerifyArtMethod(Value* art_method) { VERIFIED_; std::vector<Value*> args{ art_method }; std::vector<Type*> params{ irb_->getVoidPointerType() }; Type* retTy = irb_->getJVoidTy(); artCall(kQuickLLVMVerifyArtMethod, retTy, params, args); } void HGraphToLLVM::ArtCallVerifyArtClass(Value* art_class) { VERIFIED_; std::vector<Value*> args{ art_class }; std::vector<Type*> params{ irb_->getVoidPointerType() }; Type* retTy = irb_->getJVoidTy(); artCall(kQuickLLVMVerifyArtClass, retTy, params, args); } void HGraphToLLVM::ArtCallVerifyArtObject(Value* object) { std::vector<Value*> args{ object }; std::vector<Type*> params{ irb_->getVoidPointerType() }; Type* retTy = irb_->getJVoidTy(); artCall(kQuickLLVMVerifyArtObject, retTy, params, args); } /** * @brief Handled a bit specially. * I am sending an extra parameter in comparison to quick, * which is ArtMethod. * * We could have skipped though: * This is because quick has QuickFrame that contains caller and outer. * We have `ShadowFrame` that contains only the caller/referrer. * However, we don't need outer, as outer has different value * with caller probably in inline cases. Since we have disabled inlining * to the call site of LLVM (so we can actually invoke LLVM), we should * be OK. * * Still we are using different entrypoint. * To use quick's entrypoint, we have to do something like: * if (FROM_LLVM()) * outer = caller = LLVM::shadow_frame_->GetMethod(); * * INFO this is may now fixed, as we are setting up ShadowFrame for the LLVM call * * @param irb * @param qpoint * @param caller * @param type_idx * * @return */ // art_llvm_resolve_type Value* HGraphToLLVM::ArtCallResolveType__( QuickEntrypointEnum qpoint, Value* caller, uint32_t type_idx, Value* llvm_bss_slot) { VERIFY_LLVMD(qpoint); std::vector<Value*> args { caller, irb_->getJUnsignedInt(type_idx), llvm_bss_slot }; std::vector<Type*> params { irb_->getVoidPointerType(), irb_->getJIntTy(), irb_->getVoidPointerType()->getPointerTo()}; Type* retTy = irb_->getVoidPointerType(); return artCall(qpoint, retTy, params, args); } /** * from TypeCheckSlowPathARM64: * called by: * - VisitInstanceOf (qpoint: InstanceofNonTrivial) */ // artInstanceOfFromCode Value* HGraphToLLVM::ArtCallInstanceOfNonTrivial( Value* lobj, Value* lclass) { VERIFY_LLVMD3_; std::vector<Value*> args{ lobj, lclass }; std::vector<Type*> params{ 2, irb_->getVoidPointerType() }; Type* retTy = irb_->getJIntTy(); return artCall(kQuickInstanceofNonTrivial, retTy, params, args); } void HGraphToLLVM::ArtCallDeliverException(Value* lexception) { VERIFY_LLVM_; std::vector<Value*> args{ lexception }; std::vector<Type*> params{ irb_->getVoidPointerType() }; Type* retTy = irb_->getJVoidTy(); artCall(kQuickDeliverException, retTy, params, args); } /** * called by: * - CheckInstanceOf (qpoint: CheckInstanceOf) VERIFY_LLVM * * art_quick_check_instance_of */ void HGraphToLLVM::ArtCallCheckInstanceOf(Value* lobj, Value* lclass) { VERIFY_LLVMD2_; std::vector<Value*> args{ lobj, lclass }; std::vector<Type*> params{ 2, irb_->getVoidPointerType() }; Type* retTy = irb_->getJVoidTy(); artCall(kQuickCheckInstanceOf, retTy, params, args); } // art_quick_initialize_static_storage void HGraphToLLVM::ArtCallInitializeStaticStorage(Value* klass) { VERIFY_LLVMD3_; // DONE std::vector<Value*> args{ klass }; std::vector<Type*> params{ irb_->getVoidPointerType() }; Type* retTy = irb_->getJVoidTy(); artCall(kQuickInitializeStaticStorage, retTy, params, args); } // art_quick_alloc_object__ Value* HGraphToLLVM::ArtCallAllocObject__( QuickEntrypointEnum qpoint, Value* klass) { VERIFY_LLVMD3(qpoint); std::vector<Value*> args{ klass }; std::vector<Type*> params{ irb_->getVoidPointerType() }; Type* retTy = irb_->getVoidPointerType(); return artCall(qpoint, retTy, params, args); } // art_quick_alloc_array_resolved (not used actually..) // art_quick_alloc_array_resolved8 // art_quick_alloc_array_resolved16 // art_quick_alloc_array_resolved32 // art_quick_alloc_array_resolved64 Value* HGraphToLLVM::ArtCallAllocArray__( QuickEntrypointEnum qpoint, Value* klass, Value* length) { VERIFIED(qpoint); std::vector<Value*> args{ klass, length }; std::vector<Type*> params{ irb_->getVoidPointerType(), irb_->getJIntTy() }; Type* retTy = irb_->getVoidPointerType(); return artCall(qpoint, retTy, params, args); } // art_quick_aput_obj INFO only this one is used // art_quick_aput_obj_with_bound_check // art_quick_aput_obj_with_null_and_bound_check void HGraphToLLVM::ArtCallAputObject( Value* array, Value* index, Value* storeObj) { QuickEntrypointEnum qpoint = kQuickAputObject ; VERIFY_LLVMD(qpoint); std::vector<Value*> args{ array, index, storeObj }; std::vector<Type*> params{ irb_->getVoidPointerType(), irb_->getJIntTy(), irb_->getVoidPointerType() }; Type* retTy = irb_->getJVoidTy(); artCall(qpoint, retTy, params, args); } // art_llvm_get_obj_instance Value* HGraphToLLVM::ArtCallGetObjInstance( uint32_t field_idx, Value* lobj, Value* lreferrer) { CHECK_LLVM("Must only be used by: GenerateUnresolvedFieldAccess"); // Which is used by HInstructions: // VisitUnresolved<Static/Instance>Field<Get/Set> std::vector<Value*> args{irb_->getJUnsignedInt(field_idx), lobj, lreferrer}; std::vector<Type*> params{ irb_->getJIntTy(), irb_->getVoidPointerType(), irb_->getVoidPointerType(), }; Type* retTy = irb_->getVoidPointerType(); return artCall(kQuickLLVMGetObjInstance, retTy, params, args); } // art_llvm_get_obj_static Value* HGraphToLLVM::ArtCallGetObjStatic(uint32_t field_idx, Value* lreferrer) { CHECK_LLVM("Must only be used by: GenerateUnresolvedFieldAccess"); // Which is used by HInstructions: // VisitUnresolved<Static/Instance>Field<Get/Set> std::vector<Value*> args{irb_->getJUnsignedInt(field_idx), lreferrer}; std::vector<Type*> params{irb_->getJIntTy(), irb_->getVoidPointerType()}; Type* retTy = irb_->getVoidPointerType(); return artCall(kQuickLLVMGetObjStatic, retTy, params, args); } // art_llvm_jvalue_setl void HGraphToLLVM::ArtCallJValueSetL(Value* jvalue, Value* obj) { XLLVM; jvalue = irb_->CreateBitCast(jvalue, irb_->getVoidPointerType()); std::vector<Value*> args{ jvalue, obj }; std::vector<Type*> params{ 2, irb_->getVoidPointerType() }; Type* retTy = irb_->getJVoidTy(); artCall(kQuickLLVMJValueSetL, retTy, params, args); } /** * @brief * * @param irb * @param referrer attribute unused in: artReadBarrierSlow (quick_field_entrypoints.cc) * * @param object * @param member_offset * * @return */ // art_llvm_read_barrier_slow Value* HGraphToLLVM::ArtCallReadBarrierSlow( Value* referrer, Value* object, Value* member_offset) { // VERIFY_LLVM_; std::vector<Value*> args{ referrer, object, member_offset }; std::vector<Type*> params{ irb_->getVoidPointerType(), irb_->getVoidPointerType(), irb_->getJIntTy() }; Type* retTy = irb_->getVoidPointerType(); Value* val = artCall(kQuickLLVMReadBarrierSlow, retTy, params, args); return val; } // art_llvm_resolve_external_method Value* HGraphToLLVM::ArtCallResolveExternalMethod( Value* referrer, Value* dex_filename, Value* dex_location, Value* ldex_method_idx, Value* linvoke_type) { VERIFY_LLVMD5_; std::vector<Value*> args{ referrer, dex_filename, dex_location, ldex_method_idx, linvoke_type }; std::vector<Type*> params{ irb_->getVoidPointerType(), irb_->getVoidPointerType(), // const char* irb_->getVoidPointerType(), // const char* irb_->getJIntTy(), irb_->getJIntTy() }; Type* retTy = irb_->getVoidPointerType(); return artCall(kQuickLLVMResolveExternalMethod, retTy, params, args); } // art_llvm_resolve_external_methodII Value* HGraphToLLVM::ArtCallResolveExternalMethod( Value* referrer, Value* dex_filename, Value* dex_location, uint32_t dex_method_idx, InvokeType invoke_type) { Value* ldex_method_idx = irb_->getJUnsignedInt(dex_method_idx); Value* linvoke_type = irb_->getJUnsignedInt(static_cast<uint32_t>(invoke_type)); return ArtCallResolveExternalMethod(referrer, dex_filename, dex_location, ldex_method_idx, linvoke_type); } // art_llvm_resolve_internal_method Value* HGraphToLLVM::ArtCallResolveInternalMethod( Value* referrer, Value* ldex_method_idx, Value* linvoke_type) { VERIFIED_; std::vector<Type*> params{ irb_->getVoidPointerType(), irb_->getJIntTy(), irb_->getJIntTy() }; std::vector<Value*> args{ referrer, ldex_method_idx, linvoke_type }; Type* retTy = irb_->getVoidPointerType(); Value* resolved_method = artCall(kQuickLLVMResolveInternalMethod, retTy, params, args); return resolved_method; } // art_llvm_resolve_internal_methodII Value* HGraphToLLVM::ArtCallResolveInternalMethod( Value* referrer, uint32_t dex_method_idx, InvokeType invoke_type) { VERIFIED_; Value* ldex_method_idx = irb_->getJUnsignedInt(dex_method_idx); Value* linvoke_type = irb_->getJUnsignedInt(static_cast<uint32_t>(invoke_type)); return ArtCallResolveInternalMethod( referrer, ldex_method_idx, linvoke_type); } // art_llvm_resolve_virtual_method Value* HGraphToLLVM::ArtCallResolveVirtualMethod( Value* receiver, Value* referrer) { VERIFIED_; std::vector<Type*> params{ 2, irb_->getVoidPointerType() }; std::vector<Value*> args{ receiver, referrer }; Type* retTy = irb_->getVoidPointerType(); Value* resolved_method = artCall(kQuickLLVMResolveVirtualMethod, retTy, params, args); return resolved_method; } // do not use this! // art_llvm_resolve_interface_method Value* HGraphToLLVM::ArtCallResolveInterfaceMethod( Value* receiver, Value* referrer) { std::vector<Type*> params{ 2, irb_->getVoidPointerType() }; std::vector<Value*> args { receiver, referrer }; Type* retTy = irb_->getVoidPointerType(); Value* resolved_method = artCall(kQuickLLVMResolveInterfaceMethod, retTy, params, args); if(McrDebug::DebugLlvmCode4()) { VERIFIED("Resolved"); ArtCallVerifyArtMethod(resolved_method); } return resolved_method; } // art_llvm_resolve_string Value* HGraphToLLVM::ArtCallResolveString( Value* caller, uint32_t string_idx, Value* llvm_bss_slot) { VERIFY_LLVMD3_; std::vector<Type*> params { irb_->getVoidPointerType(), irb_->getJIntTy(), irb_->getVoidPointerType()->getPointerTo()}; std::vector<Value*> args { caller, irb_->getJUnsignedInt(string_idx), llvm_bss_slot}; Type* retTy = irb_->getVoidPointerType(); return artCall(kQuickLLVMResolveString, retTy, params, args); } void HGraphToLLVM::ArtCallMonitorOperation(Value* lobj, bool is_lock) { VERIFY_LLVMD_; std::vector<Value*> args{ lobj }; std::vector<Type*> params{ irb_->getVoidPointerType() }; Type* retTy = irb_->getJVoidTy(); QuickEntrypointEnum qpoint = is_lock ? kQuickLockObject : kQuickUnlockObject; artCall(qpoint, retTy, params, args); } void HGraphToLLVM::ArtCallTestSuspend() { // Go through LLVM as Quick has some time issues // ArtCallLLVMTestSuspend(); ArtCallQuickTestSuspend(); } // this adds an extra unnecessary wrapper // on top of art_quick_test_suspend // art_llvm_test_suspend void HGraphToLLVM::ArtCallLLVMTestSuspend() { DIE << "DONT USE THIS!"; VERIFY_LLVMD5(__func__); Type* retTy = irb_->getVoidPointerType(); artCall(kQuickLLVMTestSuspend, retTy); } // art_quick_test_suspend void HGraphToLLVM::ArtCallQuickTestSuspend() { // CHECK: this might cause issues after all.. VERIFY_LLVMD(__func__); Type* retTy = irb_->getVoidPointerType(); artCall(kQuickTestSuspend, retTy); } // art_llvm_push_quick_frame void HGraphToLLVM::ArtCallPushQuickFrame(Value* fragment) { VERIFIED_; fragment=irb_->CreateBitCast(fragment, irb_->getVoidPointerType()); std::vector<Value*> args {fragment}; std::vector<Type*> params {irb_->getVoidPointerType()}; Type* retTy = irb_->getVoidPointerType(); artCall(kQuickLLVMPushQuickFrame, retTy, params, args); } // art_llvm_pop_quick_frame void HGraphToLLVM::ArtCallPopQuickFrame(Value* fragment) { VERIFIED_; fragment=irb_->CreateBitCast(fragment, irb_->getVoidPointerType()); std::vector<Value*> args {fragment}; std::vector<Type*> params {irb_->getVoidPointerType()}; Type* retTy = irb_->getJVoidTy(); artCall(kQuickLLVMPopQuickFrame, retTy, params, args); } // art_llvm_clear_top_of_stack void HGraphToLLVM::ArtCallClearTopOfStack() { DIE << "done use this"; Type* retTy = irb_->getVoidPointerType(); artCall(kQuickLLVMClearTopOfStack, retTy); } /** * extern"C" void art_quick_invoke_stub(ArtMethod *method, x0 * uint32_t *args, x1 * uint32_t argsize, w2 * Thread *self, x3 * JValue *result, x4 * char *shorty); x5 */ void HGraphToLLVM::ArtCallInvokeQuick__( HInvoke* hinvoke, Value* art_method, Value* qargs, Value* qargs_size, Value* jvalue, Value* shorty, bool is_static, bool use_wrapper) { QuickEntrypointEnum entrypoint; CHECK(!use_wrapper) << "don't use wrapper entrypoint."; entrypoint = is_static ? kQuickLLVMInvokeQuickStaticDirect : kQuickLLVMInvokeQuickDirect; // use method index instead of ArtMethod* bool use_method_idx = false; std::vector<Type*> params; if(use_method_idx) { params.push_back(irb_->getJIntTy()); } else { params.push_back(irb_->getVoidPointerType()); // method } params.push_back(irb_->getJIntTy()->getPointerTo()); // args params.push_back(irb_->getJIntTy()); // argssize params.push_back(irb_->getVoidPointerType()); // Thread params.push_back(irb_->getJValueTy()->getPointerTo()); // result params.push_back(irb_->getVoidPointerType()); // shorty std::vector<Value*> args{ art_method, qargs, qargs_size, GetLoadedThread(), jvalue, shorty }; Type* retTy = irb_->getJVoidTy(); artCall(entrypoint, retTy, params, args); } } // namespace LLVM } // namespace art #include "llvm_macros_undef.h"
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/automation/url_request_failed_dns_job.h" #include "base/message_loop.h" #include "googleurl/src/gurl.h" #include "net/base/net_errors.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_filter.h" const char URLRequestFailedDnsJob::kTestUrl[] = "http://url.handled.by.fake.dns/"; void URLRequestFailedDnsJob::Start() { MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod( this, &URLRequestFailedDnsJob::StartAsync)); } /* static */ void URLRequestFailedDnsJob::AddUITestUrls() { URLRequestFilter* filter = URLRequestFilter::GetInstance(); filter->AddUrlHandler(GURL(kTestUrl), &URLRequestFailedDnsJob::Factory); } /*static */ URLRequestJob* URLRequestFailedDnsJob::Factory(URLRequest* request, const std::string& scheme) { return new URLRequestFailedDnsJob(request); } void URLRequestFailedDnsJob::StartAsync() { NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, net::ERR_NAME_NOT_RESOLVED)); }
#include "BooterChain.h" #include <cassert> void Booter::Chain::AddNode(Node * newNode) { assert(m_firstNode.load() != nullptr); Node* currentNode = m_firstNode.exchange(newNode); assert(currentNode->m_nextNode.load() == nullptr); currentNode->m_nextNode = newNode; } void Booter::Chain::BuildAllNodes() { assert(m_firstNode.load() != nullptr); for (Node* currentNode = m_nextNode.load(); currentNode != nullptr; currentNode = currentNode->m_nextNode.load()) { currentNode->BuildNode(); } } void Booter::Chain::KnockAllNodes() { // This currently clean all nodes up... consider if these should be separate steps. assert(m_firstNode.load() != nullptr); for (Node* currentNode = m_nextNode.exchange(nullptr); currentNode != nullptr; currentNode = currentNode->m_nextNode.exchange(nullptr)) { currentNode->KnockNode(); } }
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/emr/v20190103/model/InquiryPriceCreateInstanceRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Emr::V20190103::Model; using namespace rapidjson; using namespace std; InquiryPriceCreateInstanceRequest::InquiryPriceCreateInstanceRequest() : m_timeUnitHasBeenSet(false), m_timeSpanHasBeenSet(false), m_resourceSpecHasBeenSet(false), m_currencyHasBeenSet(false), m_payModeHasBeenSet(false), m_supportHAHasBeenSet(false), m_softwareHasBeenSet(false), m_placementHasBeenSet(false), m_vPCSettingsHasBeenSet(false) { } string InquiryPriceCreateInstanceRequest::ToJsonString() const { Document d; d.SetObject(); Document::AllocatorType& allocator = d.GetAllocator(); if (m_timeUnitHasBeenSet) { Value iKey(kStringType); string key = "TimeUnit"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(m_timeUnit.c_str(), allocator).Move(), allocator); } if (m_timeSpanHasBeenSet) { Value iKey(kStringType); string key = "TimeSpan"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_timeSpan, allocator); } if (m_resourceSpecHasBeenSet) { Value iKey(kStringType); string key = "ResourceSpec"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(kObjectType).Move(), allocator); m_resourceSpec.ToJsonObject(d[key.c_str()], allocator); } if (m_currencyHasBeenSet) { Value iKey(kStringType); string key = "Currency"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(m_currency.c_str(), allocator).Move(), allocator); } if (m_payModeHasBeenSet) { Value iKey(kStringType); string key = "PayMode"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_payMode, allocator); } if (m_supportHAHasBeenSet) { Value iKey(kStringType); string key = "SupportHA"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_supportHA, allocator); } if (m_softwareHasBeenSet) { Value iKey(kStringType); string key = "Software"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(kArrayType).Move(), allocator); for (auto itr = m_software.begin(); itr != m_software.end(); ++itr) { d[key.c_str()].PushBack(Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_placementHasBeenSet) { Value iKey(kStringType); string key = "Placement"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(kObjectType).Move(), allocator); m_placement.ToJsonObject(d[key.c_str()], allocator); } if (m_vPCSettingsHasBeenSet) { Value iKey(kStringType); string key = "VPCSettings"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(kObjectType).Move(), allocator); m_vPCSettings.ToJsonObject(d[key.c_str()], allocator); } StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string InquiryPriceCreateInstanceRequest::GetTimeUnit() const { return m_timeUnit; } void InquiryPriceCreateInstanceRequest::SetTimeUnit(const string& _timeUnit) { m_timeUnit = _timeUnit; m_timeUnitHasBeenSet = true; } bool InquiryPriceCreateInstanceRequest::TimeUnitHasBeenSet() const { return m_timeUnitHasBeenSet; } uint64_t InquiryPriceCreateInstanceRequest::GetTimeSpan() const { return m_timeSpan; } void InquiryPriceCreateInstanceRequest::SetTimeSpan(const uint64_t& _timeSpan) { m_timeSpan = _timeSpan; m_timeSpanHasBeenSet = true; } bool InquiryPriceCreateInstanceRequest::TimeSpanHasBeenSet() const { return m_timeSpanHasBeenSet; } ResourceSpec InquiryPriceCreateInstanceRequest::GetResourceSpec() const { return m_resourceSpec; } void InquiryPriceCreateInstanceRequest::SetResourceSpec(const ResourceSpec& _resourceSpec) { m_resourceSpec = _resourceSpec; m_resourceSpecHasBeenSet = true; } bool InquiryPriceCreateInstanceRequest::ResourceSpecHasBeenSet() const { return m_resourceSpecHasBeenSet; } string InquiryPriceCreateInstanceRequest::GetCurrency() const { return m_currency; } void InquiryPriceCreateInstanceRequest::SetCurrency(const string& _currency) { m_currency = _currency; m_currencyHasBeenSet = true; } bool InquiryPriceCreateInstanceRequest::CurrencyHasBeenSet() const { return m_currencyHasBeenSet; } uint64_t InquiryPriceCreateInstanceRequest::GetPayMode() const { return m_payMode; } void InquiryPriceCreateInstanceRequest::SetPayMode(const uint64_t& _payMode) { m_payMode = _payMode; m_payModeHasBeenSet = true; } bool InquiryPriceCreateInstanceRequest::PayModeHasBeenSet() const { return m_payModeHasBeenSet; } uint64_t InquiryPriceCreateInstanceRequest::GetSupportHA() const { return m_supportHA; } void InquiryPriceCreateInstanceRequest::SetSupportHA(const uint64_t& _supportHA) { m_supportHA = _supportHA; m_supportHAHasBeenSet = true; } bool InquiryPriceCreateInstanceRequest::SupportHAHasBeenSet() const { return m_supportHAHasBeenSet; } vector<string> InquiryPriceCreateInstanceRequest::GetSoftware() const { return m_software; } void InquiryPriceCreateInstanceRequest::SetSoftware(const vector<string>& _software) { m_software = _software; m_softwareHasBeenSet = true; } bool InquiryPriceCreateInstanceRequest::SoftwareHasBeenSet() const { return m_softwareHasBeenSet; } Placement InquiryPriceCreateInstanceRequest::GetPlacement() const { return m_placement; } void InquiryPriceCreateInstanceRequest::SetPlacement(const Placement& _placement) { m_placement = _placement; m_placementHasBeenSet = true; } bool InquiryPriceCreateInstanceRequest::PlacementHasBeenSet() const { return m_placementHasBeenSet; } VPCSettings InquiryPriceCreateInstanceRequest::GetVPCSettings() const { return m_vPCSettings; } void InquiryPriceCreateInstanceRequest::SetVPCSettings(const VPCSettings& _vPCSettings) { m_vPCSettings = _vPCSettings; m_vPCSettingsHasBeenSet = true; } bool InquiryPriceCreateInstanceRequest::VPCSettingsHasBeenSet() const { return m_vPCSettingsHasBeenSet; }
/* Copyright (C) 2021 hidenorly 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 __STREAM_MANAGER_HPP__ #define __STREAM_MANAGER_HPP__ #include <vector> #include <memory> #include <map> #include "Pipe.hpp" #include "Sink.hpp" #include "Source.hpp" #include "Strategy.hpp" #include "Singleton.hpp" class StreamInfo { public: int id; std::shared_ptr<StrategyContext> context; std::shared_ptr<IPipe> pipe; StreamInfo(){}; virtual ~StreamInfo(){}; }; class StreamManager; class StreamManager : public SingletonBase<StreamManager> { protected: std::vector<std::shared_ptr<StreamInfo>> mStreamInfos; int mId; virtual void onInstantiate(void){ mId = 0; }; virtual void onFinalize(void){ clear(); }; public: std::shared_ptr<StreamInfo> get(int id); std::shared_ptr<StreamInfo> get(std::shared_ptr<IPipe> pPipe); std::shared_ptr<StreamInfo> get(std::shared_ptr<StrategyContext> pContext); int add(std::shared_ptr<StrategyContext> pContext, std::shared_ptr<IPipe> pPipe); int add(std::shared_ptr<StreamInfo> pStreamInfo ); bool remove(int id); bool remove(std::shared_ptr<IPipe> pPipe); bool remove(std::shared_ptr<StrategyContext> pContext); bool remove(std::shared_ptr<StreamInfo> pStreamInfo); void clear(void); int getId(std::shared_ptr<IPipe> pPipe); int getId(std::shared_ptr<StrategyContext> pContext); std::shared_ptr<IPipe> getPipe(int id); std::shared_ptr<IPipe> getPipe(std::shared_ptr<StrategyContext> pContext); std::shared_ptr<StrategyContext> getContext(int id); std::shared_ptr<StrategyContext> getContext(std::shared_ptr<IPipe> pPipe); }; #endif /* __STREAM_MANAGER_HPP__ */
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/live/v20180801/model/UpdateLiveWatermarkRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Live::V20180801::Model; using namespace std; UpdateLiveWatermarkRequest::UpdateLiveWatermarkRequest() : m_watermarkIdHasBeenSet(false), m_pictureUrlHasBeenSet(false), m_xPositionHasBeenSet(false), m_yPositionHasBeenSet(false), m_watermarkNameHasBeenSet(false), m_widthHasBeenSet(false), m_heightHasBeenSet(false) { } string UpdateLiveWatermarkRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_watermarkIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "WatermarkId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_watermarkId, allocator); } if (m_pictureUrlHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PictureUrl"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_pictureUrl.c_str(), allocator).Move(), allocator); } if (m_xPositionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "XPosition"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_xPosition, allocator); } if (m_yPositionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "YPosition"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_yPosition, allocator); } if (m_watermarkNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "WatermarkName"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_watermarkName.c_str(), allocator).Move(), allocator); } if (m_widthHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Width"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_width, allocator); } if (m_heightHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Height"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_height, allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } int64_t UpdateLiveWatermarkRequest::GetWatermarkId() const { return m_watermarkId; } void UpdateLiveWatermarkRequest::SetWatermarkId(const int64_t& _watermarkId) { m_watermarkId = _watermarkId; m_watermarkIdHasBeenSet = true; } bool UpdateLiveWatermarkRequest::WatermarkIdHasBeenSet() const { return m_watermarkIdHasBeenSet; } string UpdateLiveWatermarkRequest::GetPictureUrl() const { return m_pictureUrl; } void UpdateLiveWatermarkRequest::SetPictureUrl(const string& _pictureUrl) { m_pictureUrl = _pictureUrl; m_pictureUrlHasBeenSet = true; } bool UpdateLiveWatermarkRequest::PictureUrlHasBeenSet() const { return m_pictureUrlHasBeenSet; } int64_t UpdateLiveWatermarkRequest::GetXPosition() const { return m_xPosition; } void UpdateLiveWatermarkRequest::SetXPosition(const int64_t& _xPosition) { m_xPosition = _xPosition; m_xPositionHasBeenSet = true; } bool UpdateLiveWatermarkRequest::XPositionHasBeenSet() const { return m_xPositionHasBeenSet; } int64_t UpdateLiveWatermarkRequest::GetYPosition() const { return m_yPosition; } void UpdateLiveWatermarkRequest::SetYPosition(const int64_t& _yPosition) { m_yPosition = _yPosition; m_yPositionHasBeenSet = true; } bool UpdateLiveWatermarkRequest::YPositionHasBeenSet() const { return m_yPositionHasBeenSet; } string UpdateLiveWatermarkRequest::GetWatermarkName() const { return m_watermarkName; } void UpdateLiveWatermarkRequest::SetWatermarkName(const string& _watermarkName) { m_watermarkName = _watermarkName; m_watermarkNameHasBeenSet = true; } bool UpdateLiveWatermarkRequest::WatermarkNameHasBeenSet() const { return m_watermarkNameHasBeenSet; } int64_t UpdateLiveWatermarkRequest::GetWidth() const { return m_width; } void UpdateLiveWatermarkRequest::SetWidth(const int64_t& _width) { m_width = _width; m_widthHasBeenSet = true; } bool UpdateLiveWatermarkRequest::WidthHasBeenSet() const { return m_widthHasBeenSet; } int64_t UpdateLiveWatermarkRequest::GetHeight() const { return m_height; } void UpdateLiveWatermarkRequest::SetHeight(const int64_t& _height) { m_height = _height; m_heightHasBeenSet = true; } bool UpdateLiveWatermarkRequest::HeightHasBeenSet() const { return m_heightHasBeenSet; }
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "Function.h" namespace paddle { void BufferArgs::addArg(const Matrix& arg, const TensorShape& shape, ArgType argType) { _args_.push_back(new BufferArg(arg, shape, argType)); addArg(*_args_.back()); } void BufferArgs::addArg(const CpuSparseMatrix& arg, ArgType argType) { _args_.push_back(new SparseMatrixArg(arg, argType)); addArg(*_args_.back()); } void BufferArgs::addArg(const GpuSparseMatrix& arg, ArgType argType) { _args_.push_back(new SparseMatrixArg(arg, argType)); addArg(*_args_.back()); } void BufferArgs::addArg(const Matrix& matrix, const IVector& vector, ArgType argType) { _args_.push_back(new SequenceArg(matrix, vector, argType)); addArg(*_args_.back()); } ClassRegistrar<FunctionBase> FunctionBase::funcRegistrar_; } // namespace paddle
/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm/gm.h" #include "include/core/SkBlendMode.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkColorFilter.h" #include "include/core/SkMatrix.h" #include "include/core/SkPaint.h" #include "include/core/SkPoint.h" #include "include/core/SkRefCnt.h" #include "include/core/SkScalar.h" #include "include/core/SkShader.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/core/SkTileMode.h" #include "include/core/SkTypes.h" #include "include/core/SkVertices.h" #include "include/effects/SkGradientShader.h" #include "include/effects/SkRuntimeEffect.h" #include "include/private/SkTDArray.h" #include "include/utils/SkRandom.h" #include "src/core/SkVerticesPriv.h" #include "src/shaders/SkLocalMatrixShader.h" #include "src/utils/SkPatchUtils.h" #include "tools/Resources.h" #include "tools/ToolUtils.h" #include <initializer_list> #include <utility> static constexpr SkScalar kShaderSize = 40; static sk_sp<SkShader> make_shader1(SkScalar shaderScale) { const SkColor colors[] = { SK_ColorRED, SK_ColorCYAN, SK_ColorGREEN, SK_ColorWHITE, SK_ColorMAGENTA, SK_ColorBLUE, SK_ColorYELLOW, }; const SkPoint pts[] = {{kShaderSize / 4, 0}, {3 * kShaderSize / 4, kShaderSize}}; const SkMatrix localMatrix = SkMatrix::Scale(shaderScale, shaderScale); sk_sp<SkShader> grad = SkGradientShader::MakeLinear(pts, colors, nullptr, SK_ARRAY_COUNT(colors), SkTileMode::kMirror, 0, &localMatrix); // Throw in a couple of local matrix wrappers for good measure. return shaderScale == 1 ? grad : sk_make_sp<SkLocalMatrixShader>( sk_make_sp<SkLocalMatrixShader>(std::move(grad), SkMatrix::Translate(-10, 0)), SkMatrix::Translate(10, 0)); } static sk_sp<SkShader> make_shader2() { return SkShaders::Color(SK_ColorBLUE); } static sk_sp<SkColorFilter> make_color_filter() { return SkColorFilters::Blend(0xFFAABBCC, SkBlendMode::kDarken); } static constexpr SkScalar kMeshSize = 30; // start with the center of a 3x3 grid of vertices. static constexpr uint16_t kMeshFan[] = { 4, 0, 1, 2, 5, 8, 7, 6, 3, 0 }; static const int kMeshIndexCnt = (int)SK_ARRAY_COUNT(kMeshFan); static const int kMeshVertexCnt = 9; static void fill_mesh(SkPoint pts[kMeshVertexCnt], SkPoint texs[kMeshVertexCnt], SkColor colors[kMeshVertexCnt], SkScalar shaderScale) { pts[0].set(0, 0); pts[1].set(kMeshSize / 2, 3); pts[2].set(kMeshSize, 0); pts[3].set(3, kMeshSize / 2); pts[4].set(kMeshSize / 2, kMeshSize / 2); pts[5].set(kMeshSize - 3, kMeshSize / 2); pts[6].set(0, kMeshSize); pts[7].set(kMeshSize / 2, kMeshSize - 3); pts[8].set(kMeshSize, kMeshSize); const auto shaderSize = kShaderSize * shaderScale; texs[0].set(0, 0); texs[1].set(shaderSize / 2, 0); texs[2].set(shaderSize, 0); texs[3].set(0, shaderSize / 2); texs[4].set(shaderSize / 2, shaderSize / 2); texs[5].set(shaderSize, shaderSize / 2); texs[6].set(0, shaderSize); texs[7].set(shaderSize / 2, shaderSize); texs[8].set(shaderSize, shaderSize); SkRandom rand; for (size_t i = 0; i < kMeshVertexCnt; ++i) { colors[i] = rand.nextU() | 0xFF000000; } } class VerticesGM : public skiagm::GM { SkPoint fPts[kMeshVertexCnt]; SkPoint fTexs[kMeshVertexCnt]; SkColor fColors[kMeshVertexCnt]; sk_sp<SkShader> fShader1; sk_sp<SkShader> fShader2; sk_sp<SkColorFilter> fColorFilter; SkScalar fShaderScale; public: VerticesGM(SkScalar shaderScale) : fShaderScale(shaderScale) {} protected: void onOnceBeforeDraw() override { fill_mesh(fPts, fTexs, fColors, fShaderScale); fShader1 = make_shader1(fShaderScale); fShader2 = make_shader2(); fColorFilter = make_color_filter(); } SkString onShortName() override { SkString name("vertices"); if (fShaderScale != 1) { name.append("_scaled_shader"); } return name; } SkISize onISize() override { return SkISize::Make(975, 1175); } void onDraw(SkCanvas* canvas) override { const SkBlendMode modes[] = { SkBlendMode::kClear, SkBlendMode::kSrc, SkBlendMode::kDst, SkBlendMode::kSrcOver, SkBlendMode::kDstOver, SkBlendMode::kSrcIn, SkBlendMode::kDstIn, SkBlendMode::kSrcOut, SkBlendMode::kDstOut, SkBlendMode::kSrcATop, SkBlendMode::kDstATop, SkBlendMode::kXor, SkBlendMode::kPlus, SkBlendMode::kModulate, SkBlendMode::kScreen, SkBlendMode::kOverlay, SkBlendMode::kDarken, SkBlendMode::kLighten, SkBlendMode::kColorDodge, SkBlendMode::kColorBurn, SkBlendMode::kHardLight, SkBlendMode::kSoftLight, SkBlendMode::kDifference, SkBlendMode::kExclusion, SkBlendMode::kMultiply, SkBlendMode::kHue, SkBlendMode::kSaturation, SkBlendMode::kColor, SkBlendMode::kLuminosity, }; SkPaint paint; canvas->translate(4, 4); int x = 0; for (auto mode : modes) { canvas->save(); for (float alpha : {1.0f, 0.5f}) { for (const auto& cf : {sk_sp<SkColorFilter>(nullptr), fColorFilter}) { for (const auto& shader : {fShader1, fShader2}) { static constexpr struct { bool fHasColors; bool fHasTexs; } kAttrs[] = {{true, false}, {false, true}, {true, true}}; for (auto attrs : kAttrs) { paint.setShader(shader); paint.setColorFilter(cf); paint.setAlphaf(alpha); const SkColor* colors = attrs.fHasColors ? fColors : nullptr; const SkPoint* texs = attrs.fHasTexs ? fTexs : nullptr; auto v = SkVertices::MakeCopy(SkVertices::kTriangleFan_VertexMode, kMeshVertexCnt, fPts, texs, colors, kMeshIndexCnt, kMeshFan); canvas->drawVertices(v, mode, paint); canvas->translate(40, 0); ++x; } } } } canvas->restore(); canvas->translate(0, 40); } } private: typedef skiagm::GM INHERITED; }; ///////////////////////////////////////////////////////////////////////////////////// DEF_GM(return new VerticesGM(1);) DEF_GM(return new VerticesGM(1 / kShaderSize);) static void draw_batching(SkCanvas* canvas) { // Triangle fans can't batch so we convert to regular triangles, static constexpr int kNumTris = kMeshIndexCnt - 2; SkVertices::Builder builder(SkVertices::kTriangles_VertexMode, kMeshVertexCnt, 3 * kNumTris, SkVertices::kHasColors_BuilderFlag | SkVertices::kHasTexCoords_BuilderFlag); SkPoint* pts = builder.positions(); SkPoint* texs = builder.texCoords(); SkColor* colors = builder.colors(); fill_mesh(pts, texs, colors, 1); SkTDArray<SkMatrix> matrices; matrices.push()->reset(); matrices.push()->setTranslate(0, 40); SkMatrix* m = matrices.push(); m->setRotate(45, kMeshSize / 2, kMeshSize / 2); m->postScale(1.2f, .8f, kMeshSize / 2, kMeshSize / 2); m->postTranslate(0, 80); auto shader = make_shader1(1); uint16_t* indices = builder.indices(); for (size_t i = 0; i < kNumTris; ++i) { indices[3 * i] = kMeshFan[0]; indices[3 * i + 1] = kMeshFan[i + 1]; indices[3 * i + 2] = kMeshFan[i + 2]; } canvas->save(); canvas->translate(10, 10); for (bool useShader : {false, true}) { for (bool useTex : {false, true}) { for (const auto& m : matrices) { canvas->save(); canvas->concat(m); SkPaint paint; paint.setShader(useShader ? shader : nullptr); const SkPoint* t = useTex ? texs : nullptr; auto v = SkVertices::MakeCopy(SkVertices::kTriangles_VertexMode, kMeshVertexCnt, pts, t, colors, kNumTris * 3, indices); canvas->drawVertices(v, SkBlendMode::kModulate, paint); canvas->restore(); } canvas->translate(0, 120); } } canvas->restore(); } // This test exists to exercise batching in the gpu backend. DEF_SIMPLE_GM(vertices_batching, canvas, 100, 500) { draw_batching(canvas); canvas->translate(50, 0); draw_batching(canvas); } using AttrType = SkVertices::Attribute::Type; DEF_SIMPLE_GM(vertices_data, canvas, 512, 256) { for (auto attrType : {AttrType::kFloat4, AttrType::kByte4_unorm}) { SkRect r = SkRect::MakeWH(256, 256); int vcount = 4; // just a quad int icount = 0; SkVertices::Attribute attrs[] = { attrType }; SkVertices::Builder builder(SkVertices::kTriangleFan_VertexMode, vcount, icount, attrs, 1); r.toQuad(builder.positions()); if (attrType == AttrType::kFloat4) { SkV4* col = (SkV4*)builder.customData(); col[0] = {1, 0, 0, 1}; // red col[1] = {0, 1, 0, 1}; // green col[2] = {0, 0, 1, 1}; // blue col[3] = {0.5, 0.5, 0.5, 1}; // gray } else { uint32_t* col = (uint32_t*)builder.customData(); col[0] = 0xFF0000FF; col[1] = 0xFF00FF00; col[2] = 0xFFFF0000; col[3] = 0xFF7F7F7F; } SkPaint paint; const char* gProg = R"( varying float4 vtx_color; half4 main(float2 p) { return half4(vtx_color); } )"; auto[effect, errorText] = SkRuntimeEffect::Make(SkString(gProg)); if (!effect) { SK_ABORT("RuntimeEffect error: %s\n", errorText.c_str()); } paint.setShader(effect->makeShader(nullptr, nullptr, 0, nullptr, true)); canvas->drawVertices(builder.detach(), paint); canvas->translate(r.width(), 0); } } // Test case for skbug.com/10069. We need to draw the vertices twice (with different matrices) to // trigger the bug. DEF_SIMPLE_GM(vertices_perspective, canvas, 256, 256) { SkPaint paint; paint.setShader(ToolUtils::create_checkerboard_shader(SK_ColorBLACK, SK_ColorWHITE, 32)); SkRect r = SkRect::MakeWH(128, 128); SkPoint pos[4]; r.toQuad(pos); auto verts = SkVertices::MakeCopy(SkVertices::kTriangleFan_VertexMode, 4, pos, pos, nullptr); SkMatrix persp; persp.setPerspY(SK_Scalar1 / 100); canvas->save(); canvas->concat(persp); canvas->drawRect(r, paint); canvas->restore(); canvas->save(); canvas->translate(r.width(), 0); canvas->concat(persp); canvas->drawRect(r, paint); canvas->restore(); canvas->save(); canvas->translate(0, r.height()); canvas->concat(persp); canvas->drawVertices(verts, paint); canvas->restore(); canvas->save(); canvas->translate(r.width(), r.height()); canvas->concat(persp); canvas->drawVertices(verts, paint); canvas->restore(); } DEF_SIMPLE_GM(vertices_data_lerp, canvas, 256, 256) { SkPoint pts[12] = {{0, 0}, {85, 0}, {171, 0}, {256, 0}, {256, 85}, {256, 171}, {256, 256}, {171, 256}, {85, 256}, {0, 256}, {0, 171}, {0, 85}}; auto patchVerts = SkPatchUtils::MakeVertices(pts, nullptr, nullptr, 12, 12); SkVerticesPriv pv(patchVerts->priv()); SkVertices::Attribute attrs[1] = { AttrType::kFloat }; SkVertices::Builder builder(pv.mode(), pv.vertexCount(), pv.indexCount(), attrs, 1); memcpy(builder.positions(), pv.positions(), pv.vertexCount() * sizeof(SkPoint)); memcpy(builder.indices(), pv.indices(), pv.indexCount() * sizeof(uint16_t)); SkRandom rnd; float* lerpData = (float*)builder.customData(); for (int i = 0; i < pv.vertexCount(); ++i) { lerpData[i] = rnd.nextBool() ? 1.0f : 0.0f; } auto verts = builder.detach(); SkPaint paint; const char* gProg = R"( in shader c0; in shader c1; varying float vtx_lerp; half4 main(float2 p) { half4 col0 = sample(c0, p); half4 col1 = sample(c1, p); return mix(col0, col1, half(vtx_lerp)); } )"; auto [effect, errorText] = SkRuntimeEffect::Make(SkString(gProg)); SkMatrix scale = SkMatrix::Scale(2, 2); sk_sp<SkShader> children[] = { GetResourceAsImage("images/mandrill_256.png")->makeShader(), GetResourceAsImage("images/color_wheel.png")->makeShader(scale), }; paint.setShader(effect->makeShader(nullptr, children, 2, nullptr, false)); canvas->drawVertices(verts, paint); } static constexpr SkScalar kSin60 = 0.8660254f; // sqrt(3) / 2 static constexpr SkPoint kHexVerts[] = { { 0, 0 }, { 0, -1 }, { kSin60, -0.5f }, { kSin60, 0.5f }, { 0, 1 }, { -kSin60, 0.5f }, { -kSin60, -0.5f }, { 0, -1 }, }; static constexpr SkColor4f kColors[] = { SkColors::kWhite, SkColors::kRed, SkColors::kYellow, SkColors::kGreen, SkColors::kCyan, SkColors::kBlue, SkColors::kMagenta, SkColors::kRed, }; using Attr = SkVertices::Attribute; DEF_SIMPLE_GM(vertices_custom_colors, canvas, 400, 200) { ToolUtils::draw_checkerboard(canvas); auto draw = [=](SkScalar cx, SkScalar cy, SkVertices::Builder& builder, const SkPaint& paint) { memcpy(builder.positions(), kHexVerts, sizeof(kHexVerts)); canvas->save(); canvas->translate(cx, cy); canvas->scale(45, 45); canvas->drawVertices(builder.detach(), paint); canvas->restore(); }; auto transColor = [](int i) { return SkColor4f { kColors[i].fR, kColors[i].fG, kColors[i].fB, i % 2 ? 0.5f : 1.0f }; }; // Fixed function SkVertices, opaque { SkVertices::Builder builder(SkVertices::kTriangleFan_VertexMode, 8, 0, SkVertices::kHasColors_BuilderFlag); for (int i = 0; i < 8; ++i) { builder.colors()[i] = kColors[i].toSkColor(); } draw(50, 50, builder, SkPaint()); } // Fixed function SkVertices, w/transparency { SkVertices::Builder builder(SkVertices::kTriangleFan_VertexMode, 8, 0, SkVertices::kHasColors_BuilderFlag); for (int i = 0; i < 8; ++i) { builder.colors()[i] = transColor(i).toSkColor(); } draw(50, 150, builder, SkPaint()); } const char* gProg = R"( varying half4 vtx_color; half4 main(float2 p) { return vtx_color; } )"; SkPaint skslPaint; auto [effect, errorText] = SkRuntimeEffect::Make(SkString(gProg)); skslPaint.setShader(effect->makeShader(nullptr, nullptr, 0, nullptr, false)); Attr byteColorAttr(Attr::Type::kByte4_unorm, Attr::Usage::kColor); Attr float4ColorAttr(Attr::Type::kFloat4, Attr::Usage::kColor); Attr float3ColorAttr(Attr::Type::kFloat3, Attr::Usage::kColor); // Custom vertices, byte colors, opaque { SkVertices::Builder builder(SkVertices::kTriangleFan_VertexMode, 8, 0, &byteColorAttr, 1); for (int i = 0; i < 8; ++i) { ((uint32_t*)builder.customData())[i] = kColors[i].toBytes_RGBA(); } draw(150, 50, builder, skslPaint); } // Custom vertices, byte colors, w/transparency { SkVertices::Builder builder(SkVertices::kTriangleFan_VertexMode, 8, 0, &byteColorAttr, 1); for (int i = 0; i < 8; ++i) { ((uint32_t*)builder.customData())[i] = transColor(i).toBytes_RGBA(); } draw(150, 150, builder, skslPaint); } // Custom vertices, float4 colors, opaque { SkVertices::Builder builder(SkVertices::kTriangleFan_VertexMode, 8, 0, &float4ColorAttr, 1); for (int i = 0; i < 8; ++i) { ((SkColor4f*)builder.customData())[i] = kColors[i]; } draw(250, 50, builder, skslPaint); } // Custom vertices, float4 colors, w/transparency { SkVertices::Builder builder(SkVertices::kTriangleFan_VertexMode, 8, 0, &float4ColorAttr, 1); SkColor4f* clr = (SkColor4f*)builder.customData(); for (int i = 0; i < 8; ++i) { clr[i] = transColor(i); } draw(250, 150, builder, skslPaint); } // Custom vertices, float3 colors, opaque { SkVertices::Builder builder(SkVertices::kTriangleFan_VertexMode, 8, 0, &float3ColorAttr, 1); for (int i = 0; i < 8; ++i) { ((SkV3*)builder.customData())[i] = { kColors[i].fR, kColors[i].fG, kColors[i].fB }; } draw(350, 50, builder, skslPaint); } } static sk_sp<SkVertices> make_cone(Attr::Usage u, const char* markerName) { Attr attr(Attr::Type::kFloat3, u, markerName); constexpr int kPerimeterVerts = 64; // +1 for the center, +1 to repeat the first perimeter point (so we draw a complete circle) constexpr int kNumVerts = kPerimeterVerts + 2; SkVertices::Builder builder(SkVertices::kTriangleFan_VertexMode, kNumVerts, /*indexCount=*/0, &attr, /*attrCount=*/1); SkPoint* pos = builder.positions(); SkPoint3* vec = static_cast<SkPoint3*>(builder.customData()); pos[0] = { 0, 0 }; vec[0] = { 0, 0, 1 }; for (int i = 0; i < kPerimeterVerts + 1; ++i) { SkScalar t = (i / SkIntToScalar(kPerimeterVerts)) * 2 * SK_ScalarPI; SkScalar s = SkScalarSin(t), c = SkScalarCos(t); pos[i + 1] = { c, s }; vec[i + 1] = { c, s, 0 }; } return builder.detach(); } DEF_SIMPLE_GM(vertices_custom_matrices, canvas, 400, 400) { ToolUtils::draw_checkerboard(canvas); const char* kViewSpace = "local_to_view"; const char* kWorldSpace = "local_to_world"; const char* kLocalSpace = "local_to_local"; auto draw = [=](SkScalar cx, SkScalar cy, sk_sp<SkVertices> vertices, const char* prog, SkScalar squish = 1.0f) { SkPaint paint; auto [effect, errorText] = SkRuntimeEffect::Make(SkString(prog)); paint.setShader(effect->makeShader(nullptr, nullptr, 0, nullptr, false)); canvas->save(); // Device space: mesh is upright, translated to its "cell" canvas->translate(cx, cy); // View (camera) space: Mesh is upright, centered on origin, device scale canvas->markCTM(kViewSpace); canvas->rotate(90); // World space: Mesh is sideways, centered on origin, device scale (possibly squished) canvas->markCTM(kWorldSpace); canvas->rotate(-90); canvas->scale(45, 45 * squish); // Local space: Mesh is upright, centered on origin, unit scale canvas->markCTM(kLocalSpace); canvas->drawVertices(vertices, paint); canvas->restore(); }; const char* vectorProg = R"( varying float3 vtx_vec; half4 main(float2 p) { return (half3(vtx_vec) * 0.5 + 0.5).rgb1; })"; // raw, local vectors, normals, and positions should all look the same (no real transform) draw(50, 50, make_cone(Attr::Usage::kRaw, nullptr), vectorProg); draw(150, 50, make_cone(Attr::Usage::kVector, kLocalSpace), vectorProg); draw(250, 50, make_cone(Attr::Usage::kNormalVector, kLocalSpace), vectorProg); draw(350, 50, make_cone(Attr::Usage::kPosition, kLocalSpace), vectorProg); // world-space vectors and normals are rotated 90 degrees, positions are centered but scaled up draw(150, 150, make_cone(Attr::Usage::kVector, kWorldSpace), vectorProg); draw(250, 150, make_cone(Attr::Usage::kNormalVector, kWorldSpace), vectorProg); draw(350, 150, make_cone(Attr::Usage::kPosition, kWorldSpace), vectorProg); // Squished vectors are "wrong", but normals are correct (because we use the inverse transpose) // Positions remain scaled up (saturated), but otherwise correct draw(150, 250, make_cone(Attr::Usage::kVector, kWorldSpace), vectorProg, 0.5f); draw(250, 250, make_cone(Attr::Usage::kNormalVector, kWorldSpace), vectorProg, 0.5f); draw(350, 250, make_cone(Attr::Usage::kPosition, kWorldSpace), vectorProg, 0.5f); draw( 50, 350, make_cone(Attr::Usage::kVector, nullptr), vectorProg, 0.5f); draw(150, 350, make_cone(Attr::Usage::kNormalVector, nullptr), vectorProg, 0.5f); // For canvas-space positions, color them according to their position relative to the center. // We do this test twice, with and without saveLayer. That ensures that we get the canvas CTM, // not just a local-to-device matrix, which exposes effect authors to an implementation detail. const char* ctmPositionProg250 = R"( varying float3 vtx_pos; half4 main(float2 p) { return ((half3(vtx_pos) - half3(250, 350, 0)) / 50 + 0.5).rgb1; } )"; draw(250, 350, make_cone(Attr::Usage::kPosition, nullptr), ctmPositionProg250, 0.5f); const char* ctmPositionProg350 = R"( varying float3 vtx_pos; half4 main(float2 p) { return ((half3(vtx_pos) - half3(350, 350, 0)) / 50 + 0.5).rgb1; } )"; canvas->saveLayer({ 300, 300, 400, 400 }, nullptr); draw(350, 350, make_cone(Attr::Usage::kPosition, nullptr), ctmPositionProg350, 0.5f); canvas->restore(); }
/********************************************************************** Copyright (c)2017 Advanced Micro Devices, 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. 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. ********************************************************************/ #ifndef MLO_SOFTMAXHOST_H_ #define MLO_SOFTMAXHOST_H_ //////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////// #define NEGATIVE_INF_FP32 (-1e20) #define NEGATIVE_INF_FP16 (-1e5) template <typename T> T logaddexp(T x, T y, T neg_inf) { T a = std::max(x, y); T b = std::min(x, y); T c = b - a; return c <= neg_inf ? std::max(a, neg_inf) : std::max(T(a + log(T(1) + exp(b - a))), neg_inf); } template <typename Tgpu, typename Tcheck /* the data type used in CPU checkings (usually double) */> int mloSoftmaxForwardRunHost(miopenTensorDescriptor_t inputTensor, miopenTensorDescriptor_t outputTensor, Tgpu* in, Tcheck* outhost, float alpha, float beta, miopenSoftmaxAlgorithm_t algo, miopenSoftmaxMode_t mode) { int n, c, h, w, in_nstr, in_cstr, in_hstr, in_wstr; int out_nstr, out_cstr, out_hstr, out_wstr; miopenGet4dTensorDescriptorLengths(inputTensor, &n, &c, &h, &w); miopenGet4dTensorDescriptorStrides(inputTensor, &in_nstr, &in_cstr, &in_hstr, &in_wstr); miopenGet4dTensorDescriptorStrides(outputTensor, &out_nstr, &out_cstr, &out_hstr, &out_wstr); (void)in_wstr; (void)out_wstr; Tcheck max_val = (sizeof(Tgpu) == 4) ? 3.402823466e+38f : 65504.; std::vector<Tcheck> channel_max((mode == MIOPEN_SOFTMAX_MODE_INSTANCE ? n : n * h * w), static_cast<Tcheck>(-max_val)); std::vector<Tcheck> results(n * c * h * w, static_cast<Tcheck>(0.0)); int ret = 0; if(mode == MIOPEN_SOFTMAX_MODE_INSTANCE) { for(int i = 0; i < n; i++) { if(algo == MIOPEN_SOFTMAX_FAST) { for(int j = 0; j < c; j++) for(int s0 = 0; s0 < h; s0++) for(int s1 = 0; s1 < w; s1++) { results[(i * c + j) * h * w + s0 * w + s1] = static_cast<Tcheck>( in[i * in_nstr + j * in_cstr + s0 * in_hstr + s1]); } } else { for(int j = 0; j < c; j++) for(int s0 = 0; s0 < h; s0++) for(int s1 = 0; s1 < w; s1++) { channel_max[i] = std::max(static_cast<Tcheck>( in[i * in_nstr + j * in_cstr + s0 * in_hstr + s1]), channel_max[i]); } for(int j = 0; j < c; j++) for(int s0 = 0; s0 < h; s0++) for(int s1 = 0; s1 < w; s1++) { results[(i * c + j) * h * w + s0 * w + s1] = static_cast<Tcheck>( in[i * in_nstr + j * in_cstr + s0 * in_hstr + s1]) - channel_max[i]; } } if(algo == MIOPEN_SOFTMAX_LOG) { Tcheck neg_inf = static_cast<Tcheck>( miopen::deref(inputTensor).GetType() == miopenHalf ? NEGATIVE_INF_FP16 : NEGATIVE_INF_FP32); channel_max[i] = neg_inf; for(int j = 0; j < c; j++) for(int s0 = 0; s0 < h; s0++) for(int s1 = 0; s1 < w; s1++) { channel_max[i] = logaddexp(results[(i * c + j) * h * w + s0 * w + s1], channel_max[i], neg_inf); } for(int j = 0; j < c; j++) for(int s0 = 0; s0 < h; s0++) for(int s1 = 0; s1 < w; s1++) { outhost[i * out_nstr + j * out_cstr + s0 * out_hstr + s1] = alpha * (results[(i * c + j) * h * w + s0 * w + s1] - channel_max[i]) + beta * outhost[i * out_nstr + j * out_cstr + s0 * out_hstr + s1]; } } else { channel_max[i] = 0.0; for(int j = 0; j < c; j++) for(int s0 = 0; s0 < h; s0++) for(int s1 = 0; s1 < w; s1++) { results[(i * c + j) * h * w + s0 * w + s1] = exp(results[(i * c + j) * h * w + s0 * w + s1]); channel_max[i] += results[(i * c + j) * h * w + s0 * w + s1]; } for(int j = 0; j < c; j++) for(int s0 = 0; s0 < h; s0++) for(int s1 = 0; s1 < w; s1++) { outhost[i * out_nstr + j * out_cstr + s0 * out_hstr + s1] = alpha * (results[(i * c + j) * h * w + s0 * w + s1] / channel_max[i]) + beta * outhost[i * out_nstr + j * out_cstr + s0 * out_hstr + s1]; } } } } else { for(int i = 0; i < n; i++) { for(int s0 = 0; s0 < h; s0++) for(int s1 = 0; s1 < w; s1++) { if(algo == MIOPEN_SOFTMAX_FAST) { for(int j = 0; j < c; j++) { results[(i * c + j) * h * w + s0 * w + s1] = static_cast<Tcheck>( in[i * in_nstr + j * in_cstr + s0 * in_hstr + s1]); } } else { for(int j = 0; j < c; j++) { channel_max[i * h * w + s0 * w + s1] = std::max(static_cast<Tcheck>( in[i * in_nstr + j * in_cstr + s0 * in_hstr + s1]), channel_max[i * h * w + s0 * w + s1]); } for(int j = 0; j < c; j++) { results[(i * c + j) * h * w + s0 * w + s1] = static_cast<Tcheck>( in[i * in_nstr + j * in_cstr + s0 * in_hstr + s1]) - channel_max[i * h * w + s0 * w + s1]; } } if(algo == MIOPEN_SOFTMAX_LOG) { Tcheck neg_inf = static_cast<Tcheck>( miopen::deref(inputTensor).GetType() == miopenHalf ? NEGATIVE_INF_FP16 : NEGATIVE_INF_FP32); channel_max[i * h * w + s0 * w + s1] = results[i * c * h * w + s0 * w + s1]; for(int j = 1; j < c; j++) { channel_max[i * h * w + s0 * w + s1] = logaddexp(results[(i * c + j) * h * w + s0 * w + s1], channel_max[i * h * w + s0 * w + s1], neg_inf); } for(int j = 0; j < c; j++) { outhost[i * out_nstr + j * out_cstr + s0 * out_hstr + s1] = alpha * (results[(i * c + j) * h * w + s0 * w + s1] - channel_max[i * h * w + s0 * w + s1]) + beta * outhost[i * out_nstr + j * out_cstr + s0 * out_hstr + s1]; } } else { channel_max[i * h * w + s0 * w + s1] = 0.0; for(int j = 0; j < c; j++) { results[(i * c + j) * h * w + s0 * w + s1] = exp(results[(i * c + j) * h * w + s0 * w + s1]); channel_max[i * h * w + s0 * w + s1] += results[(i * c + j) * h * w + s0 * w + s1]; } for(int j = 0; j < c; j++) { outhost[i * out_nstr + j * out_cstr + s0 * out_hstr + s1] = alpha * (results[(i * c + j) * h * w + s0 * w + s1] / channel_max[i * h * w + s0 * w + s1]) + beta * outhost[i * out_nstr + j * out_cstr + s0 * out_hstr + s1]; } } } } } return ret; } template <typename Tgpu /* the data type used in GPU computations (usually half) */, typename Tcheck /* the data type used in CPU checkings (usually double) */> int mloSoftmaxBackwardRunHost(miopenTensorDescriptor_t dInputTensor, miopenTensorDescriptor_t dOutputTensor, Tgpu* out, Tgpu* dout, Tcheck* dinhost, float alpha, float beta, miopenSoftmaxAlgorithm_t algo, miopenSoftmaxMode_t mode) { int n, c, h, w, in_nstr, in_cstr, in_hstr, in_wstr; int out_nstr, out_cstr, out_hstr, out_wstr; miopenGet4dTensorDescriptorLengths(dOutputTensor, &n, &c, &h, &w); miopenGet4dTensorDescriptorStrides(dInputTensor, &in_nstr, &in_cstr, &in_hstr, &in_wstr); miopenGet4dTensorDescriptorStrides(dOutputTensor, &out_nstr, &out_cstr, &out_hstr, &out_wstr); (void)in_wstr; (void)out_wstr; std::vector<Tcheck> channel_dot((mode == MIOPEN_SOFTMAX_MODE_INSTANCE ? n : n * h * w), static_cast<Tcheck>(0.0)); std::vector<Tcheck> results(n * c * h * w, static_cast<Tcheck>(0.0)); int ret = 0; for(int i = 0; i < n; i++) { if(mode == MIOPEN_SOFTMAX_MODE_INSTANCE) { for(int j = 0; j < c; j++) for(int s0 = 0; s0 < h; s0++) for(int s1 = 0; s1 < w; s1++) { channel_dot[i] += static_cast<Tcheck>( out[i * out_nstr + j * out_cstr + s0 * out_hstr + s1]) * static_cast<Tcheck>( dout[i * out_nstr + j * out_cstr + s0 * out_hstr + s1]); } for(int j = 0; j < c; j++) for(int s0 = 0; s0 < h; s0++) for(int s1 = 0; s1 < w; s1++) { results[(i * c + j) * h * w + s0 * w + s1] = static_cast<Tcheck>( dout[i * out_nstr + j * out_cstr + s0 * out_hstr + s1]) - channel_dot[i]; if(algo != MIOPEN_SOFTMAX_LOG) results[(i * c + j) * h * w + s0 * w + s1] *= static_cast<Tcheck>( out[i * out_nstr + j * out_cstr + s0 * out_hstr + s1]); dinhost[i * in_nstr + j * in_cstr + s0 * in_hstr + s1] = alpha * results[(i * c + j) * h * w + s0 * w + s1] + beta * dinhost[i * in_nstr + j * in_cstr + s0 * in_hstr + s1]; } } else { for(int s0 = 0; s0 < h; s0++) for(int s1 = 0; s1 < w; s1++) { for(int j = 0; j < c; j++) { channel_dot[i * h * w + s0 * w + s1] += static_cast<Tcheck>( out[i * out_nstr + j * out_cstr + s0 * out_hstr + s1]) * static_cast<Tcheck>( dout[i * out_nstr + j * out_cstr + s0 * out_hstr + s1]); } for(int j = 0; j < c; j++) { results[(i * c + j) * h * w + s0 * w + s1] = static_cast<Tcheck>( dout[i * out_nstr + j * out_cstr + s0 * out_hstr + s1]) - channel_dot[i * h * w + s0 * w + s1]; if(algo != MIOPEN_SOFTMAX_LOG) results[(i * c + j) * h * w + s0 * w + s1] *= static_cast<Tcheck>( out[i * out_nstr + j * out_cstr + s0 * out_hstr + s1]); dinhost[i * in_nstr + j * in_cstr + s0 * in_hstr + s1] = alpha * results[(i * c + j) * h * w + s0 * w + s1] + beta * dinhost[i * in_nstr + j * in_cstr + s0 * in_hstr + s1]; } } } } return ret; } #endif
#include "AliNanoFilterPID.h" #include <TObject.h> #include <AliAnalysisManager.h> #include <AliAODTrack.h> #include <AliESDtrackCuts.h> #include <AliInputEventHandler.h> #include <AliPIDResponse.h> #include <AliAnalysisTaskNucleiYield.h> #include <AliVEvent.h> AliNanoFilterPID::AliNanoFilterPID() : AliAnalysisCuts{}, fMinDeltaM{-2.4}, fMaxDeltaM{3.6 }, fTriggerOnSpecies{}, fTrackCuts{}, fFilterBits{}, fTOFpidTriggerNsigma{}, fTOFpidTriggerPtRange{}, fTPCpidTriggerNsigma{}, fTPCpidTriggerPtRange{} { for (int iSpecies{0}; iSpecies < AliPID::kSPECIESC; ++iSpecies) { fTriggerOnSpecies[iSpecies] = false; fTrackCuts[iSpecies] = nullptr; fFilterBits[iSpecies] = 0ul; fTOFpidTriggerNsigma[iSpecies] = -1.; fTOFpidTriggerPtRange[iSpecies][0] = 0.; fTOFpidTriggerPtRange[iSpecies][1] = 1000.; fTPCpidTriggerNsigma[iSpecies] = -1.; fTPCpidTriggerPtRange[iSpecies][0] = 0.; fTPCpidTriggerPtRange[iSpecies][1] = 1000.; } } void AliNanoFilterPID::TriggerOnSpecies(AliPID::EParticleType sp, AliESDtrackCuts *cuts, ULong_t fb, double nsigmaTPC, double ptRangeTPC[2], double nsigmaTOF, double ptRangeTOF[2]) { fTriggerOnSpecies[sp] = true; fTrackCuts[sp] = cuts; fFilterBits[sp] = fb; fTOFpidTriggerNsigma[sp] = nsigmaTOF; fTOFpidTriggerPtRange[sp][0] = ptRangeTOF[0]; fTOFpidTriggerPtRange[sp][1] = ptRangeTOF[1]; fTPCpidTriggerNsigma[sp] = nsigmaTPC; fTPCpidTriggerPtRange[sp][0] = ptRangeTPC[0]; fTPCpidTriggerPtRange[sp][1] = ptRangeTPC[1]; } bool AliNanoFilterPID::IsSelected(TObject *obj) { fSelected = false; fFilterMask = 0u; AliVTrack *trk = dynamic_cast<AliVTrack *>(obj); if (!trk) { return fSelected; } AliAODTrack* aodTrk = dynamic_cast<AliAODTrack *>(obj); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); AliInputEventHandler *handl = (AliInputEventHandler *)mgr->GetInputEventHandler(); AliPIDResponse *pid = handl->GetPIDResponse(); for (int iSpecies{0}; iSpecies < AliPID::kSPECIESC; ++iSpecies) { if (!fTriggerOnSpecies[iSpecies]) continue; if (fTrackCuts[iSpecies]) if (!fTrackCuts[iSpecies]->AcceptVTrack(trk)) continue; if (aodTrk && fFilterBits[iSpecies]) if (!aodTrk->TestFilterBit(fFilterBits[iSpecies])) continue; double pt = trk->Pt() * AliPID::ParticleCharge(iSpecies); double nTPCsigma = std::abs(pid->NumberOfSigmasTPC(trk, AliPID::EParticleType(iSpecies))); double nTOFsigma = std::abs(pid->NumberOfSigmasTOF(trk, AliPID::EParticleType(iSpecies))); float beta = AliAnalysisTaskNucleiYield::HasTOF(aodTrk,pid); if (beta > 1. - EPS) beta = -1; const float m2 = aodTrk->P() * aodTrk->P() * (1.f / (beta * beta) - 1.f); bool goodTOF = m2 > fMinDeltaM && m2 < fMaxDeltaM; if ((nTPCsigma < fTPCpidTriggerNsigma[iSpecies] && pt > fTPCpidTriggerPtRange[iSpecies][0] && pt < fTPCpidTriggerPtRange[iSpecies][1]) || (goodTOF && nTOFsigma < fTOFpidTriggerNsigma[iSpecies] && pt > fTOFpidTriggerPtRange[iSpecies][0] && pt < fTOFpidTriggerPtRange[iSpecies][1])) { SETBIT(fFilterMask,iSpecies); fSelected = true; } } return fSelected; } bool AliNanoFilterPID::IsSelected(TList *) { Fatal("AliNanoFilterPID::IsSelected","Method not implemented for lists"); return false; }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync/engine_impl/cycle/mock_debug_info_getter.h" namespace syncer { MockDebugInfoGetter::MockDebugInfoGetter() {} MockDebugInfoGetter::~MockDebugInfoGetter() {} void MockDebugInfoGetter::GetDebugInfo(sync_pb::DebugInfo* debug_info) { debug_info->CopyFrom(debug_info_); } void MockDebugInfoGetter::ClearDebugInfo() { debug_info_.Clear(); } void MockDebugInfoGetter::AddDebugEvent() { debug_info_.add_events(); } } // namespace syncer
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/preference/DialogPreferenceSavedState.h" namespace Elastos { namespace Droid { namespace Preference { CAR_INTERFACE_IMPL(DialogPreferenceSavedState, PreferenceBaseSavedState, IDialogPreferenceSavedState) DialogPreferenceSavedState::DialogPreferenceSavedState() : mIsDialogShowing(FALSE) {} ECode DialogPreferenceSavedState::constructor() { return PreferenceBaseSavedState::constructor(); } ECode DialogPreferenceSavedState::constructor( /* [in] */ IParcelable* source) { return PreferenceBaseSavedState::constructor(source); } ECode DialogPreferenceSavedState::GetIsDialogShowing( /* [out] */ Boolean* isShow) { VALIDATE_NOT_NULL(isShow) *isShow = mIsDialogShowing; return NOERROR; } ECode DialogPreferenceSavedState::SetIsDialogShowing( /* [in] */ Boolean isShow) { mIsDialogShowing = isShow; return NOERROR; } ECode DialogPreferenceSavedState::GetDialogBundle( /* [out] */ IBundle** bundle) { VALIDATE_NOT_NULL(bundle) *bundle = mDialogBundle; REFCOUNT_ADD(*bundle) return NOERROR; } ECode DialogPreferenceSavedState::SetDialogBundle( /* [in] */ IBundle* bundle) { mDialogBundle = bundle; return NOERROR; } ECode DialogPreferenceSavedState::ReadFromParcel( /* [in] */ IParcel* source) { PreferenceBaseSavedState::ReadFromParcel(source); source->ReadBoolean(&mIsDialogShowing); mDialogBundle = NULL; source->ReadInterfacePtr((Handle32*)(IBundle**)&mDialogBundle); return NOERROR; } ECode DialogPreferenceSavedState::WriteToParcel( /* [in] */ IParcel* dest) { PreferenceBaseSavedState::WriteToParcel(dest); dest->WriteBoolean(mIsDialogShowing); dest->WriteInterfacePtr(mDialogBundle); return NOERROR; } ECode DialogPreferenceSavedState::GetSuperState( /* [out] */ IParcelable** superState) { return PreferenceBaseSavedState::GetSuperState(superState); } } // Preference } // Droid } // Elastos
/* * This file is part of hipSYCL, a SYCL implementation based on CUDA/HIP * * Copyright (c) 2018 Aksel Alpay * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef HIPSYCL_VEC_HPP #define HIPSYCL_VEC_HPP #include <cstddef> #include <type_traits> #include "hipSYCL/sycl/libkernel/backend.hpp" #include "hipSYCL/sycl/types.hpp" #include "hipSYCL/sycl/access.hpp" #include "multi_ptr.hpp" #include "detail/vec.hpp" #include "detail/vec_common.hpp" #include "detail/vec_swizzle.hpp" namespace hipsycl { namespace sycl { namespace detail { template<class T, int N, class Function> HIPSYCL_UNIVERSAL_TARGET inline void transform_vector(vec<T,N>& v, Function f); template<class T, int N, class Function> HIPSYCL_UNIVERSAL_TARGET inline vec<T,N> binary_vector_operation(const vec<T,N>& a, const vec<T,N>& b, Function f); template<class T, int N, class Function> HIPSYCL_UNIVERSAL_TARGET inline vec<T,N> trinary_vector_operation(const vec<T,N>& a, const vec<T,N>& b, const vec<T,N>& c, Function f); } // detail struct elem { static constexpr int x = 0; static constexpr int y = 1; static constexpr int z = 2; static constexpr int w = 3; static constexpr int r = 0; static constexpr int g = 1; static constexpr int b = 2; static constexpr int a = 3; static constexpr int s0 = 0; static constexpr int s1 = 1; static constexpr int s2 = 2; static constexpr int s3 = 3; static constexpr int s4 = 4; static constexpr int s5 = 5; static constexpr int s6 = 6; static constexpr int s7 = 7; static constexpr int s8 = 8; static constexpr int s9 = 9; static constexpr int sA = 10; static constexpr int sB = 11; static constexpr int sC = 12; static constexpr int sD = 13; static constexpr int sE = 14; static constexpr int sF = 15; }; template <typename dataT, int numElements> class vec { template<class T, int N, class Function> HIPSYCL_UNIVERSAL_TARGET friend void detail::transform_vector(vec<T,N>& v, Function f); template<class T, int N, class Function> HIPSYCL_UNIVERSAL_TARGET friend vec<T,N> detail::binary_vector_operation(const vec<T,N>& a, const vec<T,N>& b, Function f); template<class T, int N, class Function> HIPSYCL_UNIVERSAL_TARGET friend vec<T,N> detail::trinary_vector_operation(const vec<T,N>& a, const vec<T,N>& b, const vec<T,N>& c, Function f); template<class T, int N> friend class vec; HIPSYCL_UNIVERSAL_TARGET explicit vec(const detail::vector_impl<dataT,numElements>& v) : _impl{v} {} /// Initialization from numElements scalars template<int... Indices, typename... Args> HIPSYCL_UNIVERSAL_TARGET void scalar_init(detail::vector_index_sequence<Indices...>, Args... args) { static_assert(sizeof...(args) == numElements, "Invalid number of arguments for vector " "initialization"); auto dummy_initializer = { ((_impl.template set<Indices>(args)), 0)... }; } /// Initialization from single scalar template<int... Indices> HIPSYCL_UNIVERSAL_TARGET void broadcast_scalar_init(detail::vector_index_sequence<Indices...>, dataT x) { auto dummy_initializer = { ((_impl.template set<Indices>(x)), 0)... }; } template<int Start_index, int N, int... Indices> HIPSYCL_UNIVERSAL_TARGET constexpr void init_from_vec(detail::vector_index_sequence<Indices...>, const vec<dataT,N>& other) { auto dummy_initializer = { ((_impl.template set<Start_index + Indices>( other._impl.template get<Indices>())), 0)... }; } template<int Start_index, int N> HIPSYCL_UNIVERSAL_TARGET constexpr void init_from_vec(const vec<dataT,N>& other) { init_from_vec<Start_index>(typename detail::vector_impl<dataT,N>::indices(), other); } template<int Position> HIPSYCL_UNIVERSAL_TARGET constexpr void init_from_argument() { static_assert (Position == numElements, "Invalid number of vector " "constructor arguments."); } template<int Position, typename... Args> HIPSYCL_UNIVERSAL_TARGET constexpr void init_from_argument(dataT scalar, const Args&... args) { _impl.template set<Position>(scalar); init_from_argument<Position+1>(args...); } template<int Position, int N, typename... Args> HIPSYCL_UNIVERSAL_TARGET constexpr void init_from_argument(const vec<dataT,N>& v, const Args&... args) { init_from_vec<Position>(v); init_from_argument<Position + N>(args...); } template<int... swizzleIndices> HIPSYCL_UNIVERSAL_TARGET auto swizzle_index_sequence(detail::vector_index_sequence<swizzleIndices...>) const { return swizzle<swizzleIndices...>(); } public: static_assert(numElements == 1 || numElements == 2 || numElements == 3 || numElements == 4 || numElements == 8 || numElements == 16, "Invalid number of vector elements. Allowed values: " "1,2,3,4,8,16"); using element_type = dataT; #ifdef SYCL_DEVICE_ONLY using vector_t = vec<dataT, numElements>; #endif HIPSYCL_UNIVERSAL_TARGET vec() : _impl {} {} template<int Original_vector_size, int... Swizzle_indices> HIPSYCL_UNIVERSAL_TARGET vec(const detail::vec_swizzle<dataT, Original_vector_size, Swizzle_indices...>& swizzled_vec) : _impl{swizzled_vec.swizzled_access().get()} {} HIPSYCL_UNIVERSAL_TARGET explicit vec(const dataT &arg) { broadcast_scalar_init(typename detail::vector_impl<dataT,numElements>::indices(), arg); } template <typename... argTN> HIPSYCL_UNIVERSAL_TARGET vec(const argTN&... args) { init_from_argument<0>(args...); } vec(const vec<dataT, numElements> &rhs) = default; // OpenCL interop is unsupported //#ifdef SYCL_DEVICE_ONLY //vec(vector_t openclVector); //operator vector_t() const; //#endif // Available only when: numElements == 1 template<int N = numElements, std::enable_if_t<N == 1>* = nullptr> HIPSYCL_UNIVERSAL_TARGET operator dataT() const { return _impl.template get<0>(); } HIPSYCL_UNIVERSAL_TARGET static constexpr int get_count() { return numElements; } HIPSYCL_UNIVERSAL_TARGET static constexpr size_t get_size() { return numElements * sizeof (dataT); } // ToDo template <typename convertT, rounding_mode roundingMode> vec<convertT, numElements> convert() const; // ToDo template <typename asT> asT as() const; #define HIPSYCL_DEFINE_VECTOR_ACCESS_IF(condition, name, id) \ template<int N = numElements, \ std::enable_if_t<(id < N) && (condition)>* = nullptr> \ HIPSYCL_UNIVERSAL_TARGET \ dataT& name() \ { return _impl.template get<id>(); } \ \ template<int N = numElements, \ std::enable_if_t<(id < N) && (condition)>* = nullptr> \ HIPSYCL_UNIVERSAL_TARGET \ dataT name() const \ { return _impl.template get<id>(); } HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 4, x, 0) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 4, y, 1) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 4, z, 2) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 4, w, 3) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements == 4, r, 0) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements == 4, g, 1) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements == 4, b, 2) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements == 4, a, 3) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, s0, 0) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, s1, 1) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, s2, 2) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, s3, 3) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, s4, 4) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, s5, 5) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, s6, 6) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, s7, 7) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, s8, 8) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, s9, 9) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, sA, 10) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, sB, 11) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, sC, 12) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, sD, 13) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, sE, 14) HIPSYCL_DEFINE_VECTOR_ACCESS_IF(numElements <= 16, sF, 15) template<int... swizzleIndexes> HIPSYCL_UNIVERSAL_TARGET auto swizzle() const { return detail::vec_swizzle<dataT, numElements, swizzleIndexes...>{ const_cast<detail::vector_impl<dataT,numElements>&>(_impl) }; } template<int N = numElements, std::enable_if_t<(N > 1)>* = nullptr> HIPSYCL_UNIVERSAL_TARGET auto lo() const { return swizzle_index_sequence( typename detail::vector_impl<dataT, numElements>::lo_indices()); } template<int N = numElements, std::enable_if_t<(N > 1)>* = nullptr> HIPSYCL_UNIVERSAL_TARGET auto hi() const { return swizzle_index_sequence( typename detail::vector_impl<dataT, numElements>::hi_indices()); } template<int N = numElements, std::enable_if_t<(N > 1)>* = nullptr> HIPSYCL_UNIVERSAL_TARGET auto even() const { return swizzle_index_sequence( typename detail::vector_impl<dataT, numElements>::even_indices()); } template<int N = numElements, std::enable_if_t<(N > 1)>* = nullptr> HIPSYCL_UNIVERSAL_TARGET auto odd() const { return swizzle_index_sequence( typename detail::vector_impl<dataT, numElements>::odd_indices()); } #ifdef SYCL_SIMPLE_SWIZZLES #define HIPSYCL_DEFINE_VECTOR_SWIZZLE2(name, N, i0, i1) \ template<int n = numElements, \ std::enable_if_t<(n >= N && n <= 4)>* = nullptr> \ HIPSYCL_UNIVERSAL_TARGET \ auto name() const \ {return swizzle<i0,i1>(); } #define HIPSYCL_DEFINE_VECTOR_SWIZZLE3(name, N, i0, i1, i2) \ template<int n = numElements, \ std::enable_if_t<(n >= N && n <= 4)>* = nullptr> \ HIPSYCL_UNIVERSAL_TARGET \ auto name() const \ {return swizzle<i0,i1,i2>(); } #define HIPSYCL_DEFINE_VECTOR_SWIZZLE4(name, i0, i1, i2, i3) \ template<int n = numElements, \ std::enable_if_t<(n == 4)>* = nullptr> \ HIPSYCL_UNIVERSAL_TARGET \ auto name() const \ {return swizzle<i0,i1,i2,i3>(); } HIPSYCL_DEFINE_VECTOR_SWIZZLE2(xx, 2, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(yx, 2, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(xy, 2, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(yy, 2, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(xz, 3, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(yz, 3, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(zy, 3, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(zx, 3, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(zz, 3, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(xw, 4, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(yw, 4, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(zw, 4, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(ww, 4, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(wx, 4, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(wy, 4, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE2(wz, 4, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xxx, 3, 0, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(yxx, 3, 1, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zxx, 3, 2, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xyx, 3, 0, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(yyx, 3, 1, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zyx, 3, 2, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xzx, 3, 0, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(yzx, 3, 1, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zzx, 3, 2, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xxy, 3, 0, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(yxy, 3, 1, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zxy, 3, 2, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xyy, 3, 0, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(yyy, 3, 1, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zyy, 3, 2, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xzy, 3, 0, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(yzy, 3, 1, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zzy, 3, 2, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xxz, 3, 0, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(yxz, 3, 1, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zxz, 3, 2, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xyz, 3, 0, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(yyz, 3, 1, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zyz, 3, 2, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xzz, 3, 0, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(yzz, 3, 1, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zzz, 3, 2, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xxw, 4, 0, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(yxw, 4, 1, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zxw, 4, 2, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xyw, 4, 0, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(yyw, 4, 1, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zyw, 4, 2, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xzw, 4, 0, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(yzw, 4, 1, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zzw, 4, 2, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xwx, 4, 0, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(ywx, 4, 1, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zwx, 4, 2, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xwy, 4, 0, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(ywy, 4, 1, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zwy, 4, 2, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xwz, 4, 0, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(ywz, 4, 1, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zwz, 4, 2, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(wxx, 4, 3, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(wyx, 4, 3, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(wzx, 4, 3, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(wxy, 4, 3, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(wyy, 4, 3, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(wzy, 4, 3, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(wxz, 4, 3, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(wyz, 4, 3, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(wzz, 4, 3, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(xww, 4, 0, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(yww, 4, 1, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(zww, 4, 2, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(wwx, 4, 3, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(wwy, 4, 3, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(wwz, 4, 3, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE3(www, 4, 3, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxxx, 0, 0, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrrr, 0, 0, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxxx, 1, 0, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grrr, 1, 0, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxxx, 2, 0, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brrr, 2, 0, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxxx, 3, 0, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(arrr, 3, 0, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xyxx, 0, 1, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rgrr, 0, 1, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yyxx, 1, 1, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ggrr, 1, 1, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zyxx, 2, 1, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bgrr, 2, 1, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wyxx, 3, 1, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(agrr, 3, 1, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzxx, 0, 2, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbrr, 0, 2, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzxx, 1, 2, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbrr, 1, 2, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzxx, 2, 2, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbrr, 2, 2, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzxx, 3, 2, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abrr, 3, 2, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwxx, 0, 3, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rarr, 0, 3, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywxx, 1, 3, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(garr, 1, 3, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwxx, 2, 3, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(barr, 2, 3, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwxx, 3, 3, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aarr, 3, 3, 0, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxyx, 0, 0, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrgr, 0, 0, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxyx, 1, 0, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grgr, 1, 0, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxyx, 2, 0, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brgr, 2, 0, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxyx, 3, 0, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(argr, 3, 0, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xyyx, 0, 1, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rggr, 0, 1, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yyyx, 1, 1, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gggr, 1, 1, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zyyx, 2, 1, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bggr, 2, 1, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wyyx, 3, 1, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aggr, 3, 1, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzyx, 0, 2, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbgr, 0, 2, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzyx, 1, 2, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbgr, 1, 2, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzyx, 2, 2, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbgr, 2, 2, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzyx, 3, 2, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abgr, 3, 2, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwyx, 0, 3, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ragr, 0, 3, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywyx, 1, 3, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gagr, 1, 3, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwyx, 2, 3, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bagr, 2, 3, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwyx, 3, 3, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aagr, 3, 3, 1, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxzx, 0, 0, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrbr, 0, 0, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxzx, 1, 0, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grbr, 1, 0, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxzx, 2, 0, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brbr, 2, 0, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxzx, 3, 0, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(arbr, 3, 0, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xyzx, 0, 1, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rgbr, 0, 1, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yyzx, 1, 1, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ggbr, 1, 1, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zyzx, 2, 1, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bgbr, 2, 1, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wyzx, 3, 1, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(agbr, 3, 1, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzzx, 0, 2, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbbr, 0, 2, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzzx, 1, 2, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbbr, 1, 2, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzzx, 2, 2, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbbr, 2, 2, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzzx, 3, 2, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abbr, 3, 2, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwzx, 0, 3, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rabr, 0, 3, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywzx, 1, 3, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gabr, 1, 3, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwzx, 2, 3, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(babr, 2, 3, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwzx, 3, 3, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aabr, 3, 3, 2, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxwx, 0, 0, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrar, 0, 0, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxwx, 1, 0, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grar, 1, 0, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxwx, 2, 0, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brar, 2, 0, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxwx, 3, 0, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(arar, 3, 0, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xywx, 0, 1, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rgar, 0, 1, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yywx, 1, 1, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ggar, 1, 1, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zywx, 2, 1, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bgar, 2, 1, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wywx, 3, 1, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(agar, 3, 1, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzwx, 0, 2, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbar, 0, 2, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzwx, 1, 2, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbar, 1, 2, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzwx, 2, 2, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbar, 2, 2, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzwx, 3, 2, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abar, 3, 2, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwwx, 0, 3, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(raar, 0, 3, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywwx, 1, 3, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gaar, 1, 3, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwwx, 2, 3, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(baar, 2, 3, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwwx, 3, 3, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aaar, 3, 3, 3, 0) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxxy, 0, 0, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrrg, 0, 0, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxxy, 1, 0, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grrg, 1, 0, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxxy, 2, 0, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brrg, 2, 0, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxxy, 3, 0, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(arrg, 3, 0, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xyxy, 0, 1, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rgrg, 0, 1, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yyxy, 1, 1, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ggrg, 1, 1, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zyxy, 2, 1, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bgrg, 2, 1, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wyxy, 3, 1, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(agrg, 3, 1, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzxy, 0, 2, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbrg, 0, 2, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzxy, 1, 2, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbrg, 1, 2, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzxy, 2, 2, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbrg, 2, 2, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzxy, 3, 2, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abrg, 3, 2, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwxy, 0, 3, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rarg, 0, 3, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywxy, 1, 3, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(garg, 1, 3, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwxy, 2, 3, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(barg, 2, 3, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwxy, 3, 3, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aarg, 3, 3, 0, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxyy, 0, 0, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrgg, 0, 0, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxyy, 1, 0, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grgg, 1, 0, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxyy, 2, 0, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brgg, 2, 0, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxyy, 3, 0, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(argg, 3, 0, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xyyy, 0, 1, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rggg, 0, 1, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yyyy, 1, 1, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gggg, 1, 1, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zyyy, 2, 1, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bggg, 2, 1, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wyyy, 3, 1, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aggg, 3, 1, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzyy, 0, 2, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbgg, 0, 2, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzyy, 1, 2, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbgg, 1, 2, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzyy, 2, 2, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbgg, 2, 2, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzyy, 3, 2, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abgg, 3, 2, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwyy, 0, 3, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ragg, 0, 3, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywyy, 1, 3, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gagg, 1, 3, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwyy, 2, 3, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bagg, 2, 3, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwyy, 3, 3, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aagg, 3, 3, 1, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxzy, 0, 0, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrbg, 0, 0, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxzy, 1, 0, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grbg, 1, 0, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxzy, 2, 0, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brbg, 2, 0, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxzy, 3, 0, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(arbg, 3, 0, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xyzy, 0, 1, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rgbg, 0, 1, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yyzy, 1, 1, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ggbg, 1, 1, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zyzy, 2, 1, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bgbg, 2, 1, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wyzy, 3, 1, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(agbg, 3, 1, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzzy, 0, 2, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbbg, 0, 2, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzzy, 1, 2, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbbg, 1, 2, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzzy, 2, 2, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbbg, 2, 2, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzzy, 3, 2, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abbg, 3, 2, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwzy, 0, 3, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rabg, 0, 3, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywzy, 1, 3, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gabg, 1, 3, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwzy, 2, 3, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(babg, 2, 3, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwzy, 3, 3, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aabg, 3, 3, 2, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxwy, 0, 0, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrag, 0, 0, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxwy, 1, 0, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grag, 1, 0, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxwy, 2, 0, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brag, 2, 0, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxwy, 3, 0, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(arag, 3, 0, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xywy, 0, 1, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rgag, 0, 1, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yywy, 1, 1, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ggag, 1, 1, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zywy, 2, 1, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bgag, 2, 1, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wywy, 3, 1, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(agag, 3, 1, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzwy, 0, 2, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbag, 0, 2, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzwy, 1, 2, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbag, 1, 2, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzwy, 2, 2, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbag, 2, 2, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzwy, 3, 2, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abag, 3, 2, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwwy, 0, 3, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(raag, 0, 3, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywwy, 1, 3, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gaag, 1, 3, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwwy, 2, 3, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(baag, 2, 3, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwwy, 3, 3, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aaag, 3, 3, 3, 1) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxxz, 0, 0, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrrb, 0, 0, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxxz, 1, 0, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grrb, 1, 0, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxxz, 2, 0, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brrb, 2, 0, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxxz, 3, 0, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(arrb, 3, 0, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xyxz, 0, 1, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rgrb, 0, 1, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yyxz, 1, 1, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ggrb, 1, 1, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zyxz, 2, 1, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bgrb, 2, 1, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wyxz, 3, 1, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(agrb, 3, 1, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzxz, 0, 2, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbrb, 0, 2, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzxz, 1, 2, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbrb, 1, 2, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzxz, 2, 2, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbrb, 2, 2, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzxz, 3, 2, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abrb, 3, 2, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwxz, 0, 3, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rarb, 0, 3, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywxz, 1, 3, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(garb, 1, 3, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwxz, 2, 3, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(barb, 2, 3, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwxz, 3, 3, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aarb, 3, 3, 0, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxyz, 0, 0, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrgb, 0, 0, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxyz, 1, 0, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grgb, 1, 0, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxyz, 2, 0, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brgb, 2, 0, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxyz, 3, 0, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(argb, 3, 0, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xyyz, 0, 1, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rggb, 0, 1, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yyyz, 1, 1, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gggb, 1, 1, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zyyz, 2, 1, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bggb, 2, 1, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wyyz, 3, 1, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aggb, 3, 1, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzyz, 0, 2, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbgb, 0, 2, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzyz, 1, 2, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbgb, 1, 2, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzyz, 2, 2, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbgb, 2, 2, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzyz, 3, 2, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abgb, 3, 2, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwyz, 0, 3, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ragb, 0, 3, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywyz, 1, 3, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gagb, 1, 3, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwyz, 2, 3, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bagb, 2, 3, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwyz, 3, 3, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aagb, 3, 3, 1, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxzz, 0, 0, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrbb, 0, 0, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxzz, 1, 0, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grbb, 1, 0, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxzz, 2, 0, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brbb, 2, 0, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxzz, 3, 0, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(arbb, 3, 0, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xyzz, 0, 1, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rgbb, 0, 1, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yyzz, 1, 1, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ggbb, 1, 1, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zyzz, 2, 1, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bgbb, 2, 1, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wyzz, 3, 1, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(agbb, 3, 1, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzzz, 0, 2, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbbb, 0, 2, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzzz, 1, 2, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbbb, 1, 2, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzzz, 2, 2, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbbb, 2, 2, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzzz, 3, 2, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abbb, 3, 2, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwzz, 0, 3, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rabb, 0, 3, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywzz, 1, 3, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gabb, 1, 3, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwzz, 2, 3, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(babb, 2, 3, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwzz, 3, 3, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aabb, 3, 3, 2, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxwz, 0, 0, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrab, 0, 0, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxwz, 1, 0, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grab, 1, 0, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxwz, 2, 0, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brab, 2, 0, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxwz, 3, 0, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(arab, 3, 0, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xywz, 0, 1, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rgab, 0, 1, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yywz, 1, 1, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ggab, 1, 1, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zywz, 2, 1, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bgab, 2, 1, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wywz, 3, 1, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(agab, 3, 1, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzwz, 0, 2, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbab, 0, 2, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzwz, 1, 2, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbab, 1, 2, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzwz, 2, 2, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbab, 2, 2, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzwz, 3, 2, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abab, 3, 2, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwwz, 0, 3, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(raab, 0, 3, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywwz, 1, 3, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gaab, 1, 3, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwwz, 2, 3, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(baab, 2, 3, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwwz, 3, 3, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aaab, 3, 3, 3, 2) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxxw, 0, 0, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrra, 0, 0, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxxw, 1, 0, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grra, 1, 0, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxxw, 2, 0, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brra, 2, 0, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxxw, 3, 0, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(arra, 3, 0, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xyxw, 0, 1, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rgra, 0, 1, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yyxw, 1, 1, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ggra, 1, 1, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zyxw, 2, 1, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bgra, 2, 1, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wyxw, 3, 1, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(agra, 3, 1, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzxw, 0, 2, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbra, 0, 2, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzxw, 1, 2, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbra, 1, 2, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzxw, 2, 2, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbra, 2, 2, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzxw, 3, 2, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abra, 3, 2, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwxw, 0, 3, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rara, 0, 3, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywxw, 1, 3, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gara, 1, 3, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwxw, 2, 3, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bara, 2, 3, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwxw, 3, 3, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aara, 3, 3, 0, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxyw, 0, 0, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrga, 0, 0, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxyw, 1, 0, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grga, 1, 0, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxyw, 2, 0, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brga, 2, 0, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxyw, 3, 0, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(arga, 3, 0, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xyyw, 0, 1, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rgga, 0, 1, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yyyw, 1, 1, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ggga, 1, 1, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zyyw, 2, 1, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bgga, 2, 1, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wyyw, 3, 1, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(agga, 3, 1, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzyw, 0, 2, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbga, 0, 2, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzyw, 1, 2, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbga, 1, 2, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzyw, 2, 2, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbga, 2, 2, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzyw, 3, 2, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abga, 3, 2, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwyw, 0, 3, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(raga, 0, 3, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywyw, 1, 3, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gaga, 1, 3, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwyw, 2, 3, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(baga, 2, 3, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwyw, 3, 3, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aaga, 3, 3, 1, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxzw, 0, 0, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rrba, 0, 0, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxzw, 1, 0, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(grba, 1, 0, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxzw, 2, 0, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(brba, 2, 0, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxzw, 3, 0, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(arba, 3, 0, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xyzw, 0, 1, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rgba, 0, 1, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yyzw, 1, 1, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ggba, 1, 1, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zyzw, 2, 1, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bgba, 2, 1, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wyzw, 3, 1, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(agba, 3, 1, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzzw, 0, 2, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbba, 0, 2, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzzw, 1, 2, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbba, 1, 2, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzzw, 2, 2, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbba, 2, 2, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzzw, 3, 2, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abba, 3, 2, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwzw, 0, 3, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(raba, 0, 3, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywzw, 1, 3, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gaba, 1, 3, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwzw, 2, 3, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(baba, 2, 3, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwzw, 3, 3, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aaba, 3, 3, 2, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xxww, 0, 0, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rraa, 0, 0, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yxww, 1, 0, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(graa, 1, 0, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zxww, 2, 0, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(braa, 2, 0, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wxww, 3, 0, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(araa, 3, 0, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xyww, 0, 1, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rgaa, 0, 1, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yyww, 1, 1, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ggaa, 1, 1, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zyww, 2, 1, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bgaa, 2, 1, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wyww, 3, 1, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(agaa, 3, 1, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xzww, 0, 2, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(rbaa, 0, 2, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(yzww, 1, 2, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gbaa, 1, 2, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zzww, 2, 2, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(bbaa, 2, 2, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wzww, 3, 2, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(abaa, 3, 2, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(xwww, 0, 3, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(raaa, 0, 3, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(ywww, 1, 3, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(gaaa, 1, 3, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(zwww, 2, 3, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(baaa, 2, 3, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(wwww, 3, 3, 3, 3) HIPSYCL_DEFINE_VECTOR_SWIZZLE4(aaaa, 3, 3, 3, 3) #endif // ToDo: load and store member functions template <access::address_space addressSpace> HIPSYCL_UNIVERSAL_TARGET void load(size_t offset, multi_ptr<dataT, addressSpace> ptr); template <access::address_space addressSpace> HIPSYCL_UNIVERSAL_TARGET void store(size_t offset, multi_ptr<dataT, addressSpace> ptr) const; // OP is: +, -, *, /, % /* When OP is % available only when: dataT != cl_float && dataT != cl_double && dataT != cl_half. */ HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator+(const vec<dataT, numElements> &lhs, const vec<dataT, numElements> &rhs) { return vec<dataT,numElements>{lhs._impl + rhs._impl}; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator-(const vec<dataT, numElements> &lhs, const vec<dataT, numElements> &rhs) { return vec<dataT,numElements>{lhs._impl - rhs._impl}; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator*(const vec<dataT, numElements> &lhs, const vec<dataT, numElements> &rhs) { return vec<dataT,numElements>{lhs._impl * rhs._impl}; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator/(const vec<dataT, numElements> &lhs, const vec<dataT, numElements> &rhs) { return vec<dataT,numElements>{lhs._impl / rhs._impl}; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator%(const vec<dataT, numElements> &lhs, const vec<dataT, numElements> &rhs) { return vec<dataT,numElements>{lhs._impl % rhs._impl}; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator+(const vec<dataT, numElements> &lhs, const dataT &rhs) { return vec<dataT,numElements>{lhs._impl + rhs}; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator-(const vec<dataT, numElements> &lhs, const dataT &rhs) { return vec<dataT,numElements>{lhs._impl - rhs}; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator*(const vec<dataT, numElements> &lhs, const dataT &rhs) { return vec<dataT,numElements>{lhs._impl * rhs}; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator/(const vec<dataT, numElements> &lhs, const dataT &rhs) { return vec<dataT,numElements>{lhs._impl / rhs}; } // OP is: +=, -=, *=, /=, %= /* When OP is %= available only when: dataT != cl_float && dataT != cl_double && dataT != cl_half. */ HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> &operator+=(vec<dataT, numElements> &lhs, const vec<dataT, numElements> &rhs) { lhs._impl += rhs._impl; return lhs; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> &operator-=(vec<dataT, numElements> &lhs, const vec<dataT, numElements> &rhs) { lhs._impl -= rhs._impl; return lhs; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> &operator*=(vec<dataT, numElements> &lhs, const vec<dataT, numElements> &rhs) { lhs._impl *= rhs._impl; return lhs; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> &operator/=(vec<dataT, numElements> &lhs, const vec<dataT, numElements> &rhs) { lhs._impl /= rhs._impl; return lhs; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> &operator%=(vec<dataT, numElements> &lhs, const vec<dataT, numElements> &rhs) { lhs._impl %= rhs._impl; return lhs; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> &operator+=(vec<dataT, numElements> &lhs, const dataT &rhs) { lhs._impl += rhs; return lhs; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> &operator-=(vec<dataT, numElements> &lhs, const dataT &rhs) { lhs._impl -= rhs; return lhs; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> &operator*=(vec<dataT, numElements> &lhs, const dataT &rhs) { lhs._impl *= rhs; return lhs; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> &operator/=(vec<dataT, numElements> &lhs, const dataT &rhs) { lhs._impl /= rhs; return lhs; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> &operator%=(vec<dataT, numElements> &lhs, const dataT &rhs) { lhs._impl %= rhs; return lhs; } // OP is: ++, -- HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> &operator++(vec<dataT, numElements> &lhs) { lhs += 1; return lhs; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> &operator--(vec<dataT, numElements> &lhs) { lhs -= 1; return lhs; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator++(vec<dataT, numElements> &lhs,int) { vec<dataT, numElements> old = lhs; ++lhs; return old; } HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator--(vec<dataT, numElements> &lhs, int) { vec<dataT, numElements> old = lhs; --lhs; return old; } // OP is: &, |, ˆ /* Available only when: dataT != cl_float && dataT != cl_double && dataT != cl_half. */ template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator&(const vec<dataT,numElements> &lhs, const vec<dataT,numElements> &rhs) { return vec<dataT,numElements>{lhs._impl & rhs._impl}; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator|(const vec<dataT, numElements> &lhs, const vec<dataT,numElements> &rhs) { return vec<dataT,numElements>{lhs._impl | rhs._impl}; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator^(const vec<dataT, numElements> &lhs, const vec<dataT,numElements> &rhs) { return vec<dataT,numElements>{lhs._impl ^ rhs._impl}; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator&(const vec<dataT, numElements> &lhs, const dataT &rhs) { return vec<dataT,numElements>{lhs._impl & rhs}; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator|(const vec<dataT, numElements> &lhs, const dataT &rhs) { return vec<dataT,numElements>{lhs._impl | rhs}; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements> operator^(const vec<dataT, numElements> &lhs, const dataT &rhs) { return vec<dataT,numElements>{lhs._impl ^ rhs}; } // OP is: &=, |=, ˆ= /* Available only when: dataT != cl_float && dataT != cl_double && dataT != cl_half. */ template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements>& operator&=(vec<dataT, numElements> &lhs, const vec<dataT,numElements> &rhs) { lhs._impl &= rhs._impl; return lhs; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements>& operator|=(vec<dataT, numElements> &lhs, const vec<dataT,numElements> &rhs) { lhs._impl |= rhs._impl; return lhs; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements>& operator^=(const vec<dataT, numElements> &lhs, const vec<dataT,numElements> &rhs) { lhs._impl ^= rhs._impl; return lhs; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements>& operator&=(const vec<dataT, numElements> &lhs, const dataT& rhs) { lhs._impl &= rhs; return lhs; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements>& operator|=(const vec<dataT, numElements> &lhs, const dataT& rhs) { lhs._impl |= rhs; return lhs; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements>& operator^=(const vec<dataT, numElements> &lhs, const dataT& rhs) { lhs._impl ^= rhs; return lhs; } HIPSYCL_UNIVERSAL_TARGET friend auto operator&& (const vec<dataT, numElements>& lhs, const vec<dataT, numElements>& rhs) { using result_type = typename detail::logical_vector_op_result<dataT>::type; return vec<result_type, numElements>{ lhs._impl && rhs._impl }; } HIPSYCL_UNIVERSAL_TARGET friend auto operator|| (const vec<dataT, numElements> &lhs, const vec<dataT, numElements>& rhs) { using result_type = typename detail::logical_vector_op_result<dataT>::type; return vec<result_type, numElements>{ lhs._impl || rhs._impl }; } // OP is: &&, || HIPSYCL_UNIVERSAL_TARGET friend auto operator&& (const vec<dataT, numElements> &lhs, const dataT &rhs) { return lhs && vec<dataT,numElements>{rhs}; } HIPSYCL_UNIVERSAL_TARGET friend auto operator|| (const vec<dataT, numElements> &lhs, const dataT &rhs) { return lhs || vec<dataT,numElements>{rhs}; } // OP is: <<, >> /* Available only when: dataT != cl_float && dataT != cl_double && dataT != cl_half. */ template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT,numElements> operator <<(const vec<dataT, numElements> &lhs, const vec<dataT, numElements>& rhs) { return vec<dataT,numElements>{lhs._impl << rhs._impl}; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT,numElements> operator >>(const vec<dataT, numElements> &lhs, const vec<dataT, numElements>& rhs) { return vec<dataT,numElements>{lhs._impl >> rhs._impl}; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT,numElements> operator <<(const vec<dataT, numElements> &lhs, const dataT& rhs) { return vec<dataT,numElements>{lhs._impl << rhs}; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT,numElements> operator >>(const vec<dataT, numElements> &lhs, const dataT& rhs) { return vec<dataT,numElements>{lhs._impl >> rhs}; } // OP is: <<=, >>= /* Available only when: dataT != cl_float && dataT != cl_double && dataT != cl_half. */ template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements>& operator<<=(const vec<dataT, numElements> &lhs, const vec<dataT, numElements> &rhs) { lhs._impl <<= rhs._impl; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements>& operator>>=(const vec<dataT, numElements> &lhs, const vec<dataT, numElements> &rhs) { lhs._impl >>= rhs._impl; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements>& operator<<=(const vec<dataT, numElements> &lhs, const dataT &rhs) { lhs._impl <<= rhs; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend vec<dataT, numElements>& operator>>=(const vec<dataT, numElements> &lhs, const dataT &rhs) { lhs._impl >>= rhs; } HIPSYCL_UNIVERSAL_TARGET friend auto operator== (const vec<dataT, numElements> &lhs, const vec<dataT, numElements>& rhs) { using result_type = typename detail::logical_vector_op_result<dataT>::type; return vec<result_type, numElements>{ lhs._impl == rhs._impl }; } HIPSYCL_UNIVERSAL_TARGET friend auto operator!= (const vec<dataT, numElements>& lhs, const vec<dataT, numElements>& rhs) { using result_type = typename detail::logical_vector_op_result<dataT>::type; return vec<result_type, numElements>{ lhs._impl != rhs._impl }; } HIPSYCL_UNIVERSAL_TARGET friend auto operator< (const vec<dataT, numElements>& lhs, const vec<dataT, numElements>& rhs) { using result_type = typename detail::logical_vector_op_result<dataT>::type; return vec<result_type, numElements>{ lhs._impl < rhs._impl }; } HIPSYCL_UNIVERSAL_TARGET friend auto operator> (const vec<dataT, numElements>& lhs, const vec<dataT, numElements>& rhs) { using result_type = typename detail::logical_vector_op_result<dataT>::type; return vec<result_type, numElements>{ lhs._impl > rhs._impl }; } HIPSYCL_UNIVERSAL_TARGET friend auto operator<= (const vec<dataT, numElements>& lhs, const vec<dataT, numElements>& rhs) { using result_type = typename detail::logical_vector_op_result<dataT>::type; return vec<result_type, numElements>{ lhs._impl <= rhs._impl }; } HIPSYCL_UNIVERSAL_TARGET friend auto operator>= (const vec<dataT, numElements>& lhs, const vec<dataT, numElements>& rhs) { using result_type = typename detail::logical_vector_op_result<dataT>::type; return vec<result_type, numElements>{ lhs._impl >= rhs._impl }; } HIPSYCL_UNIVERSAL_TARGET friend auto operator== (const vec<dataT, numElements>& lhs, const dataT &rhs) { return lhs == vec<dataT,numElements>{rhs}; } HIPSYCL_UNIVERSAL_TARGET friend auto operator!= (const vec<dataT, numElements>& lhs, const dataT &rhs) { return lhs != vec<dataT,numElements>{rhs}; } HIPSYCL_UNIVERSAL_TARGET friend auto operator< (const vec<dataT, numElements>& lhs, const dataT &rhs) { return lhs < vec<dataT,numElements>{rhs}; } HIPSYCL_UNIVERSAL_TARGET friend auto operator> (const vec<dataT, numElements>& lhs, const dataT &rhs) { return lhs > vec<dataT,numElements>{rhs}; } HIPSYCL_UNIVERSAL_TARGET friend auto operator<= (const vec<dataT, numElements>& lhs, const dataT &rhs) { return lhs <= vec<dataT,numElements>{rhs}; } HIPSYCL_UNIVERSAL_TARGET friend auto operator>= (const vec<dataT, numElements>& lhs, const dataT &rhs) { return lhs >= vec<dataT,numElements>{rhs}; } /* Available only when: dataT != cl_float && dataT != cl_double && dataT != cl_half. */ template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend auto operator~(vec<dataT, numElements>& lhs) { return vec<dataT, numElements>{~lhs._impl}; } template<class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET friend auto operator!(vec<dataT, numElements>& lhs) { return vec<dataT, numElements>{!lhs._impl}; } // OP is: +, -, *, /, % HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator+ (const dataT &lhs, const vec<dataT, numElements> &rhs) { return rhs + lhs; } HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator* (const dataT &lhs, const vec<dataT, numElements> &rhs) { return rhs * lhs; } HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator- (const dataT &lhs, const vec<dataT, numElements> &rhs) { return vec<dataT,numElements>{lhs} - rhs; } HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator/ (const dataT &lhs, const vec<dataT, numElements> &rhs) { return vec<dataT,numElements>{lhs} / rhs; } template <class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator% (const dataT &lhs, const vec<dataT, numElements> &rhs) { return vec<dataT,numElements>{lhs} % rhs; } // OP is: &, |, ˆ // Available only when: dataT != cl_float && dataT != cl_double && dataT != cl_half. template <class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator&(const dataT& lhs, const vec<dataT, numElements>& rhs) { return rhs & lhs; } template <class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator|(const dataT& lhs, const vec<dataT, numElements>& rhs) { return rhs | lhs; } template <class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator^(const dataT& lhs, const vec<dataT, numElements>& rhs) { return rhs ^ lhs; } // OP is: &&, || HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator&&(const dataT& lhs, const vec<dataT, numElements>& rhs) { return rhs && lhs; } HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator||(const dataT& lhs, const vec<dataT, numElements>& rhs) { return rhs || lhs; } // OP is: <<, >> // Available only when: dataT != cl_float && dataT != cl_double && dataT != cl_half. template <class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator<<(const dataT &lhs, const vec<dataT, numElements> &rhs) { return vec<dataT, numElements>{lhs} << rhs; } template <class t = dataT, std::enable_if_t<std::is_integral<t>::value>* = nullptr> HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator>>(const dataT &lhs, const vec<dataT, numElements> &rhs) { return vec<dataT, numElements>{lhs} >> rhs; } // OP is: ==, !=, <, >, <=, >= HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator==(const dataT& lhs, const vec<dataT, numElements>& rhs) { return rhs == lhs; } HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator!=(const dataT& lhs, const vec<dataT, numElements>& rhs) { return rhs != lhs; } HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator< (const dataT& lhs, const vec<dataT, numElements>& rhs) { return rhs >= lhs; } HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator<=(const dataT& lhs, const vec<dataT, numElements>& rhs) { return rhs > lhs; } HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator> (const dataT& lhs, const vec<dataT, numElements>& rhs) { return rhs <= lhs; } HIPSYCL_UNIVERSAL_TARGET inline friend vec<dataT, numElements> operator>=(const dataT& lhs, const vec<dataT, numElements>& rhs) { return rhs < lhs; } HIPSYCL_UNIVERSAL_TARGET vec<dataT, numElements> &operator=(const vec<dataT, numElements> &rhs) { _impl = rhs._impl; return *this; } HIPSYCL_UNIVERSAL_TARGET vec<dataT, numElements> &operator=(const dataT &rhs) { broadcast_scalar_init(typename detail::vector_impl<dataT,numElements>::indices(), rhs); return *this; } template<int Original_vec_size, int... Access_indices> HIPSYCL_UNIVERSAL_TARGET vec<dataT, numElements>& operator=( const detail::vec_swizzle<dataT, Original_vec_size, Access_indices...>& swizzled_vec) { _impl = swizzled_vec.swizzled_access().get(); return *this; } private: detail::vector_impl<dataT, numElements> _impl; }; #define HIPSYCL_DEFINE_VECTOR_ALIAS(T, alias) \ using alias ## 2 = vec<T, 2 >; \ using alias ## 3 = vec<T, 3 >; \ using alias ## 4 = vec<T, 4 >; \ using alias ## 8 = vec<T, 8 >; \ using alias ## 16 = vec<T, 16> HIPSYCL_DEFINE_VECTOR_ALIAS(char, char); HIPSYCL_DEFINE_VECTOR_ALIAS(short, short); HIPSYCL_DEFINE_VECTOR_ALIAS(int, int); HIPSYCL_DEFINE_VECTOR_ALIAS(long, long); HIPSYCL_DEFINE_VECTOR_ALIAS(float, float); HIPSYCL_DEFINE_VECTOR_ALIAS(double, double); HIPSYCL_DEFINE_VECTOR_ALIAS(detail::hp_float, half); HIPSYCL_DEFINE_VECTOR_ALIAS(detail::s_char, cl_char); HIPSYCL_DEFINE_VECTOR_ALIAS(detail::u_char, cl_uchar); HIPSYCL_DEFINE_VECTOR_ALIAS(detail::s_short, cl_short); HIPSYCL_DEFINE_VECTOR_ALIAS(detail::u_short, cl_ushort); HIPSYCL_DEFINE_VECTOR_ALIAS(detail::s_int, cl_int); HIPSYCL_DEFINE_VECTOR_ALIAS(detail::u_int, cl_uint); HIPSYCL_DEFINE_VECTOR_ALIAS(detail::s_long, cl_long); HIPSYCL_DEFINE_VECTOR_ALIAS(detail::u_long, cl_ulong); HIPSYCL_DEFINE_VECTOR_ALIAS(detail::sp_float, cl_float); HIPSYCL_DEFINE_VECTOR_ALIAS(detail::dp_float, cl_double); HIPSYCL_DEFINE_VECTOR_ALIAS(detail::hp_float, cl_half); HIPSYCL_DEFINE_VECTOR_ALIAS(signed char, schar); HIPSYCL_DEFINE_VECTOR_ALIAS(unsigned char, uchar); HIPSYCL_DEFINE_VECTOR_ALIAS(unsigned short, ushort); HIPSYCL_DEFINE_VECTOR_ALIAS(unsigned int, uint); HIPSYCL_DEFINE_VECTOR_ALIAS(unsigned long, ulong); HIPSYCL_DEFINE_VECTOR_ALIAS(long long, longlong); HIPSYCL_DEFINE_VECTOR_ALIAS(unsigned long long, ulonglong); namespace detail { template<class T, int N, class Function> HIPSYCL_UNIVERSAL_TARGET void transform_vector(vec<T,N>& v, Function f) { v._impl.transform(f); } template<class T, int N, class Function> HIPSYCL_UNIVERSAL_TARGET vec<T,N> binary_vector_operation(const vec<T,N>& a, const vec<T,N>& b, Function f) { return vec<T,N>(a._impl.binary_operation(f, b._impl)); } template<class T, int N, class Function> HIPSYCL_UNIVERSAL_TARGET vec<T,N> trinary_vector_operation(const vec<T,N>& a, const vec<T,N>& b, const vec<T,N>& c, Function f) { return vec<T,N>{ vector_impl<T,N>::trinary_operation(f, a._impl, b._impl, c._impl) }; } template<class T, int Original_vec_size, int... Access_indices> HIPSYCL_UNIVERSAL_TARGET vec_swizzle<T,Original_vec_size,Access_indices...>& vec_swizzle<T,Original_vec_size,Access_indices...>::operator=( const vec<T, vec_swizzle<T,Original_vec_size,Access_indices...>::N>& rhs) { _swizzled_access.set(rhs._impl); return *this; } } // namespace detail } // namespace sycl } // namespace hipsycl #endif
#include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include "guiconstants.h" #include <QString> #include <QTranslator> #include <QDateTime> #include <QDoubleValidator> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #if BOOST_FILESYSTEM_VERSION >= 3 #include <boost/filesystem/detail/utf8_codecvt_facet.hpp> static boost::filesystem::detail::utf8_codecvt_facet utf8; #endif #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { bool fTicker = true; bool fNoHeaders = false; bool fSmallHeaders = false; int TOOLBAR_WIDTH = 120; int TOOLBAR_ICON_WIDTH = TOOLBAR_WIDTH; int TOOLBAR_ICON_HEIGHT = 48; int HEADER_WIDTH = 1024; int HEADER_HEIGHT = 160; int BUTTON_WIDTH = 140; int BUTTON_HEIGHT = 27; int FRAMEBLOCKS_LABEL_WIDTH = 100; int WINDOW_MIN_WIDTH = TOOLBAR_WIDTH + HEADER_WIDTH; #ifdef Q_OS_WIN int WINDOW_MIN_HEIGHT = 768; #else #ifdef Q_OS_MAC int WINDOW_MIN_HEIGHT = 748; #else int WINDOW_MIN_HEIGHT = 772; #endif #endif int STATUSBAR_ICONSIZE = 16; int STATUSBAR_MARGIN = 10; int STATUSBAR_HEIGHT = 32; void refactorGUI(QRect screenSize) { // Set the new geometry #ifdef Q_OS_WIN int newHeight = screenSize.height() - 40; #else #ifdef Q_OS_MAC int newHeight = screenSize.height() - 30; #else int newHeight = screenSize.height() - 25; #endif #endif int newWidth = WINDOW_MIN_WIDTH; if (screenSize.width() < newWidth - 2) { newWidth = screenSize.width() - 2; STATUSBAR_MARGIN = 0; TOOLBAR_WIDTH = 90; TOOLBAR_ICON_WIDTH = TOOLBAR_WIDTH; HEADER_WIDTH = newWidth - TOOLBAR_WIDTH; } if (screenSize.height() <= 600) { TOOLBAR_ICON_HEIGHT = 32; HEADER_HEIGHT = 0; fNoHeaders = true; fTicker = false; } else if (screenSize.height() < 728) // 728px if OS taskbar is not hidden { TOOLBAR_ICON_HEIGHT = 32; HEADER_HEIGHT = 32; fNoHeaders = true; fTicker = false; } else // Default small wallet at 728px to 768px { TOOLBAR_ICON_HEIGHT = 34; HEADER_HEIGHT = 85; fSmallHeaders = true; } WINDOW_MIN_WIDTH = TOOLBAR_WIDTH + HEADER_WIDTH; WINDOW_MIN_HEIGHT = newHeight; } int pointsToPixels(int points) { return(points * 4 / 3); } void setFontPixelSize(QFont *font) { font->setPixelSize(pointsToPixels(font->pointSize())); } void setFontPixelSizes() { setFontPixelSize((QFont *)&qFontSmallest); setFontPixelSize((QFont *)&qFontSmaller); setFontPixelSize((QFont *)&qFontSmall); setFontPixelSize((QFont *)&qFont); setFontPixelSize((QFont *)&qFontLarge); setFontPixelSize((QFont *)&qFontLarger); setFontPixelSize((QFont *)&qFontSmallerBold); setFontPixelSize((QFont *)&qFontSmallBold); setFontPixelSize((QFont *)&qFontBold); setFontPixelSize((QFont *)&qFontLargeBold); setFontPixelSize((QFont *)&qFontLargerBold); } // Common LeCoin stylesheets QString veriCentralWidgetStyleSheet = QString("QStackedWidget { background: white; } "); QString veriTabWidgetStyleSheet = QString("QTabWidget::pane { background: white; color: " + STR_FONT_COLOR + "; border: 1px; }"); QString veriPushButtonStyleSheet = QString("QPushButton { background: " + STR_COLOR + "; width: %1px; height: %2px; border: none; color: white} \ QPushButton:disabled { background: #EBEBEB; color: #E30011; } \ QPushButton:hover { background: " + STR_COLOR_LT + "; } \ QPushButton:pressed { background: " + STR_COLOR_LT + "; } ").arg(BUTTON_WIDTH).arg(BUTTON_HEIGHT); QString veriToolBarStyleSheet = QString("QToolBar { background: " + STR_COLOR + "; color: white; border: none; } \ QToolButton { background: " + STR_COLOR + "; color: white; border: none; font-family: Lato; font-style: normal; font-weight: normal; font-size: 12px; } \ QToolButton:hover { background: " + STR_COLOR_HOVER + "; color: white; border: none; } \ QToolButton:pressed { background: " + STR_COLOR_LT + "; color: white; border: none; } \ QToolButton:checked { background: " + STR_COLOR_LT + "; color: white; border: none; } "); QString veriToolTipStyleSheet = QString("QToolTip { background-color: " + STR_COLOR_TTBG + "; color: white; border: 1px solid #EBEBEB; border-radius: 3px; margin: 0; padding: 4px; white-space: nowrap; } "); QString veriMiscStyleSheet = QString("QStatusBar { background: " + STR_COLOR + "; color: white; } QStatusBar::item { border: none; } QDialog { background: white; color: " + STR_FONT_COLOR + "; } QTableView::item:hover { background: #EBEBEB; color: " + STR_FONT_COLOR + "; } "); QString veriMenuStyleSheet = QString("QMenuBar { background-color: " + STR_COLOR_HOVER + "; color: white; } \ QMenuBar::item { background-color: transparent; margin: 0px; padding: 4px 16px 4px 16px; } \ QMenuBar::item:selected { background-color: " + STR_COLOR + "; color: white; } \ QMenu { background-color: " + STR_COLOR_HOVER + "; color: white; } \ QMenu::item { background-color: transparent; margin: 0px 0px 4px 4px; padding: 4px 8px 4px 24px; } \ QMenu::item:selected { background-color: " + STR_COLOR + "; color: white; }"); // Put them all together QString veriStyleSheet = veriCentralWidgetStyleSheet + veriPushButtonStyleSheet + veriToolBarStyleSheet + veriToolTipStyleSheet + veriMiscStyleSheet + veriMenuStyleSheet; // Special styling for AskPassphrasePage QString veriAskPassphrasePushButtonStyleSheet = QString("QPushButton { background: " + STR_COLOR_LT + "; width: %1px; height: %2px; border: none; color: white} \ QPushButton:disabled { background: #EBEBEB; color: ##E30011; } \ QPushButton:hover { background: " + STR_COLOR_LT + "; } \ QPushButton:pressed { background: " + STR_COLOR_LT + "; } ").arg(BUTTON_WIDTH).arg(BUTTON_HEIGHT); QString veriAskPassphrasePageStyleSheet = QString("QDialog { border-image: url(:images/askPassphraseBackground) repeat 0px 0px; background-color: " + STR_COLOR + "; } QLabel { color: white; } QLineEdit { background: white; color: " + STR_COLOR + "; } ") + veriAskPassphrasePushButtonStyleSheet + veriToolTipStyleSheet; // Setup header and styles QGraphicsView *header(QWidget *parent, QString backgroundImage) { QGraphicsView *h = new QGraphicsView(parent); h->setStyleSheet("QGraphicsView { background: url(" + backgroundImage + ") no-repeat 0px 0px; border: none; background-color: " + STR_COLOR + "; }"); h->setObjectName(QStringLiteral("header")); h->setContentsMargins(0,0,0,0); QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(h->sizePolicy().hasHeightForWidth()); h->setSizePolicy(sizePolicy); h->setMinimumSize(QSize(16777215, HEADER_HEIGHT)); h->setMaximumSize(QSize(16777215, HEADER_HEIGHT)); h->setAutoFillBackground(true); h->setFrameShape(QFrame::NoFrame); h->setFrameShadow(QFrame::Plain); h->setLineWidth(0); h->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); h->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); h->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop); h->setCacheMode(QGraphicsView::CacheBackground); return h; } QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(BitcoinUnits::decimals(BitcoinUnits::LEC)); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // LeCoin: check prefix if(uri.scheme() != QString("lecoin")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::LEC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert lecoin:// to lecoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("lecoin://")) { uri.replace(0, 12, "lecoin:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt>" + HtmlEscape(tooltip, true) + "<qt/>"; widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "LeCoin.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "lecoin.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=LeCoin\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #else // TODO: OSX startup stuff; see: // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("LeCoin-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " lecoin-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("LeCoin-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } #if BOOST_FILESYSTEM_VERSION >= 3 boost::filesystem::path qstringToBoostPath(const QString &path) { return boost::filesystem::path(path.toStdString(), utf8); } QString boostPathToQString(const boost::filesystem::path &path) { return QString::fromStdString(path.string(utf8)); } #else #warning Conversion between boost path and QString can use invalid character encoding with boost_filesystem v2 and older boost::filesystem::path qstringToBoostPath(const QString &path) { return boost::filesystem::path(path.toStdString()); } QString boostPathToQString(const boost::filesystem::path &path) { return QString::fromStdString(path.string()); } #endif } // namespace GUIUtil
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// UNIX_SCSIPathConfigurationService::UNIX_SCSIPathConfigurationService(void) { } UNIX_SCSIPathConfigurationService::~UNIX_SCSIPathConfigurationService(void) { } Boolean UNIX_SCSIPathConfigurationService::getInstanceID(CIMProperty &p) const { p = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID()); return true; } String UNIX_SCSIPathConfigurationService::getInstanceID() const { return String (""); } Boolean UNIX_SCSIPathConfigurationService::getCaption(CIMProperty &p) const { p = CIMProperty(PROPERTY_CAPTION, getCaption()); return true; } String UNIX_SCSIPathConfigurationService::getCaption() const { return String (""); } Boolean UNIX_SCSIPathConfigurationService::getDescription(CIMProperty &p) const { p = CIMProperty(PROPERTY_DESCRIPTION, getDescription()); return true; } String UNIX_SCSIPathConfigurationService::getDescription() const { return String (""); } Boolean UNIX_SCSIPathConfigurationService::getElementName(CIMProperty &p) const { p = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName()); return true; } String UNIX_SCSIPathConfigurationService::getElementName() const { return String("SCSIPathConfigurationService"); } Boolean UNIX_SCSIPathConfigurationService::getInstallDate(CIMProperty &p) const { p = CIMProperty(PROPERTY_INSTALL_DATE, getInstallDate()); return true; } CIMDateTime UNIX_SCSIPathConfigurationService::getInstallDate() const { struct tm* clock; // create a time structure time_t val = time(NULL); clock = gmtime(&(val)); // Get the last modified time and put it into the time structure return CIMDateTime( clock->tm_year + 1900, clock->tm_mon + 1, clock->tm_mday, clock->tm_hour, clock->tm_min, clock->tm_sec, 0,0, clock->tm_gmtoff); } Boolean UNIX_SCSIPathConfigurationService::getName(CIMProperty &p) const { p = CIMProperty(PROPERTY_NAME, getName()); return true; } String UNIX_SCSIPathConfigurationService::getName() const { return String (""); } Boolean UNIX_SCSIPathConfigurationService::getOperationalStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_OPERATIONAL_STATUS, getOperationalStatus()); return true; } Array<Uint16> UNIX_SCSIPathConfigurationService::getOperationalStatus() const { Array<Uint16> as; return as; } Boolean UNIX_SCSIPathConfigurationService::getStatusDescriptions(CIMProperty &p) const { p = CIMProperty(PROPERTY_STATUS_DESCRIPTIONS, getStatusDescriptions()); return true; } Array<String> UNIX_SCSIPathConfigurationService::getStatusDescriptions() const { Array<String> as; return as; } Boolean UNIX_SCSIPathConfigurationService::getStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_STATUS, getStatus()); return true; } String UNIX_SCSIPathConfigurationService::getStatus() const { return String(DEFAULT_STATUS); } Boolean UNIX_SCSIPathConfigurationService::getHealthState(CIMProperty &p) const { p = CIMProperty(PROPERTY_HEALTH_STATE, getHealthState()); return true; } Uint16 UNIX_SCSIPathConfigurationService::getHealthState() const { return Uint16(DEFAULT_HEALTH_STATE); } Boolean UNIX_SCSIPathConfigurationService::getCommunicationStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_COMMUNICATION_STATUS, getCommunicationStatus()); return true; } Uint16 UNIX_SCSIPathConfigurationService::getCommunicationStatus() const { return Uint16(0); } Boolean UNIX_SCSIPathConfigurationService::getDetailedStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_DETAILED_STATUS, getDetailedStatus()); return true; } Uint16 UNIX_SCSIPathConfigurationService::getDetailedStatus() const { return Uint16(0); } Boolean UNIX_SCSIPathConfigurationService::getOperatingStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_OPERATING_STATUS, getOperatingStatus()); return true; } Uint16 UNIX_SCSIPathConfigurationService::getOperatingStatus() const { return Uint16(DEFAULT_OPERATING_STATUS); } Boolean UNIX_SCSIPathConfigurationService::getPrimaryStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_PRIMARY_STATUS, getPrimaryStatus()); return true; } Uint16 UNIX_SCSIPathConfigurationService::getPrimaryStatus() const { return Uint16(DEFAULT_PRIMARY_STATUS); } Boolean UNIX_SCSIPathConfigurationService::getEnabledState(CIMProperty &p) const { p = CIMProperty(PROPERTY_ENABLED_STATE, getEnabledState()); return true; } Uint16 UNIX_SCSIPathConfigurationService::getEnabledState() const { return Uint16(DEFAULT_ENABLED_STATE); } Boolean UNIX_SCSIPathConfigurationService::getOtherEnabledState(CIMProperty &p) const { p = CIMProperty(PROPERTY_OTHER_ENABLED_STATE, getOtherEnabledState()); return true; } String UNIX_SCSIPathConfigurationService::getOtherEnabledState() const { return String (""); } Boolean UNIX_SCSIPathConfigurationService::getRequestedState(CIMProperty &p) const { p = CIMProperty(PROPERTY_REQUESTED_STATE, getRequestedState()); return true; } Uint16 UNIX_SCSIPathConfigurationService::getRequestedState() const { return Uint16(0); } Boolean UNIX_SCSIPathConfigurationService::getEnabledDefault(CIMProperty &p) const { p = CIMProperty(PROPERTY_ENABLED_DEFAULT, getEnabledDefault()); return true; } Uint16 UNIX_SCSIPathConfigurationService::getEnabledDefault() const { return Uint16(0); } Boolean UNIX_SCSIPathConfigurationService::getTimeOfLastStateChange(CIMProperty &p) const { p = CIMProperty(PROPERTY_TIME_OF_LAST_STATE_CHANGE, getTimeOfLastStateChange()); return true; } CIMDateTime UNIX_SCSIPathConfigurationService::getTimeOfLastStateChange() const { struct tm* clock; // create a time structure time_t val = time(NULL); clock = gmtime(&(val)); // Get the last modified time and put it into the time structure return CIMDateTime( clock->tm_year + 1900, clock->tm_mon + 1, clock->tm_mday, clock->tm_hour, clock->tm_min, clock->tm_sec, 0,0, clock->tm_gmtoff); } Boolean UNIX_SCSIPathConfigurationService::getAvailableRequestedStates(CIMProperty &p) const { p = CIMProperty(PROPERTY_AVAILABLE_REQUESTED_STATES, getAvailableRequestedStates()); return true; } Array<Uint16> UNIX_SCSIPathConfigurationService::getAvailableRequestedStates() const { Array<Uint16> as; return as; } Boolean UNIX_SCSIPathConfigurationService::getTransitioningToState(CIMProperty &p) const { p = CIMProperty(PROPERTY_TRANSITIONING_TO_STATE, getTransitioningToState()); return true; } Uint16 UNIX_SCSIPathConfigurationService::getTransitioningToState() const { return Uint16(0); } Boolean UNIX_SCSIPathConfigurationService::getSystemCreationClassName(CIMProperty &p) const { p = CIMProperty(PROPERTY_SYSTEM_CREATION_CLASS_NAME, getSystemCreationClassName()); return true; } String UNIX_SCSIPathConfigurationService::getSystemCreationClassName() const { return String("UNIX_ComputerSystem"); } Boolean UNIX_SCSIPathConfigurationService::getSystemName(CIMProperty &p) const { p = CIMProperty(PROPERTY_SYSTEM_NAME, getSystemName()); return true; } String UNIX_SCSIPathConfigurationService::getSystemName() const { return CIMHelper::HostName; } Boolean UNIX_SCSIPathConfigurationService::getCreationClassName(CIMProperty &p) const { p = CIMProperty(PROPERTY_CREATION_CLASS_NAME, getCreationClassName()); return true; } String UNIX_SCSIPathConfigurationService::getCreationClassName() const { return String("UNIX_SCSIPathConfigurationService"); } Boolean UNIX_SCSIPathConfigurationService::getPrimaryOwnerName(CIMProperty &p) const { p = CIMProperty(PROPERTY_PRIMARY_OWNER_NAME, getPrimaryOwnerName()); return true; } String UNIX_SCSIPathConfigurationService::getPrimaryOwnerName() const { return String (""); } Boolean UNIX_SCSIPathConfigurationService::getPrimaryOwnerContact(CIMProperty &p) const { p = CIMProperty(PROPERTY_PRIMARY_OWNER_CONTACT, getPrimaryOwnerContact()); return true; } String UNIX_SCSIPathConfigurationService::getPrimaryOwnerContact() const { return String (""); } Boolean UNIX_SCSIPathConfigurationService::getStartMode(CIMProperty &p) const { p = CIMProperty(PROPERTY_START_MODE, getStartMode()); return true; } String UNIX_SCSIPathConfigurationService::getStartMode() const { return String (""); } Boolean UNIX_SCSIPathConfigurationService::getStarted(CIMProperty &p) const { p = CIMProperty(PROPERTY_STARTED, getStarted()); return true; } Boolean UNIX_SCSIPathConfigurationService::getStarted() const { return Boolean(false); } Boolean UNIX_SCSIPathConfigurationService::initialize() { return false; } Boolean UNIX_SCSIPathConfigurationService::load(int &pIndex) { return false; } Boolean UNIX_SCSIPathConfigurationService::finalize() { return false; } Boolean UNIX_SCSIPathConfigurationService::find(Array<CIMKeyBinding> &kbArray) { CIMKeyBinding kb; String systemCreationClassNameKey; String systemNameKey; String creationClassNameKey; String nameKey; for(Uint32 i = 0; i < kbArray.size(); i++) { kb = kbArray[i]; CIMName keyName = kb.getName(); if (keyName.equal(PROPERTY_SYSTEM_CREATION_CLASS_NAME)) systemCreationClassNameKey = kb.getValue(); else if (keyName.equal(PROPERTY_SYSTEM_NAME)) systemNameKey = kb.getValue(); else if (keyName.equal(PROPERTY_CREATION_CLASS_NAME)) creationClassNameKey = kb.getValue(); else if (keyName.equal(PROPERTY_NAME)) nameKey = kb.getValue(); } /* EXecute find with extracted keys */ return false; }
#include "duckdb/main/client_context.hpp" #include "duckdb/main/client_context_file_opener.hpp" #include "duckdb/main/query_profiler.hpp" #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/scalar_function_catalog_entry.hpp" #include "duckdb/catalog/catalog_search_path.hpp" #include "duckdb/common/serializer/buffered_deserializer.hpp" #include "duckdb/common/serializer/buffered_serializer.hpp" #include "duckdb/execution/physical_plan_generator.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/materialized_query_result.hpp" #include "duckdb/main/client_data.hpp" #include "duckdb/main/query_result.hpp" #include "duckdb/main/stream_query_result.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/parser/parser.hpp" #include "duckdb/parser/expression/constant_expression.hpp" #include "duckdb/parser/parsed_data/create_function_info.hpp" #include "duckdb/parser/statement/drop_statement.hpp" #include "duckdb/parser/statement/explain_statement.hpp" #include "duckdb/parser/statement/select_statement.hpp" #include "duckdb/planner/operator/logical_execute.hpp" #include "duckdb/planner/planner.hpp" #include "duckdb/transaction/transaction_manager.hpp" #include "duckdb/transaction/transaction.hpp" #include "duckdb/storage/data_table.hpp" #include "duckdb/main/appender.hpp" #include "duckdb/main/relation.hpp" #include "duckdb/parser/statement/relation_statement.hpp" #include "duckdb/parallel/task_scheduler.hpp" #include "duckdb/common/serializer/buffered_file_writer.hpp" #include "duckdb/planner/pragma_handler.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/execution/column_binding_resolver.hpp" #include "duckdb/parser/query_node/select_node.hpp" namespace duckdb { struct ActiveQueryContext { //! The query that is currently being executed string query; //! The currently open result BaseQueryResult *open_result = nullptr; //! Prepared statement data shared_ptr<PreparedStatementData> prepared; //! The query executor unique_ptr<Executor> executor; //! The progress bar unique_ptr<ProgressBar> progress_bar; }; ClientContext::ClientContext(shared_ptr<DatabaseInstance> database) : db(move(database)), transaction(db->GetTransactionManager(), *this), interrupted(false), client_data(make_unique<ClientData>(*this)) { } ClientContext::~ClientContext() { if (Exception::UncaughtException()) { return; } // destroy the client context and rollback if there is an active transaction // but only if we are not destroying this client context as part of an exception stack unwind Destroy(); } unique_ptr<ClientContextLock> ClientContext::LockContext() { return make_unique<ClientContextLock>(context_lock); } void ClientContext::Destroy() { auto lock = LockContext(); if (transaction.HasActiveTransaction()) { ActiveTransaction().active_query = MAXIMUM_QUERY_ID; if (!transaction.IsAutoCommit()) { transaction.Rollback(); } } CleanupInternal(*lock); } unique_ptr<DataChunk> ClientContext::Fetch(ClientContextLock &lock, StreamQueryResult &result) { D_ASSERT(IsActiveResult(lock, &result)); D_ASSERT(active_query->executor); return FetchInternal(lock, *active_query->executor, result); } unique_ptr<DataChunk> ClientContext::FetchInternal(ClientContextLock &lock, Executor &executor, BaseQueryResult &result) { bool invalidate_query = true; try { // fetch the chunk and return it auto chunk = executor.FetchChunk(); if (!chunk || chunk->size() == 0) { CleanupInternal(lock, &result); } return chunk; } catch (StandardException &ex) { // standard exceptions do not invalidate the current transaction result.error = ex.what(); invalidate_query = false; } catch (std::exception &ex) { result.error = ex.what(); } catch (...) { // LCOV_EXCL_START result.error = "Unhandled exception in FetchInternal"; } // LCOV_EXCL_STOP result.success = false; CleanupInternal(lock, &result, invalidate_query); return nullptr; } void ClientContext::BeginTransactionInternal(ClientContextLock &lock, bool requires_valid_transaction) { // check if we are on AutoCommit. In this case we should start a transaction D_ASSERT(!active_query); if (requires_valid_transaction && transaction.HasActiveTransaction() && transaction.ActiveTransaction().IsInvalidated()) { throw Exception("Failed: transaction has been invalidated!"); } active_query = make_unique<ActiveQueryContext>(); if (transaction.IsAutoCommit()) { transaction.BeginTransaction(); } } void ClientContext::BeginQueryInternal(ClientContextLock &lock, const string &query) { BeginTransactionInternal(lock, false); LogQueryInternal(lock, query); active_query->query = query; query_progress = -1; ActiveTransaction().active_query = db->GetTransactionManager().GetQueryNumber(); } string ClientContext::EndQueryInternal(ClientContextLock &lock, bool success, bool invalidate_transaction) { client_data->profiler->EndQuery(); D_ASSERT(active_query.get()); string error; try { if (transaction.HasActiveTransaction()) { // Move the query profiler into the history auto &prev_profilers = client_data->query_profiler_history->GetPrevProfilers(); prev_profilers.emplace_back(transaction.ActiveTransaction().active_query, move(client_data->profiler)); // Reinitialize the query profiler client_data->profiler = make_shared<QueryProfiler>(*this); // Propagate settings of the saved query into the new profiler. client_data->profiler->Propagate(*prev_profilers.back().second); if (prev_profilers.size() >= client_data->query_profiler_history->GetPrevProfilersSize()) { prev_profilers.pop_front(); } ActiveTransaction().active_query = MAXIMUM_QUERY_ID; if (transaction.IsAutoCommit()) { if (success) { transaction.Commit(); } else { transaction.Rollback(); } } else if (invalidate_transaction) { D_ASSERT(!success); ActiveTransaction().Invalidate(); } } } catch (std::exception &ex) { error = ex.what(); } catch (...) { // LCOV_EXCL_START error = "Unhandled exception!"; } // LCOV_EXCL_STOP active_query.reset(); query_progress = -1; return error; } void ClientContext::CleanupInternal(ClientContextLock &lock, BaseQueryResult *result, bool invalidate_transaction) { if (!active_query) { // no query currently active return; } if (active_query->executor) { active_query->executor->CancelTasks(); } active_query->progress_bar.reset(); auto error = EndQueryInternal(lock, result ? result->success : false, invalidate_transaction); if (result && result->success) { // if an error occurred while committing report it in the result result->error = error; result->success = error.empty(); } D_ASSERT(!active_query); } Executor &ClientContext::GetExecutor() { D_ASSERT(active_query); D_ASSERT(active_query->executor); return *active_query->executor; } const string &ClientContext::GetCurrentQuery() { D_ASSERT(active_query); return active_query->query; } unique_ptr<QueryResult> ClientContext::FetchResultInternal(ClientContextLock &lock, PendingQueryResult &pending, bool allow_stream_result) { D_ASSERT(active_query); D_ASSERT(active_query->open_result == &pending); D_ASSERT(active_query->prepared); auto &prepared = *active_query->prepared; bool create_stream_result = prepared.properties.allow_stream_result && allow_stream_result; if (create_stream_result) { active_query->progress_bar.reset(); query_progress = -1; // successfully compiled SELECT clause, and it is the last statement // return a StreamQueryResult so the client can call Fetch() on it and stream the result auto stream_result = make_unique<StreamQueryResult>(pending.statement_type, pending.properties, shared_from_this(), pending.types, pending.names); active_query->open_result = stream_result.get(); return move(stream_result); } // create a materialized result by continuously fetching auto result = make_unique<MaterializedQueryResult>(pending.statement_type, pending.properties, pending.types, pending.names, shared_from_this()); result->properties = pending.properties; while (true) { auto chunk = FetchInternal(lock, GetExecutor(), *result); if (!chunk || chunk->size() == 0) { break; } #ifdef DEBUG for (idx_t i = 0; i < chunk->ColumnCount(); i++) { if (pending.types[i].id() == LogicalTypeId::VARCHAR) { chunk->data[i].UTFVerify(chunk->size()); } } #endif result->collection.Append(*chunk); } return move(result); } shared_ptr<PreparedStatementData> ClientContext::CreatePreparedStatement(ClientContextLock &lock, const string &query, unique_ptr<SQLStatement> statement, vector<Value> *values) { StatementType statement_type = statement->type; auto result = make_shared<PreparedStatementData>(statement_type); auto &profiler = QueryProfiler::Get(*this); profiler.StartPhase("planner"); Planner planner(*this); if (values) { for (auto &value : *values) { planner.parameter_types.push_back(value.type()); } } planner.CreatePlan(move(statement)); D_ASSERT(planner.plan); profiler.EndPhase(); auto plan = move(planner.plan); #ifdef DEBUG plan->Verify(); #endif // extract the result column names from the plan result->properties = planner.properties; result->names = planner.names; result->types = planner.types; result->value_map = move(planner.value_map); result->catalog_version = Transaction::GetTransaction(*this).catalog_version; if (config.enable_optimizer) { profiler.StartPhase("optimizer"); Optimizer optimizer(*planner.binder, *this); plan = optimizer.Optimize(move(plan)); D_ASSERT(plan); profiler.EndPhase(); #ifdef DEBUG plan->Verify(); #endif } profiler.StartPhase("physical_planner"); // now convert logical query plan into a physical query plan PhysicalPlanGenerator physical_planner(*this); auto physical_plan = physical_planner.CreatePlan(move(plan)); profiler.EndPhase(); #ifdef DEBUG D_ASSERT(!physical_plan->ToString().empty()); #endif result->plan = move(physical_plan); return result; } double ClientContext::GetProgress() { return query_progress.load(); } unique_ptr<PendingQueryResult> ClientContext::PendingPreparedStatement(ClientContextLock &lock, shared_ptr<PreparedStatementData> statement_p, vector<Value> bound_values) { D_ASSERT(active_query); auto &statement = *statement_p; if (ActiveTransaction().IsInvalidated() && statement.properties.requires_valid_transaction) { throw Exception("Current transaction is aborted (please ROLLBACK)"); } auto &db_config = DBConfig::GetConfig(*this); if (db_config.access_mode == AccessMode::READ_ONLY && !statement.properties.read_only) { throw Exception(StringUtil::Format("Cannot execute statement of type \"%s\" in read-only mode!", StatementTypeToString(statement.statement_type))); } // bind the bound values before execution statement.Bind(move(bound_values)); active_query->executor = make_unique<Executor>(*this); auto &executor = *active_query->executor; if (config.enable_progress_bar) { active_query->progress_bar = make_unique<ProgressBar>(executor, config.wait_time); active_query->progress_bar->Start(); query_progress = 0; } executor.Initialize(statement.plan.get()); auto types = executor.GetTypes(); D_ASSERT(types == statement.types); D_ASSERT(!active_query->open_result); auto pending_result = make_unique<PendingQueryResult>(shared_from_this(), *statement_p, move(types)); active_query->prepared = move(statement_p); active_query->open_result = pending_result.get(); return pending_result; } PendingExecutionResult ClientContext::ExecuteTaskInternal(ClientContextLock &lock, PendingQueryResult &result) { D_ASSERT(active_query); D_ASSERT(active_query->open_result == &result); try { auto result = active_query->executor->ExecuteTask(); if (active_query->progress_bar) { active_query->progress_bar->Update(result == PendingExecutionResult::RESULT_READY); query_progress = active_query->progress_bar->GetCurrentPercentage(); } return result; } catch (std::exception &ex) { result.error = ex.what(); } catch (...) { // LCOV_EXCL_START result.error = "Unhandled exception in ExecuteTaskInternal"; } // LCOV_EXCL_STOP EndQueryInternal(lock, false, true); result.success = false; return PendingExecutionResult::EXECUTION_ERROR; } void ClientContext::InitialCleanup(ClientContextLock &lock) { //! Cleanup any open results and reset the interrupted flag CleanupInternal(lock); interrupted = false; } vector<unique_ptr<SQLStatement>> ClientContext::ParseStatements(const string &query) { auto lock = LockContext(); return ParseStatementsInternal(*lock, query); } vector<unique_ptr<SQLStatement>> ClientContext::ParseStatementsInternal(ClientContextLock &lock, const string &query) { Parser parser(GetParserOptions()); parser.ParseQuery(query); PragmaHandler handler(*this); handler.HandlePragmaStatements(lock, parser.statements); return move(parser.statements); } void ClientContext::HandlePragmaStatements(vector<unique_ptr<SQLStatement>> &statements) { auto lock = LockContext(); PragmaHandler handler(*this); handler.HandlePragmaStatements(*lock, statements); } unique_ptr<LogicalOperator> ClientContext::ExtractPlan(const string &query) { auto lock = LockContext(); auto statements = ParseStatementsInternal(*lock, query); if (statements.size() != 1) { throw Exception("ExtractPlan can only prepare a single statement"); } unique_ptr<LogicalOperator> plan; RunFunctionInTransactionInternal(*lock, [&]() { Planner planner(*this); planner.CreatePlan(move(statements[0])); D_ASSERT(planner.plan); plan = move(planner.plan); if (config.enable_optimizer) { Optimizer optimizer(*planner.binder, *this); plan = optimizer.Optimize(move(plan)); } ColumnBindingResolver resolver; resolver.VisitOperator(*plan); plan->ResolveOperatorTypes(); }); return plan; } unique_ptr<PreparedStatement> ClientContext::PrepareInternal(ClientContextLock &lock, unique_ptr<SQLStatement> statement) { auto n_param = statement->n_param; auto statement_query = statement->query; shared_ptr<PreparedStatementData> prepared_data; auto unbound_statement = statement->Copy(); RunFunctionInTransactionInternal( lock, [&]() { prepared_data = CreatePreparedStatement(lock, statement_query, move(statement)); }, false); prepared_data->unbound_statement = move(unbound_statement); return make_unique<PreparedStatement>(shared_from_this(), move(prepared_data), move(statement_query), n_param); } unique_ptr<PreparedStatement> ClientContext::Prepare(unique_ptr<SQLStatement> statement) { auto lock = LockContext(); // prepare the query try { InitialCleanup(*lock); return PrepareInternal(*lock, move(statement)); } catch (std::exception &ex) { return make_unique<PreparedStatement>(ex.what()); } } unique_ptr<PreparedStatement> ClientContext::Prepare(const string &query) { auto lock = LockContext(); // prepare the query try { InitialCleanup(*lock); // first parse the query auto statements = ParseStatementsInternal(*lock, query); if (statements.empty()) { throw Exception("No statement to prepare!"); } if (statements.size() > 1) { throw Exception("Cannot prepare multiple statements at once!"); } return PrepareInternal(*lock, move(statements[0])); } catch (std::exception &ex) { return make_unique<PreparedStatement>(ex.what()); } } unique_ptr<PendingQueryResult> ClientContext::PendingQueryPreparedInternal(ClientContextLock &lock, const string &query, shared_ptr<PreparedStatementData> &prepared, vector<Value> &values) { try { InitialCleanup(lock); } catch (std::exception &ex) { return make_unique<PendingQueryResult>(ex.what()); } return PendingStatementOrPreparedStatementInternal(lock, query, nullptr, prepared, &values); } unique_ptr<PendingQueryResult> ClientContext::PendingQuery(const string &query, shared_ptr<PreparedStatementData> &prepared, vector<Value> &values) { auto lock = LockContext(); return PendingQueryPreparedInternal(*lock, query, prepared, values); } unique_ptr<QueryResult> ClientContext::Execute(const string &query, shared_ptr<PreparedStatementData> &prepared, vector<Value> &values, bool allow_stream_result) { auto lock = LockContext(); auto pending = PendingQueryPreparedInternal(*lock, query, prepared, values); if (!pending->success) { return make_unique<MaterializedQueryResult>(pending->error); } return pending->ExecuteInternal(*lock, allow_stream_result); } unique_ptr<PendingQueryResult> ClientContext::PendingStatementInternal(ClientContextLock &lock, const string &query, unique_ptr<SQLStatement> statement) { // prepare the query for execution auto prepared = CreatePreparedStatement(lock, query, move(statement)); // by default, no values are bound vector<Value> bound_values; // execute the prepared statement return PendingPreparedStatement(lock, move(prepared), move(bound_values)); } unique_ptr<QueryResult> ClientContext::RunStatementInternal(ClientContextLock &lock, const string &query, unique_ptr<SQLStatement> statement, bool allow_stream_result, bool verify) { auto pending = PendingQueryInternal(lock, move(statement), verify); if (!pending->success) { return make_unique<MaterializedQueryResult>(move(pending->error)); } return ExecutePendingQueryInternal(lock, *pending, allow_stream_result); } bool ClientContext::IsActiveResult(ClientContextLock &lock, BaseQueryResult *result) { if (!active_query) { return false; } return active_query->open_result == result; } static bool IsExplainAnalyze(SQLStatement *statement) { if (!statement) { return false; } if (statement->type != StatementType::EXPLAIN_STATEMENT) { return false; } auto &explain = (ExplainStatement &)*statement; return explain.explain_type == ExplainType::EXPLAIN_ANALYZE; } unique_ptr<PendingQueryResult> ClientContext::PendingStatementOrPreparedStatementInternal( ClientContextLock &lock, const string &query, unique_ptr<SQLStatement> statement, shared_ptr<PreparedStatementData> &prepared, vector<Value> *values) { // check if we are on AutoCommit. In this case we should start a transaction. if (statement && config.query_verification_enabled) { // query verification is enabled // create a copy of the statement, and use the copy // this way we verify that the copy correctly copies all properties auto copied_statement = statement->Copy(); switch (statement->type) { case StatementType::SELECT_STATEMENT: { // in case this is a select query, we verify the original statement string error; try { error = VerifyQuery(lock, query, move(statement)); } catch (std::exception &ex) { error = ex.what(); } if (!error.empty()) { // error in verifying query return make_unique<PendingQueryResult>(error); } statement = move(copied_statement); break; } case StatementType::INSERT_STATEMENT: case StatementType::DELETE_STATEMENT: case StatementType::UPDATE_STATEMENT: { auto sql = statement->ToString(); Parser parser; parser.ParseQuery(sql); statement = move(parser.statements[0]); break; } default: statement = move(copied_statement); break; } } return PendingStatementOrPreparedStatement(lock, query, move(statement), prepared, values); } unique_ptr<PendingQueryResult> ClientContext::PendingStatementOrPreparedStatement(ClientContextLock &lock, const string &query, unique_ptr<SQLStatement> statement, shared_ptr<PreparedStatementData> &prepared, vector<Value> *values) { unique_ptr<PendingQueryResult> result; BeginQueryInternal(lock, query); // start the profiler auto &profiler = QueryProfiler::Get(*this); profiler.StartQuery(query, IsExplainAnalyze(statement ? statement.get() : prepared->unbound_statement.get())); bool invalidate_query = true; try { if (statement) { result = PendingStatementInternal(lock, query, move(statement)); } else { auto &catalog = Catalog::GetCatalog(*this); if (prepared->unbound_statement && (catalog.GetCatalogVersion() != prepared->catalog_version || !prepared->properties.bound_all_parameters)) { // catalog was modified: rebind the statement before execution auto new_prepared = CreatePreparedStatement(lock, query, prepared->unbound_statement->Copy(), values); if (prepared->types != new_prepared->types && prepared->properties.bound_all_parameters) { throw BinderException("Rebinding statement after catalog change resulted in change of types"); } D_ASSERT(new_prepared->properties.bound_all_parameters); new_prepared->unbound_statement = move(prepared->unbound_statement); prepared = move(new_prepared); prepared->properties.bound_all_parameters = false; } result = PendingPreparedStatement(lock, prepared, *values); } } catch (StandardException &ex) { // standard exceptions do not invalidate the current transaction result = make_unique<PendingQueryResult>(ex.what()); invalidate_query = false; } catch (std::exception &ex) { // other types of exceptions do invalidate the current transaction result = make_unique<PendingQueryResult>(ex.what()); } if (!result->success) { // query failed: abort now EndQueryInternal(lock, false, invalidate_query); return result; } D_ASSERT(active_query->open_result == result.get()); return result; } void ClientContext::LogQueryInternal(ClientContextLock &, const string &query) { if (!client_data->log_query_writer) { #ifdef DUCKDB_FORCE_QUERY_LOG try { string log_path(DUCKDB_FORCE_QUERY_LOG); client_data->log_query_writer = make_unique<BufferedFileWriter>(FileSystem::GetFileSystem(*this), log_path, BufferedFileWriter::DEFAULT_OPEN_FLAGS, client_data->file_opener.get()); } catch (...) { return; } #else return; #endif } // log query path is set: log the query client_data->log_query_writer->WriteData((const_data_ptr_t)query.c_str(), query.size()); client_data->log_query_writer->WriteData((const_data_ptr_t) "\n", 1); client_data->log_query_writer->Flush(); client_data->log_query_writer->Sync(); } unique_ptr<QueryResult> ClientContext::Query(unique_ptr<SQLStatement> statement, bool allow_stream_result) { auto pending_query = PendingQuery(move(statement)); return pending_query->Execute(allow_stream_result); } unique_ptr<QueryResult> ClientContext::Query(const string &query, bool allow_stream_result) { auto lock = LockContext(); string error; vector<unique_ptr<SQLStatement>> statements; if (!ParseStatements(*lock, query, statements, error)) { return make_unique<MaterializedQueryResult>(move(error)); } if (statements.empty()) { // no statements, return empty successful result StatementProperties properties; vector<LogicalType> types; vector<string> names; return make_unique<MaterializedQueryResult>(StatementType::INVALID_STATEMENT, properties, move(types), move(names), shared_from_this()); } unique_ptr<QueryResult> result; QueryResult *last_result = nullptr; for (idx_t i = 0; i < statements.size(); i++) { auto &statement = statements[i]; bool is_last_statement = i + 1 == statements.size(); bool stream_result = allow_stream_result && is_last_statement; auto pending_query = PendingQueryInternal(*lock, move(statement)); unique_ptr<QueryResult> current_result; if (!pending_query->success) { current_result = make_unique<MaterializedQueryResult>(pending_query->error); } else { current_result = ExecutePendingQueryInternal(*lock, *pending_query, stream_result); } // now append the result to the list of results if (!last_result) { // first result of the query result = move(current_result); last_result = result.get(); } else { // later results; attach to the result chain last_result->next = move(current_result); last_result = last_result->next.get(); } } return result; } bool ClientContext::ParseStatements(ClientContextLock &lock, const string &query, vector<unique_ptr<SQLStatement>> &result, string &error) { try { InitialCleanup(lock); // parse the query and transform it into a set of statements result = ParseStatementsInternal(lock, query); return true; } catch (std::exception &ex) { error = ex.what(); return false; } } unique_ptr<PendingQueryResult> ClientContext::PendingQuery(const string &query) { auto lock = LockContext(); string error; vector<unique_ptr<SQLStatement>> statements; if (!ParseStatements(*lock, query, statements, error)) { return make_unique<PendingQueryResult>(move(error)); } if (statements.size() != 1) { return make_unique<PendingQueryResult>("PendingQuery can only take a single statement"); } return PendingQueryInternal(*lock, move(statements[0])); } unique_ptr<PendingQueryResult> ClientContext::PendingQuery(unique_ptr<SQLStatement> statement) { auto lock = LockContext(); return PendingQueryInternal(*lock, move(statement)); } unique_ptr<PendingQueryResult> ClientContext::PendingQueryInternal(ClientContextLock &lock, unique_ptr<SQLStatement> statement, bool verify) { auto query = statement->query; shared_ptr<PreparedStatementData> prepared; if (verify) { return PendingStatementOrPreparedStatementInternal(lock, query, move(statement), prepared, nullptr); } else { return PendingStatementOrPreparedStatement(lock, query, move(statement), prepared, nullptr); } } unique_ptr<QueryResult> ClientContext::ExecutePendingQueryInternal(ClientContextLock &lock, PendingQueryResult &query, bool allow_stream_result) { return query.ExecuteInternal(lock, allow_stream_result); } void ClientContext::Interrupt() { interrupted = true; } void ClientContext::EnableProfiling() { auto lock = LockContext(); auto &config = ClientConfig::GetConfig(*this); config.enable_profiler = true; } void ClientContext::DisableProfiling() { auto lock = LockContext(); auto &config = ClientConfig::GetConfig(*this); config.enable_profiler = false; } struct VerifyStatement { VerifyStatement(unique_ptr<SelectStatement> statement_p, string statement_name_p, bool require_equality = true, bool disable_optimizer = false) : statement(move(statement_p)), statement_name(move(statement_name_p)), require_equality(require_equality), disable_optimizer(disable_optimizer), select_list(statement->node->GetSelectList()) { } unique_ptr<SelectStatement> statement; string statement_name; bool require_equality; bool disable_optimizer; const vector<unique_ptr<ParsedExpression>> &select_list; }; string ClientContext::VerifyQuery(ClientContextLock &lock, const string &query, unique_ptr<SQLStatement> statement) { D_ASSERT(statement->type == StatementType::SELECT_STATEMENT); // aggressive query verification // the purpose of this function is to test correctness of otherwise hard to test features: // Copy() of statements and expressions // Serialize()/Deserialize() of expressions // Hash() of expressions // Equality() of statements and expressions // ToString() of statements and expressions // Correctness of plans both with and without optimizers vector<VerifyStatement> verify_statements; // copy the statement auto select_stmt = (SelectStatement *)statement.get(); auto copied_stmt = unique_ptr_cast<SQLStatement, SelectStatement>(select_stmt->Copy()); auto unoptimized_stmt = unique_ptr_cast<SQLStatement, SelectStatement>(select_stmt->Copy()); BufferedSerializer serializer; select_stmt->Serialize(serializer); BufferedDeserializer source(serializer); auto deserialized_stmt = SelectStatement::Deserialize(source); auto query_str = select_stmt->ToString(); Parser parser; parser.ParseQuery(query_str); D_ASSERT(parser.statements.size() == 1); D_ASSERT(parser.statements[0]->type == StatementType::SELECT_STATEMENT); auto parsed_statement = move(parser.statements[0]); verify_statements.emplace_back(unique_ptr_cast<SQLStatement, SelectStatement>(move(statement)), "Original statement"); verify_statements.emplace_back(move(copied_stmt), "Copied statement"); verify_statements.emplace_back(move(deserialized_stmt), "Deserialized statement"); verify_statements.emplace_back(unique_ptr_cast<SQLStatement, SelectStatement>(move(parsed_statement)), "Parsed statement", false); verify_statements.emplace_back(unique_ptr_cast<SQLStatement, SelectStatement>(move(unoptimized_stmt)), "Unoptimized", true, true); // all the statements should be equal for (idx_t i = 1; i < verify_statements.size(); i++) { if (!verify_statements[i].require_equality) { continue; } D_ASSERT(verify_statements[i].statement->Equals(verify_statements[0].statement.get())); } // now perform checking on the expressions #ifdef DEBUG for (idx_t i = 1; i < verify_statements.size(); i++) { D_ASSERT(verify_statements[i].select_list.size() == verify_statements[0].select_list.size()); } auto expr_count = verify_statements[0].select_list.size(); auto &orig_expr_list = verify_statements[0].select_list; for (idx_t i = 0; i < expr_count; i++) { // run the ToString, to verify that it doesn't crash auto str = orig_expr_list[i]->ToString(); for (idx_t v_idx = 0; v_idx < verify_statements.size(); v_idx++) { if (!verify_statements[v_idx].require_equality && orig_expr_list[i]->HasSubquery()) { continue; } // check that the expressions are equivalent D_ASSERT(orig_expr_list[i]->Equals(verify_statements[v_idx].select_list[i].get())); // check that the hashes are equivalent too D_ASSERT(orig_expr_list[i]->Hash() == verify_statements[v_idx].select_list[i]->Hash()); verify_statements[v_idx].select_list[i]->Verify(); } D_ASSERT(!orig_expr_list[i]->Equals(nullptr)); if (orig_expr_list[i]->HasSubquery()) { continue; } // ToString round trip auto parsed_list = Parser::ParseExpressionList(str); D_ASSERT(parsed_list.size() == 1); D_ASSERT(parsed_list[0]->Equals(orig_expr_list[i].get())); } // perform additional checking within the expressions for (idx_t outer_idx = 0; outer_idx < orig_expr_list.size(); outer_idx++) { auto hash = orig_expr_list[outer_idx]->Hash(); for (idx_t inner_idx = 0; inner_idx < orig_expr_list.size(); inner_idx++) { auto hash2 = orig_expr_list[inner_idx]->Hash(); if (hash != hash2) { // if the hashes are not equivalent, the expressions should not be equivalent D_ASSERT(!orig_expr_list[outer_idx]->Equals(orig_expr_list[inner_idx].get())); } } } #endif // disable profiling if it is enabled auto &config = ClientConfig::GetConfig(*this); bool profiling_is_enabled = config.enable_profiler; if (profiling_is_enabled) { config.enable_profiler = false; } // see below auto statement_copy_for_explain = select_stmt->Copy(); // execute the original statement auto optimizer_enabled = config.enable_optimizer; vector<unique_ptr<MaterializedQueryResult>> results; for (idx_t i = 0; i < verify_statements.size(); i++) { interrupted = false; config.enable_optimizer = !verify_statements[i].disable_optimizer; try { auto result = RunStatementInternal(lock, query, move(verify_statements[i].statement), false, false); results.push_back(unique_ptr_cast<QueryResult, MaterializedQueryResult>(move(result))); } catch (std::exception &ex) { results.push_back(make_unique<MaterializedQueryResult>(ex.what())); } } config.enable_optimizer = optimizer_enabled; // check explain, only if q does not already contain EXPLAIN if (results[0]->success) { auto explain_q = "EXPLAIN " + query; auto explain_stmt = make_unique<ExplainStatement>(move(statement_copy_for_explain)); try { RunStatementInternal(lock, explain_q, move(explain_stmt), false, false); } catch (std::exception &ex) { // LCOV_EXCL_START return "EXPLAIN failed but query did not (" + string(ex.what()) + ")"; } // LCOV_EXCL_STOP } if (profiling_is_enabled) { config.enable_profiler = true; } // now compare the results // the results of all runs should be identical for (idx_t i = 1; i < results.size(); i++) { auto name = verify_statements[i].statement_name; if (results[0]->success != results[i]->success) { // LCOV_EXCL_START string result = name + " differs from original result!\n"; result += "Original Result:\n" + results[0]->ToString(); result += name + ":\n" + results[i]->ToString(); return result; } // LCOV_EXCL_STOP if (!results[0]->collection.Equals(results[i]->collection)) { // LCOV_EXCL_START string result = name + " differs from original result!\n"; result += "Original Result:\n" + results[0]->ToString(); result += name + ":\n" + results[i]->ToString(); return result; } // LCOV_EXCL_STOP } return ""; } bool ClientContext::UpdateFunctionInfoFromEntry(ScalarFunctionCatalogEntry *existing_function, CreateScalarFunctionInfo *new_info) { if (new_info->functions.empty()) { throw InternalException("Registering function without scalar function definitions!"); } bool need_rewrite_entry = false; idx_t size_new_func = new_info->functions.size(); for (idx_t exist_idx = 0; exist_idx < existing_function->functions.size(); ++exist_idx) { bool can_add = true; for (idx_t new_idx = 0; new_idx < size_new_func; ++new_idx) { if (new_info->functions[new_idx].Equal(existing_function->functions[exist_idx])) { can_add = false; break; } } if (can_add) { new_info->functions.push_back(existing_function->functions[exist_idx]); need_rewrite_entry = true; } } return need_rewrite_entry; } void ClientContext::RegisterFunction(CreateFunctionInfo *info) { RunFunctionInTransaction([&]() { auto &catalog = Catalog::GetCatalog(*this); auto existing_function = (ScalarFunctionCatalogEntry *)catalog.GetEntry( *this, CatalogType::SCALAR_FUNCTION_ENTRY, info->schema, info->name, true); if (existing_function) { if (UpdateFunctionInfoFromEntry(existing_function, (CreateScalarFunctionInfo *)info)) { // function info was updated from catalog entry, rewrite is needed info->on_conflict = OnCreateConflict::REPLACE_ON_CONFLICT; } } // create function catalog.CreateFunction(*this, info); }); } void ClientContext::RunFunctionInTransactionInternal(ClientContextLock &lock, const std::function<void(void)> &fun, bool requires_valid_transaction) { if (requires_valid_transaction && transaction.HasActiveTransaction() && transaction.ActiveTransaction().IsInvalidated()) { throw Exception("Failed: transaction has been invalidated!"); } // check if we are on AutoCommit. In this case we should start a transaction bool require_new_transaction = transaction.IsAutoCommit() && !transaction.HasActiveTransaction(); if (require_new_transaction) { D_ASSERT(!active_query); transaction.BeginTransaction(); } try { fun(); } catch (StandardException &ex) { if (require_new_transaction) { transaction.Rollback(); } throw; } catch (std::exception &ex) { if (require_new_transaction) { transaction.Rollback(); } else { ActiveTransaction().Invalidate(); } throw; } if (require_new_transaction) { transaction.Commit(); } } void ClientContext::RunFunctionInTransaction(const std::function<void(void)> &fun, bool requires_valid_transaction) { auto lock = LockContext(); RunFunctionInTransactionInternal(*lock, fun, requires_valid_transaction); } unique_ptr<TableDescription> ClientContext::TableInfo(const string &schema_name, const string &table_name) { unique_ptr<TableDescription> result; RunFunctionInTransaction([&]() { // obtain the table info auto &catalog = Catalog::GetCatalog(*this); auto table = catalog.GetEntry<TableCatalogEntry>(*this, schema_name, table_name, true); if (!table) { return; } // write the table info to the result result = make_unique<TableDescription>(); result->schema = schema_name; result->table = table_name; for (auto &column : table->columns) { result->columns.emplace_back(column.name, column.type); } }); return result; } void ClientContext::Append(TableDescription &description, ChunkCollection &collection) { RunFunctionInTransaction([&]() { auto &catalog = Catalog::GetCatalog(*this); auto table_entry = catalog.GetEntry<TableCatalogEntry>(*this, description.schema, description.table); // verify that the table columns and types match up if (description.columns.size() != table_entry->columns.size()) { throw Exception("Failed to append: table entry has different number of columns!"); } for (idx_t i = 0; i < description.columns.size(); i++) { if (description.columns[i].type != table_entry->columns[i].type) { throw Exception("Failed to append: table entry has different number of columns!"); } } for (auto &chunk : collection.Chunks()) { table_entry->storage->Append(*table_entry, *this, *chunk); } }); } void ClientContext::TryBindRelation(Relation &relation, vector<ColumnDefinition> &result_columns) { #ifdef DEBUG D_ASSERT(!relation.GetAlias().empty()); D_ASSERT(!relation.ToString().empty()); #endif RunFunctionInTransaction([&]() { // bind the expressions auto binder = Binder::CreateBinder(*this); auto result = relation.Bind(*binder); D_ASSERT(result.names.size() == result.types.size()); for (idx_t i = 0; i < result.names.size(); i++) { result_columns.emplace_back(result.names[i], result.types[i]); } }); } unordered_set<string> ClientContext::GetTableNames(const string &query) { auto lock = LockContext(); auto statements = ParseStatementsInternal(*lock, query); if (statements.size() != 1) { throw InvalidInputException("Expected a single statement"); } unordered_set<string> result; RunFunctionInTransactionInternal(*lock, [&]() { // bind the expressions auto binder = Binder::CreateBinder(*this); binder->SetBindingMode(BindingMode::EXTRACT_NAMES); binder->Bind(*statements[0]); result = binder->GetTableNames(); }); return result; } unique_ptr<QueryResult> ClientContext::Execute(const shared_ptr<Relation> &relation) { auto lock = LockContext(); InitialCleanup(*lock); string query; if (config.query_verification_enabled) { // run the ToString method of any relation we run, mostly to ensure it doesn't crash relation->ToString(); relation->GetAlias(); if (relation->IsReadOnly()) { // verify read only statements by running a select statement auto select = make_unique<SelectStatement>(); select->node = relation->GetQueryNode(); RunStatementInternal(*lock, query, move(select), false); } } auto &expected_columns = relation->Columns(); auto relation_stmt = make_unique<RelationStatement>(relation); unique_ptr<QueryResult> result; result = RunStatementInternal(*lock, query, move(relation_stmt), false); if (!result->success) { return result; } // verify that the result types and result names of the query match the expected result types/names if (result->types.size() == expected_columns.size()) { bool mismatch = false; for (idx_t i = 0; i < result->types.size(); i++) { if (result->types[i] != expected_columns[i].type || result->names[i] != expected_columns[i].name) { mismatch = true; break; } } if (!mismatch) { // all is as expected: return the result return result; } } // result mismatch string err_str = "Result mismatch in query!\nExpected the following columns: ["; for (idx_t i = 0; i < expected_columns.size(); i++) { if (i > 0) { err_str += ", "; } err_str += expected_columns[i].name + " " + expected_columns[i].type.ToString(); } err_str += "]\nBut result contained the following: "; for (idx_t i = 0; i < result->types.size(); i++) { err_str += i == 0 ? "[" : ", "; err_str += result->names[i] + " " + result->types[i].ToString(); } err_str += "]"; return make_unique<MaterializedQueryResult>(err_str); } bool ClientContext::TryGetCurrentSetting(const std::string &key, Value &result) { // first check the built-in settings auto &db_config = DBConfig::GetConfig(*this); auto option = db_config.GetOptionByName(key); if (option) { result = option->get_setting(*this); return true; } // then check the session values const auto &session_config_map = config.set_variables; const auto &global_config_map = db_config.set_variables; auto session_value = session_config_map.find(key); bool found_session_value = session_value != session_config_map.end(); auto global_value = global_config_map.find(key); bool found_global_value = global_value != global_config_map.end(); if (!found_session_value && !found_global_value) { return false; } result = found_session_value ? session_value->second : global_value->second; return true; } ParserOptions ClientContext::GetParserOptions() { ParserOptions options; options.preserve_identifier_case = ClientConfig::GetConfig(*this).preserve_identifier_case; options.max_expression_depth = ClientConfig::GetConfig(*this).max_expression_depth; return options; } } // namespace duckdb
#include "TDES.h" std::string TDES::run(const std::string & data, const std::string & key, const bool & mode){ if (!keyset){ throw std::runtime_error("Error: Key has not been set."); } if (data.size() != 8){ throw std::runtime_error("Error: Data must be 64 bits in length."); } if (!mode){ return DES(key).encrypt(data); } return DES(key).decrypt(data); } TDES::TDES() : SymAlg(), k1(), k2(), k3(), m1(), m2(), m3() { } TDES::TDES(const std::string & key1, const std::string & mode1, const std::string & key2, const std::string & mode2, const std::string & key3, const std::string & mode3) : TDES() { setkey(key1, mode1, key2, mode2, key3, mode3); } void TDES::setkey(const std::string & key1, const std::string & mode1, const std::string & key2, const std::string & mode2, const std::string & key3, const std::string & mode3){ if (keyset){ throw std::runtime_error("Error: Key has already been set."); } if (key1.size() != 8){ throw std::runtime_error("Error: Key must be 64 bits in length."); } if (key2.size() != 8){ throw std::runtime_error("Error: Key must be 64 bits in length."); } if (key3.size() != 8){ throw std::runtime_error("Error: Key must be 64 bits in length."); } k1 = key1; k2 = key2; k3 = key3; m1 = (mode1 == "d"); m2 = (mode2 == "d"); m3 = (mode3 == "d"); keyset = true; } std::string TDES::encrypt(const std::string & DATA){ return run(run(run(DATA, k1, m1), k2, m2), k3, m3); } std::string TDES::decrypt(const std::string & DATA){ return run(run(run(DATA, k1, !m1), k2, !m2), k3, !m3); } unsigned int TDES::blocksize() const{ return 64; }
/* * Copyright (C) 2015 Open Source Robotics Foundation * * 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 _GAZEBO_VIEW_ANGLE_WIDGET_HH_ #define _GAZEBO_VIEW_ANGLE_WIDGET_HH_ #include <string> #include <ignition/math/Vector3.hh> #include "gazebo/gui/qt.h" #include "gazebo/util/system.hh" namespace gazebo { namespace gui { class ViewAngleWidgetPrivate; /// \brief A gui widget for changing the camera view angle. class GAZEBO_VISIBLE ViewAngleWidget : public QWidget { Q_OBJECT /// \brief View angle modes public: enum Mode { /// \brief Top TOP, /// \brief Bottom BOTTOM, /// \brief Front FRONT, /// \brief Back BACK, /// \brief Left LEFT, /// \brief Right RIGHT, /// \brief Reset view RESET }; /// \brief Constructor /// \param[in] _parent Parent Qt widget. public: ViewAngleWidget(QWidget *_parent = 0); /// \brief Destructor public: virtual ~ViewAngleWidget(); /// \brief Add an action to the widget. /// \param[in] _mode View mode /// \param[in] _action The Qt action to add. public: void Add(const Mode _mode, QAction *_action); /// \brief Qt callback when the top view has been triggered. private slots: void OnTopView(); /// \brief Qt callback when the bottom view has been triggered. private slots: void OnBottomView(); /// \brief Qt callback when the front view has been triggered. private slots: void OnFrontView(); /// \brief Qt callback when the back view has been triggered. private slots: void OnBackView(); /// \brief Qt callback when the left view has been triggered. private slots: void OnLeftView(); /// \brief Qt callback when the right view has been triggered. private slots: void OnRightView(); /// \brief Qt callback when reset view has been triggered. private slots: void OnResetView(); /// \brief Qt callback when the index of the QComboBox has been changed. /// \param[in] _index Index: 0 for perpective, 1 for orthographic. private slots: void OnProjection(int _index); /// \brief QT Callback that turns on orthographic projection. private slots: void OnOrtho(); /// \brief QT Callback that turns on perspective projection. private slots: void OnPerspective(); /// \brief Move the camera to face the given direction. In case there's /// an object immediately in front of the camera, the camera will /// continue facing the object, with about the same distance (zoom). If /// there's no object, the camera will face the world origin. The movement /// takes 1 second. /// \param[in] _dir Direction for the camera to face. private: void LookDirection(const ignition::math::Vector3d &_dir); /// \internal /// \brief Pointer to private data. private: ViewAngleWidgetPrivate *dataPtr; }; } } #endif
/* Copyright (c) 2003, Daniel Wallin Copyright (c) 2003, 2009, 2011, 2013-2020, Arvid Norberg Copyright (c) 2016, 2018, Alden Torres Copyright (c) 2018-2019, Steven Siloti All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author 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 TORRENT_STORAGE_HPP_INCLUDE #define TORRENT_STORAGE_HPP_INCLUDE #include "libtorrent/config.hpp" #include <mutex> #include <atomic> #include <memory> #include "libtorrent/fwd.hpp" #include "libtorrent/aux_/disk_job_fence.hpp" #include "libtorrent/storage_defs.hpp" #include "libtorrent/part_file.hpp" #include "libtorrent/stat_cache.hpp" #include "libtorrent/bitfield.hpp" #include "libtorrent/span.hpp" #include "libtorrent/aux_/vector.hpp" #include "libtorrent/aux_/open_mode.hpp" // for aux::open_mode_t #include "libtorrent/aux_/disable_warnings_push.hpp" #include <boost/optional.hpp> #include "libtorrent/aux_/disable_warnings_pop.hpp" namespace libtorrent { namespace aux { struct session_settings; struct file_view_pool; struct file_view; } struct TORRENT_EXTRA_EXPORT mmap_storage : std::enable_shared_from_this<mmap_storage> , aux::disk_job_fence { // constructs the mmap_storage based on the give file_storage (fs). // ``mapped`` is an optional argument (it may be nullptr). If non-nullptr it // represents the file mapping that have been made to the torrent before // adding it. That's where files are supposed to be saved and looked for // on disk. ``save_path`` is the root save folder for this torrent. // ``file_view_pool`` is the cache of file mappings that the storage will use. // All files it opens will ask the file_view_pool to open them. ``file_prio`` // is a vector indicating the priority of files on startup. It may be // an empty vector. Any file whose index is not represented by the vector // (because the vector is too short) are assumed to have priority 1. // this is used to treat files with priority 0 slightly differently. mmap_storage(storage_params const& params, aux::file_view_pool&); // hidden ~mmap_storage(); mmap_storage(mmap_storage const&) = delete; mmap_storage& operator=(mmap_storage const&) = delete; void abort_jobs(); bool has_any_file(storage_error&); void set_file_priority(settings_interface const& , aux::vector<download_priority_t, file_index_t>& prio , storage_error&); void rename_file(file_index_t index, std::string const& new_filename , storage_error&); void release_files(storage_error&); void delete_files(remove_flags_t options, storage_error&); void initialize(settings_interface const&, storage_error&); std::pair<status_t, std::string> move_storage(std::string save_path , move_flags_t, storage_error&); bool verify_resume_data(add_torrent_params const& rd , aux::vector<std::string, file_index_t> const& links , storage_error&); bool tick(); int readv(settings_interface const&, span<iovec_t const> bufs , piece_index_t piece, int offset, aux::open_mode_t flags, storage_error&); int writev(settings_interface const&, span<iovec_t const> bufs , piece_index_t piece, int offset, aux::open_mode_t flags, storage_error&); int hashv(settings_interface const&, hasher& ph, std::ptrdiff_t len , piece_index_t piece, int offset, aux::open_mode_t flags , storage_error&); int hashv2(settings_interface const&, hasher256& ph, std::ptrdiff_t len , piece_index_t piece, int offset, aux::open_mode_t flags, storage_error&); // if the files in this storage are mapped, returns the mapped // file_storage, otherwise returns the original file_storage object. file_storage const& files() const { return m_mapped_files ? *m_mapped_files : m_files; } file_storage const& orig_files() const { return m_files; } bool set_need_tick() { bool const prev = m_need_tick; m_need_tick = true; return prev; } void do_tick() { m_need_tick = false; tick(); } void set_owner(std::shared_ptr<void> const& tor) { m_torrent = tor; } storage_index_t storage_index() const { return m_storage_index; } void set_storage_index(storage_index_t st) { m_storage_index = st; } private: bool m_need_tick = false; file_storage const& m_files; // the reason for this to be a void pointer // is to avoid creating a dependency on the // torrent. This shared_ptr is here only // to keep the torrent object alive until // the storage destructs. This is because // the file_storage object is owned by the torrent. std::shared_ptr<void> m_torrent; storage_index_t m_storage_index{0}; void need_partfile(); std::unique_ptr<file_storage> m_mapped_files; // in order to avoid calling stat() on each file multiple times // during startup, cache the results in here, and clear it all // out once the torrent starts (to avoid getting stale results) // each entry represents the size and timestamp of the file mutable stat_cache m_stat_cache; // helper function to open a file in the file pool with the right mode boost::optional<aux::file_view> open_file(settings_interface const&, file_index_t , aux::open_mode_t, storage_error&) const; boost::optional<aux::file_view> open_file_impl(settings_interface const& , file_index_t, aux::open_mode_t, error_code&) const; bool use_partfile(file_index_t index) const; void use_partfile(file_index_t index, bool b); aux::vector<download_priority_t, file_index_t> m_file_priority; std::string m_save_path; std::string m_part_file_name; // this this is an array indexed by file-index. Each slot represents // whether this file has the part-file enabled for it. This is used for // backwards compatibility with pre-partfile versions of libtorrent. If // this vector is empty, the default is that files *do* use the partfile. // on startup, any 0-priority file that's found in it's original location // is expected to be an old-style (pre-partfile) torrent storage, and // those files have their slot set to false in this vector. // note that the vector is *sparse*, it's only allocated if a file has its // entry set to false, and only indices up to that entry. aux::vector<bool, file_index_t> m_use_partfile; // the file pool is a member of the disk_io_thread // to make all storage instances share the pool aux::file_view_pool& m_pool; // used for skipped files std::unique_ptr<part_file> m_part_file; // this is a bitfield with one bit per file. A bit being set means // we've written to that file previously. If we do write to a file // whose bit is 0, we set the file size, to make the file allocated // on disk (in full allocation mode) and just sparsely allocated in // case of sparse allocation mode mutable std::mutex m_file_created_mutex; mutable typed_bitfield<file_index_t> m_file_created; #if TORRENT_HAVE_MAP_VIEW_OF_FILE // Windows has a race condition when unmapping a view while a new // view or mapping object is being created in a different thread. // The race can cause a page of written data to be zeroed out before // it is written out to disk. To avoid the race these calls must be // serialized on a per-file basis. See github issue #3842 for details. // This array stores a mutex for each file in the storage object // It must be aquired before calling CreateFileMapping or UnmapViewOfFile mutable std::shared_ptr<std::mutex> m_file_open_unmap_lock; #endif bool m_allocate_files; }; } #endif // TORRENT_STORAGE_HPP_INCLUDED
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/autofill/core/browser/payments/full_card_request.h" #include <memory> #include "base/bind.h" #include "base/check_op.h" #include "base/notreached.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "build/build_config.h" #include "components/autofill/core/browser/data_model/credit_card.h" #include "components/autofill/core/browser/metrics/autofill_metrics.h" #include "components/autofill/core/browser/payments/payments_util.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_tick_clock.h" namespace autofill { namespace payments { FullCardRequest::FullCardRequest(RiskDataLoader* risk_data_loader, payments::PaymentsClient* payments_client, PersonalDataManager* personal_data_manager) : risk_data_loader_(risk_data_loader), payments_client_(payments_client), personal_data_manager_(personal_data_manager), result_delegate_(nullptr), ui_delegate_(nullptr), should_unmask_card_(false) { DCHECK(risk_data_loader_); DCHECK(payments_client_); DCHECK(personal_data_manager_); } FullCardRequest::~FullCardRequest() = default; void FullCardRequest::GetFullCard( const CreditCard& card, AutofillClient::UnmaskCardReason reason, base::WeakPtr<ResultDelegate> result_delegate, base::WeakPtr<UIDelegate> ui_delegate, absl::optional<GURL> last_committed_url_origin) { DCHECK(ui_delegate); GetFullCardImpl(card, reason, result_delegate, ui_delegate, /*fido_assertion_info=*/absl::nullopt, std::move(last_committed_url_origin), /*context_token=*/absl::nullopt); } void FullCardRequest::GetFullCardViaFIDO( const CreditCard& card, AutofillClient::UnmaskCardReason reason, base::WeakPtr<ResultDelegate> result_delegate, base::Value fido_assertion_info, absl::optional<GURL> last_committed_url_origin, absl::optional<std::string> context_token) { DCHECK(fido_assertion_info.is_dict()); GetFullCardImpl( card, reason, result_delegate, nullptr, std::move(fido_assertion_info), std::move(last_committed_url_origin), std::move(context_token)); } void FullCardRequest::GetFullCardImpl( const CreditCard& card, AutofillClient::UnmaskCardReason reason, base::WeakPtr<ResultDelegate> result_delegate, base::WeakPtr<UIDelegate> ui_delegate, absl::optional<base::Value> fido_assertion_info, absl::optional<GURL> last_committed_url_origin, absl::optional<std::string> context_token) { // Retrieval of card information should happen via CVC auth or FIDO, but not // both. Use |ui_delegate|'s existence as evidence of doing CVC auth and // |fido_assertion_info| as evidence of doing FIDO auth. DCHECK_NE(fido_assertion_info.has_value(), !!ui_delegate); DCHECK(result_delegate); // Only one request can be active at a time. If the member variable // |result_delegate_| is already set, then immediately reject the new request // through the method parameter |result_delegate_|. if (result_delegate_) { result_delegate_->OnFullCardRequestFailed(FailureType::GENERIC_FAILURE); return; } // If unmasking is for a virtual card and |last_committed_url_origin| is // empty, end the request as failure and reset. if (card.record_type() == CreditCard::VIRTUAL_CARD && !last_committed_url_origin.has_value()) { NOTREACHED(); if (ui_delegate_) ui_delegate_->OnUnmaskVerificationResult( AutofillClient::PaymentsRpcResult::kPermanentFailure); if (result_delegate_) result_delegate_->OnFullCardRequestFailed(FailureType::GENERIC_FAILURE); Reset(); return; } result_delegate_ = result_delegate; request_ = std::make_unique<payments::PaymentsClient::UnmaskRequestDetails>(); request_->card = card; request_->last_committed_url_origin = last_committed_url_origin; if (context_token.has_value()) request_->context_token = context_token.value(); should_unmask_card_ = card.record_type() == CreditCard::MASKED_SERVER_CARD || card.record_type() == CreditCard::VIRTUAL_CARD || (card.record_type() == CreditCard::FULL_SERVER_CARD && card.ShouldUpdateExpiration()) || card.record_type() == CreditCard::VIRTUAL_CARD; if (should_unmask_card_) { payments_client_->Prepare(); request_->billing_customer_number = GetBillingCustomerId(personal_data_manager_); } request_->fido_assertion_info = std::move(fido_assertion_info); ui_delegate_ = ui_delegate; // If there is a UI delegate, then perform a CVC check. // Otherwise, continue and use |fido_assertion_info| to unmask. if (ui_delegate_) { ui_delegate_->ShowUnmaskPrompt(request_->card, reason, weak_ptr_factory_.GetWeakPtr()); } if (should_unmask_card_) { risk_data_loader_->LoadRiskData( base::BindOnce(&FullCardRequest::OnDidGetUnmaskRiskData, weak_ptr_factory_.GetWeakPtr())); } } void FullCardRequest::OnUnmaskPromptAccepted( const UserProvidedUnmaskDetails& user_response) { if (!user_response.exp_month.empty()) request_->card.SetRawInfo(CREDIT_CARD_EXP_MONTH, user_response.exp_month); if (!user_response.exp_year.empty()) request_->card.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, user_response.exp_year); if (request_->card.record_type() == CreditCard::LOCAL_CARD && !request_->card.guid().empty() && (!user_response.exp_month.empty() || !user_response.exp_year.empty())) { personal_data_manager_->UpdateCreditCard(request_->card); } if (!should_unmask_card_) { if (result_delegate_) result_delegate_->OnFullCardRequestSucceeded(*this, request_->card, user_response.cvc); if (ui_delegate_) ui_delegate_->OnUnmaskVerificationResult( AutofillClient::PaymentsRpcResult::kSuccess); Reset(); return; } request_->user_response = user_response; #if defined(OS_ANDROID) if (ui_delegate_) { // An opt-in request to Payments must be included either if the user chose // to opt-in through the CVC prompt or if the UI delegate indicates that the // user previously chose to opt-in through the settings page. request_->user_response.enable_fido_auth = user_response.enable_fido_auth || ui_delegate_->UserOptedInToFidoFromSettingsPageOnMobile(); } #endif if (!request_->risk_data.empty()) SendUnmaskCardRequest(); } void FullCardRequest::OnUnmaskPromptClosed() { if (result_delegate_) result_delegate_->OnFullCardRequestFailed(FailureType::PROMPT_CLOSED); Reset(); } bool FullCardRequest::ShouldOfferFidoAuth() const { // FIDO opt-in is only handled from card unmask on mobile. Desktop platforms // provide a separate opt-in bubble. #if defined(OS_ANDROID) return ui_delegate_ && ui_delegate_->ShouldOfferFidoAuth(); #else return false; #endif } void FullCardRequest::OnDidGetUnmaskRiskData(const std::string& risk_data) { request_->risk_data = risk_data; if (!request_->user_response.cvc.empty() || request_->fido_assertion_info.has_value()) { SendUnmaskCardRequest(); } } void FullCardRequest::SendUnmaskCardRequest() { real_pan_request_timestamp_ = AutofillTickClock::NowTicks(); payments_client_->UnmaskCard(*request_, base::BindOnce(&FullCardRequest::OnDidGetRealPan, weak_ptr_factory_.GetWeakPtr())); } void FullCardRequest::OnDidGetRealPan( AutofillClient::PaymentsRpcResult result, payments::PaymentsClient::UnmaskResponseDetails& response_details) { // If the CVC field is populated, that means the user performed a CVC check. // If FIDO AssertionInfo is populated, then the user must have performed FIDO // authentication. Exactly one of these fields must be populated. DCHECK_NE(!request_->user_response.cvc.empty(), request_->fido_assertion_info.has_value()); AutofillClient::PaymentsRpcCardType card_type = response_details.card_type; if (!request_->user_response.cvc.empty()) { AutofillMetrics::LogRealPanDuration( AutofillTickClock::NowTicks() - real_pan_request_timestamp_, result, card_type); } else if (request_->fido_assertion_info.has_value()) { AutofillMetrics::LogCardUnmaskDurationAfterWebauthn( AutofillTickClock::NowTicks() - real_pan_request_timestamp_, result, card_type); } if (ui_delegate_) ui_delegate_->OnUnmaskVerificationResult(result); switch (result) { // Wait for user retry. case AutofillClient::PaymentsRpcResult::kTryAgainFailure: break; // Neither PERMANENT_FAILURE, NETWORK_ERROR nor VCN retrieval errors allow // retry. case AutofillClient::PaymentsRpcResult::kPermanentFailure: { if (result_delegate_) { result_delegate_->OnFullCardRequestFailed( FailureType::VERIFICATION_DECLINED); } Reset(); break; } case AutofillClient::PaymentsRpcResult::kNetworkError: { if (result_delegate_) result_delegate_->OnFullCardRequestFailed(FailureType::GENERIC_FAILURE); Reset(); break; } case AutofillClient::PaymentsRpcResult::kVcnRetrievalTryAgainFailure: { if (result_delegate_) { result_delegate_->OnFullCardRequestFailed( FailureType::VIRTUAL_CARD_RETRIEVAL_TRANSIENT_FAILURE); } Reset(); break; } case AutofillClient::PaymentsRpcResult::kVcnRetrievalPermanentFailure: { if (result_delegate_) { result_delegate_->OnFullCardRequestFailed( FailureType::VIRTUAL_CARD_RETRIEVAL_PERMANENT_FAILURE); } Reset(); break; } case AutofillClient::PaymentsRpcResult::kSuccess: { DCHECK(!response_details.real_pan.empty()); request_->card.SetNumber(base::UTF8ToUTF16(response_details.real_pan)); if (response_details.card_type == AutofillClient::PaymentsRpcCardType::kVirtualCard) { request_->card.set_record_type(CreditCard::VIRTUAL_CARD); request_->card.SetExpirationMonthFromString( base::UTF8ToUTF16(response_details.expiration_month), /*app_locale=*/std::string()); request_->card.SetExpirationYearFromString( base::UTF8ToUTF16(response_details.expiration_year)); } else if (response_details.card_type == AutofillClient::PaymentsRpcCardType::kServerCard) { request_->card.set_record_type(CreditCard::FULL_SERVER_CARD); } else { NOTREACHED(); } // TODO(crbug/949269): Once |fido_opt_in| is added to // UserProvidedUnmaskDetails, clear out |creation_options| from // |response_details_| if |user_response.fido_opt_in| was not set to true // to avoid an unwanted registration prompt. unmask_response_details_ = response_details; const std::u16string cvc = (base::FeatureList::IsEnabled( features::kAutofillEnableGoogleIssuedCard) || base::FeatureList::IsEnabled( features::kAutofillAlwaysReturnCloudTokenizedCard) || base::FeatureList::IsEnabled( features::kAutofillEnableMerchantBoundVirtualCards)) && !response_details.dcvv.empty() ? base::UTF8ToUTF16(response_details.dcvv) : request_->user_response.cvc; if (result_delegate_) result_delegate_->OnFullCardRequestSucceeded(*this, request_->card, cvc); Reset(); break; } case AutofillClient::PaymentsRpcResult::kNone: NOTREACHED(); break; } } void FullCardRequest::OnFIDOVerificationCancelled() { Reset(); } void FullCardRequest::Reset() { weak_ptr_factory_.InvalidateWeakPtrs(); payments_client_->CancelRequest(); result_delegate_ = nullptr; ui_delegate_ = nullptr; request_.reset(); should_unmask_card_ = false; unmask_response_details_ = payments::PaymentsClient::UnmaskResponseDetails(); } } // namespace payments } // namespace autofill
#include "libOTe/Base/BaseOT.h" #include <ios> #ifdef ENABLE_KKRT #include "KkrtDefines.h" #include "KkrtNcoOtReceiver.h" #include "libOTe/Tools/Tools.h" #include <cryptoTools/Common/Log.h> #include <cryptoTools/Crypto/RandomOracle.h> #include <mmintrin.h> using namespace std; namespace osuCrypto { void KkrtNcoOtReceiver::setBaseOts(gsl::span<std::array<block, 2>> baseRecvOts) { if (baseRecvOts.size() % 128 != 0) throw std::runtime_error("rt error at " LOCATION); if (u64(baseRecvOts.size()) != u64(mGens.size())) throw std::runtime_error("rt error at " LOCATION); // mGens.resize(baseRecvOts.size()); mGensBlkIdx.resize(baseRecvOts.size(), 0); for (u64 i = 0; i < mGens.size(); i++) { mGens[i][0].setKey(baseRecvOts[i][0]); mGens[i][1].setKey(baseRecvOts[i][1]); } } void KkrtNcoOtReceiver::initStep1(u64 numOtExt, const block seed, const u8* theirComm, const block theirSeed) { static const u64 superBlkSize(8); // this will be used as temporary buffers of 128 columns, // each containing 1024 bits. Once transposed, they will be copied // into the T1, T0 buffers for long term storage. std::array<std::array<block, superBlkSize>, 128> t0; std::array<std::array<block, superBlkSize>, 128> t1; // we are going to process OTs in blocks of 128 * superblkSize messages. u64 numSuperBlocks = ((numOtExt + 127) / 128 + superBlkSize - 1) / superBlkSize; u64 numCols = mGens.size(); // We need two matrices, T0 and T1. These will hold the expanded and transposed // rows that we got the using the base OTs as PRNG seed. mT0.resize(numOtExt, numCols / 128); mT1.resize(numOtExt, numCols / 128); // The is the index of the last correction value u = T0 ^ T1 ^ c(w) // that was sent to the sender. mCorrectionIdx = 0; // the index of the OT that has been completed. u64 doneIdx = 0; // NOTE: We do not transpose a bit-matrix of size numCol * numCol. // Instead we break it down into smaller chunks. We do 128 columns // times 8 * 128 rows at a time, where 8 = superBlkSize. This is done for // performance reasons. The reason for 8 is that most CPUs have 8 AES vector // lanes, and so its more efficient to encrypt (aka prng) 8 blocks at a time. // So that's what we do. for (u64 superBlkIdx = 0; superBlkIdx < numSuperBlocks; ++superBlkIdx) { // compute at what row does the user want us to stop. // The code will still compute the transpose for these // extra rows, but it is thrown away. u64 stopIdx = doneIdx + std::min<u64>(u64(128) * superBlkSize, numOtExt - doneIdx); for (u64 i = 0; i < numCols / 128; ++i) { for (u64 tIdx = 0, colIdx = i * 128; tIdx < 128; ++tIdx, ++colIdx) { // generate the column indexed by colIdx. This is done with // AES in counter mode acting as a PRNG. We don't use the normal // PRNG interface because that would result in a data copy when // we move it into the T0,T1 matrices. Instead we do it directly. mGens[colIdx][0].ecbEncCounterMode( mGensBlkIdx[colIdx], superBlkSize, ((block*)t0.data() + superBlkSize * tIdx)); mGens[colIdx][1].ecbEncCounterMode( mGensBlkIdx[colIdx], superBlkSize, ((block*)t1.data() + superBlkSize * tIdx)); // increment the counter mode idx. mGensBlkIdx[colIdx] += superBlkSize; } // transpose our 128 columns of 1024 bits. We will have 1024 rows, // each 128 bits wide. transpose128x1024(t0); transpose128x1024(t1); // This is the index of where we will store the matrix long term. // doneIdx is the starting row. i is the offset into the blocks of 128 bits. // __restrict isn't crucial, it just tells the compiler that this pointer // is unique and it shouldn't worry about pointer aliasing. block* __restrict mT0Iter = mT0.data() + mT0.stride() * doneIdx + i; block* __restrict mT1Iter = mT1.data() + mT1.stride() * doneIdx + i; for (u64 rowIdx = doneIdx, j = 0; rowIdx < stopIdx; ++j) { // because we transposed 1024 rows, the indexing gets a bit weird. But this // is the location of the next row that we want. Keep in mind that we had long // **contiguous** columns. block* __restrict t0Iter = ((block*)t0.data()) + j; block* __restrict t1Iter = ((block*)t1.data()) + j; // do the copy! for (u64 k = 0; rowIdx < stopIdx && k < 128; ++rowIdx, ++k) { *mT0Iter = *(t0Iter); *mT1Iter = *(t1Iter); t0Iter += superBlkSize; t1Iter += superBlkSize; mT0Iter += mT0.stride(); mT1Iter += mT0.stride(); } } } doneIdx = stopIdx; } // fu.get(); // block theirSeed; // chl.recv((u8*)&theirSeed, sizeof(block)); RandomOracle sha; sha.Update(theirSeed); u8 cc[RandomOracle::HashSize]; sha.Final(cc); if (memcmp(theirComm, cc, RandomOracle::HashSize)) throw std::runtime_error(LOCATION); std::array<block, 4> keys; PRNG(seed ^ theirSeed).get(keys.data(), keys.size()); mMultiKeyAES.setKeys(keys); } void KkrtNcoOtReceiver::init(u64 numOtExt, PRNG& prng, Channel& chl) { if (hasBaseOts() == false) genBaseOts(prng, chl); block seed = prng.get<block>(); u8 theirComm[RandomOracle::HashSize]; auto fu = chl.asyncRecv( theirComm, RandomOracle::HashSize, [&]() { chl.asyncSendCopy((u8*)&seed, sizeof(block)); }); static const u64 superBlkSize(8); // this will be used as temporary buffers of 128 columns, // each containing 1024 bits. Once transposed, they will be copied // into the T1, T0 buffers for long term storage. std::array<std::array<block, superBlkSize>, 128> t0; std::array<std::array<block, superBlkSize>, 128> t1; // we are going to process OTs in blocks of 128 * superblkSize messages. u64 numSuperBlocks = ((numOtExt + 127) / 128 + superBlkSize - 1) / superBlkSize; u64 numCols = mGens.size(); // We need two matrices, T0 and T1. These will hold the expanded and transposed // rows that we got the using the base OTs as PRNG seed. mT0.resize(numOtExt, numCols / 128); mT1.resize(numOtExt, numCols / 128); // The is the index of the last correction value u = T0 ^ T1 ^ c(w) // that was sent to the sender. mCorrectionIdx = 0; // the index of the OT that has been completed. u64 doneIdx = 0; // NOTE: We do not transpose a bit-matrix of size numCol * numCol. // Instead we break it down into smaller chunks. We do 128 columns // times 8 * 128 rows at a time, where 8 = superBlkSize. This is done for // performance reasons. The reason for 8 is that most CPUs have 8 AES vector // lanes, and so its more efficient to encrypt (aka prng) 8 blocks at a time. // So that's what we do. for (u64 superBlkIdx = 0; superBlkIdx < numSuperBlocks; ++superBlkIdx) { // compute at what row does the user want us to stop. // The code will still compute the transpose for these // extra rows, but it is thrown away. u64 stopIdx = doneIdx + std::min<u64>(u64(128) * superBlkSize, numOtExt - doneIdx); for (u64 i = 0; i < numCols / 128; ++i) { for (u64 tIdx = 0, colIdx = i * 128; tIdx < 128; ++tIdx, ++colIdx) { // generate the column indexed by colIdx. This is done with // AES in counter mode acting as a PRNG. We don't use the normal // PRNG interface because that would result in a data copy when // we move it into the T0,T1 matrices. Instead we do it directly. mGens[colIdx][0].ecbEncCounterMode( mGensBlkIdx[colIdx], superBlkSize, ((block*)t0.data() + superBlkSize * tIdx)); mGens[colIdx][1].ecbEncCounterMode( mGensBlkIdx[colIdx], superBlkSize, ((block*)t1.data() + superBlkSize * tIdx)); // increment the counter mode idx. mGensBlkIdx[colIdx] += superBlkSize; } // transpose our 128 columns of 1024 bits. We will have 1024 rows, // each 128 bits wide. transpose128x1024(t0); transpose128x1024(t1); // This is the index of where we will store the matrix long term. // doneIdx is the starting row. i is the offset into the blocks of 128 bits. // __restrict isn't crucial, it just tells the compiler that this pointer // is unique and it shouldn't worry about pointer aliasing. block* __restrict mT0Iter = mT0.data() + mT0.stride() * doneIdx + i; block* __restrict mT1Iter = mT1.data() + mT1.stride() * doneIdx + i; for (u64 rowIdx = doneIdx, j = 0; rowIdx < stopIdx; ++j) { // because we transposed 1024 rows, the indexing gets a bit weird. But this // is the location of the next row that we want. Keep in mind that we had long // **contiguous** columns. block* __restrict t0Iter = ((block*)t0.data()) + j; block* __restrict t1Iter = ((block*)t1.data()) + j; // do the copy! for (u64 k = 0; rowIdx < stopIdx && k < 128; ++rowIdx, ++k) { *mT0Iter = *(t0Iter); *mT1Iter = *(t1Iter); t0Iter += superBlkSize; t1Iter += superBlkSize; mT0Iter += mT0.stride(); mT1Iter += mT0.stride(); } } } doneIdx = stopIdx; } fu.get(); block theirSeed; chl.recv((u8*)&theirSeed, sizeof(block)); RandomOracle sha; sha.Update(theirSeed); u8 cc[RandomOracle::HashSize]; sha.Final(cc); if (memcmp(theirComm, cc, RandomOracle::HashSize)) throw std::runtime_error(LOCATION); std::array<block, 4> keys; PRNG(seed ^ theirSeed).get(keys.data(), keys.size()); mMultiKeyAES.setKeys(keys); } u64 KkrtNcoOtReceiver::getBaseOTCount() const { if (mGens.size()) return mGens.size(); else throw std::runtime_error("must call configure(...) before getBaseOTCount() " LOCATION); } KkrtNcoOtReceiver KkrtNcoOtReceiver::splitBase() { KkrtNcoOtReceiver raw; raw.mGens.resize(mGens.size()); raw.mInputByteCount = mInputByteCount; raw.mMultiKeyAES = mMultiKeyAES; if (hasBaseOts()) { std::vector<std::array<block, 2>> base(mGens.size()); for (u64 i = 0; i < base.size(); ++i) { mGens[i][0].ecbEncCounterMode(mGensBlkIdx[i], 1, &base[i][0]); mGens[i][1].ecbEncCounterMode(mGensBlkIdx[i], 1, &base[i][1]); ++mGensBlkIdx[i]; } raw.setBaseOts(base); } return std::move(raw); } std::unique_ptr<NcoOtExtReceiver> KkrtNcoOtReceiver::split() { return std::make_unique<KkrtNcoOtReceiver>(std::move(splitBase())); } void KkrtNcoOtReceiver::encode(u64 otIdx, const void* input, void* dest, u64 destSize) { static const int width(4); #ifndef NDEBUG if (mT0.stride() != width) throw std::runtime_error(LOCATION); // if (choice.size() != mT0.stride()) // throw std::invalid_argument(""); if (eq(mT0[otIdx][0], ZeroBlock)) throw std::runtime_error("uninitialized OT extension"); if (eq(mT0[otIdx][0], AllOneBlock)) throw std::runtime_error("This otIdx has already been encoded"); #endif // !NDEBUG block* t0Val = mT0.data() + mT0.stride() * otIdx; block* t1Val = mT1.data() + mT0.stride() * otIdx; // 128 bit input restriction block word = ZeroBlock; memcpy(&word, input, mInputByteCount); // run the input word through AES to get a psuedo-random codeword. Then // XOR the input with the AES output. std::array<block, width> choice{word, word, word, word}, code; mMultiKeyAES.ecbEncNBlocks(choice.data(), code.data()); // encode the correction value as u = T0 + T1 + c(w), there c(w) is a pseudo-random codeword. for (u64 i = 0; i < width; ++i) { // final code is the output of AES plus the input code[i] = code[i] ^ choice[i]; // reuse mT1 as the place we store the correlated value. // this will later get sent to the sender. t1Val[i] = code[i] ^ t0Val[i] ^ t1Val[i]; } #ifdef KKRT_SHA_HASH // now hash it to remove the correlation. RandomOracle sha1(destSize); sha1.Update((u8*)mT0[otIdx].data(), mT0[otIdx].size() * sizeof(block)); sha1.Final((u8*)dest); #else s std::array<block, 10> aesBuff; mAesFixedKey.ecbEncBlocks(t0Val, mT0.stride(), aesBuff.data()); val = ZeroBlock; for (u64 i = 0; i < mT0.stride(); ++i) val = val ^ aesBuff[i] ^ t0Val[i]; #endif #ifndef NDEBUG // a debug check to mark this OT as used and ready to send. mT0[otIdx][0] = AllOneBlock; #endif } void KkrtNcoOtReceiver::zeroEncode(u64 otIdx) { #ifndef NDEBUG if (eq(mT0[otIdx][0], ZeroBlock)) throw std::runtime_error("uninitialized OT extension"); if (eq(mT0[otIdx][0], AllOneBlock)) throw std::runtime_error("This otIdx has already been encoded"); #endif // !NDEBUG block* t0Val = mT0.data() + mT0.stride() * otIdx; block* t1Val = mT1.data() + mT0.stride() * otIdx; // This is here in the case that you done want to encode a message. // It s more efficient since we don't call SHA. for (u64 i = 0; i < mT0.stride(); ++i) { // reuse mT1 as the place we store the correlated value. // this will later get sent to the sender. t1Val[i] = t0Val[i] ^ t1Val[i]; } #ifndef NDEBUG // a debug check to mark this OT as used and ready to send. mT0[otIdx][0] = AllOneBlock; #endif } void KkrtNcoOtReceiver::configure(bool maliciousSecure, u64 statSecParam, u64 inputBitCount) { if (maliciousSecure) throw std::runtime_error(LOCATION); if (inputBitCount > 128) throw std::runtime_error( "currently only support up to 128 bit KKRT inputs. Can be extended on " "request" LOCATION); mInputByteCount = (inputBitCount + 7) / 8; auto count = 128 * 4; mGens.resize(count); } void KkrtNcoOtReceiver::sendCorrection(u64 sendCount, u8* matrix) { mHasPendingSendFuture = false; // mHasPendingSendFuture = true; matrix = (u8*)(mT1.data() + (mCorrectionIdx * mT1.stride())); mCorrectionIdx += sendCount; } void KkrtNcoOtReceiver::sendCorrection(Channel& chl, u64 sendCount) { #ifndef NDEBUG // make sure these OTs all contain valid correction values, aka encode has been called. for (u64 i = mCorrectionIdx; i < mCorrectionIdx + sendCount; ++i) if (neq(mT0[i][0], AllOneBlock)) throw std::runtime_error( "This send request contains uninitialized OT. Call encode first..."); #endif // this is potentially dangerous. We dont have a guarantee that mT1 will still exist when // the network gets around to sending this. Oh well. mHasPendingSendFuture = true; mPendingSendFuture = chl.asyncSendFuture((u8*)(mT1.data() + (mCorrectionIdx * mT1.stride())), mT1.stride() * sendCount * sizeof(block)); // std::cout<<"recvCorrection receiver = "<<((u8*)(mT1.data() + (mCorrectionIdx * mT1.stride())))<<std::endl; mCorrectionIdx += sendCount; } } // namespace osuCrypto #endif
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 <gtest/gtest.h> #include "ModelFixture.hpp" #include "../Blind.hpp" #include "../Blind_Impl.hpp" using namespace openstudio; using namespace openstudio::model; TEST_F(ModelFixture, Blind_GettersSetters) { Model m; Blind blind(m); // Slat Orientation: String // Check Idd default: "Horizontal" EXPECT_EQ("Horizontal", blind.slatOrientation()); // Test a valid choice EXPECT_TRUE(blind.setSlatOrientation("Vertical")); EXPECT_EQ("Vertical", blind.slatOrientation()); // Test an invalid choice EXPECT_FALSE(blind.setSlatOrientation("BadChoice")); EXPECT_EQ("Vertical", blind.slatOrientation()); // Slat Width: Double // Check Idd default: 0.025 EXPECT_EQ(0.025, blind.slatWidth()); EXPECT_TRUE(blind.setSlatWidth(0.01)); EXPECT_EQ(0.01, blind.slatWidth()); // Slat Separation: Double // Check Idd default: 0.01875 EXPECT_EQ(0.01875, blind.slatSeparation()); EXPECT_TRUE(blind.setSlatSeparation(0.01)); EXPECT_EQ(0.01, blind.slatSeparation()); // Slat Thickness: Double // Check Idd default: 0.001 EXPECT_EQ(0.001, blind.slatThickness()); EXPECT_TRUE(blind.setSlatThickness(0.021)); EXPECT_EQ(0.021, blind.slatThickness()); blind.resetSlatThickness(); EXPECT_EQ(0.001, blind.slatThickness()); // Slat Angle: Double // Check Idd default: 45 EXPECT_EQ(45, blind.slatAngle()); EXPECT_TRUE(blind.setSlatAngle(22.5)); EXPECT_EQ(22.5, blind.slatAngle()); blind.resetSlatAngle(); EXPECT_EQ(45, blind.slatAngle()); // Slat Conductivity: Double // Check Idd default: 221.0 EXPECT_EQ(221.0, blind.slatConductivity()); EXPECT_TRUE(blind.setSlatConductivity(110.5)); EXPECT_EQ(110.5, blind.slatConductivity()); blind.resetSlatConductivity(); EXPECT_EQ(221.0, blind.slatConductivity()); // Slat Beam Solar Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatBeamSolarTransmittance()); EXPECT_TRUE(blind.setSlatBeamSolarTransmittance(0.35)); EXPECT_EQ(0.35, blind.slatBeamSolarTransmittance()); blind.resetSlatBeamSolarTransmittance(); EXPECT_EQ(0.0, blind.slatBeamSolarTransmittance()); // Front Side Slat Beam Solar Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.frontSideSlatBeamSolarReflectance()); EXPECT_TRUE(blind.setFrontSideSlatBeamSolarReflectance(0.205)); EXPECT_EQ(0.205, blind.frontSideSlatBeamSolarReflectance()); // Back Side Slat Beam Solar Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.backSideSlatBeamSolarReflectance()); EXPECT_TRUE(blind.setBackSideSlatBeamSolarReflectance(0.105)); EXPECT_EQ(0.105, blind.backSideSlatBeamSolarReflectance()); // Slat Diffuse Solar Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatDiffuseSolarTransmittance()); EXPECT_TRUE(blind.setSlatDiffuseSolarTransmittance(0.31)); EXPECT_EQ(0.31, blind.slatDiffuseSolarTransmittance()); // Front Side Slat Diffuse Solar Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.frontSideSlatDiffuseSolarReflectance()); EXPECT_TRUE(blind.setFrontSideSlatDiffuseSolarReflectance(0.225)); EXPECT_EQ(0.225, blind.frontSideSlatDiffuseSolarReflectance()); // Back Side Slat Diffuse Solar Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.backSideSlatDiffuseSolarReflectance()); EXPECT_TRUE(blind.setBackSideSlatDiffuseSolarReflectance(0.336)); EXPECT_EQ(0.336, blind.backSideSlatDiffuseSolarReflectance()); // Slat Beam Visible Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatBeamVisibleTransmittance()); EXPECT_TRUE(blind.setSlatBeamVisibleTransmittance(0.112)); EXPECT_EQ(0.112, blind.slatBeamVisibleTransmittance()); // Front Side Slat Beam Visible Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.frontSideSlatBeamVisibleReflectance()); EXPECT_TRUE(blind.setFrontSideSlatBeamVisibleReflectance(0.145)); EXPECT_EQ(0.145, blind.frontSideSlatBeamVisibleReflectance()); blind.resetFrontSideSlatBeamVisibleReflectance(); EXPECT_EQ(0.5, blind.frontSideSlatBeamVisibleReflectance()); // Back Side Slat Beam Visible Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.backSideSlatBeamVisibleReflectance()); EXPECT_TRUE(blind.setBackSideSlatBeamVisibleReflectance(0.185)); EXPECT_EQ(0.185, blind.backSideSlatBeamVisibleReflectance()); blind.resetBackSideSlatBeamVisibleReflectance(); EXPECT_EQ(0.5, blind.backSideSlatBeamVisibleReflectance()); // Slat Diffuse Visible Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatDiffuseVisibleTransmittance()); EXPECT_TRUE(blind.setSlatDiffuseVisibleTransmittance(0.015)); EXPECT_EQ(0.015, blind.slatDiffuseVisibleTransmittance()); blind.resetSlatDiffuseVisibleTransmittance(); EXPECT_EQ(0.0, blind.slatDiffuseVisibleTransmittance()); // Front Side Slat Diffuse Visible Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.frontSideSlatDiffuseVisibleReflectance()); EXPECT_TRUE(blind.setFrontSideSlatDiffuseVisibleReflectance(0.055)); EXPECT_EQ(0.055, blind.frontSideSlatDiffuseVisibleReflectance()); blind.resetFrontSideSlatDiffuseVisibleReflectance(); EXPECT_EQ(0.5, blind.frontSideSlatDiffuseVisibleReflectance()); // Back Side Slat Diffuse Visible Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.backSideSlatDiffuseVisibleReflectance()); EXPECT_TRUE(blind.setBackSideSlatDiffuseVisibleReflectance(0.085)); EXPECT_EQ(0.085, blind.backSideSlatDiffuseVisibleReflectance()); blind.resetBackSideSlatDiffuseVisibleReflectance(); EXPECT_EQ(0.5, blind.backSideSlatDiffuseVisibleReflectance()); // Slat Infrared Hemispherical Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatInfraredHemisphericalTransmittance()); EXPECT_TRUE(blind.setSlatInfraredHemisphericalTransmittance(0.095)); EXPECT_EQ(0.095, blind.slatInfraredHemisphericalTransmittance()); blind.resetSlatInfraredHemisphericalTransmittance(); EXPECT_EQ(0.0, blind.slatInfraredHemisphericalTransmittance()); // Front Side Slat Infrared Hemispherical Emissivity: Double // Check Idd default: 0.9 EXPECT_EQ(0.9, blind.frontSideSlatInfraredHemisphericalEmissivity()); EXPECT_TRUE(blind.setFrontSideSlatInfraredHemisphericalEmissivity(0.451)); EXPECT_EQ(0.451, blind.frontSideSlatInfraredHemisphericalEmissivity()); blind.resetFrontSideSlatInfraredHemisphericalEmissivity(); EXPECT_EQ(0.9, blind.frontSideSlatInfraredHemisphericalEmissivity()); // Back Side Slat Infrared Hemispherical Emissivity: Double // Check Idd default: 0.9 EXPECT_EQ(0.9, blind.backSideSlatInfraredHemisphericalEmissivity()); EXPECT_TRUE(blind.setBackSideSlatInfraredHemisphericalEmissivity(0.455)); EXPECT_EQ(0.455, blind.backSideSlatInfraredHemisphericalEmissivity()); blind.resetBackSideSlatInfraredHemisphericalEmissivity(); EXPECT_EQ(0.9, blind.backSideSlatInfraredHemisphericalEmissivity()); // Blind to Glass Distance: Double // Check Idd default: 0.050 EXPECT_EQ(0.050, blind.blindtoGlassDistance()); EXPECT_TRUE(blind.setBlindtoGlassDistance(0.033)); EXPECT_EQ(0.033, blind.blindtoGlassDistance()); blind.resetBlindtoGlassDistance(); EXPECT_EQ(0.050, blind.blindtoGlassDistance()); // Blind Top Opening Multiplier: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.blindTopOpeningMultiplier()); EXPECT_TRUE(blind.setBlindTopOpeningMultiplier(0.259)); EXPECT_EQ(0.259, blind.blindTopOpeningMultiplier()); blind.resetBlindTopOpeningMultiplier(); EXPECT_EQ(0.5, blind.blindTopOpeningMultiplier()); // Blind Bottom Opening Multiplier: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.blindBottomOpeningMultiplier()); EXPECT_TRUE(blind.setBlindBottomOpeningMultiplier(0.278)); EXPECT_EQ(0.278, blind.blindBottomOpeningMultiplier()); blind.resetBlindBottomOpeningMultiplier(); EXPECT_EQ(0.5, blind.blindBottomOpeningMultiplier()); // Blind Left Side Opening Multiplier: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.blindLeftSideOpeningMultiplier()); EXPECT_TRUE(blind.setBlindLeftSideOpeningMultiplier(0.324)); EXPECT_EQ(0.324, blind.blindLeftSideOpeningMultiplier()); blind.resetBlindLeftSideOpeningMultiplier(); EXPECT_EQ(0.5, blind.blindLeftSideOpeningMultiplier()); // Blind Right Side Opening Multiplier: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.blindRightSideOpeningMultiplier()); EXPECT_TRUE(blind.setBlindRightSideOpeningMultiplier(0.165)); EXPECT_EQ(0.165, blind.blindRightSideOpeningMultiplier()); blind.resetBlindRightSideOpeningMultiplier(); EXPECT_EQ(0.5, blind.blindRightSideOpeningMultiplier()); // Minimum Slat Angle: Double // Check Idd default: 0 EXPECT_EQ(0, blind.minimumSlatAngle()); EXPECT_TRUE(blind.setMinimumSlatAngle(13.0)); EXPECT_EQ(13.0, blind.minimumSlatAngle()); blind.resetMinimumSlatAngle(); EXPECT_EQ(0, blind.minimumSlatAngle()); // Maximum Slat Angle: Double // Check Idd default: 180 EXPECT_EQ(180, blind.maximumSlatAngle()); EXPECT_TRUE(blind.setMaximumSlatAngle(74.0)); EXPECT_EQ(74.0, blind.maximumSlatAngle()); blind.resetMaximumSlatAngle(); EXPECT_EQ(180, blind.maximumSlatAngle()); }
/*========================================================================= * * Copyright NumFOCUS * * 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 * * https://www.apache.org/licenses/LICENSE-2.0.txt * * 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. * *=========================================================================*/ // Software Guide : BeginLatex // // This example illustrates how to perform Iterative Closest Point (ICP) // registration in ITK. The main class featured in this section is the // \doxygen{EuclideanDistancePointMetric}. // // Software Guide : EndLatex // Software Guide : BeginLatex // // The first step is to include the relevant headers. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkTranslationTransform.h" #include "itkEuclideanDistancePointMetric.h" #include "itkLevenbergMarquardtOptimizer.h" #include "itkPointSetToPointSetRegistrationMethod.h" // Software Guide : EndCodeSnippet #include <iostream> #include <fstream> class CommandIterationUpdate : public itk::Command { public: using Self = CommandIterationUpdate; using Superclass = itk::Command; using Pointer = itk::SmartPointer<Self>; itkNewMacro(Self); protected: CommandIterationUpdate() = default; public: using OptimizerType = itk::LevenbergMarquardtOptimizer; using OptimizerPointer = const OptimizerType *; void Execute(itk::Object * caller, const itk::EventObject & event) override { Execute((const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) override { auto optimizer = dynamic_cast<OptimizerPointer>(object); if (optimizer == nullptr) { itkExceptionMacro("Could not cast optimizer."); } if (!itk::IterationEvent().CheckEvent(&event)) { return; } std::cout << "Value = " << optimizer->GetCachedValue() << std::endl; std::cout << "Position = " << optimizer->GetCachedCurrentPosition(); std::cout << std::endl << std::endl; } }; int main(int argc, char * argv[]) { if (argc < 3) { std::cerr << "Arguments Missing. " << std::endl; std::cerr << "Usage: IterativeClosestPoint1 fixedPointsFile movingPointsFile " << std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // Next, define the necessary types for the fixed and moving pointsets and // point containers. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet constexpr unsigned int Dimension = 2; using PointSetType = itk::PointSet<float, Dimension>; auto fixedPointSet = PointSetType::New(); auto movingPointSet = PointSetType::New(); using PointType = PointSetType::PointType; using PointsContainer = PointSetType::PointsContainer; auto fixedPointContainer = PointsContainer::New(); auto movingPointContainer = PointsContainer::New(); PointType fixedPoint; PointType movingPoint; // Software Guide : EndCodeSnippet // Read the file containing coordinates of fixed points. std::ifstream fixedFile; fixedFile.open(argv[1]); if (fixedFile.fail()) { std::cerr << "Error opening points file with name : " << std::endl; std::cerr << argv[1] << std::endl; return EXIT_FAILURE; } unsigned int pointId = 0; fixedFile >> fixedPoint; while (!fixedFile.eof()) { fixedPointContainer->InsertElement(pointId, fixedPoint); fixedFile >> fixedPoint; pointId++; } fixedPointSet->SetPoints(fixedPointContainer); std::cout << "Number of fixed Points = " << fixedPointSet->GetNumberOfPoints() << std::endl; // Read the file containing coordinates of moving points. std::ifstream movingFile; movingFile.open(argv[2]); if (movingFile.fail()) { std::cerr << "Error opening points file with name : " << std::endl; std::cerr << argv[2] << std::endl; return EXIT_FAILURE; } pointId = 0; movingFile >> movingPoint; while (!movingFile.eof()) { movingPointContainer->InsertElement(pointId, movingPoint); movingFile >> movingPoint; pointId++; } movingPointSet->SetPoints(movingPointContainer); std::cout << "Number of moving Points = " << movingPointSet->GetNumberOfPoints() << std::endl; // Software Guide : BeginLatex // // After the points are read in from files, set up the metric type. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet using MetricType = itk::EuclideanDistancePointMetric<PointSetType, PointSetType>; auto metric = MetricType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now, setup the transform, optimizers, and registration method using the // point set types defined earlier. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet using TransformType = itk::TranslationTransform<double, Dimension>; auto transform = TransformType::New(); // Optimizer Type using OptimizerType = itk::LevenbergMarquardtOptimizer; auto optimizer = OptimizerType::New(); optimizer->SetUseCostFunctionGradient(false); // Registration Method using RegistrationType = itk::PointSetToPointSetRegistrationMethod<PointSetType, PointSetType>; auto registration = RegistrationType::New(); // Scale the translation components of the Transform in the Optimizer OptimizerType::ScalesType scales(transform->GetNumberOfParameters()); scales.Fill(0.01); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next we setup the convergence criteria, and other properties required // by the optimizer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet unsigned long numberOfIterations = 100; double gradientTolerance = 1e-5; // convergence criterion double valueTolerance = 1e-5; // convergence criterion double epsilonFunction = 1e-6; // convergence criterion optimizer->SetScales(scales); optimizer->SetNumberOfIterations(numberOfIterations); optimizer->SetValueTolerance(valueTolerance); optimizer->SetGradientTolerance(gradientTolerance); optimizer->SetEpsilonFunction(epsilonFunction); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // In this case we start from an identity transform, but in reality the user // will usually be able to provide a better guess than this. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet transform->SetIdentity(); // Software Guide : EndCodeSnippet registration->SetInitialTransformParameters(transform->GetParameters()); // Software Guide : BeginLatex // // Finally, connect all the components required for the registration, and an // observer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet registration->SetMetric(metric); registration->SetOptimizer(optimizer); registration->SetTransform(transform); registration->SetFixedPointSet(fixedPointSet); registration->SetMovingPointSet(movingPointSet); // Connect an observer auto observer = CommandIterationUpdate::New(); optimizer->AddObserver(itk::IterationEvent(), observer); // Software Guide : EndCodeSnippet try { registration->Update(); } catch (const itk::ExceptionObject & e) { std::cerr << e << std::endl; return EXIT_FAILURE; } std::cout << "Solution = " << transform->GetParameters() << std::endl; return EXIT_SUCCESS; }
#ifdef HAVE_CONFIG_H #include <config.h> #endif #include "LegacySecAttr.h" namespace ArcSHCLegacy { static std::string empty_string; static std::list<std::string> empty_list; LegacySecAttr::LegacySecAttr(Arc::Logger& logger):logger_(logger) { } LegacySecAttr::~LegacySecAttr(void) { } static char const * parse_vo_name(const std::string& id) { if(::strncmp(id.c_str(), "VO:", 3) == 0) { return id.c_str() + 3; }; return NULL; } static char const * parse_voms_name(const std::string& id) { if(::strncmp(id.c_str(), "VOMS:", 5) == 0) { return id.c_str() + 5; }; return NULL; } std::string LegacySecAttr::get(const std::string& id) const { if(id == "GROUP") { if(groups_.size() > 0) return *groups_.begin(); return ""; }; if(id == "VO") { if(VOs_.size() > 0) return *VOs_.begin(); return ""; }; if(char const * group = parse_voms_name(id)) { const std::list<std::string>& VOMSs = LegacySecAttr::GetGroupVOMS(group); if(VOMSs.size() > 0) return *VOMSs.begin(); return ""; }; if(char const * group = parse_vo_name(id)) { const std::list<std::string>& VOs = LegacySecAttr::GetGroupVO(group); if(VOs.size() > 0) return *VOs.begin(); return ""; }; return ""; } std::list<std::string> LegacySecAttr::getAll(const std::string& id) const { if(id == "GROUP") return groups_; if(id == "VO") return VOs_; if(char const * group = parse_voms_name(id)) return GetGroupVOMS(group); if(char const * group = parse_vo_name(id)) return GetGroupVO(group); return std::list<std::string>(); } bool LegacySecAttr::Export(Arc::SecAttrFormat format,Arc::XMLNode &val) const { // No need to export information yet. return true; } bool LegacySecAttr::equal(const SecAttr &b) const { try { const LegacySecAttr& a = dynamic_cast<const LegacySecAttr&>(b); if (!a) return false; // ... return false; } catch(std::exception&) { }; return false; } LegacySecAttr::operator bool(void) const { return true; } const std::list<std::string>& LegacySecAttr::GetGroupVO(const std::string& group) const { std::list< std::list<std::string> >::const_iterator vo = groupsVO_.begin(); for(std::list<std::string>::const_iterator grp = groups_.begin(); grp != groups_.end(); ++grp) { if(vo == groupsVO_.end()) break; if(*grp == group) return *vo; ++vo; }; return empty_list; } const std::list<std::string>& LegacySecAttr::GetGroupVOMS(const std::string& group) const { std::list< std::list<std::string> >::const_iterator voms = groupsVOMS_.begin(); for(std::list<std::string>::const_iterator grp = groups_.begin(); grp != groups_.end(); ++grp) { if(voms == groupsVOMS_.end()) break; if(*grp == group) return *voms; ++voms; }; return empty_list; } void LegacySecAttr::AddGroup(const std::string& group, const std::list<std::string>& vo, const std::list<std::string>& voms) { groups_.push_back(group); groupsVO_.push_back(vo); groupsVOMS_.push_back(voms); } } // namespace ArcSHCLegacy
// Kolmogorov-Smirnov 1st order asymptotic distribution // Copyright Evan Miller 2020 // // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // The Kolmogorov-Smirnov test in statistics compares two empirical distributions, // or an empirical distribution against any theoretical distribution. It makes // use of a specific distribution which doesn't have a formal name, but which // is often called the Kolmogorv-Smirnov distribution for lack of anything // better. This file implements the limiting form of this distribution, first // identified by Andrey Kolmogorov in // // Kolmogorov, A. (1933) "Sulla Determinazione Empirica di una Legge di // Distribuzione." Giornale dell' Istituto Italiano degli Attuari // // This limiting form of the CDF is a first-order Taylor expansion that is // easily implemented by the fourth Jacobi Theta function (setting z=0). The // PDF is then implemented here as a derivative of the Theta function. Note // that this derivative is with respect to x, which enters into \tau, and not // with respect to the z argument, which is always zero, and so the derivative // identities in DLMF 20.4 do not apply here. // // A higher order order expansion is possible, and was first outlined by // // Pelz W, Good IJ (1976). "Approximating the Lower Tail-Areas of the // Kolmogorov-Smirnov One-sample Statistic." Journal of the Royal Statistical // Society B. // // The terms in this expansion get fairly complicated, and as far as I know the // Pelz-Good expansion is not used in any statistics software. Someone could // consider updating this implementation to use the Pelz-Good expansion in the // future, but the math gets considerably hairier with each additional term. // // A formula for an exact version of the Kolmogorov-Smirnov test is laid out in // Equation 2.4.4 of // // Durbin J (1973). "Distribution Theory for Tests Based on the Sample // Distribution Func- tion." In SIAM CBMS-NSF Regional Conference Series in // Applied Mathematics. SIAM, Philadelphia, PA. // // which is available in book form from Amazon and others. This exact version // involves taking powers of large matrices. To do that right you need to // compute eigenvalues and eigenvectors, which are beyond the scope of Boost. // (Some recent work indicates the exact form can also be computed via FFT, see // https://cran.r-project.org/web/packages/KSgeneral/KSgeneral.pdf). // // Even if the CDF of the exact distribution could be computed using Boost // libraries (which would be cumbersome), the PDF would present another // difficulty. Therefore I am limiting this implementation to the asymptotic // form, even though the exact form has trivial values for certain specific // values of x and n. For more on trivial values see // // Ruben H, Gambino J (1982). "The Exact Distribution of Kolmogorov's Statistic // Dn for n <= 10." Annals of the Institute of Statistical Mathematics. // // For a good bibliography and overview of the various algorithms, including // both exact and asymptotic forms, see // https://www.jstatsoft.org/article/view/v039i11 // // As for this implementation: the distribution is parameterized by n (number // of observations) in the spirit of chi-squared's degrees of freedom. It then // takes a single argument x. In terms of the Kolmogorov-Smirnov statistical // test, x represents the distribution of D_n, where D_n is the maximum // difference between the CDFs being compared, that is, // // D_n = sup|F_n(x) - G(x)| // // In the exact distribution, x is confined to the support [0, 1], but in this // limiting approximation, we allow x to exceed unity (similar to how a normal // approximation always spills over any boundaries). // // As mentioned previously, the CDF is implemented using the \tau // parameterization of the fourth Jacobi Theta function as // // CDF=theta_4(0|2*x*x*n/pi) // // The PDF is a hand-coded derivative of that function. Actually, there are two // (independent) derivatives, as separate code paths are used for "small x" // (2*x*x*n < pi) and "large x", mirroring the separate code paths in the // Jacobi Theta implementation to achieve fast convergence. Quantiles are // computed using a Newton-Raphson iteration from an initial guess that I // arrived at by trial and error. // // The mean and variance are implemented using simple closed-form expressions. // Skewness and kurtosis use slightly more complicated closed-form expressions // that involve the zeta function. The mode is calculated at run-time by // maximizing the PDF. If you have an analytical solution for the mode, feel // free to plop it in. // // The CDF and PDF could almost certainly be re-implemented and sped up using a // polynomial or rational approximation, since the only meaningful argument is // x * sqrt(n). But that is left as an exercise for the next maintainer. // // In the future, the Pelz-Good approximation could be added. I suggest adding // a second parameter representing the order, e.g. // // kolmogorov_smirnov_dist<>(100) // N=100, order=1 // kolmogorov_smirnov_dist<>(100, 1) // N=100, order=1, i.e. Kolmogorov's formula // kolmogorov_smirnov_dist<>(100, 4) // N=100, order=4, i.e. Pelz-Good formula // // The exact distribution could be added to the API with a special order // parameter (e.g. 0 or infinity), or a separate distribution type altogether // (e.g. kolmogorov_smirnov_exact_distribution). // #ifndef BOOST_MATH_DISTRIBUTIONS_KOLMOGOROV_SMIRNOV_HPP #define BOOST_MATH_DISTRIBUTIONS_KOLMOGOROV_SMIRNOV_HPP #include <boost/math/distributions/fwd.hpp> #include <boost/math/distributions/complement.hpp> #include <boost/math/distributions/detail/common_error_handling.hpp> #include <boost/math/special_functions/jacobi_theta.hpp> #include <boost/math/tools/tuple.hpp> #include <boost/math/tools/roots.hpp> // Newton-Raphson #include <boost/math/tools/minima.hpp> // For the mode namespace boost { namespace math { namespace detail { template <class RealType> inline RealType kolmogorov_smirnov_quantile_guess(RealType p) { // Choose a starting point for the Newton-Raphson iteration if (p > 0.9) return RealType(1.8) - 5 * (1 - p); if (p < 0.3) return p + RealType(0.45); return p + RealType(0.3); } // d/dk (theta2(0, 1/(2*k*k/M_PI))/sqrt(2*k*k*M_PI)) template <class RealType, class Policy> RealType kolmogorov_smirnov_pdf_small_x(RealType x, RealType n, const Policy&) { BOOST_MATH_STD_USING RealType value = RealType(0), delta = RealType(0), last_delta = RealType(0); RealType eps = policies::get_epsilon<RealType, Policy>(); int i = 0; RealType pi2 = constants::pi_sqr<RealType>(); RealType x2n = x*x*n; if (x2n*x2n == 0.0) { return static_cast<RealType>(0); } while (1) { delta = exp(-RealType(i+0.5)*RealType(i+0.5)*pi2/(2*x2n)) * (RealType(i+0.5)*RealType(i+0.5)*pi2 - x2n); if (delta == 0.0) break; if (last_delta != 0.0 && fabs(delta/last_delta) < eps) break; value += delta + delta; last_delta = delta; i++; } return value * sqrt(n) * constants::root_half_pi<RealType>() / (x2n*x2n); } // d/dx (theta4(0, 2*x*x*n/M_PI)) template <class RealType, class Policy> inline RealType kolmogorov_smirnov_pdf_large_x(RealType x, RealType n, const Policy&) { BOOST_MATH_STD_USING RealType value = RealType(0), delta = RealType(0), last_delta = RealType(0); RealType eps = policies::get_epsilon<RealType, Policy>(); int i = 1; while (1) { delta = 8*x*i*i*exp(-2*i*i*x*x*n); if (delta == 0.0) break; if (last_delta != 0.0 && fabs(delta / last_delta) < eps) break; if (i%2 == 0) delta = -delta; value += delta; last_delta = delta; i++; } return value * n; } }; // detail template <class RealType = double, class Policy = policies::policy<> > class kolmogorov_smirnov_distribution { public: typedef RealType value_type; typedef Policy policy_type; // Constructor kolmogorov_smirnov_distribution( RealType n ) : n_obs_(n) { RealType result; detail::check_df( "boost::math::kolmogorov_smirnov_distribution<%1%>::kolmogorov_smirnov_distribution", n_obs_, &result, Policy()); } RealType number_of_observations()const { return n_obs_; } private: RealType n_obs_; // positive integer }; typedef kolmogorov_smirnov_distribution<double> kolmogorov_k; // Convenience typedef for double version. namespace detail { template <class RealType, class Policy> struct kolmogorov_smirnov_quantile_functor { kolmogorov_smirnov_quantile_functor(const boost::math::kolmogorov_smirnov_distribution<RealType, Policy> dist, RealType const& p) : distribution(dist), prob(p) { } boost::math::tuple<RealType, RealType> operator()(RealType const& x) { RealType fx = cdf(distribution, x) - prob; // Difference cdf - value - to minimize. RealType dx = pdf(distribution, x); // pdf is 1st derivative. // return both function evaluation difference f(x) and 1st derivative f'(x). return boost::math::make_tuple(fx, dx); } private: const boost::math::kolmogorov_smirnov_distribution<RealType, Policy> distribution; RealType prob; }; template <class RealType, class Policy> struct kolmogorov_smirnov_complementary_quantile_functor { kolmogorov_smirnov_complementary_quantile_functor(const boost::math::kolmogorov_smirnov_distribution<RealType, Policy> dist, RealType const& p) : distribution(dist), prob(p) { } boost::math::tuple<RealType, RealType> operator()(RealType const& x) { RealType fx = cdf(complement(distribution, x)) - prob; // Difference cdf - value - to minimize. RealType dx = -pdf(distribution, x); // pdf is the negative of the derivative of (1-CDF) // return both function evaluation difference f(x) and 1st derivative f'(x). return boost::math::make_tuple(fx, dx); } private: const boost::math::kolmogorov_smirnov_distribution<RealType, Policy> distribution; RealType prob; }; template <class RealType, class Policy> struct kolmogorov_smirnov_negative_pdf_functor { RealType operator()(RealType const& x) { if (2*x*x < constants::pi<RealType>()) { return -kolmogorov_smirnov_pdf_small_x(x, static_cast<RealType>(1), Policy()); } return -kolmogorov_smirnov_pdf_large_x(x, static_cast<RealType>(1), Policy()); } }; } // namespace detail template <class RealType, class Policy> inline const std::pair<RealType, RealType> range(const kolmogorov_smirnov_distribution<RealType, Policy>& /*dist*/) { // Range of permissible values for random variable x. using boost::math::tools::max_value; return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); } template <class RealType, class Policy> inline const std::pair<RealType, RealType> support(const kolmogorov_smirnov_distribution<RealType, Policy>& /*dist*/) { // Range of supported values for random variable x. // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero. // In the exact distribution, the upper limit would be 1. using boost::math::tools::max_value; return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); } template <class RealType, class Policy> inline RealType pdf(const kolmogorov_smirnov_distribution<RealType, Policy>& dist, const RealType& x) { BOOST_FPU_EXCEPTION_GUARD BOOST_MATH_STD_USING // for ADL of std functions. RealType n = dist.number_of_observations(); RealType error_result; static const char* function = "boost::math::pdf(const kolmogorov_smirnov_distribution<%1%>&, %1%)"; if(false == detail::check_x_not_NaN(function, x, &error_result, Policy())) return error_result; if(false == detail::check_df(function, n, &error_result, Policy())) return error_result; if (x < 0 || !(boost::math::isfinite)(x)) { return policies::raise_domain_error<RealType>( function, "Kolmogorov-Smirnov parameter was %1%, but must be > 0 !", x, Policy()); } if (2*x*x*n < constants::pi<RealType>()) { return detail::kolmogorov_smirnov_pdf_small_x(x, n, Policy()); } return detail::kolmogorov_smirnov_pdf_large_x(x, n, Policy()); } // pdf template <class RealType, class Policy> inline RealType cdf(const kolmogorov_smirnov_distribution<RealType, Policy>& dist, const RealType& x) { BOOST_MATH_STD_USING // for ADL of std function exp. static const char* function = "boost::math::cdf(const kolmogorov_smirnov_distribution<%1%>&, %1%)"; RealType error_result; RealType n = dist.number_of_observations(); if(false == detail::check_x_not_NaN(function, x, &error_result, Policy())) return error_result; if(false == detail::check_df(function, n, &error_result, Policy())) return error_result; if((x < 0) || !(boost::math::isfinite)(x)) { return policies::raise_domain_error<RealType>( function, "Random variable parameter was %1%, but must be between > 0 !", x, Policy()); } if (x*x*n == 0) return 0; return jacobi_theta4tau(RealType(0), 2*x*x*n/constants::pi<RealType>(), Policy()); } // cdf template <class RealType, class Policy> inline RealType cdf(const complemented2_type<kolmogorov_smirnov_distribution<RealType, Policy>, RealType>& c) { BOOST_MATH_STD_USING // for ADL of std function exp. RealType x = c.param; static const char* function = "boost::math::cdf(const complemented2_type<const kolmogorov_smirnov_distribution<%1%>&, %1%>)"; RealType error_result; kolmogorov_smirnov_distribution<RealType, Policy> const& dist = c.dist; RealType n = dist.number_of_observations(); if(false == detail::check_x_not_NaN(function, x, &error_result, Policy())) return error_result; if(false == detail::check_df(function, n, &error_result, Policy())) return error_result; if((x < 0) || !(boost::math::isfinite)(x)) return policies::raise_domain_error<RealType>( function, "Random variable parameter was %1%, but must be between > 0 !", x, Policy()); if (x*x*n == 0) return 1; if (2*x*x*n > constants::pi<RealType>()) return -jacobi_theta4m1tau(RealType(0), 2*x*x*n/constants::pi<RealType>(), Policy()); return RealType(1) - jacobi_theta4tau(RealType(0), 2*x*x*n/constants::pi<RealType>(), Policy()); } // cdf (complemented) template <class RealType, class Policy> inline RealType quantile(const kolmogorov_smirnov_distribution<RealType, Policy>& dist, const RealType& p) { BOOST_MATH_STD_USING static const char* function = "boost::math::quantile(const kolmogorov_smirnov_distribution<%1%>&, %1%)"; // Error check: RealType error_result; RealType n = dist.number_of_observations(); if(false == detail::check_probability(function, p, &error_result, Policy())) return error_result; if(false == detail::check_df(function, n, &error_result, Policy())) return error_result; RealType k = detail::kolmogorov_smirnov_quantile_guess(p) / sqrt(n); const int get_digits = policies::digits<RealType, Policy>();// get digits from policy, std::uintmax_t m = policies::get_max_root_iterations<Policy>(); // and max iterations. return tools::newton_raphson_iterate(detail::kolmogorov_smirnov_quantile_functor<RealType, Policy>(dist, p), k, RealType(0), boost::math::tools::max_value<RealType>(), get_digits, m); } // quantile template <class RealType, class Policy> inline RealType quantile(const complemented2_type<kolmogorov_smirnov_distribution<RealType, Policy>, RealType>& c) { BOOST_MATH_STD_USING static const char* function = "boost::math::quantile(const kolmogorov_smirnov_distribution<%1%>&, %1%)"; kolmogorov_smirnov_distribution<RealType, Policy> const& dist = c.dist; RealType n = dist.number_of_observations(); // Error check: RealType error_result; RealType p = c.param; if(false == detail::check_probability(function, p, &error_result, Policy())) return error_result; if(false == detail::check_df(function, n, &error_result, Policy())) return error_result; RealType k = detail::kolmogorov_smirnov_quantile_guess(RealType(1-p)) / sqrt(n); const int get_digits = policies::digits<RealType, Policy>();// get digits from policy, std::uintmax_t m = policies::get_max_root_iterations<Policy>(); // and max iterations. return tools::newton_raphson_iterate( detail::kolmogorov_smirnov_complementary_quantile_functor<RealType, Policy>(dist, p), k, RealType(0), boost::math::tools::max_value<RealType>(), get_digits, m); } // quantile (complemented) template <class RealType, class Policy> inline RealType mode(const kolmogorov_smirnov_distribution<RealType, Policy>& dist) { BOOST_MATH_STD_USING static const char* function = "boost::math::mode(const kolmogorov_smirnov_distribution<%1%>&)"; RealType n = dist.number_of_observations(); RealType error_result; if(false == detail::check_df(function, n, &error_result, Policy())) return error_result; std::pair<RealType, RealType> r = boost::math::tools::brent_find_minima( detail::kolmogorov_smirnov_negative_pdf_functor<RealType, Policy>(), static_cast<RealType>(0), static_cast<RealType>(1), policies::digits<RealType, Policy>()); return r.first / sqrt(n); } // Mean and variance come directly from // https://www.jstatsoft.org/article/view/v008i18 Section 3 template <class RealType, class Policy> inline RealType mean(const kolmogorov_smirnov_distribution<RealType, Policy>& dist) { BOOST_MATH_STD_USING static const char* function = "boost::math::mean(const kolmogorov_smirnov_distribution<%1%>&)"; RealType n = dist.number_of_observations(); RealType error_result; if(false == detail::check_df(function, n, &error_result, Policy())) return error_result; return constants::root_half_pi<RealType>() * constants::ln_two<RealType>() / sqrt(n); } template <class RealType, class Policy> inline RealType variance(const kolmogorov_smirnov_distribution<RealType, Policy>& dist) { static const char* function = "boost::math::variance(const kolmogorov_smirnov_distribution<%1%>&)"; RealType n = dist.number_of_observations(); RealType error_result; if(false == detail::check_df(function, n, &error_result, Policy())) return error_result; return (constants::pi_sqr_div_six<RealType>() - constants::pi<RealType>() * constants::ln_two<RealType>() * constants::ln_two<RealType>()) / (2*n); } // Skewness and kurtosis come from integrating the PDF // The alternating series pops out a Dirichlet eta function which is related to the zeta function template <class RealType, class Policy> inline RealType skewness(const kolmogorov_smirnov_distribution<RealType, Policy>& dist) { BOOST_MATH_STD_USING static const char* function = "boost::math::skewness(const kolmogorov_smirnov_distribution<%1%>&)"; RealType n = dist.number_of_observations(); RealType error_result; if(false == detail::check_df(function, n, &error_result, Policy())) return error_result; RealType ex3 = RealType(0.5625) * constants::root_half_pi<RealType>() * constants::zeta_three<RealType>() / n / sqrt(n); RealType mean = boost::math::mean(dist); RealType var = boost::math::variance(dist); return (ex3 - 3 * mean * var - mean * mean * mean) / var / sqrt(var); } template <class RealType, class Policy> inline RealType kurtosis(const kolmogorov_smirnov_distribution<RealType, Policy>& dist) { BOOST_MATH_STD_USING static const char* function = "boost::math::kurtosis(const kolmogorov_smirnov_distribution<%1%>&)"; RealType n = dist.number_of_observations(); RealType error_result; if(false == detail::check_df(function, n, &error_result, Policy())) return error_result; RealType ex4 = 7 * constants::pi_sqr_div_six<RealType>() * constants::pi_sqr_div_six<RealType>() / 20 / n / n; RealType mean = boost::math::mean(dist); RealType var = boost::math::variance(dist); RealType skew = boost::math::skewness(dist); return (ex4 - 4 * mean * skew * var * sqrt(var) - 6 * mean * mean * var - mean * mean * mean * mean) / var / var; } template <class RealType, class Policy> inline RealType kurtosis_excess(const kolmogorov_smirnov_distribution<RealType, Policy>& dist) { static const char* function = "boost::math::kurtosis_excess(const kolmogorov_smirnov_distribution<%1%>&)"; RealType n = dist.number_of_observations(); RealType error_result; if(false == detail::check_df(function, n, &error_result, Policy())) return error_result; return kurtosis(dist) - 3; } }} #endif
#include "G4NistManager.hh" #include "G4UnitsTable.hh" #include "G4Region.hh" #include "G4ProductionCuts.hh" #include "G4UserLimits.hh" #include "G4RotationMatrix.hh" #include "G4FieldManager.hh" #include "G4UniformMagField.hh" #include "G4TransportationManager.hh" #include "G4ChordFinder.hh" #include "SHDetectorConstruction.hh" #include "HGSDCounter.hh" #include "PRIMSD.hh" #include "HESD.hh" #include <math.h> /* * Volume's dimensions */ // World // G4double fullWorldX = 15.*m; G4double fullWorldY = 15.*m; G4double fullWorldZ = 20.*m; // Shashlik // G4double fullShashlikX = 14.*mm; G4double fullShashlikY = 14.*mm; G4double fullShashlikZ = 114.*mm; // Shashlik's container // G4double fullShashlikContainerX; G4double fullShashlikContainerY; G4double fullShashlikContainerZ = fullShashlikZ; // Absorber // G4double fullAbsX = 14.*mm; G4double fullAbsY = 14.*mm; G4double fullAbsZ = 2.5*mm; // Active Material // G4double fullActX = 14.*mm; G4double fullActY = 14.*mm; G4double fullActZ = 1.5*mm; // 1 Layer // G4double fullLayerX = 14.*mm; G4double fullLayerY = 14.*mm; G4double fullLayerZ = fullAbsZ + fullActZ; // Fiber // G4double inRFiber = 0.*mm; G4double outRFiber = 0.5*mm; G4double fullAbsFiberZ = fullAbsZ; G4double fullActFiberZ = fullActZ; // Gap // G4double fullGapX = 0.75*mm; G4double fullGapY = 0.75*mm; /* * Member Functions */ SHDetectorConstruction::~SHDetectorConstruction() { } // // New Constructor: As of V5. To separate EM/FH/BH parts output. // SHDetectorConstruction::SHDetectorConstruction(RunParams params, TTree *emTree, TTree *fhTree, TTree *bhTree) : _emTree(emTree), _fhTree(fhTree), _bhTree(bhTree) { MyConstructor(params, emTree); } // // New Constructor. // SHDetectorConstruction::SHDetectorConstruction(RunParams params, const vector<TTree*> &vTrees) { // the tree we are sending here is here only for hist. reasons. // Mainly, construct all the materials. // MyConstructor(params, vTrees[0]); } // // Constructor // SHDetectorConstruction::SHDetectorConstruction(RunParams params, HGCReadoutModule *readout) { _readout = readout; MyConstructor(params, NULL); } // // Constructor // SHDetectorConstruction::SHDetectorConstruction(RunParams params, TTree *tree) { MyConstructor(params, tree); } // MyConstructor // void SHDetectorConstruction::MyConstructor(RunParams params, TTree *tree) { runParams = params; shTree = tree; _heTree = shTree; // Set the Shashlik's Container Dimensions // fullShashlikContainerX = runParams.numModules*fullShashlikX + (runParams.numModules-1)*fullGapX; fullShashlikContainerY = runParams.numModules*fullShashlikY + (runParams.numModules-1)*fullGapY; // Let's build materials // G4double a; G4double z; G4double density; G4double weightRatio; G4String name; G4String symbol; G4int nElem; G4int natoms; // Elements go first // G4Element *eC = new G4Element(name="Carbon", symbol="C", z=6., a=12.01*g/mole); G4Element *eN = new G4Element(name="Nitrogen", symbol="N", z=7., a=14.01*g/mole); eO = new G4Element(name="Oxygen", symbol="O", z=8, a=16.00*g/mole); G4Element *eFe = new G4Element(name="Iron", symbol="Fe", z=26., a=55.845*g/mole); // eH = G4NistManager::Instance()->FindOrBuildMaterial("G4_H"); eH = new G4Element("Hydrogen", symbol="H", z=1, a=1.00794*g/mole); eLu = new G4Element(name="Lutetium", symbol="Lu", z=71., a=174.97*g/mole); eSi = new G4Element(name="Silicium", symbol="Si", z=14., a=28.09*g/mole); eY = new G4Element(name="Yttrium", symbol="Y", z=39., a=88.91*g/mole); density = 2.700*g/cm3; a = 26.98*g/mole; G4Element *eAl = new G4Element(name="Aluminum", symbol="Al", z=13., a); G4Element *eBe = new G4Element(name="Beryllium", symbol="Be", z=4, a=9.012*g/mole); G4Element *eMg = new G4Element(name="Magnesium", symbol="Mg", z=12., a=24.305*g/mole); G4Element *eTi = new G4Element(name="Titanium", symbol="Ti", z=22., a=47.867*g/mole); G4Element *eCs = new G4Element(name="Cesium", symbol="Cs", z=55., a=132.90546*g/mole); G4Element *eSb = new G4Element(name="Antimony", symbol="Sb", z=51., a=121.76*g/mole); G4Element *eGa = new G4Element(name="Gallium", symbol="Ga", z=31., a=69.723*g/mole); G4Element *eP = new G4Element(name="Phosphorus", symbol="P", z=15., a=30.97376*g/mole); G4Element *eAs = new G4Element(name="Arsenic", symbol="As", z=33., a=74.9216*g/mole); G4Element *eIn = new G4Element(name="Indium", symbol="In", z=49., a=114.818*g/mole); // Build the final compositions -> TODO // mAl2O3 = new G4Material(name="AluminumOxide", density=3.95*g/cm3, nElem=2); mAl2O3->AddElement(eAl, natoms=2); mAl2O3->AddElement(eO, natoms=3); //mBeO = new G4Material(name="BerylliumOxide", density=3.02*g/cm3, // nElem=2); mBeO = G4NistManager::Instance()->FindOrBuildMaterial("G4_BERYLLIUM_OXIDE"); // mBeO->AddElement(eBe, natoms=1); // mBeO->AddElement(eO, natoms=1); mMgO = new G4Material(name="MagnesiumOxide", density=3.58*g/cm3, nElem=2); mMgO->AddElement(eMg, natoms=1); mMgO->AddElement(eO, natoms=1); mTiO = new G4Material(name="TitaniumOxide", density=4.23*g/cm3, nElem=2); mTiO->AddElement(eTi, natoms=1); mTiO->AddElement(eO, natoms=1); mCs3Sb = new G4Material(name="AntimonyTriCesium", density=3.076*g/cm3, nElem=2); mCs3Sb->AddElement(eCs, natoms=3); mCs3Sb->AddElement(eSb, natoms=1); mGaP = new G4Material(name="GalliumPhosphide", density=4.138*g/cm3, nElem=2); mGaP->AddElement(eGa, natoms=1); mGaP->AddElement(eP, natoms=1); mGaAsP = new G4Material(name="GalliumArsenicPhosphide", density=4.482*g/cm3, nElem=3); mGaAsP->AddElement(eGa, natoms=1); mGaAsP->AddElement(eAs, natoms=1); mGaAsP->AddElement(eP, natoms=1); mGaPCs = new G4Material(name="GalliumCesiumPhosphide", density=3.2*g/cm3, nElem=3); mGaPCs->AddElement(eGa, natoms=1); mGaPCs->AddElement(eP, natoms=1); mGaPCs->AddElement(eCs, natoms=1); mGaInP = new G4Material(name="GalliumIndiumPhosphide", density=5.012*g/cm3, nElem=3); mGaInP->AddElement(eGa, natoms=1); mGaInP->AddElement(eIn, natoms=1); mGaInP->AddElement(eP, natoms=1); //mVacuum = new G4Material("Vacuum", z=1., a=1.008*g/mole, density=1.3-25*g/cm3, kStateGas, 2.73*kelvin, 3.e-18*pascal); // mVacuum = G4NistManager::Instance()->FindOrBuildMaterial("G4_AIR"); density = universe_mean_density; G4double pressure = 1.e-19*pascal; G4double temperature = 0.1*kelvin; mVacuum = new G4Material(name="Galactic", z=1., a=1.01*g/mole, density, kStateGas, temperature, pressure); // Tungsten // mW = G4NistManager::Instance()->FindOrBuildMaterial("G4_W"); // Lead // mPb = G4NistManager::Instance()->FindOrBuildMaterial("G4_Pb"); // Copper // mCu = G4NistManager::Instance()->FindOrBuildMaterial("G4_Cu"); // Silicon Material // mSi = G4NistManager::Instance()->FindOrBuildMaterial("G4_Si"); // Zink // mZn = G4NistManager::Instance()->FindOrBuildMaterial("G4_Zn"); // Brass // mBrass = new G4Material("Brass", density=8.5*g/cm3, 2); mBrass->AddMaterial(mCu, 70*perCent); mBrass->AddMaterial(mZn, 30*perCent); // SiO2 or Quartz // density = 2.648*g/cm3; mSiO2 = new G4Material(name="SiO2", density, nElem=2); mSiO2->AddElement(eSi, natoms=1); mSiO2->AddElement(eO, natoms=2); // Clm from DHCAL // mClm = G4NistManager::Instance()->FindOrBuildMaterial("G4_Cl"); // Glass from DHCAL // mGlass = G4NistManager::Instance()->FindOrBuildMaterial("G4_GLASS_PLATE"); // Epoxy from DHCAL // mEpoxy = new G4Material("Epoxy", density=1.3*g/cm3, 3); mEpoxy->AddElement(eH, 44); mEpoxy->AddElement(eC, 15); mEpoxy->AddElement(eO, 7); // G10 from DHCAL code // mG10 = new G4Material("G10", density=1.9*g/cm3, 3); mG10->AddMaterial(mClm, 0.08); mG10->AddMaterial(mGlass, 0.773); mG10->AddMaterial(mEpoxy, 0.147); // LYSO // mLYSO = new G4Material(name="LYSO", density=7.1*g/cm3, nElem=4); mLYSO->AddElement(eLu, 0.31101534); mLYSO->AddElement(eY, 0.368765605); mLYSO->AddElement(eSi, 0.083209699); mLYSO->AddElement(eO, 0.237009356); // // Now, we have to build the Material's Properties Table // // LYSO MPT // G4MaterialPropertiesTable *mptLYSO = new G4MaterialPropertiesTable(); // More realistic Emission Spectrum // const G4int NENTRIES = 27; G4double PHOTONENERGY_LYSO[NENTRIES] = {2.066333*eV, 2.101356*eV, 2.137586*eV, 2.175088*eV, 2.213929*eV, 2.254182*eV, 2.295926*eV, 2.339245*eV, 2.384231*eV, 2.43098*eV, 2.4796*eV, 2.530204*eV, 2.582917*eV, 2.637872*eV, 2.695217*eV, 2.755111*eV, 2.817727*eV, 2.883256*eV, 2.917176*eV, 2.951905*eV, 3.023902*eV, 3.0995*eV, 3.178974*eV, 3.262632*eV, 3.350811*eV, 3.443889*eV, 3.542286*eV}; G4double RINDEX_LYSO[NENTRIES] = { 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82, 1.82}; G4double SLOW_LYSO[NENTRIES] = { 0.000313, 0.000938, 0.003125, 0.00625, 0.009375, 0.01875, 0.025, 0.03125, 0.046875, 0.0625, 0.0875, 0.125, 0.1875, 0.21875, 0.3125, 0.515625, 0.6875, 0.84375, 0.94375, 0.9375, 0.9375, 1, 0.75, 0.5625, 0.0625, 0.00625, 0.000313}; // For Debugging... // for (int i=0; i<NENTRIES; i++) cout << i << " " << PHOTONENERGY_LYSO[i]/eV << " " << SLOW_LYSO[i] << endl; mptLYSO->AddProperty("RINDEX", PHOTONENERGY_LYSO, RINDEX_LYSO, NENTRIES); mptLYSO->AddProperty("SLOWCOMPONENT", PHOTONENERGY_LYSO, SLOW_LYSO, NENTRIES); mptLYSO->AddConstProperty("SCINTILLATIONYIELD", 32000/MeV); mptLYSO->AddConstProperty("RESOLUTIONSCALE", 1.0); mptLYSO->AddConstProperty("SLOWTIMECONSTANT", 41.*ns); // POLYETHYLENE + its MPT // Properties for MPT are for SCSN81 // mPOLYETHYLENE = G4NistManager::Instance()->FindOrBuildMaterial("G4_POLYETHYLENE"); G4MaterialPropertiesTable *mptSCSN = new G4MaterialPropertiesTable(); const G4int NENTRIES_SCSN = 15; G4double PHOTONENERGY_SCSN[NENTRIES_SCSN] = { 2.25418*eV, 2.36152*eV, 2.4796*eV, 2.53020*eV, 2.69522*eV, 2.75511*eV, 2.81773*eV, 2.88326*eV, 2.95190*eV, 3.02390*eV, 3.06123*eV, 3.09950*eV, 3.17897*eV, 3.26263*eV, 3.54229*eV}; G4double RINDEX_SCSN[NENTRIES_SCSN] = { 1.57, 1.57, 1.57, 1.57, 1.57, 1.57, 1.57, 1.57, 1.57, 1.57, 1.57, 1.57, 1.57, 1.57, 1.57}; G4double SLOW_SCSN[NENTRIES_SCSN] = { 0.05, 0.1, 0.16, 0.2, 0.6, 0.67, 0.8, 1., 0.8, 0.72, 0.75, 0.6, 0.1, 0.05, 0.001}; mptSCSN->AddProperty("RINDEX", PHOTONENERGY_SCSN, RINDEX_SCSN, NENTRIES_SCSN); mptSCSN->AddProperty("SLOWCOMPONENT", PHOTONENERGY_SCSN, SLOW_SCSN, NENTRIES_SCSN); mptSCSN->AddConstProperty("SCINTILLATIONYIELD", 10000/MeV); mptSCSN->AddConstProperty("RESOLUTIONSCALE", 1.0); mptSCSN->AddConstProperty("SLOWTIMECONSTANT", 2.5*ns); mPOLYETHYLENE->SetMaterialPropertiesTable(mptSCSN); mHEScintMain = mPOLYETHYLENE; /* const G4int nEntries = 2; G4double photonEnergy[nEntries] = {1.5*eV, 6.2*eV}; G4double refractiveIndex[nEntries] = {1.82, 1.82}; G4double fast[nEntries] = {1, 1}; G4double slow[nEntries] = {1, 1}; mptLYSO->AddProperty("RINDEX", photonEnergy, refractiveIndex, nEntries); mptLYSO->AddProperty("FASTCOMPONENT", photonEnergy, fast, nEntries); mptLYSO->AddProperty("SLOWCOMPONENT", photonEnergy, slow, nEntries); mptLYSO->AddConstProperty("SCINTILLATIONYIELD", 32000/MeV); mptLYSO->AddConstProperty("RESOLUTIONSCALE", 1.0); mptLYSO->AddConstProperty("FASTTIMECONSTANT", 41.*ns); mptLYSO->AddConstProperty("SLOWTIMECONSTANT", 41.*ns); mptLYSO->AddConstProperty("YIELDRATIO", 0.5); */ // mLYSO->SetMaterialPropertiesTable(mptLYSO); // Choose Materials for EM Absorber // 1 - Lead // 2 - Copper // if (hgcParameters.em.iAbsMaterial == 1) mEMAbsMat = mPb; else mEMAbsMat = mCu; // Choose Material for FH Absorber // 1 - Brass // 2 - Silicon??????????????????????? Doens't make much sense here... // if (hgcParameters.fh.iAbsMaterial == 1) mFHAbsMat = mBrass; else mFHAbsMat = mSi; // Choose a material for BH Absorber // 1 - Brass // 2 - Silicon??????????????????????????? Again, see above // if (hgcParameters.bh.iAbsMaterial == 1) mBHAbsMat = mBrass; else mBHAbsMat = mSi; // Set Material for Electronics // mElectronicsMat = mG10; // Set the HE Abs // mHEAbsMat = mBrass; } // G4 Method // G4VPhysicalVolume* SHDetectorConstruction::Construct() { return this->BuildGeometry(); } // Build all the Geometry // Include The EM Field, // G4VPhysicalVolume* SHDetectorConstruction::BuildGeometry() { // Define World Dimensions // // G4double fullWorldZ = 1*m; // G4double fullWorldX = 1*m; // G4double fullWorldY = 1*m; // Create the World iteself first // solidWorld = new G4Box("solidWorld", fullWorldX/2.0, fullWorldY/2.0, fullWorldZ/2.0); logicWorld = new G4LogicalVolume(solidWorld, mVacuum, "logicWorld", 0,0,0); physWorld = new G4PVPlacement(0, G4ThreeVector(), logicWorld, "physWorld", 0, 0, 0, false); // // Put the Magnetic Field here 3.8T for the moment... // G4ThreeVector fieldValue(0, 0, 3.8*tesla); G4UniformMagField *magField = new G4UniformMagField(fieldValue); G4FieldManager *fieldManager = G4TransportationManager::GetTransportationManager()->GetFieldManager(); fieldManager->SetDetectorField(magField); fieldManager->CreateChordFinder(magField); // Double checking... // G4cout << "### World: " << fullWorldX/cm << " " << fullWorldY/cm << " " << fullWorldZ/cm << G4endl; // // Build CMS Endcap // BuildEndcap(); // Build the Shashlik Set of Modules // // BuildShashlik(); // Build HGCal // // BuildHGCal(); // Build HE // // BuildHE(); // Return pointer to the WOrld // return physWorld; } // // Build Endcap Scenario // int SHDetectorConstruction::BuildEndcap() { // Choose what to build // switch (runParams.endcapType) { case 1 : cout << "### Building HGC Geometry" << endl; BuildHGC(); break; case 2 : cout << "### Building Shashlik + HE Geometry" << endl; BuildShashlikPlusHE(); break; default : cout << "### Nothing has been built. Just World...." << endl; } } // // Build HGC // int SHDetectorConstruction::BuildHGC() { // Read/Config the geometry parameters // ConfigHGC(); const int EMPCOPYID = 0; const int EMMCOPYID = 1; const int FHPCOPYID = 2; const int FHMCOPYID = 3; const int BHPCOPYID = 4; const int BHMCOPYID = 5; const int PRIMCOPYID = 10; const int SHPCOPYID = 6; const int SHMCOPYID = 7; const int HEPCOPYID = 8; const int HEMCOPYID = 9; // // Set the step size in the Si Pad VOlume // G4double pStepMax = 1.*um; G4UserLimits *padStepLimit = new G4UserLimits(pStepMax); // // SD // G4SDManager *SDManager = G4SDManager::GetSDMpointer(); HGSDCounter *SDEM = new HGSDCounter("EM", runParams, EMPCOPYID, _readout); HGSDCounter *SDFH = new HGSDCounter("FH", runParams, FHPCOPYID, _readout); PRIMSD *primSD = new PRIMSD("PRIM", runParams, PRIMCOPYID, _readout); HESD *heSD = new HESD("HE", runParams, BHPCOPYID, _readout); //SDManager->AddNewDetector(SD); SDManager->AddNewDetector(SDEM); SDManager->AddNewDetector(SDFH); SDManager->AddNewDetector(primSD); SDManager->AddNewDetector(heSD); cout << "### SD are intialized..." << endl; // // Construct additional dimensions // G4double fullEMLayerZ_1 = cmsEndcap.cmsHGCal.EM.fullAbsZ[0] + cmsEndcap.cmsHGCal.EM.fullPadZ + cmsEndcap.cmsHGCal.EM.fullReadoutZ; G4double fullEMLayerZ_2 = cmsEndcap.cmsHGCal.EM.fullAbsZ[1] + cmsEndcap.cmsHGCal.EM.fullPadZ + cmsEndcap.cmsHGCal.EM.fullReadoutZ; G4double fullEMLayerZ_3 = cmsEndcap.cmsHGCal.EM.fullAbsZ[2] + cmsEndcap.cmsHGCal.EM.fullPadZ + cmsEndcap.cmsHGCal.EM.fullReadoutZ; G4double fullEMModuleZ = cmsEndcap.cmsHGCal.EM.n1*fullEMLayerZ_1 + cmsEndcap.cmsHGCal.EM.n2*fullEMLayerZ_2 + cmsEndcap.cmsHGCal.EM.n3*fullEMLayerZ_3; cmsEndcap.cmsHGCal.EM.centerZ = cmsEndcap.cmsHGCal.startZ + fullEMModuleZ/2.; cmsEndcap.cmsHGCal.EM.rmin2 = Getr2( cmsEndcap.cmsHGCal.EM.rmin1, cmsEndcap.cmsHGCal.startZ, cmsEndcap.cmsHGCal.startZ + fullEMModuleZ); cmsEndcap.cmsHGCal.EM.rmax2 = Getr2( cmsEndcap.cmsHGCal.EM.rmax1, cmsEndcap.cmsHGCal.startZ, cmsEndcap.cmsHGCal.startZ + fullEMModuleZ); // Debug Section // G4cout << "### HGCal::EM Location: " << cmsEndcap.cmsHGCal.EM.centerZ/cm << " Dimensions: " << fullEMModuleZ/cm << " " << cmsEndcap.cmsHGCal.EM.rmin1/cm << " " << cmsEndcap.cmsHGCal.EM.rmin2/cm << " " << cmsEndcap.cmsHGCal.EM.rmax1/cm << " " << cmsEndcap.cmsHGCal.EM.rmax2/cm << G4endl << "### HGCal::EM::Layer1,2,3 Z-Dimensions: " << fullEMLayerZ_1/cm << " " << fullEMLayerZ_2/cm << " " << fullEMLayerZ_3/cm << G4endl << "### HGCal::EM::AbsZ1,2,3 Dimensions: " << cmsEndcap.cmsHGCal.EM.fullAbsZ[0]/cm << " " << cmsEndcap.cmsHGCal.EM.fullAbsZ[1]/cm << " " << cmsEndcap.cmsHGCal.EM.fullAbsZ[2]/cm << " Material: " << cmsEndcap.cmsHGCal.EM.absMat->GetName() << G4endl << "### HGCal::EM::PadZ Dimensions: " << cmsEndcap.cmsHGCal.EM.fullPadZ/cm << G4endl << "### HGCal::EM::ReadoutZ Dimensions: " << cmsEndcap.cmsHGCal.EM.fullReadoutZ/cm << G4endl; // // Build HGC: // -- EM Module // -- -- 3 types, each consists of: // -- -- -- Abs // -- -- -- Pads // -- -- -- Readout // -- FH Module // -- -- 1 type, each consists of // -- -- -- Abs // -- -- -- Pads // -- -- -- Readout // G4Cons *sEM = new G4Cons("sEM", cmsEndcap.cmsHGCal.EM.rmin1, cmsEndcap.cmsHGCal.EM.rmax1, cmsEndcap.cmsHGCal.EM.rmin2, cmsEndcap.cmsHGCal.EM.rmax2, fullEMModuleZ/2., 0, 360*deg); cmsEndcap.cmsHGCal.EM.totalZ = fullEMModuleZ; G4LogicalVolume *lEM = new G4LogicalVolume(sEM, mVacuum, "lEM"); G4double zpos = cmsEndcap.cmsHGCal.startZ + fullEMModuleZ/2.; if (cmsEndcap.cmsHGCal.EM.onOff == 1) new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lEM, "pEM", logicWorld, 0, EMPCOPYID, true); G4RotationMatrix rotation = G4RotationMatrix(); rotation = rotation.rotateX(180.*deg); G4Transform3D transform(rotation, G4ThreeVector(0, 0, -zpos)); if (cmsEndcap.cmsHGCal.EM.onOff == 1) new G4PVPlacement(transform, lEM, "pEM", logicWorld, 0, EMMCOPYID, true); // // PRIM Detector // G4Box *sPrim = new G4Box("sPrim", 5.*m, 5.*m, 1.*mm); G4LogicalVolume *lPrim = new G4LogicalVolume(sPrim, mVacuum, "lPrim", 0, primSD, 0); zpos = cmsEndcap.cmsHGCal.startZ - 3*mm; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lPrim, "pPrim", logicWorld, 0, PRIMCOPYID, true); transform = G4Transform3D(rotation, G4ThreeVector(0, 0, -zpos)); new G4PVPlacement(transform, lPrim, "pPrim", logicWorld, 0, PRIMCOPYID, true); // // EM Part: // There are 3 sections for EM part - different abs thickness // Declare all the Dimensions here, for layers, thicknesses... // G4double z1 = cmsEndcap.cmsHGCal.startZ; G4double z2 = z1; G4double rmin1 = cmsEndcap.cmsHGCal.EM.rmin1; G4double rmin2 = Getr2(rmin1, z1, z2); G4double rmax1 = cmsEndcap.cmsHGCal.EM.rmax1; G4double rmax2 = Getr2(rmax1, z1, z2); G4double absz1 = cmsEndcap.cmsHGCal.startZ; G4double absz2 = absz1; G4double absrmin1 = cmsEndcap.cmsHGCal.EM.rmin1; G4double absrmin2 = cmsEndcap.cmsHGCal.EM.rmin2; G4double absrmax1 = cmsEndcap.cmsHGCal.EM.rmax1; G4double absrmax2 = cmsEndcap.cmsHGCal.EM.rmax2; G4double padz1 = cmsEndcap.cmsHGCal.startZ; G4double padz2 = absz1; G4double padrmin1 = cmsEndcap.cmsHGCal.EM.rmin1; G4double padrmin2 = cmsEndcap.cmsHGCal.EM.rmin2; G4double padrmax1 = cmsEndcap.cmsHGCal.EM.rmax1; G4double padrmax2 = cmsEndcap.cmsHGCal.EM.rmax2; G4double outz1 = cmsEndcap.cmsHGCal.startZ; G4double outz2 = absz1; G4double outrmin1 = cmsEndcap.cmsHGCal.EM.rmin1; G4double outrmin2 = cmsEndcap.cmsHGCal.EM.rmin2; G4double outrmax1 = cmsEndcap.cmsHGCal.EM.rmax1; G4double outrmax2 = cmsEndcap.cmsHGCal.EM.rmax2; // // Section1: Layers 0-9(1 - 10 overall) // -- Abs // -- Pads // -- Readout // for (int i=0; i<cmsEndcap.cmsHGCal.EM.n1; i++) { if (i>0) { z1 = z2; rmin1 = rmin2; rmax1 = rmax2; } z2 += fullEMLayerZ_1; rmin2 = Getr2(rmin1, z1, z2); rmax2 = Getr2(rmax1, z1, z2); absz1 = z1; absz2 = absz1 + cmsEndcap.cmsHGCal.EM.fullAbsZ[0]; absrmin1 = rmin1; absrmax1 = rmax1; absrmin2 = Getr2(absrmin1, absz1, absz2); absrmax2 = Getr2(absrmax1, absz1, absz2); padz1 = absz2; padz2 = padz1 + cmsEndcap.cmsHGCal.EM.fullPadZ; padrmin1 = absrmin2; padrmax1 = absrmax2; padrmin2 = Getr2(padrmin1, padz1, padz2); padrmax2 = Getr2(padrmax1, padz1, padz2); outz1 = padz2; outz2 = outz1 + cmsEndcap.cmsHGCal.EM.fullReadoutZ; outrmin1 = padrmin2; outrmax1 = padrmax2; outrmin2 = Getr2(outrmin1, outz1, outz2); outrmax2 = Getr2(outrmax1, outz1, outz2); // absrmin2 = Getr2(absrmin1, absz1, absz2); // absrmax2 = Getr2(absrmax1, absz1, absz2); G4cout << "### Layer " << i << " dimensions: " << rmin1/cm << " " << rmax1/cm << " " << rmin2/cm << " " << rmax2/cm << G4endl; G4Cons *sLayer = new G4Cons("sEMLayer_1", rmin1, rmax1, rmin2, rmax2, fullEMLayerZ_1/2., 0, 360*deg); G4LogicalVolume *lLayer = new G4LogicalVolume( sLayer, mVacuum, "lEMLayer_1"); // // Build Abs and put it inside the Layer // G4Cons *sAbs = new G4Cons("sEMAbs_1", absrmin1, absrmax1, absrmin2, absrmax2, cmsEndcap.cmsHGCal.EM.fullAbsZ[0]/2., 0, 360*deg); G4LogicalVolume *lAbs = new G4LogicalVolume(sAbs, cmsEndcap.cmsHGCal.EM.absMat, "lEMAbs_1"); zpos = -fullEMLayerZ_1/2. + cmsEndcap.cmsHGCal.EM.fullAbsZ[0]/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAbs, "pEMAbs_1", lLayer, 0, 0, true); // // Build the Pad Layer and place into the Layer // G4Cons *sPad = new G4Cons("sEMPad", padrmin1, padrmax1, padrmin2, padrmax2, cmsEndcap.cmsHGCal.EM.fullPadZ/2., 0, 360*deg); G4LogicalVolume *lPad = new G4LogicalVolume(sPad, mSi, "lEMPad", 0, SDEM, 0); zpos += cmsEndcap.cmsHGCal.EM.fullAbsZ[0]/2. + cmsEndcap.cmsHGCal.EM.fullPadZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lPad, "pEMPad", lLayer, 0, 0, true); // // Build the Readout and place it // G4Cons *sReadout = new G4Cons("sEMReadout", outrmin1, outrmax1, outrmin2, outrmax2, cmsEndcap.cmsHGCal.EM.fullReadoutZ/2., 0, 360*deg); G4LogicalVolume *lReadout = new G4LogicalVolume(sReadout, mElectronicsMat, "lEMReadout"); zpos += cmsEndcap.cmsHGCal.EM.fullPadZ/2. + cmsEndcap.cmsHGCal.EM.fullReadoutZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lReadout, "pEMReadout", lLayer, 0, 0, true); // // Place the Layer // zpos = -fullEMModuleZ/2. + (i + 0.5)*fullEMLayerZ_1; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lLayer, "pEMLayer_1", lEM, 0, i, true); } // // Section2: Layer0-9(11 - 20 overall) // for (int i=0; i<cmsEndcap.cmsHGCal.EM.n2; i++) { z1 = z2; z2 += fullEMLayerZ_2; rmin1 = rmin2; rmax1 = rmax2; rmin2 = Getr2(rmin1, z1, z2); rmax2 = Getr2(rmax1, z1 ,z2); absz1 = z1; absz2 = absz1 + cmsEndcap.cmsHGCal.EM.fullAbsZ[1]; absrmin1 = rmin1; absrmax1 = rmax1; absrmin2 = Getr2(absrmin1, absz1, absz2); absrmax2 = Getr2(absrmax1, absz1, absz2); padz1 = absz2; padz2 = padz1 + cmsEndcap.cmsHGCal.EM.fullPadZ; padrmin1 = absrmin2; padrmax1 = absrmax2; padrmin2 = Getr2(padrmin1, padz1, padz2); padrmax2 = Getr2(padrmax1, padz1, padz2); outz1 = padz2; outz2 = outz1 + cmsEndcap.cmsHGCal.EM.fullReadoutZ; outrmin1 = padrmin2; outrmax1 = padrmax2; outrmin2 = Getr2(outrmin1, outz1, outz2); outrmax2 = Getr2(outrmax1, outz1, outz2); G4Cons *sLayer = new G4Cons("sEMLayer_2", rmin1, rmax1, rmin2, rmax2, fullEMLayerZ_2/2., 0, 360*deg); G4LogicalVolume *lLayer = new G4LogicalVolume(sLayer, mVacuum, "lEMLayer_2"); // // Build Abs and put it inside the Layer // G4Cons *sAbs = new G4Cons("sEMAbs_2", absrmin1, absrmax1, absrmin2, absrmax2, cmsEndcap.cmsHGCal.EM.fullAbsZ[1]/2., 0, 360*deg); G4LogicalVolume *lAbs = new G4LogicalVolume(sAbs, cmsEndcap.cmsHGCal.EM.absMat, "lEMAbs_2"); zpos = -fullEMLayerZ_2/2. + cmsEndcap.cmsHGCal.EM.fullAbsZ[1]/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAbs, "pEMAbs_2", lLayer, 0, 0, true); // // Build the Pad Layer and place into the Layer // G4Cons *sPad = new G4Cons("sEMPad", padrmin1, padrmax1, padrmin2, padrmax2, cmsEndcap.cmsHGCal.EM.fullPadZ/2., 0, 360*deg); G4LogicalVolume *lPad = new G4LogicalVolume(sPad, mSi, "lEMPad", 0, SDEM, 0); zpos += cmsEndcap.cmsHGCal.EM.fullAbsZ[1]/2. + cmsEndcap.cmsHGCal.EM.fullPadZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lPad, "pEMPad", lLayer, 0, 0, true); // // Build the Readout and place it // G4Cons *sReadout = new G4Cons("sEMReadout", outrmin1, outrmax1, outrmin2, outrmax2, cmsEndcap.cmsHGCal.EM.fullReadoutZ/2., 0, 360*deg); G4LogicalVolume *lReadout = new G4LogicalVolume(sReadout, mElectronicsMat, "lEMReadout"); zpos += cmsEndcap.cmsHGCal.EM.fullPadZ/2. + cmsEndcap.cmsHGCal.EM.fullReadoutZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lReadout, "pEMReadout", lLayer, 0, 0, true); // // Place the Layer // zpos = -fullEMModuleZ/2. + cmsEndcap.cmsHGCal.EM.n1*fullEMLayerZ_1 + (i + 0.5)*fullEMLayerZ_2; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lLayer, "pEMLayer_2", lEM, 0, cmsEndcap.cmsHGCal.EM.n1 + i, true); } // // Section3: Layers 0-9 (21 - 30 overall) // for (int i=0; i<cmsEndcap.cmsHGCal.EM.n3; i++) { z1 = z2; z2 += fullEMLayerZ_3; rmin1 = rmin2; rmax1 = rmax2; rmin2 = Getr2(rmin1, z1, z2); rmax2 = Getr2(rmax1, z1, z2); G4Cons *sLayer = new G4Cons("sEMLayer_3", rmin1, rmax1, rmin2, rmax2, fullEMLayerZ_3/2., 0, 360*deg); G4LogicalVolume *lLayer = new G4LogicalVolume( sLayer, mVacuum, "lLayer_3"); absz1 = z1; absz2 = absz1 + cmsEndcap.cmsHGCal.EM.fullAbsZ[2]; absrmin1 = rmin1; absrmax1 = rmax1; absrmin2 = Getr2(absrmin1, absz1, absz2); absrmax2 = Getr2(absrmax1, absz1, absz2); padz1 = absz2; padz2 = padz1 + cmsEndcap.cmsHGCal.EM.fullPadZ; padrmin1 = absrmin2; padrmax1 = absrmax2; padrmin2 = Getr2(padrmin1, padz1, padz2); padrmax2 = Getr2(padrmax1, padz1, padz2); outz1 = padz2; outz2 = outz1 + cmsEndcap.cmsHGCal.EM.fullReadoutZ; outrmin1 = padrmin2; outrmax1 = padrmax2; outrmin2 = Getr2(outrmin1, outz1, outz2); outrmax2 = Getr2(outrmax1, outz1, outz2); // // Build Abs and put it inside the Layer // G4Cons *sAbs = new G4Cons("sEMAbs_3", absrmin1, absrmax1, absrmin2, absrmax2, cmsEndcap.cmsHGCal.EM.fullAbsZ[2]/2., 0, 360*deg); G4LogicalVolume *lAbs = new G4LogicalVolume(sAbs, cmsEndcap.cmsHGCal.EM.absMat, "lEMAbs_3"); zpos = -fullEMLayerZ_3/2. + cmsEndcap.cmsHGCal.EM.fullAbsZ[2]/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAbs, "pEMAbs_3", lLayer, 0, 0, true); // // Build the Pad Layer and place into the Layer // G4Cons *sPad = new G4Cons("sEMPad", padrmin1, padrmax1, padrmin2, padrmax2, cmsEndcap.cmsHGCal.EM.fullPadZ/2., 0, 360*deg); G4LogicalVolume *lPad = new G4LogicalVolume(sPad, mSi, "lEMPad", 0, SDEM, 0); zpos += cmsEndcap.cmsHGCal.EM.fullAbsZ[2]/2. + cmsEndcap.cmsHGCal.EM.fullPadZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lPad, "pEMPad", lLayer, 0, 0, true); // // Build the Readout and place it // G4Cons *sReadout = new G4Cons("sEMReadout", outrmin1, outrmax1, outrmin2, outrmax2, cmsEndcap.cmsHGCal.EM.fullReadoutZ/2., 0, 360*deg); G4LogicalVolume *lReadout = new G4LogicalVolume(sReadout, mElectronicsMat, "lEMReadout"); zpos += cmsEndcap.cmsHGCal.EM.fullPadZ/2. + cmsEndcap.cmsHGCal.EM.fullReadoutZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lReadout, "pEMReadout", lLayer, 0, 0, true); // // Place the Layer // zpos = -fullEMModuleZ/2. + cmsEndcap.cmsHGCal.EM.n1*fullEMLayerZ_1 + cmsEndcap.cmsHGCal.EM.n2*fullEMLayerZ_2 + (i+0.5)*fullEMLayerZ_3; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lLayer, "pEMLayer_3", lEM, 0, cmsEndcap.cmsHGCal.EM.n1 + cmsEndcap.cmsHGCal.EM.n2 + i, true); } // // Construct additional dimensions for FH // G4double fullFHLayerZ = cmsEndcap.cmsHGCal.FH.fullAbsZ + cmsEndcap.cmsHGCal.FH.fullPadZ + cmsEndcap.cmsHGCal.FH.fullReadoutZ; G4double fullFHModuleZ = cmsEndcap.cmsHGCal.FH.n*fullFHLayerZ; cmsEndcap.cmsHGCal.FH.centerZ = cmsEndcap.cmsHGCal.startZ + fullEMModuleZ + fullFHModuleZ/2.; cmsEndcap.cmsHGCal.FH.rmin1 = cmsEndcap.cmsHGCal.EM.rmin2; cmsEndcap.cmsHGCal.FH.rmax1 = cmsEndcap.cmsHGCal.EM.rmax2; cmsEndcap.cmsHGCal.FH.rmin2 = Getr2( cmsEndcap.cmsHGCal.FH.rmin1, cmsEndcap.cmsHGCal.FH.centerZ - fullFHModuleZ/2., cmsEndcap.cmsHGCal.FH.centerZ + fullFHModuleZ/2.); cmsEndcap.cmsHGCal.FH.rmax2 = Getr2( cmsEndcap.cmsHGCal.FH.rmax1, cmsEndcap.cmsHGCal.FH.centerZ - fullFHModuleZ/2., cmsEndcap.cmsHGCal.FH.centerZ + fullFHModuleZ/2.); // // FH Debug Section // G4cout << "### HGCal::FH Location: " << cmsEndcap.cmsHGCal.FH.centerZ/cm << " Dimensions: " << fullFHModuleZ/cm << " " << cmsEndcap.cmsHGCal.FH.rmin1/cm << " " << cmsEndcap.cmsHGCal.FH.rmax1/cm << " " << cmsEndcap.cmsHGCal.FH.rmin2/cm << " " << cmsEndcap.cmsHGCal.FH.rmax2/cm << G4endl << "### HGCal::FH::Layer Dimensions: " << fullFHLayerZ/cm << G4endl << "### HGCal::FH::Abs Dimensions: " << cmsEndcap.cmsHGCal.FH.fullAbsZ/cm << " Material: " << cmsEndcap.cmsHGCal.FH.absMat->GetName() << G4endl << "### HGCal::FH::PadZ Dimensions: " << cmsEndcap.cmsHGCal.FH.fullPadZ/cm << G4endl << "### HGCal::FH::ReadoutZ Dimensions: " << cmsEndcap.cmsHGCal.FH.fullReadoutZ/cm << G4endl; // // Build FH // G4Cons *sFH = new G4Cons("sFH", cmsEndcap.cmsHGCal.FH.rmin1, cmsEndcap.cmsHGCal.FH.rmax1, cmsEndcap.cmsHGCal.FH.rmin2, cmsEndcap.cmsHGCal.FH.rmax2, fullFHModuleZ/2., 0, 360*deg); cmsEndcap.cmsHGCal.FH.totalZ = fullFHModuleZ; G4LogicalVolume *lFH = new G4LogicalVolume(sFH, mVacuum, "lFH"); zpos = cmsEndcap.cmsHGCal.FH.centerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lFH, "pFH", logicWorld, 0, FHPCOPYID, true); transform = G4Transform3D(rotation, G4ThreeVector(0, 0, -zpos)); new G4PVPlacement(transform, lFH, "pFH", logicWorld, 0, FHMCOPYID, true); // // for FH we got just 1 section. // z1 = cmsEndcap.cmsHGCal.FH.centerZ - fullFHModuleZ/2.; z2 = z1; rmin1 = cmsEndcap.cmsHGCal.FH.rmin1; rmin2 = Getr2(rmin1, z1, z2); rmax1 = cmsEndcap.cmsHGCal.FH.rmax1; rmax2 = Getr2(rmax1, z1, z2); // // BUILDING... // for (int i=0; i<cmsEndcap.cmsHGCal.FH.n; i++) { if (i>0) { z1 = z2; rmin1 = rmin2; rmax1 = rmax2; } z2 += fullFHLayerZ; rmin2 = Getr2(rmin1, z1, z2); rmax2 = Getr2(rmax1, z1, z2); absz1 = z1; absz2 = absz1 + cmsEndcap.cmsHGCal.FH.fullAbsZ; absrmin1 = rmin1; absrmax1 = rmax1; absrmin2 = Getr2(absrmin1, absz1, absz2); absrmax2 = Getr2(absrmax1, absz1, absz2); padz1 = absz2; padz2 = padz1 + cmsEndcap.cmsHGCal.FH.fullPadZ; padrmin1 = absrmin2; padrmax1 = absrmax2; padrmin2 = Getr2(padrmin1, padz1, padz2); padrmax2 = Getr2(padrmax1, padz1, padz2); outz1 = padz2; outz2 = outz1 + cmsEndcap.cmsHGCal.FH.fullReadoutZ; outrmin1 = padrmin2; outrmax1 = padrmax2; outrmin2 = Getr2(outrmin1, outz1, outz2); outrmax2 = Getr2(outrmax1, outz1, outz2); // // Create a Layer // G4Cons *sLayer = new G4Cons("sFHLayer", rmin1, rmax1, rmin2, rmax2, fullFHLayerZ/2., 0, 360*deg); G4LogicalVolume *lLayer = new G4LogicalVolume(sLayer, mVacuum, "sFHLayer"); // // Build Abs // G4Cons *sAbs = new G4Cons("sFHAbs", absrmin1, absrmax1, absrmin2, absrmax2, cmsEndcap.cmsHGCal.FH.fullAbsZ/2., 0, 360*deg); G4LogicalVolume *lAbs = new G4LogicalVolume(sAbs, cmsEndcap.cmsHGCal.FH.absMat, "lFHAbs"); zpos = -fullFHLayerZ/2. + cmsEndcap.cmsHGCal.FH.fullAbsZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAbs, "pFHAbs", lLayer, 0, 0, true); // // Build the Pad Layer and place into the layer // G4Cons *sPad = new G4Cons("sFHPad", padrmin1 ,padrmax1, padrmin2, padrmax2, cmsEndcap.cmsHGCal.FH.fullPadZ/2., 0, 360*deg); G4LogicalVolume *lPad = new G4LogicalVolume(sPad, mSi, "lFHPad", 0, SDFH, 0); zpos += cmsEndcap.cmsHGCal.FH.fullAbsZ/2. + cmsEndcap.cmsHGCal.FH.fullPadZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lPad, "pFHPad", lLayer, 0, 0, true); // // Build the Readout and place it // G4Cons *sReadout = new G4Cons("sFHReadout", outrmin1, outrmax1, outrmin2, outrmax2, cmsEndcap.cmsHGCal.FH.fullReadoutZ/2., 0, 360*deg); G4LogicalVolume *lReadout = new G4LogicalVolume(sReadout, mElectronicsMat, "lFHReadout"); zpos += cmsEndcap.cmsHGCal.FH.fullPadZ/2. + cmsEndcap.cmsHGCal.FH.fullReadoutZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lReadout, "pFHReadout", lLayer, 0, 0, true); // // Place the Layer // zpos = -fullFHModuleZ/2. + (i + 0.5)*fullFHLayerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lLayer, "pFHLayer", lFH, 0, i, true); } // // BH part: Construct additional dimensions for BH // G4double fullBHLayerZ = cmsEndcap.cmsHGCal.BH.fullAbsZ + cmsEndcap.cmsHGCal.BH.fullActZ; G4double fullBHModuleZ = cmsEndcap.cmsHGCal.BH.n*fullBHLayerZ; cmsEndcap.cmsHGCal.BH.centerZ = cmsEndcap.cmsHGCal.startZ + fullEMModuleZ + fullFHModuleZ + fullBHModuleZ/2.; cmsEndcap.cmsHGCal.BH.rmin1 = cmsEndcap.cmsHGCal.FH.rmin2; cmsEndcap.cmsHGCal.BH.rmax2 = cmsEndcap.cmsHGCal.BH.rmax1; cmsEndcap.cmsHGCal.BH.rmin2 = Getr2( cmsEndcap.cmsHGCal.BH.rmin1, cmsEndcap.cmsHGCal.BH.centerZ - fullFHModuleZ/2., cmsEndcap.cmsHGCal.BH.centerZ + fullFHModuleZ/2.); // // BH Debug Section // G4cout << "### HGCal::BH Location: " << cmsEndcap.cmsHGCal.BH.centerZ/cm << " Dimensions: " << fullBHModuleZ/cm << " " << cmsEndcap.cmsHGCal.BH.rmin1/cm << " " << cmsEndcap.cmsHGCal.BH.rmax1/cm << " " << cmsEndcap.cmsHGCal.BH.rmin2/cm << " " << cmsEndcap.cmsHGCal.BH.rmax2/cm << G4endl << "### HGCal::BH::Layer Dimensions: " << fullBHLayerZ/cm << G4endl << "### HGCal::BH::Abs Dimensions: " << cmsEndcap.cmsHGCal.BH.fullAbsZ/cm << " Material: " << cmsEndcap.cmsHGCal.BH.absMat << G4endl << "### HGCal::BH::ActZ Dimensions: " << cmsEndcap.cmsHGCal.BH.fullActZ/cm << G4endl; // // Build BH(HE basically) // G4Cons *sBH = new G4Cons("sBH", cmsEndcap.cmsHGCal.BH.rmin1, cmsEndcap.cmsHGCal.BH.rmax1, cmsEndcap.cmsHGCal.BH.rmin2, cmsEndcap.cmsHGCal.BH.rmax2, fullBHModuleZ/2., 0, 360*deg); cmsEndcap.cmsHGCal.BH.totalZ = fullBHModuleZ; G4LogicalVolume *lBH = new G4LogicalVolume(sBH, mVacuum, "lBH"); zpos = cmsEndcap.cmsHGCal.BH.centerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lBH, "pBH", logicWorld, 0, BHPCOPYID, true); transform = G4Transform3D(rotation, G4ThreeVector(0, 0, -zpos)); new G4PVPlacement(transform, lBH, "pBH", logicWorld, 0, BHMCOPYID, true); // // For BH, we got just 1 section // z1 = cmsEndcap.cmsHGCal.BH.centerZ - fullBHModuleZ/2.; z2 = z1; rmin1 = cmsEndcap.cmsHGCal.BH.rmin1; rmax1 = cmsEndcap.cmsHGCal.BH.rmax1; G4double actz1, actz2, actrmin1, actrmin2, actrmax1, actrmax2; // // BUILDING... // for (int i=0; i<cmsEndcap.cmsHGCal.BH.n; i++) { if (i>0) { z1 = z2; rmin1 = rmin2; rmax1 = rmax2; } z2 += fullBHLayerZ; rmin2 = Getr2(rmin1, z1, z2); rmax2 = cmsEndcap.cmsHGCal.BH.rmax2; absz1 = z1; absz2 = absz1 + cmsEndcap.cmsHGCal.BH.fullAbsZ; absrmin1 = rmin1; absrmax1 = rmax1; absrmin2 = Getr2(absrmin1, absz1, absz2); absrmax2 = absrmax1; actz1 = absz2; actz2 = actz1 + cmsEndcap.cmsHGCal.BH.fullActZ; actrmin1 = absrmin2; actrmax1 = absrmax2; actrmin2 = Getr2(actrmin1, actz1, actz2); actrmax2 = actrmax1; // // Create a Layer // G4Cons *sLayer = new G4Cons("sBHLayer", rmin1, rmax1, rmin2, rmax2, fullBHLayerZ/2., 0, 360*deg); G4LogicalVolume *lLayer = new G4LogicalVolume(sLayer, mVacuum, "lBHLayer"); // // Build Abs // G4Cons *sAbs = new G4Cons("sBHAbs", absrmin1, absrmax1, absrmin2, absrmax2, cmsEndcap.cmsHGCal.BH.fullAbsZ/2., 0, 360*deg); G4LogicalVolume *lAbs = new G4LogicalVolume(sAbs, cmsEndcap.cmsHGCal.BH.absMat, "lBHAbs"); zpos = -fullBHLayerZ/2. + cmsEndcap.cmsHGCal.BH.fullAbsZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAbs, "pBHAbs", lLayer, 0, 0, true); // // BUild the Active Material(SCSN-81) // G4Cons *sAct = new G4Cons("sBHAct", actrmin1, actrmax1, actrmin2, actrmax2, cmsEndcap.cmsHGCal.BH.fullActZ/2., 0, 360*deg); G4LogicalVolume *lAct = new G4LogicalVolume(sAct, mHEScintMain, "lBHAct", 0, heSD, 0); zpos += cmsEndcap.cmsHGCal.BH.fullAbsZ/2. + cmsEndcap.cmsHGCal.BH.fullActZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAct, "pBHAct", lLayer, 0, 0, true); // // Place the Layer // zpos = -fullBHModuleZ/2. + (i + 0.5)*fullBHLayerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lLayer, "pBHLayer", lBH, 0, i + cmsEndcap.cmsHGCal.SHE.n, true); } // // SHE Part: Construct additional dims for SHE // G4double fullSHELayerZ = cmsEndcap.cmsHGCal.SHE.fullAbsZ + cmsEndcap.cmsHGCal.SHE.fullActZ; G4double fullSHEModuleZ = cmsEndcap.cmsHGCal.SHE.n*fullSHELayerZ; cmsEndcap.cmsHGCal.SHE.centerZ = cmsEndcap.cmsHGCal.startZ + fullEMModuleZ + fullFHModuleZ - fullSHEModuleZ/2.; cmsEndcap.cmsHGCal.SHE.rmin1 = cmsEndcap.cmsHGCal.FH.rmax2; cmsEndcap.cmsHGCal.SHE.rmin2 = cmsEndcap.cmsHGCal.SHE.rmin1; cmsEndcap.cmsHGCal.SHE.rmax2 = cmsEndcap.cmsHGCal.BH.rmax1; cmsEndcap.cmsHGCal.SHE.rmax1 = cmsEndcap.cmsHGCal.SHE.rmax2 - fullSHEModuleZ*tan(3.14159265/180*cmsEndcap.cmsHGCal.SHE.incline); // // SHE Debug Section // G4cout << "### HGCal::SHE Location: " << cmsEndcap.cmsHGCal.SHE.centerZ/cm << " Dimensions: " << fullSHEModuleZ/cm << " " << cmsEndcap.cmsHGCal.SHE.rmin1/cm << " " << cmsEndcap.cmsHGCal.SHE.rmax1/cm << " " << cmsEndcap.cmsHGCal.SHE.rmin2/cm << " " << cmsEndcap.cmsHGCal.SHE.rmax2/cm << G4endl << "### HGCal::SHE::Layer Dimensions: " << fullSHELayerZ/cm << G4endl << "### HGCal::SHE::Abs Dimensions: " << cmsEndcap.cmsHGCal.SHE.fullAbsZ/cm << " Material: " << cmsEndcap.cmsHGCal.SHE.absMat << G4endl << "### HGCal::SHE::ActZ Dimensions: " << cmsEndcap.cmsHGCal.SHE.fullActZ/cm << G4endl; // // Build SHE - Side HE Part // G4Cons *sSHE = new G4Cons("sSHE", cmsEndcap.cmsHGCal.SHE.rmin1, cmsEndcap.cmsHGCal.SHE.rmax1, cmsEndcap.cmsHGCal.SHE.rmin2, cmsEndcap.cmsHGCal.SHE.rmax2, fullSHEModuleZ/2., 0, 360*deg); cmsEndcap.cmsHGCal.SHE.totalZ = fullSHEModuleZ; G4LogicalVolume *lSHE = new G4LogicalVolume(sSHE, mVacuum, "lSHE"); zpos = cmsEndcap.cmsHGCal.SHE.centerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lSHE, "pSHE", logicWorld, 0, BHPCOPYID, true); transform = G4Transform3D(rotation, G4ThreeVector(0, 0, -zpos)); new G4PVPlacement(transform, lSHE, "pSHE", logicWorld, 0, BHMCOPYID, true); // // 1 Section for SHE // z1 = cmsEndcap.cmsHGCal.SHE.centerZ - fullSHEModuleZ/2.; z2 = z1; rmin1 = cmsEndcap.cmsHGCal.SHE.rmin1; rmax1 = cmsEndcap.cmsHGCal.SHE.rmax1; rmin2 = rmin1; rmax2 = rmax1; G4double tang = (cmsEndcap.cmsHGCal.SHE.rmax2 - cmsEndcap.cmsHGCal.SHE.rmax1)/ fullSHEModuleZ; // // BUILDING // for (int i=0; i<cmsEndcap.cmsHGCal.SHE.n; i++) { z1 = z2; rmin1 = rmin2; rmax1 = rmax2; z2 += fullSHELayerZ; rmin2 = rmin1; rmax2 = rmax1 + (z2 - z1)*tang; absz1 = z1; absz2 = absz1 + cmsEndcap.cmsHGCal.SHE.fullAbsZ; absrmin1 = rmin1; absrmax1 = rmax1; absrmin2 = absrmin1; absrmax2 = absrmax1 + (absz2 - absz1)*tang; actz1 = absz2; actz2 = actz1 + cmsEndcap.cmsHGCal.SHE.fullActZ; actrmin1 = absrmin2; actrmax1 = absrmax2; actrmin2 = actrmin1; actrmax2 = actrmax1 + (actz2 - actz1)*tang; // // Create a layer // G4Cons *sLayer = new G4Cons("sSHELayer", rmin1, rmax1, rmin2, rmax2, fullSHELayerZ/2., 0, 360*deg); G4LogicalVolume *lLayer = new G4LogicalVolume(sLayer, mVacuum, "lSHELayer"); // // Build Abs // G4Cons *sAbs = new G4Cons("sSHEAbs", absrmin1, absrmax1, absrmin2, absrmax2, cmsEndcap.cmsHGCal.SHE.fullAbsZ/2., 0, 360*deg); G4LogicalVolume *lAbs = new G4LogicalVolume(sAbs, cmsEndcap.cmsHGCal.SHE.absMat, "lSHEAbs"); zpos = -fullSHELayerZ/2. + cmsEndcap.cmsHGCal.SHE.fullAbsZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAbs, "pSHEAbs", lLayer, 0, 0, true); // // Build the Active MAterial // G4Cons *sAct = new G4Cons("sSHEAct", actrmin1, actrmax1, actrmin2, actrmax2, cmsEndcap.cmsHGCal.SHE.fullActZ/2., 0, 360*deg); G4LogicalVolume *lAct = new G4LogicalVolume(sAct, mHEScintMain, "lSHEAct", 0, heSD, 0); zpos += cmsEndcap.cmsHGCal.SHE.fullAbsZ/2. + cmsEndcap.cmsHGCal.SHE.fullActZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAct, "pSHEAct", lLayer, 0, 0, true); // // Place a layer // zpos = -fullSHEModuleZ/2. + (i + 0.5)*fullSHELayerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lLayer, "pSHELayer", lSHE, 0, i, true); } // // Push Geometry Info to Readout Module // _readout->PushGeomInfo(cmsEndcap.cmsHGCal); cout << "### Total Z-Dimensions: EM: " << cmsEndcap.cmsHGCal.EM.totalZ/mm << " FH: " << cmsEndcap.cmsHGCal.FH.totalZ/mm << " BH: " << cmsEndcap.cmsHGCal.BH.totalZ/mm << " SHE: " << cmsEndcap.cmsHGCal.SHE.totalZ/mm << endl; return 1; } // // Calculate the max radius(r2), given r1, z1, z2. // Use Simmiliarity of Triangles. // G4double SHDetectorConstruction::Getr2(G4double r1, G4double z1, G4double z2) { G4double r2 = r1 * (z2/z1); return r2; } // // Configure the geometry of HGC by reading neccessary parameters // from a file. // int SHDetectorConstruction::ConfigHGC() { cout << "### Configuring HGC Input..." << endl; // Check the file // ifstream hgcFile(runParams.endcapConfigFileName); if (!hgcFile) { cout << "### ERROR: file " << runParams.endcapConfigFileName << " hasn't been found!!!" << endl; return -1; } // Read in/Config. All dimensions are in mm // double z1, z2, z3; int n1, n2, n3, iMat; double startz; double rmin1, rmin2, rmax1, rmax2; int onOff; // CMS Endcap Starting Position // hgcFile >> startz; cmsEndcap.cmsHGCal.startZ = startz*mm; // // EM Part: Basic Dimensions neccessary to construct the whole module; // Total Length in Z will be calculated using the Abs + pad + readout // hgcFile >> n1 >> n2 >> n3 >> iMat >> onOff; cmsEndcap.cmsHGCal.EM.n1 = n1; cmsEndcap.cmsHGCal.EM.n2 = n2; cmsEndcap.cmsHGCal.EM.n3 = n3; cmsEndcap.cmsHGCal.EM.iMat = iMat; cmsEndcap.cmsHGCal.EM.onOff = onOff; if (iMat == 1) cmsEndcap.cmsHGCal.EM.absMat = mPb; else if (iMat == 2) cmsEndcap.cmsHGCal.EM.absMat = mCu; else cout << "### ERROR: HGCal::EM::ABS UNKNOWN Material Specification" << endl; hgcFile >> rmin1 >> rmax1; cmsEndcap.cmsHGCal.EM.rmin1 = rmin1*mm; // cmsEndcap.cmsHGCal.EM.rmin2 = rmin2*mm; cmsEndcap.cmsHGCal.EM.rmax1 = rmax1*mm; // cmsEndcap.cmsHGCal.EM.rmax2 = rmax2*mm; // Abs z-dimensions of 3 kinds as expected.... // hgcFile >> z1 >> z2 >> z3; cmsEndcap.cmsHGCal.EM.fullAbsZ[0] = z1*mm; cmsEndcap.cmsHGCal.EM.fullAbsZ[1] = z2*mm; cmsEndcap.cmsHGCal.EM.fullAbsZ[2] = z3*mm; // Pads z-dimension // hgcFile >> z1; cmsEndcap.cmsHGCal.EM.fullPadZ = z1*mm; // Readout Z // hgcFile >> z1; cmsEndcap.cmsHGCal.EM.fullReadoutZ = z1*mm; // // FH Part: Basic Dimensions neccesary to construct the whole module // NOTE: Starting point is assumed from EM Part(both transverse/longitud) // hgcFile >> n1 >> iMat; cmsEndcap.cmsHGCal.FH.n = n1; cmsEndcap.cmsHGCal.FH.iMat = iMat; if (iMat == 1) cmsEndcap.cmsHGCal.FH.absMat = mBrass; else cmsEndcap.cmsHGCal.FH.absMat = mCu; hgcFile >> z1; cmsEndcap.cmsHGCal.FH.fullAbsZ = z1; hgcFile >> z1; cmsEndcap.cmsHGCal.FH.fullPadZ = z1; hgcFile >> z1; cmsEndcap.cmsHGCal.FH.fullReadoutZ = z1; // // BH Part: Basic Dimensions neccessary to construct the whole module // NOTE: Starting point depends only on longitudinal dimensions of FH-part // and rmin1, but rmax1 MUST be provided in the config file... // hgcFile >> n1 >> iMat; cmsEndcap.cmsHGCal.BH.n = n1; cmsEndcap.cmsHGCal.BH.iMat = iMat; cmsEndcap.cmsHGCal.BH.absMat = mBrass; hgcFile >> rmax1; cmsEndcap.cmsHGCal.BH.rmax1 = rmax1*mm; hgcFile >> z1; cmsEndcap.cmsHGCal.BH.fullAbsZ = z1*mm; hgcFile >> z1; cmsEndcap.cmsHGCal.BH.fullActZ = z1*mm; // // Side HE, right on top of FH part // hgcFile >> n1 >> iMat; cmsEndcap.cmsHGCal.SHE.n = n1; cmsEndcap.cmsHGCal.SHE.iMat = iMat; cmsEndcap.cmsHGCal.SHE.absMat = mBrass; double inclineAngle; hgcFile >> inclineAngle; cmsEndcap.cmsHGCal.SHE.incline = inclineAngle; hgcFile >> z1; cmsEndcap.cmsHGCal.SHE.fullAbsZ = z1*mm; hgcFile >> z1; cmsEndcap.cmsHGCal.SHE.fullActZ = z1*mm; cout << "### Done Configuring HGC... Geometry Parameters" << endl; return 1; } // // Build Shashlik + HE // int SHDetectorConstruction::BuildShashlikPlusHE() { // // Read/Config the geometry parameters // ConfigShashlikPlusHE(); const int EMPCOPYID = 0; const int EMMCOPYID = 1; const int FHPCOPYID = 2; const int FHMCOPYID = 3; const int BHPCOPYID = 4; const int BHMCOPYID = 5; const int PRIMCOPYID = 10; const int SHPCOPYID = 6; const int SHMCOPYID = 7; const int HEPCOPYID = 8; const int HEMCOPYID = 9; // // SD // G4SDManager *SDManager = G4SDManager::GetSDMpointer(); SHSDCounter *SHSD = new SHSDCounter("SH", runParams, SHPCOPYID, _readout); HESD *heSD = new HESD("HE", runParams, HEPCOPYID, _readout); PRIMSD *primSD = new PRIMSD("PRIM", runParams, PRIMCOPYID, _readout); SDManager->AddNewDetector(SHSD); SDManager->AddNewDetector(heSD); SDManager->AddNewDetector(primSD); cout << "### SDs are initialized..." << endl; // // Construct additional dimensions. // G4double fullEMLayerZ = cmsEndcap.cmsSHE.EM.fullAbsZ + cmsEndcap.cmsSHE.EM.fullActZ; G4double fullEMModuleZ = cmsEndcap.cmsSHE.EM.n*fullEMLayerZ + cmsEndcap.cmsSHE.EM.fullActZ; // NOTE: + 1 act plate at the back... cmsEndcap.cmsSHE.EM.centerZ = cmsEndcap.cmsSHE.startZ + fullEMModuleZ/2.; cmsEndcap.cmsSHE.EM.rmin2 = Getr2( cmsEndcap.cmsSHE.EM.rmin1, cmsEndcap.cmsSHE.startZ, cmsEndcap.cmsSHE.startZ + fullEMModuleZ); cmsEndcap.cmsSHE.EM.rmax2 = Getr2( cmsEndcap.cmsSHE.EM.rmax1, cmsEndcap.cmsSHE.startZ, cmsEndcap.cmsSHE.startZ + fullEMModuleZ); // // Shashlik Debug Section // G4cout << "### SHE::EM(Shashlik) Location: " << cmsEndcap.cmsSHE.EM.centerZ/cm << " Dimensions: " << fullEMModuleZ/cm << " " << cmsEndcap.cmsSHE.EM.rmin1/cm << " " << cmsEndcap.cmsSHE.EM.rmax1/cm << " " << cmsEndcap.cmsSHE.EM.rmin2/cm << " " << cmsEndcap.cmsSHE.EM.rmax2/cm << G4endl << "### SHE::EM::Layer Dimensions: " << fullEMLayerZ/cm << G4endl << "### SHE::EM::Abs Dimensions: " << cmsEndcap.cmsSHE.EM.fullAbsZ/cm << " Material: " << cmsEndcap.cmsSHE.EM.absMat << G4endl << "### SHE::EM::Act Dimensions: " << cmsEndcap.cmsSHE.EM.fullActZ/cm << G4endl; // // Build SHE: // -- EM (Shashlik) Module // -- -- Abs(W) // -- -- Act(LYSO) // -- HE Module // -- -- Abs // -- -- Scint(SCSN81) // G4Cons *sEM = new G4Cons("sEM", cmsEndcap.cmsSHE.EM.rmin1, cmsEndcap.cmsSHE.EM.rmax1, cmsEndcap.cmsSHE.EM.rmin2, cmsEndcap.cmsSHE.EM.rmax2, fullEMModuleZ/2., 0, 360*deg); cmsEndcap.cmsSHE.EM.totalZ = fullEMModuleZ; G4LogicalVolume *lEM = new G4LogicalVolume(sEM, mVacuum, "lEM"); G4double zpos = cmsEndcap.cmsSHE.EM.centerZ; if (cmsEndcap.cmsSHE.EM.onOff == 1) new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lEM, "pEM", logicWorld, 0, SHPCOPYID, true); G4RotationMatrix rotation = G4RotationMatrix(); rotation = rotation.rotateX(180.*deg); G4Transform3D transform(rotation, G4ThreeVector(0, 0, -zpos)); if (cmsEndcap.cmsSHE.EM.onOff == 1) new G4PVPlacement(transform, lEM, "pEM", logicWorld, 0, SHMCOPYID, true); // // PRIM Detector // G4Box *sPrim = new G4Box("sPrim", 5.*m, 5.*m, 1.*mm); G4LogicalVolume *lPrim = new G4LogicalVolume(sPrim, mVacuum, "lPrim", 0, primSD, 0); zpos = cmsEndcap.cmsHGCal.startZ - 3*mm; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lPrim, "pPrim", logicWorld, 0, PRIMCOPYID, true); transform = G4Transform3D(rotation, G4ThreeVector(0, 0, -zpos)); new G4PVPlacement(transform, lPrim, "pPrim", logicWorld, 0, PRIMCOPYID, true); // // EM Part Constituents: // G4double z1 = cmsEndcap.cmsSHE.startZ; G4double z2 = z1; G4double rmin1 = cmsEndcap.cmsSHE.EM.rmin1; G4double rmax1 = cmsEndcap.cmsSHE.EM.rmax1; G4double rmin2 = rmin1; G4double rmax2 = rmax1; G4double absz1 = z1; G4double absz2 = absz1; G4double absrmin1 = rmin1; G4double absrmax1 = rmax1; G4double absrmin2 = absrmin1; G4double absrmax2 = absrmax1; G4double actz1 = absz1; G4double actz2 = actz1; G4double actrmin1 = rmin1; G4double actrmax1 = rmax1; G4double actrmin2 = actrmin1; G4double actrmax2 = actrmax1; // // BUILDING // for (int i=0; i<cmsEndcap.cmsSHE.EM.n; i++) { z1 = z2; z2 += fullEMLayerZ; rmin1 = rmin2; rmax1 = rmax2; rmin2 = Getr2(rmin1, z1, z2); rmax2 = Getr2(rmax1, z1, z2); actz1 = z1; actz2 = actz1 + cmsEndcap.cmsSHE.EM.fullActZ; actrmin1 = rmin1; actrmax1 = rmax1; actrmin2 = Getr2(actrmin1, actz1, actz2); actrmax2 = Getr2(actrmax1, actz1, actz2); absz1 = actz2; absz2 = absz1 + cmsEndcap.cmsSHE.EM.fullAbsZ; absrmin1 = actrmin2; absrmax1 = actrmax2; absrmin2 = Getr2(absrmin1, absz1, absz2); absrmax2 = Getr2(absrmax1, absz1, absz2); G4Cons *sLayer = new G4Cons("sEMLayer", rmin1, rmax1, rmin2, rmax2, fullEMLayerZ/2., 0, 360.*deg); G4LogicalVolume *lLayer = new G4LogicalVolume(sLayer, mVacuum, "lLayer"); // // Build the Active Material // G4Cons *sAct = new G4Cons("sEMAct", actrmin1, actrmax1, actrmin2, actrmax2, cmsEndcap.cmsSHE.EM.fullActZ/2., 0, 360.*deg); G4LogicalVolume *lAct = new G4LogicalVolume(sAct, mLYSO, "lEMAct", 0, SHSD, 0); zpos = -fullEMLayerZ/2. + cmsEndcap.cmsSHE.EM.fullActZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAct, "pEMAct", lLayer, 0, 0, true); // // Build the Abs and put it inside the Layer // G4Cons *sAbs = new G4Cons("sEMAbs", absrmin1, absrmax1, absrmin2, absrmax2, cmsEndcap.cmsSHE.EM.fullAbsZ/2., 0, 360*deg); G4LogicalVolume *lAbs = new G4LogicalVolume(sAbs, cmsEndcap.cmsSHE.EM.absMat, "lEMAbs"); zpos += cmsEndcap.cmsSHE.EM.fullActZ/2. + cmsEndcap.cmsSHE.EM.fullAbsZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAbs, "pEMAbs", lLayer, 0, 0, true); // // Place the Layer // zpos = -fullEMModuleZ/2. + (i + 0.5)*fullEMLayerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lLayer, "pEMLayer", lEM, 0, i, true); } // // We have to place another Active Material isnide the Shashlik, not // Layer!!! See the Layout.... // actz1 = z2; actz2 = actz1 + cmsEndcap.cmsSHE.EM.fullActZ; actrmin1 = rmin2; actrmax1 = rmax2; actrmin2 = Getr2(actrmin1, actz1, actz2); actrmax2 = Getr2(actrmax1, actz1, actz2); G4Cons *sLastAct = new G4Cons("sLastEMAct", actrmin1 ,actrmax1, actrmin2, actrmax2, cmsEndcap.cmsSHE.EM.fullActZ/2., 0, 360*deg); G4LogicalVolume *lLastAct = new G4LogicalVolume(sLastAct, mLYSO, "lLastEMAct", 0, SHSD, 0); zpos = -fullEMModuleZ/2. + cmsEndcap.cmsSHE.EM.n*fullEMLayerZ + cmsEndcap.cmsSHE.EM.fullActZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lLastAct, "pLastEMAct", lEM, 0, cmsEndcap.cmsSHE.EM.n, true); // // HE Part: Construct Additional dimensions for HE // G4double fullFHELayerZ = cmsEndcap.cmsSHE.FHE.fullAbsZ + cmsEndcap.cmsSHE.FHE.fullActZ; G4double fullFHEModuleZ = cmsEndcap.cmsSHE.FHE.n*fullFHELayerZ; cmsEndcap.cmsSHE.FHE.centerZ = cmsEndcap.cmsSHE.startZ + fullEMModuleZ + fullFHEModuleZ/2.; cmsEndcap.cmsSHE.FHE.rmin1 = cmsEndcap.cmsSHE.EM.rmin2; cmsEndcap.cmsSHE.FHE.rmax1 = cmsEndcap.cmsSHE.EM.rmax2; cmsEndcap.cmsSHE.FHE.rmin2 = Getr2( cmsEndcap.cmsSHE.FHE.rmin1, cmsEndcap.cmsSHE.FHE.centerZ - fullFHEModuleZ/2., cmsEndcap.cmsSHE.FHE.centerZ + fullFHEModuleZ/2.); cmsEndcap.cmsSHE.FHE.rmax2 = Getr2( cmsEndcap.cmsSHE.FHE.rmax1, cmsEndcap.cmsSHE.FHE.centerZ - fullFHEModuleZ/2., cmsEndcap.cmsSHE.FHE.centerZ + fullFHEModuleZ/2.); // // HE Debug Section // G4cout << "### SHE::FHE Location: " << cmsEndcap.cmsSHE.FHE.centerZ/cm << " Dimensions: " << fullFHEModuleZ/cm << " " << cmsEndcap.cmsSHE.FHE.rmin1/cm << " " << cmsEndcap.cmsSHE.FHE.rmax1/cm << " " << cmsEndcap.cmsSHE.FHE.rmin2/cm << " " << cmsEndcap.cmsSHE.FHE.rmax2/cm << G4endl << "### SHE::FHE::Layer Dimensions: " << fullFHELayerZ/cm << G4endl << "### SHE::FHE::Abs Dimensions: " << cmsEndcap.cmsSHE.FHE.fullAbsZ/cm << cmsEndcap.cmsSHE.FHE.absMat << G4endl << "### SHE::FHE::Act Dimensions: " << cmsEndcap.cmsSHE.FHE.fullActZ/cm << G4endl; // // Build FHE(Front HE...) // G4Cons *sFHE = new G4Cons("sFHE", cmsEndcap.cmsSHE.FHE.rmin1, cmsEndcap.cmsSHE.FHE.rmax1, cmsEndcap.cmsSHE.FHE.rmin2, cmsEndcap.cmsSHE.FHE.rmax2, fullFHEModuleZ/2., 0, 360*deg); cmsEndcap.cmsSHE.FHE.totalZ = fullFHEModuleZ; G4LogicalVolume *lFHE = new G4LogicalVolume(sFHE, mVacuum, "lFHE"); zpos = cmsEndcap.cmsSHE.FHE.centerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lFHE, "pFHE", logicWorld, 0, HEPCOPYID, true); transform = G4Transform3D(rotation, G4ThreeVector(0, 0, -zpos)); new G4PVPlacement(transform, lFHE, "pFHE", logicWorld, 0, HEMCOPYID, true); // // Additional Dimensions/Variables for FHE // z1 = cmsEndcap.cmsSHE.FHE.centerZ - fullFHEModuleZ/2.; z2 = z1; rmin1 = cmsEndcap.cmsSHE.FHE.rmin1; rmax1 = cmsEndcap.cmsSHE.FHE.rmax1; rmin2 = rmin1; rmax2 = rmax1; // // BUILDING // for (int i=0; i<cmsEndcap.cmsSHE.FHE.n; i++) { z1 = z2; rmin1 = rmin2; rmax1 = rmax2; z2 += fullFHELayerZ; rmin2 = Getr2(rmin1, z1, z2); rmax2 = Getr2(rmax1, z1, z2); absz1 = z1; absz2 = absz1 + cmsEndcap.cmsSHE.FHE.fullAbsZ; absrmin1 = rmin1; absrmax1 = rmax1; absrmin2 = Getr2(absrmin1, absz1, absz2); absrmax2 = Getr2(absrmax1, absz1, absz2); actz1 = absz2; actz2 = actz1 + cmsEndcap.cmsSHE.FHE.fullActZ; actrmin1 = absrmin2; actrmax1 = absrmax2; actrmin2 = Getr2(actrmin1, actz1, actz2); actrmax2 = Getr2(actrmax1, actz1, actz2); // // Create a Layer // G4Cons *sLayer = new G4Cons("sFHELayer", rmin1, rmax1, rmin2, rmax2, fullFHELayerZ/2., 0, 360*deg); G4LogicalVolume *lLayer = new G4LogicalVolume(sLayer, mVacuum, "sFHELayer"); // // Build Abs // G4Cons *sAbs = new G4Cons("sFHEAbs", absrmin1, absrmax1, absrmin2, absrmax2, cmsEndcap.cmsSHE.FHE.fullAbsZ/2., 0, 360*deg); G4LogicalVolume *lAbs = new G4LogicalVolume(sAbs, cmsEndcap.cmsSHE.FHE.absMat, "sFHEAbs"); zpos = -fullFHELayerZ/2. + cmsEndcap.cmsSHE.FHE.fullAbsZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAbs, "pFHEAbs", lLayer, 0, 0, true); // // Build the Active Material // G4Cons *sAct = new G4Cons("sFHEAct", actrmin1, actrmax1, actrmin2, actrmax2, cmsEndcap.cmsSHE.FHE.fullActZ/2., 0, 360*deg); G4LogicalVolume *lAct = new G4LogicalVolume(sAct, mHEScintMain, "lFHEAct", 0, heSD, 0); zpos += cmsEndcap.cmsSHE.FHE.fullAbsZ/2. + cmsEndcap.cmsSHE.FHE.fullActZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAct, "pFHEAct", lLayer, 0, 0, true); // // Place the Layer // zpos = -fullFHEModuleZ/2. + (i + 0.5)*fullFHELayerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lLayer, "pFHELayer", lFHE, 0, i, true); } // // MHE1 Part // G4double fullMHE1LayerZ = cmsEndcap.cmsSHE.MHE1.fullAbsZ + cmsEndcap.cmsSHE.MHE1.fullActZ; G4double fullMHE1ModuleZ = cmsEndcap.cmsSHE.MHE1.n*fullMHE1LayerZ; cmsEndcap.cmsSHE.MHE1.centerZ = cmsEndcap.cmsSHE.startZ + fullEMModuleZ + fullFHEModuleZ + fullMHE1ModuleZ/2.; cmsEndcap.cmsSHE.MHE1.rmin1 = cmsEndcap.cmsSHE.FHE.rmin2; cmsEndcap.cmsSHE.MHE1.rmax1 = cmsEndcap.cmsSHE.FHE.rmax2; cmsEndcap.cmsSHE.MHE1.rmin2 = Getr2( cmsEndcap.cmsSHE.MHE1.rmin1, cmsEndcap.cmsSHE.MHE1.centerZ - fullMHE1ModuleZ/2., cmsEndcap.cmsSHE.MHE1.centerZ + fullMHE1ModuleZ/2.); cmsEndcap.cmsSHE.MHE1.rmax2 = cmsEndcap.cmsSHE.MHE2.rmax1; // // MHE1 debug Section // G4cout << "### SHE::MHE1 Location: " << cmsEndcap.cmsSHE.MHE1.centerZ/cm << " Dimensions: " << fullMHE1ModuleZ/cm << " " << cmsEndcap.cmsSHE.MHE1.rmin1/cm << " " << cmsEndcap.cmsSHE.MHE1.rmax1/cm << " " << cmsEndcap.cmsSHE.MHE1.rmin2/cm << " " << cmsEndcap.cmsSHE.MHE1.rmax2/cm << G4endl << "### SHE::MHE1::Layer Dimensions: " << fullMHE1LayerZ/cm << G4endl << "### SHE::MHE1::Abs Dimensions: " << cmsEndcap.cmsSHE.MHE1.fullAbsZ/cm << cmsEndcap.cmsSHE.MHE1.absMat << G4endl << "### SHE::MHE1::Act Dimensions: " << cmsEndcap.cmsSHE.MHE1.fullActZ/cm << G4endl; // // Build MHE1(Middle HE...) // G4Cons *sMHE = new G4Cons("sMHE1", cmsEndcap.cmsSHE.MHE1.rmin1, cmsEndcap.cmsSHE.MHE1.rmax1, cmsEndcap.cmsSHE.MHE1.rmin2, cmsEndcap.cmsSHE.MHE1.rmax2, fullMHE1ModuleZ/2., 0, 360*deg); cmsEndcap.cmsSHE.MHE1.totalZ = fullMHE1ModuleZ; G4LogicalVolume *lMHE = new G4LogicalVolume(sMHE, mVacuum, "lMHE1"); zpos = cmsEndcap.cmsSHE.MHE1.centerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lMHE, "pMHE1", logicWorld, 0, HEPCOPYID, true); transform = G4Transform3D(rotation, G4ThreeVector(0, 0, -zpos)); new G4PVPlacement(transform, lMHE, "pMHE1", logicWorld, 0, HEMCOPYID, true); // // Additional Dimensions/Variables for MHE1 // z1 = cmsEndcap.cmsSHE.MHE1.centerZ - fullMHE1ModuleZ/2.; G4double zref = z1; z2 = z1; rmin1 = cmsEndcap.cmsSHE.MHE1.rmin1; rmax1 = cmsEndcap.cmsSHE.MHE1.rmax1; rmin2 = rmin1; rmax2 = rmax1; G4double tang = (cmsEndcap.cmsSHE.MHE1.rmax2 - cmsEndcap.cmsSHE.MHE1.rmax1)/ fullMHE1ModuleZ; // // BUILDING // for (int i=0; i<cmsEndcap.cmsSHE.MHE1.n; i++) { z1 = z2; rmin1 = rmin2; rmax1 = rmax2; z2 += fullMHE1LayerZ; rmin2 = Getr2(rmin1, z1, z2); rmax2 = rmax1 + (z2-z1)*tang; absz1 = z1; absz2 = absz1 + cmsEndcap.cmsSHE.MHE1.fullAbsZ; absrmin1 = rmin1; absrmax1 = rmax1; absrmin2 = Getr2(absrmin1, absz1, absz2); absrmax2 = absrmax1 + (absz2 - absz1)*tang; actz1 = absz2; actz2 = actz1 + cmsEndcap.cmsSHE.MHE1.fullActZ; actrmin1 = absrmin2; actrmax1 = absrmax2; actrmin2 = Getr2(actrmin1, actz1, actz2); actrmax2 = actrmax1 + (actz2 - actz1)*tang; // // Create a Layer // G4Cons *sLayer = new G4Cons("sMHE1Layer", rmin1, rmax1, rmin2, rmax2, fullMHE1LayerZ/2., 0, 360*deg); G4LogicalVolume *lLayer = new G4LogicalVolume(sLayer, mVacuum, "sMHE1Layer"); // // Build Abs // G4Cons *sAbs = new G4Cons("sMHE1Abs", absrmin1, absrmax1, absrmin2, absrmax2, cmsEndcap.cmsSHE.MHE1.fullAbsZ/2., 0, 360*deg); G4LogicalVolume *lAbs = new G4LogicalVolume(sAbs, cmsEndcap.cmsSHE.MHE1.absMat, "sMHE1Abs"); zpos = -fullMHE1LayerZ/2. + cmsEndcap.cmsSHE.MHE1.fullAbsZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAbs, "pMHE1Abs", lLayer, 0, 0, true); // // Build the Active Material // G4Cons *sAct = new G4Cons("sMHE1Act", actrmin1, actrmax1, actrmin2, actrmax2, cmsEndcap.cmsSHE.MHE1.fullActZ/2., 0, 360*deg); G4LogicalVolume *lAct = new G4LogicalVolume(sAct, mHEScintMain, "lMHE1Act", 0, heSD, 0); zpos += cmsEndcap.cmsSHE.MHE1.fullAbsZ/2. + cmsEndcap.cmsSHE.MHE1.fullActZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAct, "pMHE1Act", lLayer, 0, 0, true); // // Place the Layer // zpos = -fullMHE1ModuleZ/2. + (i + 0.5)*fullMHE1LayerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lLayer, "pMHE1Layer", lMHE, 0, i + cmsEndcap.cmsSHE.FHE.n, true); } // // // // // MHE2 Part // G4double fullMHE2LayerZ = cmsEndcap.cmsSHE.MHE2.fullAbsZ + cmsEndcap.cmsSHE.MHE2.fullActZ; G4double fullMHE2ModuleZ = cmsEndcap.cmsSHE.MHE2.n*fullMHE2LayerZ; cmsEndcap.cmsSHE.MHE2.centerZ = cmsEndcap.cmsSHE.startZ + fullEMModuleZ + fullFHEModuleZ + fullMHE1ModuleZ + fullMHE2ModuleZ/2.; cmsEndcap.cmsSHE.MHE2.rmin1 = cmsEndcap.cmsSHE.MHE1.rmin2; cmsEndcap.cmsSHE.MHE2.rmin2 = Getr2( cmsEndcap.cmsSHE.MHE2.rmin1, cmsEndcap.cmsSHE.MHE2.centerZ - fullMHE2ModuleZ/2., cmsEndcap.cmsSHE.MHE2.centerZ + fullMHE2ModuleZ/2.); cmsEndcap.cmsSHE.MHE2.rmax2 = cmsEndcap.cmsSHE.MHE2.rmax1; // // MHE2 debug Section // G4cout << "### SHE::MHE2 Location: " << cmsEndcap.cmsSHE.MHE2.centerZ/cm << " Dimensions: " << fullMHE2ModuleZ/cm << " " << cmsEndcap.cmsSHE.MHE2.rmin1/cm << " " << cmsEndcap.cmsSHE.MHE2.rmax1/cm << " " << cmsEndcap.cmsSHE.MHE2.rmin2/cm << " " << cmsEndcap.cmsSHE.MHE2.rmax2/cm << G4endl << "### SHE::MHE2::Layer Dimensions: " << fullMHE2LayerZ/cm << G4endl << "### SHE::MHE2::Abs Dimensions: " << cmsEndcap.cmsSHE.MHE2.fullAbsZ/cm << cmsEndcap.cmsSHE.MHE2.absMat << G4endl << "### SHE::MHE2::Act Dimensions: " << cmsEndcap.cmsSHE.MHE2.fullActZ/cm << G4endl; // // Build FHE(Front HE...) // sMHE = new G4Cons("sMHE2", cmsEndcap.cmsSHE.MHE2.rmin1, cmsEndcap.cmsSHE.MHE2.rmax1, cmsEndcap.cmsSHE.MHE2.rmin2, cmsEndcap.cmsSHE.MHE2.rmax2, fullMHE2ModuleZ/2., 0, 360*deg); cmsEndcap.cmsSHE.MHE2.totalZ = fullMHE2ModuleZ; lMHE = new G4LogicalVolume(sMHE, mVacuum, "lMHE2"); zpos = cmsEndcap.cmsSHE.MHE2.centerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lMHE, "pMHE2", logicWorld, 0, HEPCOPYID, true); transform = G4Transform3D(rotation, G4ThreeVector(0, 0, -zpos)); new G4PVPlacement(transform, lMHE, "pMHE2", logicWorld, 0, HEMCOPYID, true); // // Additional Dimensions/Variables for FHE // z1 = cmsEndcap.cmsSHE.MHE2.centerZ - fullMHE2ModuleZ/2.; zref = z1; z2 = z1; rmin1 = cmsEndcap.cmsSHE.MHE2.rmin1; rmax1 = cmsEndcap.cmsSHE.MHE2.rmax1; rmin2 = rmin1; rmax2 = rmax1; // // BUILDING // for (int i=0; i<cmsEndcap.cmsSHE.MHE2.n; i++) { z1 = z2; rmin1 = rmin2; rmax1 = rmax2; z2 += fullMHE1LayerZ; rmin2 = Getr2(rmin1, z1, z2); rmax2 = rmax1; // rmax2 = rmax1 + (z2-z1)*tang; absz1 = z1; absz2 = absz1 + cmsEndcap.cmsSHE.MHE2.fullAbsZ; absrmin1 = rmin1; absrmax1 = rmax1; absrmin2 = Getr2(absrmin1, absz1, absz2); absrmax2 = absrmax1; // absrmax2 = absrmax1 + (absz2 - absz1)*tang; actz1 = absz2; actz2 = actz1 + cmsEndcap.cmsSHE.MHE2.fullActZ; actrmin1 = absrmin2; actrmax1 = absrmax2; actrmin2 = Getr2(actrmin1, actz1, actz2); actrmax2 = actrmax1; // actrmax2 = actrmax1 + (actz2 - actz1)*tang; // // Create a Layer // G4Cons *sLayer = new G4Cons("sMHE2Layer", rmin1, rmax1, rmin2, rmax2, fullMHE2LayerZ/2., 0, 360*deg); G4LogicalVolume *lLayer = new G4LogicalVolume(sLayer, mVacuum, "sMHE2Layer"); // // Build Abs // G4Cons *sAbs = new G4Cons("sMHE2Abs", absrmin1, absrmax1, absrmin2, absrmax2, cmsEndcap.cmsSHE.MHE2.fullAbsZ/2., 0, 360*deg); G4LogicalVolume *lAbs = new G4LogicalVolume(sAbs, cmsEndcap.cmsSHE.MHE2.absMat, "sMHE2Abs"); zpos = -fullMHE2LayerZ/2. + cmsEndcap.cmsSHE.MHE2.fullAbsZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAbs, "pMHE2Abs", lLayer, 0, 0, true); // // Build the Active Material // G4Cons *sAct = new G4Cons("sMHE2Act", actrmin1, actrmax1, actrmin2, actrmax2, cmsEndcap.cmsSHE.MHE2.fullActZ/2., 0, 360*deg); G4LogicalVolume *lAct = new G4LogicalVolume(sAct, mHEScintMain, "lMHE2Act", 0, heSD, 0); zpos += cmsEndcap.cmsSHE.MHE2.fullAbsZ/2. + cmsEndcap.cmsSHE.MHE2.fullActZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAct, "pMHE2Act", lLayer, 0, 0, true); // // Place the Layer // zpos = -fullMHE2ModuleZ/2. + (i + 0.5)*fullMHE2LayerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lLayer, "pMHE2Layer", lMHE, 0, i + cmsEndcap.cmsSHE.FHE.n + cmsEndcap.cmsSHE.MHE1.n, true); } // // // // // BHE Part - Back HE Part // smaller outer constant radius // G4double fullBHELayerZ = cmsEndcap.cmsSHE.BHE.fullAbsZ + cmsEndcap.cmsSHE.BHE.fullActZ; G4double fullBHEModuleZ = cmsEndcap.cmsSHE.BHE.n*fullBHELayerZ; cmsEndcap.cmsSHE.BHE.centerZ = cmsEndcap.cmsSHE.startZ + fullEMModuleZ + fullFHEModuleZ + fullMHE1ModuleZ + fullMHE2ModuleZ + fullBHEModuleZ/2.; cmsEndcap.cmsSHE.BHE.rmin1 = cmsEndcap.cmsSHE.MHE2.rmin2; cmsEndcap.cmsSHE.BHE.rmin2 = Getr2( cmsEndcap.cmsSHE.BHE.rmin1, cmsEndcap.cmsSHE.BHE.centerZ - fullBHEModuleZ/2., cmsEndcap.cmsSHE.BHE.centerZ + fullBHEModuleZ/2.); cmsEndcap.cmsSHE.BHE.rmax2 = cmsEndcap.cmsSHE.BHE.rmax1; // // BHE debug Section // G4cout << "### SHE::BHE Location: " << cmsEndcap.cmsSHE.BHE.centerZ/cm << " Dimensions: " << fullBHEModuleZ/cm << " " << cmsEndcap.cmsSHE.BHE.rmin1/cm << " " << cmsEndcap.cmsSHE.BHE.rmax1/cm << " " << cmsEndcap.cmsSHE.BHE.rmin2/cm << " " << cmsEndcap.cmsSHE.BHE.rmax2/cm << G4endl << "### SHE::BHE::Layer Dimensions: " << fullBHELayerZ/cm << G4endl << "### SHE::BHE::Abs Dimensions: " << cmsEndcap.cmsSHE.BHE.fullAbsZ/cm << cmsEndcap.cmsSHE.BHE.absMat << G4endl << "### SHE::BHE::Act Dimensions: " << cmsEndcap.cmsSHE.BHE.fullActZ/cm << G4endl; // // Build FHE(Front HE...) // G4Cons *sBHE = new G4Cons("sBHE", cmsEndcap.cmsSHE.BHE.rmin1, cmsEndcap.cmsSHE.BHE.rmax1, cmsEndcap.cmsSHE.BHE.rmin2, cmsEndcap.cmsSHE.BHE.rmax2, fullBHEModuleZ/2., 0, 360*deg); cmsEndcap.cmsSHE.BHE.totalZ = fullBHEModuleZ; G4LogicalVolume *lBHE = new G4LogicalVolume(sBHE, mVacuum, "lBHE"); zpos = cmsEndcap.cmsSHE.BHE.centerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lBHE, "pBHE", logicWorld, 0, HEPCOPYID, true); transform = G4Transform3D(rotation, G4ThreeVector(0, 0, -zpos)); new G4PVPlacement(transform, lBHE, "pBHE", logicWorld, 0, HEMCOPYID, true); // // Additional Dimensions/Variables for FHE // z1 = cmsEndcap.cmsSHE.BHE.centerZ - fullBHEModuleZ/2.; zref = z1; z2 = z1; rmin1 = cmsEndcap.cmsSHE.BHE.rmin1; rmax1 = cmsEndcap.cmsSHE.BHE.rmax1; rmin2 = rmin1; rmax2 = rmax1; // G4double tang = (cmsEndcap.cmsSHE.MHE1.rmax2 - cmsEndcap.cmsSHE.MHE1.rmax1)/ // fullMHE1ModuleZ; // // BUILDING // for (int i=0; i<cmsEndcap.cmsSHE.BHE.n; i++) { z1 = z2; rmin1 = rmin2; rmax1 = rmax2; z2 += fullBHELayerZ; rmin2 = Getr2(rmin1, z1, z2); rmax2 = rmax1; // rmax2 = rmax1 + (z2-z1)*tang; absz1 = z1; absz2 = absz1 + cmsEndcap.cmsSHE.BHE.fullAbsZ; absrmin1 = rmin1; absrmax1 = rmax1; absrmin2 = Getr2(absrmin1, absz1, absz2); absrmax2 = absrmax1; // absrmax2 = absrmax1 + (absz2 - absz1)*tang; actz1 = absz2; actz2 = actz1 + cmsEndcap.cmsSHE.BHE.fullActZ; actrmin1 = absrmin2; actrmax1 = absrmax2; actrmin2 = Getr2(actrmin1, actz1, actz2); actrmax2 = actrmax1; // actrmax2 = actrmax1 + (actz2 - actz1)*tang; // // Create a Layer // G4Cons *sLayer = new G4Cons("sBHELayer", rmin1, rmax1, rmin2, rmax2, fullBHELayerZ/2., 0, 360*deg); G4LogicalVolume *lLayer = new G4LogicalVolume(sLayer, mVacuum, "sBHELayer"); // // Build Abs // G4Cons *sAbs = new G4Cons("sBHEAbs", absrmin1, absrmax1, absrmin2, absrmax2, cmsEndcap.cmsSHE.BHE.fullAbsZ/2., 0, 360*deg); G4LogicalVolume *lAbs = new G4LogicalVolume(sAbs, cmsEndcap.cmsSHE.BHE.absMat, "sBHEAbs"); zpos = -fullBHELayerZ/2. + cmsEndcap.cmsSHE.BHE.fullAbsZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAbs, "pBHEAbs", lLayer, 0, 0, true); // // Build the Active Material // G4Cons *sAct = new G4Cons("sBHEAct", actrmin1, actrmax1, actrmin2, actrmax2, cmsEndcap.cmsSHE.BHE.fullActZ/2., 0, 360*deg); G4LogicalVolume *lAct = new G4LogicalVolume(sAct, mHEScintMain, "lBHEAct", 0, heSD, 0); zpos += cmsEndcap.cmsSHE.BHE.fullAbsZ/2. + cmsEndcap.cmsSHE.BHE.fullActZ/2.; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lAct, "pBHEAct", lLayer, 0, 0, true); // // Place the Layer // zpos = -fullBHEModuleZ/2. + (i + 0.5)*fullBHELayerZ; new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), lLayer, "pBHELayer", lBHE, 0, i + cmsEndcap.cmsSHE.FHE.n + cmsEndcap.cmsSHE.MHE1.n + cmsEndcap.cmsSHE.MHE2.n, true); } // // Push the geometry information // _readout->PushGeomInfo(cmsEndcap.cmsSHE); G4cout << "### Total Z-Dimensions: EM: " << cmsEndcap.cmsSHE.EM.totalZ/mm << " HE: " << cmsEndcap.cmsSHE.FHE.totalZ/mm + cmsEndcap.cmsSHE.MHE1.totalZ/mm + cmsEndcap.cmsSHE.MHE2.totalZ/mm + cmsEndcap.cmsSHE.BHE.totalZ/mm << endl; return 1; } // // Config the geometry of Shashlik + HE scenario // int SHDetectorConstruction::ConfigShashlikPlusHE() { cout << "### Configuring SHE Input..." << endl; // // Check the file // ifstream sheFile(runParams.endcapConfigFileName); if (!sheFile) { cout << "### ERROR: file " << runParams.endcapConfigFileName << " hasn't been found!!!" << endl; return -1; } // // Read in/Config. All dimensions must be in mm // double z; int n; int iMat; double startz; double rmin1, rmax1, rmin2, rmax2; int onOff; // // CMSEndcap starting position // sheFile >> startz; cmsEndcap.cmsSHE.startZ = startz*mm; // // EM Part: Shashlik // Basic Dimensions: center wrt the World is provided with the startz // for the whole endcap + basic dimensions of Abs + Act. // sheFile >> n >> iMat >> onOff; cmsEndcap.cmsSHE.EM.n = n; cmsEndcap.cmsSHE.EM.iMat= iMat; cmsEndcap.cmsSHE.EM.onOff = onOff; if (cmsEndcap.cmsSHE.EM.iMat == 1) cmsEndcap.cmsSHE.EM.absMat = mW; else cout << "### SHASHLIK ABS Material is UNKNOWN!" << endl; sheFile >> rmin1 >> rmax1; cmsEndcap.cmsSHE.EM.rmin1 = rmin1*mm; cmsEndcap.cmsSHE.EM.rmax1 = rmax1*mm; sheFile >> z; cmsEndcap.cmsSHE.EM.fullAbsZ = z*mm; sheFile >> z; cmsEndcap.cmsSHE.EM.fullActZ = z*mm; // // HE Part: FHE - Front H // Basic Dimensinos: center wrt the World is provided with the startz // + // sheFile >> n >> iMat; cmsEndcap.cmsSHE.FHE.n = n; cmsEndcap.cmsSHE.FHE.iMat = iMat; if (cmsEndcap.cmsSHE.FHE.iMat == 1) cmsEndcap.cmsSHE.FHE.absMat = mBrass; else cout << "### HE ABS Material is UNKNOWN!" << endl; sheFile >> z; cmsEndcap.cmsSHE.FHE.fullAbsZ = z*mm; sheFile >> z; cmsEndcap.cmsSHE.FHE.fullActZ = z*mm; // // Middle HE1 Part with a "special" incline // sheFile >> n >> iMat; cmsEndcap.cmsSHE.MHE1.n = n; cmsEndcap.cmsSHE.MHE1.iMat = iMat; if (cmsEndcap.cmsSHE.MHE1.iMat == 1) cmsEndcap.cmsSHE.MHE1.absMat = mBrass; else cout << "### HE ABS MAterial is UNKNOWN!" << endl; sheFile >> z; cmsEndcap.cmsSHE.MHE1.fullAbsZ = z*mm; sheFile >> z; cmsEndcap.cmsSHE.MHE1.fullActZ = z*mm; // // Middle HE2 Part with a constant outer radius // sheFile >> n >> iMat; cmsEndcap.cmsSHE.MHE2.n = n; cmsEndcap.cmsSHE.MHE2.iMat = iMat; if (cmsEndcap.cmsSHE.MHE2.iMat == 1) cmsEndcap.cmsSHE.MHE2.absMat = mBrass; else cout << "### HE ABS material is UNKNOWN!" << endl; sheFile >> rmax1; cmsEndcap.cmsSHE.MHE2.rmax1 = rmax1*mm; sheFile >> z; cmsEndcap.cmsSHE.MHE2.fullAbsZ = z*mm; sheFile >> z; cmsEndcap.cmsSHE.MHE2.fullActZ = z*mm; // // Back HE Part wit ha constant outer radius, but smaller than for HE2 part // sheFile >> n >> iMat; cmsEndcap.cmsSHE.BHE.n = n; cmsEndcap.cmsSHE.BHE.absMat = mBrass; if (cmsEndcap.cmsSHE.BHE.iMat == 1) cmsEndcap.cmsSHE.BHE.absMat = mBrass; else cout << "### HE ABS Material is UNKNOWN!" << endl; sheFile >> rmax1; cmsEndcap.cmsSHE.BHE.rmax1 = rmax1*mm; sheFile >> z; cmsEndcap.cmsSHE.BHE.fullAbsZ = z*mm; sheFile >> z; cmsEndcap.cmsSHE.BHE.fullActZ = z*mm; return 1; } // // All the Functions from this point are from previous versions.... // They aren't being used!!! // /* * Building the Shashlik itself */ void SHDetectorConstruction::BuildShashlik() { // SD // G4SDManager *SDManager = G4SDManager::GetSDMpointer(); SHSDCounter *SD = new SHSDCounter("data", runParams, shTree); SDManager->AddNewDetector(SD); // Place the Container first // solidShashlikContainer = new G4Box("solidShashlikContainer", fullShashlikContainerX/2., fullShashlikContainerY/2., fullShashlikContainerZ/2.); logicShashlikContainer = new G4LogicalVolume(solidShashlikContainer, mVacuum, "logicShashlikContainer", 0, 0, 0); physShashlikContainer = new G4PVPlacement(0, G4ThreeVector(), logicShashlikContainer, "physShashlikContainer", logicWorld, 0, 0, true); // Place the Shashlik Module // solidShashlik = new G4Box("solidShashlik", fullShashlikX/2.0, fullShashlikY/2., fullShashlikZ/2.); logicShashlik = new G4LogicalVolume(solidShashlik, mVacuum, "logicShashlik", 0, 0, 0); for (int iModuleX=0; iModuleX<runParams.numModules; iModuleX++) { G4double xpos = -fullShashlikContainerX/2. + fullShashlikX*(iModuleX + 0.5) + iModuleX*fullGapX; for (int iModuleY=0; iModuleY<runParams.numModules; iModuleY++) { G4double ypos = -fullShashlikContainerY/2. + fullShashlikY*(iModuleY + 0.5) + iModuleY*fullGapY; physShashlik = new G4PVPlacement(0, G4ThreeVector(xpos, ypos, 0), logicShashlik, "physShashlik", logicShashlikContainer, 0, 2*iModuleX + iModuleY, true); } } // Build the Layer Up without placing it... // solidLayer = new G4Box("solidLayer", fullLayerX/2., fullLayerY/2., fullLayerZ/2); logicLayer = new G4LogicalVolume(solidLayer, mVacuum, "logicLayer", 0, 0, 0); // Build the Abs Part and place it inside the Layer // solidAbs = new G4Box("solidAbs", fullAbsX/2., fullAbsY/2., fullAbsZ/2.); logicAbs = new G4LogicalVolume(solidAbs, mW, "logicAbs", 0, 0, 0); physAbs = new G4PVPlacement(0, G4ThreeVector(0, 0, -fullLayerZ/2. + fullAbsZ/2), logicAbs, "physAbs", logicLayer, 0, 0, true); // Build and place AbsFibers inside the Abs // 4 Placements // solidAbsFiber = new G4Tubs("solidAbsFiber", inRFiber, outRFiber, fullAbsFiberZ/2., 0, 360*deg); logicAbsFiber = new G4LogicalVolume(solidAbsFiber, mSiO2, "logicAbsFiber", 0, SD, 0); for (int i=0; i<=1; i++) { G4double xpos = -0.5*fullAbsX + 0.25*fullAbsX + i*0.5*fullAbsX; for (int j=0; j<=1; j++) { G4double ypos = -0.5*fullAbsY + 0.25*fullAbsY + j*0.5*fullAbsY; physAbsFiber = new G4PVPlacement(0, G4ThreeVector(xpos, ypos, 0), logicAbsFiber, "physAbsFiber", logicAbs, 0, 2*i+j, true); } } // Build the Act Part and place it inside the Layer // solidAct = new G4Box("solidAct", fullActX/2., fullActY/2., fullActZ/2.); logicAct = new G4LogicalVolume(solidAct, mLYSO, "logicAct", 0, SD, 0); physAct = new G4PVPlacement(0, G4ThreeVector(0, 0, -fullLayerZ/2. + fullAbsZ + fullActZ/2.), logicAct, "physAct", logicLayer, 0, 0, true); // Build and place ActFibers inside the Act // 4 Placements // solidActFiber = new G4Tubs("solidActFiber", inRFiber, outRFiber, fullActFiberZ/2., 0, 360*deg); logicActFiber = new G4LogicalVolume(solidActFiber, mSiO2, "logicActFiber", 0, SD, 0); for (int i=0; i<=1; i++) { G4double xpos = -0.5*fullActX + 0.25*fullActX + i*0.5*fullActX; for (int j=0; j<=1; j++) { G4double ypos = -0.5*fullActY + 0.25*fullActY + j*0.5*fullActY; physActFiber = new G4PVPlacement(0, G4ThreeVector(xpos, ypos,0), logicActFiber, "physActFiber", logicAct, 0, 2*i+j, true); } } // A single Layer has been Built, but NOT Placed!!! // Place all of them // for (int iLayer=0; iLayer<runParams.numLayers; iLayer++) { G4double zpos = -fullShashlikZ/2.+ fullActZ + fullLayerZ*(iLayer + 0.5); physLayer = new G4PVPlacement(0, G4ThreeVector(0,0,zpos), logicLayer, "physLayer", logicShashlik, 0, iLayer, true); } // Note: We put Abs first into the module, but the number of LYSO plates // should be more by 1 ===>>> place a LYSO just inside the Shashlik. // NOTE: We arrange a spot for that just above // physAct = new G4PVPlacement(0, G4ThreeVector(0,0, -fullShashlikZ/2. + fullActZ/2.), logicAct, "physAct", logicShashlik, 0, runParams.numLayers, true); // Optical Surgace for the Shashlik's LYSO // /* G4OpticalSurface *opShashlikSurface = new G4OpticalSurface("ShashlikSurface"); opShashlikSurface->SetType(dielectric_metal); opShashlikSurface->SetFinish(polishedtyvekair); opShashlikSurface->SetModel(glisur); G4MaterialPropertiesTable *mptSurface = new G4MaterialPropertiesTable(); G4double reflectivity[2] = {1.0, 1.0}; G4double photonEnergy[2] = {1.5*eV, 6.2*eV}; mptSurface->AddProperty("REFLECTIVITY", photonEnergy, reflectivity, 2); opShashlikSurface->SetMaterialPropertiesTable(mptSurface); G4LogicalSkinSurface *skinSurface = new G4LogicalSkinSurface("Skin", logicAct, opShashlikSurface); */ return; }// end of BuildShashlik /* * Build HGCAL */ void SHDetectorConstruction::BuildHGCal() { // SD // G4SDManager *SDManager = G4SDManager::GetSDMpointer(); HGSDCounter *EMSD = new HGSDCounter("EMSD", runParams, _emTree); HGSDCounter *FHSD = new HGSDCounter("FHSD", runParams, _fhTree); HGSDCounter *BHSD = new HGSDCounter("BHSD", runParams, _bhTree); SDManager->AddNewDetector(EMSD); SDManager->AddNewDetector(FHSD); SDManager->AddNewDetector(BHSD); // Limit the step size inside the SDs // // G4UserLimits *sdLimits = new G4UserLimits( // hgcParameters.em.fullEMPadXYZ[2]); // Read in the Input Parameters for HGCAL // ReadHGConfigFile(); // Additional Dimensions for EM Part // G4double fullEMLayerX_1 = hgcParameters.em.fullEMAbsXYZ[0]; G4double fullEMLayerY_1 = hgcParameters.em.fullEMAbsXYZ[1]; G4double fullEMLayerZ_1 = hgcParameters.em.fullEMAbsXYZ[2] + hgcParameters.em.fullEMPadXYZ[2] + hgcParameters.em.fullEMPadReadoutXYZ[2]; G4double fullEMLayerX_2 = hgcParameters.em.fullEMAbsXYZ[0]; G4double fullEMLayerY_2 = hgcParameters.em.fullEMAbsXYZ[1]; G4double fullEMLayerZ_2 = hgcParameters.em.fullEMAbsXYZ[3] + hgcParameters.em.fullEMPadXYZ[2] + hgcParameters.em.fullEMPadReadoutXYZ[2]; G4double fullEMLayerX_3 = hgcParameters.em.fullEMAbsXYZ[0]; G4double fullEMLayerY_3 = hgcParameters.em.fullEMAbsXYZ[1]; G4double fullEMLayerZ_3 = hgcParameters.em.fullEMAbsXYZ[4] + hgcParameters.em.fullEMPadXYZ[2] + hgcParameters.em.fullEMPadReadoutXYZ[2]; int nPadsX_1 = fullEMLayerX_1/hgcParameters.em.fullEMPadXYZ[0]; int nPadsY_1 = fullEMLayerY_1/hgcParameters.em.fullEMPadXYZ[1]; int nPadsX_2 = fullEMLayerX_1/hgcParameters.em.fullEMPadXYZ[3]; int nPadsY_2 = fullEMLayerY_1/hgcParameters.em.fullEMPadXYZ[4]; G4double fullEMPadLayerX = fullEMLayerX_1; G4double fullEMPadLayerY = fullEMLayerY_1; G4double fullEMPadLayerZ = hgcParameters.em.fullEMPadXYZ[2]; G4double fullEMModuleX = fullEMLayerX_1; G4double fullEMModuleY = fullEMLayerY_1; G4double fullEMModuleZ = hgcParameters.em.nLayers_1*fullEMLayerZ_1 + hgcParameters.em.nLayers_2*fullEMLayerZ_2 + hgcParameters.em.nLayers_3*fullEMLayerZ_3; // Additional Dimensions for Front HCal Part // G4double fullFHLayerX = hgcParameters.fh.fullFHAbsXYZ[0]; G4double fullFHLayerY = hgcParameters.fh.fullFHAbsXYZ[1]; G4double fullFHLayerZ = hgcParameters.fh.fullFHAbsXYZ[2] + hgcParameters.fh.fullFHPadXYZ[2] + hgcParameters.fh.fullFHPadReadoutXYZ[2]; int nFHPadsX = fullFHLayerX/hgcParameters.fh.fullFHPadXYZ[0]; int nFHPadsY = fullFHLayerY/hgcParameters.fh.fullFHPadXYZ[1]; G4double fullFHPadLayerX = fullFHLayerX; G4double fullFHPadLayerY = fullFHLayerY; G4double fullFHPadLayerZ = hgcParameters.fh.fullFHPadXYZ[2]; G4double fullFHModuleX = fullFHLayerX; G4double fullFHModuleY = fullFHLayerY; G4double fullFHModuleZ = hgcParameters.fh.nLayers_Total*fullFHLayerZ; // Additional Dimensions for Back HCal part // G4double fullBHLayerX = hgcParameters.bh.fullBHAbsXYZ[0]; G4double fullBHLayerY = hgcParameters.bh.fullBHAbsXYZ[1]; G4double fullBHLayerZ = hgcParameters.bh.fullBHAbsXYZ[2] + hgcParameters.bh.fullBHPadXYZ[2] + hgcParameters.bh.fullBHPadReadoutXYZ[2]; int nBHPadsX = fullBHLayerX/hgcParameters.bh.fullBHPadXYZ[0]; int nBHPadsY = fullBHLayerY/hgcParameters.bh.fullBHPadXYZ[1]; G4double fullBHPadLayerX = fullBHLayerX; G4double fullBHPadLayerY = fullBHLayerY; G4double fullBHPadLayerZ = hgcParameters.bh.fullBHPadXYZ[2]; G4double fullBHModuleX = fullBHLayerX; G4double fullBHModuleY = fullBHLayerY; G4double fullBHModuleZ = hgcParameters.bh.nLayers_Total*fullBHLayerZ; G4double fullHGCalX = fullBHModuleX; G4double fullHGCalY = fullBHModuleY; // G4double fullHGCalZ = 2.*m; G4double fullHGCalZ = fullEMModuleZ + fullFHModuleZ + fullBHModuleZ; // // Section for Debug Purposes: Print all the Dimensions // G4cout << "### HGCAl: " << fullHGCalX/cm << " " << fullHGCalY/cm << " " << fullHGCalZ/cm << G4endl << "### Parameters: " << hgcParameters.em.nLayers_Total << " " << hgcParameters.em.nLayers_1 << " " << hgcParameters.em.nLayers_2 << " " << hgcParameters.em.nLayers_3 << " " << hgcParameters.em.iAbsMaterial << G4endl << "### EM: " << fullEMModuleX/cm << " " << fullEMModuleY/cm << " " << fullEMModuleZ/cm << G4endl << "### EM: Layer_1: " << fullEMLayerX_1/cm << " " << fullEMLayerY_1/cm << " " << fullEMLayerZ_1/cm << G4endl << "### EM: Layer_1: Abs: " << hgcParameters.em.fullEMAbsXYZ[0]/cm << " " << hgcParameters.em.fullEMAbsXYZ[1]/cm << " " << hgcParameters.em.fullEMAbsXYZ[2]/cm << G4endl << "### EM: Layer_1: PadLayer: " << fullEMPadLayerX/cm << " " << fullEMPadLayerY/cm << " " << fullEMPadLayerZ/cm << G4endl << "### EM: Layer_1: PadReadout: " << hgcParameters.em.fullEMPadReadoutXYZ[0]/cm << " " << hgcParameters.em.fullEMPadReadoutXYZ[1]/cm << " " << hgcParameters.em.fullEMPadReadoutXYZ[2]/cm << G4endl << "### EM: Layer_2: " << fullEMLayerX_2/cm << " " << fullEMLayerY_2/cm << " " << fullEMLayerZ_2/cm << G4endl << "### EM: Layer_3: " << fullEMLayerX_3/cm << " " << fullEMLayerY_3/cm << " " << fullEMLayerZ_3/cm << G4endl << "### FH: " << fullFHModuleX/cm << " " << fullFHModuleY/cm << " " << fullFHModuleZ/cm << G4endl << "### Parameters: " << hgcParameters.fh.nLayers_Total << " " << hgcParameters.fh.iAbsMaterial << G4endl << "### FH: Layer: " << fullFHLayerX/cm << " " << fullFHLayerY/cm << " " << fullFHLayerZ/cm << G4endl << "### BH: " << fullBHModuleX/cm << " " << fullBHModuleY/cm << " " << fullBHModuleZ/cm << G4endl << "### Parameters: " << hgcParameters.bh.nLayers_Total << " " << hgcParameters.bh.iAbsMaterial << G4endl << "### BH: Layer: " << fullBHLayerX/cm << " " << fullBHLayerY/cm << " " << fullBHLayerZ/cm << G4endl; cout << "### HERE: " << fullHGCalX/cm << " " << fullHGCalY/cm << " " << fullHGCalZ/cm << endl; cout << "### HERE: " << fullWorldX/cm << " " << fullWorldY/cm << " " << fullWorldZ/cm << endl; // Place the Whole HGCAL first // solidHGCal = new G4Box("solidHGCal", fullHGCalX/2., fullHGCalY/2., fullHGCalZ/2.); logicHGCal = new G4LogicalVolume(solidHGCal, mVacuum, "logicHGCal"); physHGCal = new G4PVPlacement(0, G4ThreeVector(0, 0, 0), logicHGCal, "physHGCal", logicWorld, 0, 0, true); // Build the EM Part // solidHG_EMModule = new G4Box("solidHG_EMModule", fullEMModuleX/2., fullEMModuleY/2., fullEMModuleZ/2.); logicHG_EMModule = new G4LogicalVolume(solidHG_EMModule, mVacuum, "logicHG_EMModule"); G4double zpos = -fullHGCalZ/2. + fullEMModuleZ/2; if (hgcParameters.emOnOff) physHG_EMModule = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_EMModule, "physHG_EMModule", logicHGCal, 0, 0, true); // // There are 3 sections for EM part // See pdf for specifics // // First Part of EM; // solidHG_EMLayer[0] = new G4Box("solidHG_EMLayer_1", fullEMLayerX_1/2., fullEMLayerY_1/2., fullEMLayerZ_1/2.); logicHG_EMLayer[0] = new G4LogicalVolume(solidHG_EMLayer[0], mVacuum, "logicHG_EMLayer_1"); solidHG_EMAbs[0] = new G4Box("solidHG_EMAbs_1", hgcParameters.em.fullEMAbsXYZ[0]/2., hgcParameters.em.fullEMAbsXYZ[1]/2., hgcParameters.em.fullEMAbsXYZ[2]/2.); logicHG_EMAbs[0] = new G4LogicalVolume(solidHG_EMAbs[0], mEMAbsMat, "logicHG_EMAbs_1"); zpos = -fullEMLayerZ_1/2. + hgcParameters.em.fullEMAbsXYZ[2]/2.; physHG_EMAbs = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_EMAbs[0], "phys_HF_EMAbs", logicHG_EMLayer[0], 0, 0, true); solidHG_EMPadLayer = new G4Box("solidHG_EMPadLayer", fullEMPadLayerX/2., fullEMPadLayerY/2., fullEMPadLayerZ/2.); logicHG_EMPadLayer = new G4LogicalVolume(solidHG_EMPadLayer, mSi, "logicHG_EMPadLayer", 0, EMSD, 0); // logicHG_EMPadLayer->SetUserLimits(sdLimits); zpos = -fullEMLayerZ_1/2. + hgcParameters.em.fullEMAbsXYZ[2] + fullEMPadLayerZ/2.; physHG_EMPadLayer = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_EMPadLayer, "physHG_EMPadLayer", logicHG_EMLayer[0], 0, 0, true); solidHG_EMPadReadout = new G4Box("solidHG_EMPadReadout", hgcParameters.em.fullEMPadReadoutXYZ[0]/2., hgcParameters.em.fullEMPadReadoutXYZ[1]/2., hgcParameters.em.fullEMPadReadoutXYZ[2]/2.); logicHG_EMPadReadout = new G4LogicalVolume(solidHG_EMPadReadout, mElectronicsMat, "logicHG_EMPadReadout"); zpos = -fullEMLayerZ_1/2. + hgcParameters.em.fullEMAbsXYZ[2] + fullEMPadLayerZ + hgcParameters.em.fullEMPadReadoutXYZ[2]/2.; physHG_EMPadReadout = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_EMPadReadout, "physHG_EMPadReadout", logicHG_EMLayer[0], 0, 0, true); for (int iLayer=0; iLayer<hgcParameters.em.nLayers_1; iLayer++) { zpos = -fullEMModuleZ/2. + (iLayer + 0.5)*fullEMLayerZ_1; physHG_EMLayer = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_EMLayer[0], "physHG_EMLayer", logicHG_EMModule, 0, iLayer, true); } // Second Part of EM // solidHG_EMLayer[1] = new G4Box("solidHG_EMLayer_2", fullEMLayerX_2/2., fullEMLayerY_2/2., fullEMLayerZ_2/2.); logicHG_EMLayer[1] = new G4LogicalVolume(solidHG_EMLayer[1], mVacuum, "logicHG_EMLayer_2"); solidHG_EMAbs[1] = new G4Box("solidHG_EMAbs_2", hgcParameters.em.fullEMAbsXYZ[0]/2., hgcParameters.em.fullEMAbsXYZ[1]/2., hgcParameters.em.fullEMAbsXYZ[3]/2.); logicHG_EMAbs[1] = new G4LogicalVolume(solidHG_EMAbs[1], mEMAbsMat, "logicHG_EMAbs_2"); zpos = -fullEMLayerZ_2/2. + hgcParameters.em.fullEMAbsXYZ[3]/2.; physHG_EMAbs = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_EMAbs[1], "phys_HF_EMAbs", logicHG_EMLayer[1], 0, 0, true); solidHG_EMPadLayer = new G4Box("solidHG_EMPadLayer", fullEMPadLayerX/2., fullEMPadLayerY/2., fullEMPadLayerZ/2.); logicHG_EMPadLayer = new G4LogicalVolume(solidHG_EMPadLayer, mSi, "logicHG_EMPadLayer", 0, EMSD, 0); // logicHG_EMPadLayer->SetUserLimits(sdLimits); zpos = -fullEMLayerZ_2/2. + hgcParameters.em.fullEMAbsXYZ[3] + fullEMPadLayerZ/2.; physHG_EMPadLayer = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_EMPadLayer, "physHG_EMPadLayer", logicHG_EMLayer[1], 0, 0, true); solidHG_EMPadReadout = new G4Box("solidHG_EMPadReadout", hgcParameters.em.fullEMPadReadoutXYZ[0]/2., hgcParameters.em.fullEMPadReadoutXYZ[1]/2., hgcParameters.em.fullEMPadReadoutXYZ[2]/2.); logicHG_EMPadReadout = new G4LogicalVolume(solidHG_EMPadReadout, mElectronicsMat, "logicHG_EMPadReadout"); zpos = -fullEMLayerZ_2/2. + hgcParameters.em.fullEMAbsXYZ[3] + fullEMPadLayerZ + hgcParameters.em.fullEMPadReadoutXYZ[2]/2.; physHG_EMPadReadout = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_EMPadReadout, "physHG_EMPadReadout", logicHG_EMLayer[1], 0, 0, true); for (int iLayer=0; iLayer<hgcParameters.em.nLayers_2; iLayer++) { zpos = -fullEMModuleZ/2. + hgcParameters.em.nLayers_1*fullEMLayerZ_1 + (iLayer + 0.5)*fullEMLayerZ_2; physHG_EMLayer = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_EMLayer[1], "physHG_EMLayer", logicHG_EMModule, 0, iLayer+hgcParameters.em.nLayers_1, true); } // Third part of EM // solidHG_EMLayer[2] = new G4Box("solidHG_EMLayer_3", fullEMLayerX_3/2., fullEMLayerY_3/2., fullEMLayerZ_3/2.); logicHG_EMLayer[2] = new G4LogicalVolume(solidHG_EMLayer[2], mVacuum, "logicHG_EMLayer_3"); solidHG_EMAbs[2] = new G4Box("solidHG_EMAbs_3", hgcParameters.em.fullEMAbsXYZ[0]/2., hgcParameters.em.fullEMAbsXYZ[1]/2., hgcParameters.em.fullEMAbsXYZ[4]/2.); logicHG_EMAbs[2] = new G4LogicalVolume(solidHG_EMAbs[2], mEMAbsMat, "logicHG_EMAbs_3"); zpos = -fullEMLayerZ_3/2. + hgcParameters.em.fullEMAbsXYZ[4]/2.; physHG_EMAbs = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_EMAbs[2], "phys_HF_EMAbs", logicHG_EMLayer[2], 0, 0, true); solidHG_EMPadLayer = new G4Box("solidHG_EMPadLayer", fullEMPadLayerX/2., fullEMPadLayerY/2., fullEMPadLayerZ/2.); logicHG_EMPadLayer = new G4LogicalVolume(solidHG_EMPadLayer, mSi, "logicHG_EMPadLayer", 0, EMSD, 0); // logicHG_EMPadLayer->SetUserLimits(sdLimits); zpos = -fullEMLayerZ_3/2. + hgcParameters.em.fullEMAbsXYZ[4] + fullEMPadLayerZ/2.; physHG_EMPadLayer = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_EMPadLayer, "physHG_EMPadLayer", logicHG_EMLayer[2], 0, 0, true); solidHG_EMPadReadout = new G4Box("solidHG_EMPadReadout", hgcParameters.em.fullEMPadReadoutXYZ[0]/2., hgcParameters.em.fullEMPadReadoutXYZ[1]/2., hgcParameters.em.fullEMPadReadoutXYZ[2]/2.); logicHG_EMPadReadout = new G4LogicalVolume(solidHG_EMPadReadout, mElectronicsMat, "logicHG_EMPadReadout"); zpos = -fullEMLayerZ_3/2. + hgcParameters.em.fullEMAbsXYZ[4] + fullEMPadLayerZ + hgcParameters.em.fullEMPadReadoutXYZ[2]/2.; physHG_EMPadReadout = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_EMPadReadout, "physHG_EMPadReadout", logicHG_EMLayer[2], 0, 0, true); for (int iLayer=0; iLayer<hgcParameters.em.nLayers_3; iLayer++) { zpos = -fullEMModuleZ/2. + hgcParameters.em.nLayers_1*fullEMLayerZ_1 + hgcParameters.em.nLayers_2*fullEMLayerZ_2 + (iLayer + 0.5)*fullEMLayerZ_3; physHG_EMLayer = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_EMLayer[2], "physHG_EMLayer", logicHG_EMModule, 0, iLayer + hgcParameters.em.nLayers_1 + hgcParameters.em.nLayers_2, true); } // // Place the Front HCAL Part // solidHG_FHModule = new G4Box("solidHG_FHModule", fullFHModuleX/2., fullFHModuleY/2., fullFHModuleZ/2.); logicHG_FHModule = new G4LogicalVolume(solidHG_FHModule, mFHAbsMat, "logicHG_FHModule"); zpos = -fullHGCalZ/2. + fullEMModuleZ + fullFHModuleZ/2.; if (hgcParameters.fhOnOff) physHG_FHModule = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_FHModule, "physHG_FHModule", logicHGCal, 0, 0, true); // Just 1 section // solidHG_FHLayer = new G4Box("solidHG_FHLayer", fullFHLayerX/2., fullFHLayerY/2., fullFHLayerZ/2.); logicHG_FHLayer = new G4LogicalVolume(solidHG_FHLayer, mVacuum, "logicHG_FHLayer"); solidHG_FHAbs = new G4Box("solidHG_FHAbs", hgcParameters.fh.fullFHAbsXYZ[0]/2., hgcParameters.fh.fullFHAbsXYZ[1]/2., hgcParameters.fh.fullFHAbsXYZ[2]/2.); logicHG_FHAbs = new G4LogicalVolume(solidHG_FHAbs, mFHAbsMat, "logicHG_FHAbs"); zpos = -fullFHLayerZ/2. + hgcParameters.fh.fullFHAbsXYZ[2]/2.; physHG_FHAbs = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_FHAbs, "physHG_FHAbs", logicHG_FHLayer, 0, 0, true); solidHG_FHPadLayer = new G4Box("solidHG_FHPadLayer", fullFHPadLayerX/2., fullFHPadLayerY/2., fullFHPadLayerZ/2.); logicHG_FHPadLayer = new G4LogicalVolume(solidHG_FHPadLayer, mSi, "logicHG_FHPadLayer", 0, FHSD, 0); // logicHG_FHPadLayer->SetUserLimits(sdLimits); zpos = -fullFHLayerZ/2. + hgcParameters.fh.fullFHAbsXYZ[2] + fullFHPadLayerZ/2.; physHG_FHPadLayer = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_FHPadLayer, "physHG_FHPadLayer", logicHG_FHLayer, 0,0, true); solidHG_FHPadReadout = new G4Box("solidHG_FHPadReadout", hgcParameters.fh.fullFHPadReadoutXYZ[0]/2., hgcParameters.fh.fullFHPadReadoutXYZ[1]/2., hgcParameters.fh.fullFHPadReadoutXYZ[2]/2.); logicHG_FHPadReadout = new G4LogicalVolume(solidHG_FHPadReadout, mElectronicsMat, "logicHG_FHPadReadout"); zpos = -fullFHLayerZ/2. + hgcParameters.fh.fullFHAbsXYZ[2] + fullFHPadLayerZ + hgcParameters.fh.fullFHPadReadoutXYZ[2]/2.; physHG_FHPadReadout = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_FHPadReadout, "physHG_FHPadRedout", logicHG_FHLayer, 0, 0, true); for (int iLayer=0; iLayer<hgcParameters.fh.nLayers_Total; iLayer++) { zpos = -fullFHModuleZ/2. + (iLayer + 0.5)*fullFHLayerZ; physHG_FHLayer = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_FHLayer, "physHG_FHLayer", logicHG_FHModule, 0, iLayer + hgcParameters.em.nLayers_Total, true); } // // Place the back HCAL Part // solidHG_BHModule = new G4Box("solidHG_BHModule", fullBHModuleX/2., fullBHModuleY/2., fullBHModuleZ/2.); logicHG_BHModule = new G4LogicalVolume(solidHG_BHModule, mBHAbsMat, "logicHG_BHModule"); zpos = -fullHGCalZ/2. + fullEMModuleZ + fullFHModuleZ + fullBHModuleZ/2.; if (hgcParameters.bhOnOff) physHG_BHModule = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_BHModule, "physHG_BHModule", logicHGCal, 0, 0, true); // Just 1 section // solidHG_BHLayer = new G4Box("solidHG_BHLayer", fullBHLayerX/2., fullBHLayerY/2., fullBHLayerZ/2.); logicHG_BHLayer = new G4LogicalVolume(solidHG_BHLayer, mVacuum, "logicHG_BHLayer"); solidHG_BHAbs = new G4Box("solidHG_BHAbs", hgcParameters.bh.fullBHAbsXYZ[0]/2., hgcParameters.bh.fullBHAbsXYZ[1]/2., hgcParameters.bh.fullBHAbsXYZ[2]/2.); logicHG_BHAbs = new G4LogicalVolume(solidHG_BHAbs, mBHAbsMat, "logicHG_BHAbs"); zpos = -fullBHLayerZ/2. + hgcParameters.bh.fullBHAbsXYZ[2]/2.; physHG_BHAbs = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_BHAbs, "physHG_BHAbs", logicHG_BHLayer, 0, 0, true); solidHG_BHPadLayer = new G4Box("solidHG_BHPadLayer", fullBHPadLayerX/2., fullBHPadLayerY/2., fullBHPadLayerZ/2.); logicHG_BHPadLayer = new G4LogicalVolume(solidHG_BHPadLayer, mSi, "logicHG_BHPadLayer", 0, BHSD, 0); // logicHG_BHPadLayer->SetUserLimits(sdLimits); zpos = -fullBHLayerZ/2. + hgcParameters.bh.fullBHAbsXYZ[2] + fullBHPadLayerZ/2.; physHG_BHPadLayer = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_BHPadLayer, "physHG_BHPadLayer", logicHG_BHLayer, 0,0, true); solidHG_BHPadReadout = new G4Box("solidHG_BHPadReadout", hgcParameters.bh.fullBHPadReadoutXYZ[0]/2., hgcParameters.bh.fullBHPadReadoutXYZ[1]/2., hgcParameters.bh.fullBHPadReadoutXYZ[2]/2.); logicHG_BHPadReadout = new G4LogicalVolume(solidHG_BHPadReadout, mElectronicsMat, "logicHG_BHPadReadout"); zpos = -fullBHLayerZ/2. + hgcParameters.bh.fullBHAbsXYZ[2] + fullBHPadLayerZ + hgcParameters.bh.fullBHPadReadoutXYZ[2]/2.; physHG_BHPadReadout = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_BHPadReadout, "physHG_BHPadRedout", logicHG_BHLayer, 0, 0, true); for (int iLayer=0; iLayer<hgcParameters.bh.nLayers_Total; iLayer++) { zpos = -fullBHModuleZ/2. + (iLayer + 0.5)*fullBHLayerZ; physHG_FHLayer = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHG_BHLayer, "physHG_BHLayer", logicHG_BHModule, 0, iLayer + hgcParameters.em.nLayers_Total + hgcParameters.fh.nLayers_Total, true); } return; }// end of BuildHGCal /* * Read in HGCAL configuration data * NOTE: * -- All the input sizes are in mm * -- Also, the order of dimensios is exactly as in SHDefs.hh */ int SHDetectorConstruction::ReadHGConfigFile() { cout << "### Reading in HGCAL Configuration File..." << endl; // Init/Open/Check file // ifstream hgConfigFile(runParams.hgCalInputFileName); if (!hgConfigFile) { cout << "### ERROR: File " << runParams.hgCalInputFileName << " hasn't been found!!!" << endl; return -1; } // Read in/Config // double x,y,z; int n, n1, n2, n3; int iMat; int emOnOff, fhOnOff, bhOnOff; // Input the HGCal On/Off Settings // hgConfigFile >> emOnOff >> fhOnOff >> bhOnOff; hgcParameters.emOnOff =emOnOff; hgcParameters.fhOnOff = fhOnOff; hgcParameters.bhOnOff = bhOnOff; // EM Input Part // hgConfigFile >> n >> n1 >> n2 >> n3 >> iMat; hgcParameters.em.nLayers_Total = n; hgcParameters.em.nLayers_1 = n1; hgcParameters.em.nLayers_2 = n2; hgcParameters.em.nLayers_3 = n3; hgcParameters.em.iAbsMaterial = iMat; hgConfigFile >> x >> y >> z; hgcParameters.em.fullEMAbsXYZ[0] = x*mm; hgcParameters.em.fullEMAbsXYZ[1] = y*mm; hgcParameters.em.fullEMAbsXYZ[2] = z*mm; hgConfigFile >> z; hgcParameters.em.fullEMAbsXYZ[3] = z*mm; hgConfigFile >> z; hgcParameters.em.fullEMAbsXYZ[4] = z*mm; hgConfigFile >> x >> y >> z; hgcParameters.em.fullEMPadXYZ[0] = x*mm; hgcParameters.em.fullEMPadXYZ[1] = y*mm; hgcParameters.em.fullEMPadXYZ[2] = z*mm; hgConfigFile >> x >> y; hgcParameters.em.fullEMPadXYZ[3] = x*mm; hgcParameters.em.fullEMPadXYZ[4] = y*mm; hgConfigFile >> x >> y >> z; hgcParameters.em.fullEMPadReadoutXYZ[0] = x*mm; hgcParameters.em.fullEMPadReadoutXYZ[1] = y*mm; hgcParameters.em.fullEMPadReadoutXYZ[2] = z*mm; // FH Input Part // hgConfigFile >> n >> iMat; hgcParameters.fh.nLayers_Total = n; hgcParameters.fh.iAbsMaterial = iMat; hgConfigFile >> x >> y >> z; hgcParameters.fh.fullFHAbsXYZ[0] = x*mm; hgcParameters.fh.fullFHAbsXYZ[1] = y*mm; hgcParameters.fh.fullFHAbsXYZ[2] = z*mm; hgConfigFile >> x >> y >> z; hgcParameters.fh.fullFHPadXYZ[0] = x*mm; hgcParameters.fh.fullFHPadXYZ[1] = y*mm; hgcParameters.fh.fullFHPadXYZ[2] = z*mm; hgConfigFile >> x >> y >> z; hgcParameters.fh.fullFHPadReadoutXYZ[0] = x*mm; hgcParameters.fh.fullFHPadReadoutXYZ[1] = y*mm; hgcParameters.fh.fullFHPadReadoutXYZ[2] = z*mm; // BH Input Part // hgConfigFile >> n >> iMat; hgcParameters.bh.nLayers_Total = n; hgcParameters.bh.iAbsMaterial = iMat; hgConfigFile >> x >> y >> z; hgcParameters.bh.fullBHAbsXYZ[0] = x*mm; hgcParameters.bh.fullBHAbsXYZ[1] = y*mm; hgcParameters.bh.fullBHAbsXYZ[2] = z*mm; hgConfigFile >> x >> y >> z; hgcParameters.bh.fullBHPadXYZ[0] = x*mm; hgcParameters.bh.fullBHPadXYZ[1] = y*mm; hgcParameters.bh.fullBHPadXYZ[2] = z*mm; hgConfigFile >> x >> y >> z; hgcParameters.bh.fullBHPadReadoutXYZ[0] = x*mm; hgcParameters.bh.fullBHPadReadoutXYZ[1] = y*mm; hgcParameters.bh.fullBHPadReadoutXYZ[2] = z*mm; return 1; }// end of Read HGCAL Config Data // // Build HE // void SHDetectorConstruction::BuildHE() { // SD // G4SDManager *SDManager = G4SDManager::GetSDMpointer(); SHSDCounter *SHSD = new SHSDCounter("SHSD", runParams, _heTree); SDManager->AddNewDetector(SHSD); // Read in Config File // ReadHEConfigFile(); // Additional dimensions for HE: layer's dimensions // G4double fullHELayerX = heParameters.fullHEAbsXYZ[0]; G4double fullHELayerY = heParameters.fullHEAbsXYZ[1]; G4double fullHELayerZ = heParameters.fullHEAbsXYZ[2] + heParameters.fullHEActXYZ[2]; // HE Module itself // G4double fullHEModuleX = fullHELayerX; G4double fullHEModuleY = fullHELayerY; G4double fullHEModuleZ = heParameters.nLayers_Total*fullHELayerZ; // Fot debugging... // G4cout << "### HE Module Dimensions: " << fullHEModuleX/cm << " " << fullHEModuleY/cm << " " << fullHEModuleZ/cm << G4endl << "### HE Layer: " << fullHELayerX/cm << " " << fullHELayerY/cm << " " << fullHELayerZ/cm << G4endl << "### HE Abs: " << heParameters.fullHEAbsXYZ[0]/cm << " " << heParameters.fullHEAbsXYZ[1]/cm << " " << heParameters.fullHEAbsXYZ[2]/cm << G4endl; // Place the HE Module itself first // solidHE_Module = new G4Box("solidHE_Module", fullHEModuleX/2., fullHEModuleY/2., fullHEModuleZ/2.); logicHE_Module = new G4LogicalVolume(solidHE_Module, mVacuum, "logicHE_Module"); physHE_Module = new G4PVPlacement(0, G4ThreeVector(), logicHE_Module, "physHE_Module", logicWorld, 0, 0, true); // Construct the Layer(Place it in the very end) // solidHE_Layer = new G4Box("solidHE_Layer", fullHELayerX/2., fullHELayerY/2., fullHELayerZ/2.); logicHE_Layer = new G4LogicalVolume(solidHE_Layer, mVacuum, "logicHE_Layer"); // Abs // solidHE_Abs = new G4Box("solidHE_Abs", heParameters.fullHEAbsXYZ[0]/2, heParameters.fullHEAbsXYZ[1]/2., heParameters.fullHEAbsXYZ[2]/2.); logicHE_Abs = new G4LogicalVolume(solidHE_Abs, mHEAbsMat, "logicHE_Abs"); G4double zpos = -fullHELayerZ/2. + heParameters.fullHEAbsXYZ[2]/2.; physHE_Abs = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHE_Abs, "physHE_Abs", logicHE_Layer, 0, 0, true); // Scintillator // solidHE_Act = new G4Box("solidHE_Act", heParameters.fullHEActXYZ[0]/2., heParameters.fullHEActXYZ[1]/2., heParameters.fullHEActXYZ[2]/2.); logicHE_Act = new G4LogicalVolume(solidHE_Act, mHEScintMain, "logicHE_Act", 0, SHSD, 0); zpos = -fullHELayerZ/2. + heParameters.fullHEAbsXYZ[2] + heParameters.fullHEActXYZ[2]/2.; physHE_Act = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHE_Act, "physHE_Act", logicHE_Layer, 0, 0, true); // Place all the Layeers // for (int iLayer=0; iLayer<heParameters.nLayers_Total; iLayer++) { zpos = -fullHEModuleZ/2. + (iLayer + 0.5)*fullHELayerZ; physHE_Layer = new G4PVPlacement(0, G4ThreeVector(0, 0, zpos), logicHE_Layer, "physHE_Layer", logicHE_Module, 0, iLayer, true); } } // // Read in HE Parameters // int SHDetectorConstruction::ReadHEConfigFile() { cout << "### Reading in HE Configuraiton File...." << endl; // Init/Open/Check File // ifstream heConfigFile(runParams.heInputFileName); if (!heConfigFile) { cout << "### ERROR: File " << runParams.heInputFileName << " hasn't been found!!!" << endl; return -1; } // Read in/Config // double x,y,z; int n; heConfigFile >> n; heParameters.nLayers_Total = n; heConfigFile >> x >> y >> z; heParameters.fullHEAbsXYZ[0] = x*mm; heParameters.fullHEAbsXYZ[1] = y*mm; heParameters.fullHEAbsXYZ[2] = z*mm; heConfigFile >> x >> y >> z; heParameters.fullHEActXYZ[0] = x*mm; heParameters.fullHEActXYZ[1] = y*mm; heParameters.fullHEActXYZ[2] = z*mm; return 1; }
/* * This is a simple example use of ofArduino * * ofArduino currently only supports the standard Arduino boards * (UNO, Duemilanove, Diecimila, NG, and other boards based on the * ATMega168 or ATMega328 microcontrollers * The Arduio FIO and Arduino Mini should also work. * The Arduino MEGA and other variants based on microcontrollers * other than the ATMega168 and ATMega328 are not currently supported. * * To use this example, open Arduino (preferably Arduino 1.0) and * navigate to File -> Examples -> Firmata and open StandardFirmata. * Compile and upload StandardFirmata for your board, then close * the Arduino application and run this application. * * If you have a servo attached, press the left arrow key to rotate * the servo head counterclockwise and press the right arrow key to * rotate the servo head clockwise. * * Clicking the mouse over any part of the application will turn the * on-board LED on and off. * */ #include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofSetVerticalSync(true); ofSetFrameRate(60); ofBackground(255,0,130); buttonState = "digital pin:"; potValue = "analog pin:"; bgImage.loadImage("background.png"); font.loadFont("franklinGothic.otf", 20); smallFont.loadFont("franklinGothic.otf", 14); // replace the string below with the serial port for your Arduino board // you can get this from the Arduino application or via command line // for OSX, in your terminal type "ls /dev/tty.*" to get a list of serial devices ard.connect("/dev/tty.usbmodemfd121", 57600); // listen for EInitialized notification. this indicates that // the arduino is ready to receive commands and it is safe to // call setupArduino() ofAddListener(ard.EInitialized, this, &testApp::setupArduino); bSetupArduino = false; // flag so we setup arduino when its ready, you don't need to touch this :) } //-------------------------------------------------------------- void testApp::update(){ updateArduino(); } //-------------------------------------------------------------- void testApp::setupArduino(const int & version) { // remove listener because we don't need it anymore ofRemoveListener(ard.EInitialized, this, &testApp::setupArduino); // it is now safe to send commands to the Arduino bSetupArduino = true; // print firmware name and version to the console ofLogNotice() << ard.getFirmwareName(); ofLogNotice() << "firmata v" << ard.getMajorFirmwareVersion() << "." << ard.getMinorFirmwareVersion(); // Note: pins A0 - A5 can be used as digital input and output. // Refer to them as pins 14 - 19 if using StandardFirmata from Arduino 1.0. // If using Arduino 0022 or older, then use 16 - 21. // Firmata pin numbering changed in version 2.3 (which is included in Arduino 1.0) // set pins D2 and A5 to digital input ard.sendDigitalPinMode(2, ARD_INPUT); ard.sendDigitalPinMode(19, ARD_INPUT); // pin 21 if using StandardFirmata from Arduino 0022 or older // set pin A0 to analog input ard.sendAnalogPinReporting(0, ARD_ANALOG); // set pin D13 as digital output ard.sendDigitalPinMode(13, ARD_OUTPUT); // set pin A4 as digital output ard.sendDigitalPinMode(18, ARD_OUTPUT); // pin 20 if using StandardFirmata from Arduino 0022 or older // set pin D11 as PWM (analog output) ard.sendDigitalPinMode(11, ARD_PWM); // attach a servo to pin D9 // servo motors can only be attached to pin D3, D5, D6, D9, D10, or D11 ard.sendServoAttach(9); // Listen for changes on the digital and analog pins ofAddListener(ard.EDigitalPinChanged, this, &testApp::digitalPinChanged); ofAddListener(ard.EAnalogPinChanged, this, &testApp::analogPinChanged); } //-------------------------------------------------------------- void testApp::updateArduino(){ // update the arduino, get any data or messages. // the call to ard.update() is required ard.update(); // do not send anything until the arduino has been set up if (bSetupArduino) { // fade the led connected to pin D11 ard.sendPwm(11, (int)(128 + 128 * sin(ofGetElapsedTimef()))); // pwm... } } // digital pin event handler, called whenever a digital pin value has changed // note: if an analog pin has been set as a digital pin, it will be handled // by the digitalPinChanged function rather than the analogPinChanged function. //-------------------------------------------------------------- void testApp::digitalPinChanged(const int & pinNum) { // do something with the digital input. here we're simply going to print the pin number and // value to the screen each time it changes buttonState = "digital pin: " + ofToString(pinNum) + " = " + ofToString(ard.getDigital(pinNum)); } // analog pin event handler, called whenever an analog pin value has changed //-------------------------------------------------------------- void testApp::analogPinChanged(const int & pinNum) { // do something with the analog input. here we're simply going to print the pin number and // value to the screen each time it changes potValue = "analog pin: " + ofToString(pinNum) + " = " + ofToString(ard.getAnalog(pinNum)); } //-------------------------------------------------------------- void testApp::draw(){ bgImage.draw(0,0); ofEnableAlphaBlending(); ofSetColor(0, 0, 0, 127); ofRect(510, 15, 275, 150); ofDisableAlphaBlending(); ofSetColor(255, 255, 255); if (!bSetupArduino){ font.drawString("arduino not ready...\n", 515, 40); } else { font.drawString(potValue + "\n" + buttonState + "\nsending pwm: " + ofToString((int)(128 + 128 * sin(ofGetElapsedTimef()))), 515, 40); ofSetColor(64, 64, 64); smallFont.drawString("If a servo is attached, use the left arrow key to rotate " "\ncounterclockwise and the right arrow key to rotate clockwise.", 200, 550); ofSetColor(255, 255, 255); } } //-------------------------------------------------------------- void testApp::keyPressed (int key){ switch (key) { case OF_KEY_RIGHT: // rotate servo head to 180 degrees ard.sendServo(9, 180, false); ard.sendDigital(18, ARD_HIGH); // pin 20 if using StandardFirmata from Arduino 0022 or older break; case OF_KEY_LEFT: // rotate servo head to 0 degrees ard.sendServo(9, 0, false); ard.sendDigital(18, ARD_LOW); // pin 20 if using StandardFirmata from Arduino 0022 or older break; default: break; } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ // turn on the onboard LED when the application window is clicked ard.sendDigital(13, ARD_HIGH); } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ // turn off the onboard LED when the application window is clicked ard.sendDigital(13, ARD_LOW); } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }
/* *********************************************************************************************************************** * * Copyright (c) 2017-2021 Advanced Micro Devices, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************************************************************/ /** *********************************************************************************************************************** * @file PatchInOutImportExport.cpp * @brief LLPC source file: contains implementation of class lgc::PatchInOutImportExport. *********************************************************************************************************************** */ #include "PatchInOutImportExport.h" #include "lgc/Builder.h" #include "lgc/BuiltIns.h" #include "lgc/state/AbiUnlinked.h" #include "lgc/state/PipelineShaders.h" #include "lgc/util/Debug.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/IntrinsicsAMDGPU.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #define DEBUG_TYPE "lgc-patch-in-out-import-export" using namespace llvm; using namespace lgc; namespace lgc { // ===================================================================================================================== // Initializes static members. char PatchInOutImportExport::ID = 0; // ===================================================================================================================== // Pass creator, creates the pass of LLVM patching operations for input import and output export ModulePass *createPatchInOutImportExport() { return new PatchInOutImportExport(); } // ===================================================================================================================== PatchInOutImportExport::PatchInOutImportExport() : Patch(ID), m_lds(nullptr) { memset(&m_gfxIp, 0, sizeof(m_gfxIp)); initPerShader(); } // ===================================================================================================================== PatchInOutImportExport::~PatchInOutImportExport() { } // ===================================================================================================================== // Initialize per-shader members void PatchInOutImportExport::initPerShader() { m_clipDistance = nullptr; m_cullDistance = nullptr; m_primitiveId = nullptr; m_fragDepth = nullptr; m_fragStencilRef = nullptr; m_sampleMask = nullptr; m_viewportIndex = nullptr; m_layer = nullptr; m_threadId = nullptr; m_attribExports.clear(); } // ===================================================================================================================== // Executes this LLVM patching pass on the specified LLVM module. // // @param [in/out] module : LLVM module to be run on bool PatchInOutImportExport::runOnModule(Module &module) { LLVM_DEBUG(dbgs() << "Run the pass Patch-In-Out-Import-Export\n"); Patch::init(&module); m_pipelineState = getAnalysis<PipelineStateWrapper>().getPipelineState(&module); m_gfxIp = m_pipelineState->getTargetInfo().getGfxIpVersion(); m_pipelineSysValues.initialize(m_pipelineState); const unsigned stageMask = m_pipelineState->getShaderStageMask(); m_hasTs = (stageMask & (shaderStageToMask(ShaderStageTessControl) | shaderStageToMask(ShaderStageTessEval))) != 0; m_hasGs = (stageMask & shaderStageToMask(ShaderStageGeometry)) != 0; SmallVector<Function *, 16> inputCallees, otherCallees; for (auto &func : module.functions()) { auto name = func.getName(); if (name.startswith("lgc.input")) inputCallees.push_back(&func); else if (name.startswith("lgc.output") || name == "llvm.amdgcn.s.sendmsg") otherCallees.push_back(&func); } // Create the global variable that is to model LDS // NOTE: ES -> GS ring is always on-chip on GFX9. if (m_hasTs || (m_hasGs && (m_pipelineState->isGsOnChip() || m_gfxIp.major >= 9))) m_lds = Patch::getLdsVariable(m_pipelineState, m_module); // Set buffer formats based on specific GFX static const std::array<unsigned char, 4> BufferFormatsGfx9 = { BUF_NUM_FORMAT_FLOAT << 4 | BUF_DATA_FORMAT_32, BUF_NUM_FORMAT_FLOAT << 4 | BUF_DATA_FORMAT_32_32, BUF_NUM_FORMAT_FLOAT << 4 | BUF_DATA_FORMAT_32_32_32, BUF_NUM_FORMAT_FLOAT << 4 | BUF_DATA_FORMAT_32_32_32_32, }; static const std::array<unsigned char, 4> BufferFormatsGfx10 = { BUF_FORMAT_32_FLOAT, BUF_FORMAT_32_32_FLOAT_GFX10, BUF_FORMAT_32_32_32_FLOAT_GFX10, BUF_FORMAT_32_32_32_32_FLOAT_GFX10, }; switch (m_gfxIp.major) { default: m_buffFormats = &BufferFormatsGfx9; break; case 10: m_buffFormats = &BufferFormatsGfx10; break; } // Process each shader in turn, in reverse order (because for example VS uses inOutUsage.tcs.calcFactor // set by TCS). auto pipelineShaders = &getAnalysis<PipelineShaders>(); for (int shaderStage = ShaderStageCountInternal - 1; shaderStage >= 0; --shaderStage) { auto entryPoint = pipelineShaders->getEntryPoint(static_cast<ShaderStage>(shaderStage)); if (entryPoint) { processFunction(*entryPoint, static_cast<ShaderStage>(shaderStage), inputCallees, otherCallees); if (shaderStage == ShaderStageTessControl) storeTessFactors(); } } // Process non-entry-point shaders for (Function &func : module) { if (func.isDeclaration()) continue; auto shaderStage = getShaderStage(&func); if (shaderStage == ShaderStage::ShaderStageInvalid || &func == pipelineShaders->getEntryPoint(shaderStage)) continue; processFunction(func, shaderStage, inputCallees, otherCallees); } for (auto callInst : m_importCalls) { callInst->dropAllReferences(); callInst->eraseFromParent(); } m_importCalls.clear(); for (auto callInst : m_exportCalls) { callInst->dropAllReferences(); callInst->eraseFromParent(); } m_exportCalls.clear(); m_pipelineSysValues.clear(); return true; } void PatchInOutImportExport::processFunction(Function &func, ShaderStage shaderStage, SmallVectorImpl<Function *> &inputCallees, SmallVectorImpl<Function *> &otherCallees) { PostDominatorTree &postDomTree = getAnalysis<PostDominatorTreeWrapperPass>(func).getPostDomTree(); initPerShader(); m_entryPoint = &func; m_shaderStage = shaderStage; processShader(); // We process input first, because we cache lots of arguments to output during visit for later processing. // It will be a disaster if we visit output intrinsics first, and the cached value for output was invalidated // after we process input intrinsics (consider a value read from input was exported to output). visitCallInsts(inputCallees); visitCallInsts(otherCallees); visitReturnInsts(); markExportDone(m_entryPoint, postDomTree); } // ===================================================================================================================== // Mark the 'done' flag to the very last position export instruction. // // @param [in/out] func : LLVM function to be run on // @param postDomTree : The PostDominatorTree of the \p func void PatchInOutImportExport::markExportDone(Function *func, PostDominatorTree &postDomTree) { SmallVector<CallInst *, 4> expInsts; Function *expDecl = m_module->getFunction("llvm.amdgcn.exp.f32"); if (!expDecl) return; // Get the export call instructions for (auto user : expDecl->users()) { if (CallInst *callInst = dyn_cast<CallInst>(user)) { if (callInst->getFunction() == func) { if (ConstantInt *target = dyn_cast<ConstantInt>(callInst->getOperand(0))) { uint64_t targetValue = target->getZExtValue(); if (targetValue >= EXP_TARGET_POS_0 && targetValue <= EXP_TARGET_POS_3) expInsts.push_back(callInst); } } } } if (expInsts.empty()) return; CallInst *lastExport = expInsts[0]; // Here we are trying to find the position-export that post-dominates all the other position exports (i.e. the last // export). And apply the 'done' flag to that position-export. Although in practice user can easily write a program // that put the gl_Position output inside a if-else, in which case it is hard for us to find the last export. But we // already handled such situation in previous pass to put the real position export call into the last return block. So // it would be safe for us to do like this. The reason I didn't do a simple backward traverse in return block to find // the very last export is because the copy-shader, in which case the position export is not in the return block. for (unsigned i = 1; i < expInsts.size(); i++) { if (postDomTree.dominates(expInsts[i], lastExport)) lastExport = expInsts[i]; else assert(postDomTree.dominates(lastExport, expInsts[i])); } lastExport->setOperand(6, ConstantInt::getTrue(*m_context)); } // ===================================================================================================================== // Process a single shader void PatchInOutImportExport::processShader() { // Initialize the output value for gl_PrimitiveID const auto &builtInUsage = m_pipelineState->getShaderResourceUsage(m_shaderStage)->builtInUsage; const auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(m_shaderStage)->entryArgIdxs; if (m_shaderStage == ShaderStageVertex) { if (builtInUsage.vs.primitiveId) m_primitiveId = getFunctionArgument(m_entryPoint, entryArgIdxs.vs.primitiveId); } else if (m_shaderStage == ShaderStageTessEval) { if (builtInUsage.tes.primitiveId) { m_primitiveId = getFunctionArgument(m_entryPoint, entryArgIdxs.tes.patchId); } } // Thread ID will be used in on-chip GS offset calculation (ES -> GS ring is always on-chip on GFX9) bool useThreadId = (m_hasGs && (m_pipelineState->isGsOnChip() || m_gfxIp.major >= 9)); // Thread ID will also be used for stream-out buffer export const bool enableXfb = m_pipelineState->getShaderResourceUsage(m_shaderStage)->inOutUsage.enableXfb; useThreadId = useThreadId || enableXfb; if (useThreadId) { // Calculate and store thread ID auto insertPos = m_entryPoint->begin()->getFirstInsertionPt(); m_threadId = getSubgroupLocalInvocationId(&*insertPos); } // Initialize calculation factors for tessellation shader if (m_shaderStage == ShaderStageTessControl || m_shaderStage == ShaderStageTessEval) { const unsigned stageMask = m_pipelineState->getShaderStageMask(); const bool hasTcs = ((stageMask & shaderStageToMask(ShaderStageTessControl)) != 0); auto &calcFactor = m_pipelineState->getShaderResourceUsage(ShaderStageTessControl)->inOutUsage.tcs.calcFactor; if (calcFactor.inVertexStride == InvalidValue && calcFactor.outVertexStride == InvalidValue && calcFactor.patchCountPerThreadGroup == InvalidValue && calcFactor.outPatchSize == InvalidValue && calcFactor.patchConstSize == InvalidValue) { // NOTE: The LDS space is divided to three parts: // // +----------------------------------------+ // / | TCS Vertex (Control Point) In (VS Out) | // / +----------------------------------------+ // LDS Space | TCS Vertex (Control Point) Out | // \ +----------------------------------------+ // \ | TCS Patch Constant | // +----------------------------------------+ // inPatchTotalSize = inVertexCount * inVertexStride * patchCountPerThreadGroup // outPatchTotalSize = outVertexCount * outVertexStride * patchCountPerThreadGroup // patchConstTotalSize = patchConstCount * 4 * patchCountPerThreadGroup const auto &tcsInOutUsage = m_pipelineState->getShaderResourceUsage(ShaderStageTessControl)->inOutUsage; const auto &tesInOutUsage = m_pipelineState->getShaderResourceUsage(ShaderStageTessEval)->inOutUsage; const unsigned inLocCount = std::max(tcsInOutUsage.inputMapLocCount, 1u); const unsigned outLocCount = hasTcs ? std::max(tcsInOutUsage.outputMapLocCount, 1u) : std::max(tesInOutUsage.inputMapLocCount, 1u); const unsigned inVertexCount = m_pipelineState->getInputAssemblyState().patchControlPoints; const unsigned outVertexCount = hasTcs ? m_pipelineState->getShaderModes()->getTessellationMode().outputVertices : MaxTessPatchVertices; unsigned tessFactorStride = 0; switch (m_pipelineState->getShaderModes()->getTessellationMode().primitiveMode) { case PrimitiveMode::Triangles: tessFactorStride = 4; break; case PrimitiveMode::Quads: tessFactorStride = 6; break; case PrimitiveMode::Isolines: tessFactorStride = 2; break; default: llvm_unreachable("Should never be called!"); break; } calcFactor.inVertexStride = inLocCount * 4; calcFactor.outVertexStride = outLocCount * 4; const unsigned patchConstCount = hasTcs ? tcsInOutUsage.perPatchOutputMapLocCount : tesInOutUsage.perPatchInputMapLocCount; calcFactor.patchConstSize = patchConstCount * 4; calcFactor.patchCountPerThreadGroup = calcPatchCountPerThreadGroup(inVertexCount, calcFactor.inVertexStride, outVertexCount, calcFactor.outVertexStride, patchConstCount, tessFactorStride); const unsigned inPatchSize = inVertexCount * calcFactor.inVertexStride; const unsigned inPatchTotalSize = calcFactor.patchCountPerThreadGroup * inPatchSize; const unsigned outPatchSize = outVertexCount * calcFactor.outVertexStride; const unsigned outPatchTotalSize = calcFactor.patchCountPerThreadGroup * outPatchSize; calcFactor.outPatchSize = outPatchSize; calcFactor.inPatchSize = inPatchSize; calcFactor.onChip.outPatchStart = inPatchTotalSize; calcFactor.onChip.patchConstStart = inPatchTotalSize + outPatchTotalSize; if (m_pipelineState->isTessOffChip()) { calcFactor.offChip.outPatchStart = 0; calcFactor.offChip.patchConstStart = outPatchTotalSize; } calcFactor.tessFactorStride = tessFactorStride; LLPC_OUTS("===============================================================================\n"); LLPC_OUTS("// LLPC tessellation calculation factor results\n\n"); LLPC_OUTS("Patch count per thread group: " << calcFactor.patchCountPerThreadGroup << "\n"); LLPC_OUTS("\n"); LLPC_OUTS("Input vertex count: " << inVertexCount << "\n"); LLPC_OUTS("Input vertex stride: " << calcFactor.inVertexStride << "\n"); LLPC_OUTS("Input patch size: " << inPatchSize << "\n"); LLPC_OUTS("Input patch total size: " << inPatchTotalSize << "\n"); LLPC_OUTS("\n"); LLPC_OUTS("Output vertex count: " << outVertexCount << "\n"); LLPC_OUTS("Output vertex stride: " << calcFactor.outVertexStride << "\n"); LLPC_OUTS("Output patch size: " << outPatchSize << "\n"); LLPC_OUTS("Output patch total size: " << outPatchTotalSize << "\n"); LLPC_OUTS("\n"); LLPC_OUTS("Patch constant count: " << patchConstCount << "\n"); LLPC_OUTS("Patch constant size: " << calcFactor.patchConstSize << "\n"); LLPC_OUTS("Patch constant total size: " << calcFactor.patchConstSize * calcFactor.patchCountPerThreadGroup << "\n"); LLPC_OUTS("\n"); LLPC_OUTS("Tessellation factor stride: " << tessFactorStride << " ("); switch (m_pipelineState->getShaderModes()->getTessellationMode().primitiveMode) { case PrimitiveMode::Triangles: LLPC_OUTS("triangles"); break; case PrimitiveMode::Quads: LLPC_OUTS("quads"); tessFactorStride = 6; break; case PrimitiveMode::Isolines: LLPC_OUTS("isolines"); tessFactorStride = 2; break; default: llvm_unreachable("Should never be called!"); break; } LLPC_OUTS(")\n\n"); } } if (m_shaderStage == ShaderStageCompute) { // In a compute shader, process lgc.reconfigure.local.invocation.id calls. // This does not particularly have to be done here; it could be done anywhere after BuilderImpl. for (Function &func : *m_module) { if (func.isDeclaration() && func.getName().startswith(lgcName::ReconfigureLocalInvocationId)) { WorkgroupLayout workgroupLayout = calculateWorkgroupLayout(); while (!func.use_empty()) { CallInst *reconfigCall = cast<CallInst>(*func.user_begin()); Value *localInvocationId = reconfigCall->getArgOperand(0); // If we do not need to configure our workgroup in linear layout and the layout info is not specified, we // do the reconfiguration for this workgroup. if (workgroupLayout != WorkgroupLayout::Unknown && workgroupLayout != WorkgroupLayout::Linear) localInvocationId = reconfigWorkgroup(localInvocationId, reconfigCall); reconfigCall->replaceAllUsesWith(localInvocationId); reconfigCall->eraseFromParent(); } } } } } // ===================================================================================================================== // Visits all "call" instructions against the callee functions in current entry-point function. // // @param calleeFuncs : a list of candidate callee functions to check void PatchInOutImportExport::visitCallInsts(ArrayRef<Function *> calleeFuncs) { for (auto callee : calleeFuncs) { for (auto user : callee->users()) { if (CallInst *callInst = dyn_cast<CallInst>(user)) { if (callInst->getFunction() == m_entryPoint) visitCallInst(*callInst); } } } } // ===================================================================================================================== // Visits all "ret" instructions in current entry-point function. void PatchInOutImportExport::visitReturnInsts() { for (auto &block : *m_entryPoint) if (auto *retInst = dyn_cast<ReturnInst>(block.getTerminator())) visitReturnInst(*retInst); } // ===================================================================================================================== // Visits "call" instruction. // // @param callInst : "Call" instruction void PatchInOutImportExport::visitCallInst(CallInst &callInst) { auto callee = callInst.getCalledFunction(); if (!callee) return; IRBuilder<> builder(*m_context); auto resUsage = m_pipelineState->getShaderResourceUsage(m_shaderStage); auto mangledName = callee->getName(); auto importGenericInput = lgcName::InputImportGeneric; auto importBuiltInInput = lgcName::InputImportBuiltIn; auto importInterpolantInput = lgcName::InputImportInterpolant; auto importGenericOutput = lgcName::OutputImportGeneric; auto importBuiltInOutput = lgcName::OutputImportBuiltIn; const bool isGenericInputImport = mangledName.startswith(importGenericInput); const bool isBuiltInInputImport = mangledName.startswith(importBuiltInInput); const bool isInterpolantInputImport = mangledName.startswith(importInterpolantInput); const bool isGenericOutputImport = mangledName.startswith(importGenericOutput); const bool isBuiltInOutputImport = mangledName.startswith(importBuiltInOutput); const bool isImport = (isGenericInputImport || isBuiltInInputImport || isInterpolantInputImport || isGenericOutputImport || isBuiltInOutputImport); auto exportGenericOutput = lgcName::OutputExportGeneric; auto exportBuiltInOutput = lgcName::OutputExportBuiltIn; auto exportXfbOutput = lgcName::OutputExportXfb; const bool isGenericOutputExport = mangledName.startswith(exportGenericOutput); const bool isBuiltInOutputExport = mangledName.startswith(exportBuiltInOutput); const bool isXfbOutputExport = mangledName.startswith(exportXfbOutput); const bool isExport = (isGenericOutputExport || isBuiltInOutputExport || isXfbOutputExport); const bool isInput = (isGenericInputImport || isBuiltInInputImport || isInterpolantInputImport); const bool isOutput = (isGenericOutputImport || isBuiltInOutputImport || isGenericOutputExport || isBuiltInOutputExport || isXfbOutputExport); if (isImport && isInput) { // Input imports Value *input = nullptr; Type *inputTy = callInst.getType(); // Generic value (location or SPIR-V built-in ID) unsigned value = cast<ConstantInt>(callInst.getOperand(0))->getZExtValue(); LLVM_DEBUG(dbgs() << "Find input import call: builtin = " << isBuiltInInputImport << " value = " << value << "\n"); m_importCalls.push_back(&callInst); if (isBuiltInInputImport) { const unsigned builtInId = value; switch (m_shaderStage) { case ShaderStageVertex: { input = patchVsBuiltInInputImport(inputTy, builtInId, &callInst); break; } case ShaderStageTessControl: { // Builtin Call has different number of operands Value *elemIdx = nullptr; Value *vertexIdx = nullptr; if (callInst.arg_size() > 1) elemIdx = isDontCareValue(callInst.getOperand(1)) ? nullptr : callInst.getOperand(1); if (callInst.arg_size() > 2) vertexIdx = isDontCareValue(callInst.getOperand(2)) ? nullptr : callInst.getOperand(2); input = patchTcsBuiltInInputImport(inputTy, builtInId, elemIdx, vertexIdx, &callInst); break; } case ShaderStageTessEval: { // Builtin Call has different number of operands Value *elemIdx = nullptr; Value *vertexIdx = nullptr; if (callInst.arg_size() > 1) elemIdx = isDontCareValue(callInst.getOperand(1)) ? nullptr : callInst.getOperand(1); if (callInst.arg_size() > 2) vertexIdx = isDontCareValue(callInst.getOperand(2)) ? nullptr : callInst.getOperand(2); input = patchTesBuiltInInputImport(inputTy, builtInId, elemIdx, vertexIdx, &callInst); break; } case ShaderStageGeometry: { // Builtin Call has different number of operands Value *vertexIdx = nullptr; if (callInst.arg_size() > 1) vertexIdx = isDontCareValue(callInst.getOperand(1)) ? nullptr : callInst.getOperand(1); input = patchGsBuiltInInputImport(inputTy, builtInId, vertexIdx, &callInst); break; } case ShaderStageFragment: { Value *sampleId = nullptr; if (callInst.arg_size() >= 2) sampleId = callInst.getArgOperand(1); input = patchFsBuiltInInputImport(inputTy, builtInId, sampleId, &callInst); break; } default: { llvm_unreachable("Should never be called!"); break; } } } else { assert(isGenericInputImport || isInterpolantInputImport); unsigned loc = InvalidValue; Value *locOffset = nullptr; Value *elemIdx = nullptr; bool highHalf = false; if (m_shaderStage == ShaderStageVertex) { // NOTE: For vertex shader, generic inputs are not mapped. loc = value; } else { if (m_shaderStage == ShaderStageTessControl || m_shaderStage == ShaderStageTessEval || (m_shaderStage == ShaderStageFragment && isInterpolantInputImport)) { // NOTE: If location offset is present and is a constant, we have to add it to the unmapped // location before querying the mapped location. Meanwhile, we have to adjust the location // offset to 0 (rebase it). locOffset = callInst.getOperand(1); if (isa<ConstantInt>(locOffset)) { value += cast<ConstantInt>(locOffset)->getZExtValue(); locOffset = ConstantInt::get(Type::getInt32Ty(*m_context), 0); } } InOutLocationInfo origLocInfo; origLocInfo.setLocation(value); auto locInfoMapIt = resUsage->inOutUsage.inputLocInfoMap.find(origLocInfo); if (m_shaderStage == ShaderStageTessEval) { // NOTE: For generic inputs of tessellation evaluation shader, they could be per-patch ones. if (locInfoMapIt != resUsage->inOutUsage.inputLocInfoMap.end()) { loc = locInfoMapIt->second.getLocation(); } else { assert(resUsage->inOutUsage.perPatchInputLocMap.find(value) != resUsage->inOutUsage.perPatchInputLocMap.end()); loc = resUsage->inOutUsage.perPatchInputLocMap[value]; } } else { if (m_pipelineState->canPackInput(m_shaderStage)) { // The inputLocInfoMap of {TCS, GS, FS} maps original InOutLocationInfo to tightly compact InOutLocationInfo const bool isTcs = m_shaderStage == ShaderStageTessControl; const uint32_t elemIdxArgIdx = (isInterpolantInputImport || isTcs) ? 2 : 1; bool hasDynIndex = false; if (isTcs) { hasDynIndex = !isa<ConstantInt>(callInst.getOperand(1)) || !isa<ConstantInt>(callInst.getOperand(2)); if (!hasDynIndex) { // TCS input calls at the same location may have dynamic indexing or not // Try the key as combination of location and component at first origLocInfo.setComponent(cast<ConstantInt>(callInst.getOperand(elemIdxArgIdx))->getZExtValue()); locInfoMapIt = resUsage->inOutUsage.inputLocInfoMap.find(origLocInfo); if (locInfoMapIt == resUsage->inOutUsage.inputLocInfoMap.end()) { // Try the key as the plain location origLocInfo.setComponent(0); locInfoMapIt = resUsage->inOutUsage.inputLocInfoMap.find(origLocInfo); hasDynIndex = true; } } else { locInfoMapIt = resUsage->inOutUsage.inputLocInfoMap.find(origLocInfo); } } else { origLocInfo.setComponent(cast<ConstantInt>(callInst.getOperand(elemIdxArgIdx))->getZExtValue()); locInfoMapIt = resUsage->inOutUsage.inputLocInfoMap.find(origLocInfo); } assert(locInfoMapIt != resUsage->inOutUsage.inputLocInfoMap.end()); loc = locInfoMapIt->second.getLocation(); if (!hasDynIndex) elemIdx = builder.getInt32(locInfoMapIt->second.getComponent()); highHalf = locInfoMapIt->second.isHighHalf(); } else { assert(locInfoMapIt != resUsage->inOutUsage.inputLocInfoMap.end()); loc = locInfoMapIt->second.getLocation(); } } } assert(loc != InvalidValue); switch (m_shaderStage) { case ShaderStageTessControl: { assert(callInst.arg_size() == 4); if (!elemIdx) { elemIdx = callInst.getOperand(2); assert(isDontCareValue(elemIdx) == false); } auto vertexIdx = callInst.getOperand(3); assert(isDontCareValue(vertexIdx) == false); input = patchTcsGenericInputImport(inputTy, loc, locOffset, elemIdx, vertexIdx, &callInst); break; } case ShaderStageTessEval: { assert(callInst.arg_size() == 4); auto elemIdx = callInst.getOperand(2); assert(isDontCareValue(elemIdx) == false); auto vertexIdx = isDontCareValue(callInst.getOperand(3)) ? nullptr : callInst.getOperand(3); input = patchTesGenericInputImport(inputTy, loc, locOffset, elemIdx, vertexIdx, &callInst); break; } case ShaderStageGeometry: { assert(callInst.arg_size() == 3); if (!elemIdx) elemIdx = cast<ConstantInt>(callInst.getOperand(1)); const unsigned compIdx = cast<ConstantInt>(elemIdx)->getZExtValue(); assert(isDontCareValue(elemIdx) == false); Value *vertexIdx = callInst.getOperand(2); assert(isDontCareValue(vertexIdx) == false); input = patchGsGenericInputImport(inputTy, loc, compIdx, vertexIdx, &callInst); break; } case ShaderStageFragment: { unsigned interpMode = InOutInfo::InterpModeSmooth; unsigned interpLoc = InOutInfo::InterpLocCenter; if (!elemIdx) elemIdx = callInst.getOperand(isInterpolantInputImport ? 2 : 1); assert(isDontCareValue(elemIdx) == false); Value *auxInterpValue = nullptr; if (isGenericInputImport) { assert(callInst.arg_size() == 4); interpMode = cast<ConstantInt>(callInst.getOperand(2))->getZExtValue(); interpLoc = cast<ConstantInt>(callInst.getOperand(3))->getZExtValue(); } else { assert(isInterpolantInputImport); assert(callInst.arg_size() == 5); interpMode = cast<ConstantInt>(callInst.getOperand(3))->getZExtValue(); interpLoc = InOutInfo::InterpLocUnknown; auxInterpValue = callInst.getOperand(4); } input = patchFsGenericInputImport(inputTy, loc, locOffset, elemIdx, auxInterpValue, interpMode, interpLoc, highHalf, &callInst); break; } case ShaderStageCompute: { llvm_unreachable("Should never be called!"); break; } default: { llvm_unreachable("Should never be called!"); break; } } } callInst.replaceAllUsesWith(input); } else if (isImport && isOutput) { // Output imports assert(m_shaderStage == ShaderStageTessControl); Value *output = nullptr; Type *outputTy = callInst.getType(); // Generic value (location or SPIR-V built-in ID) unsigned value = cast<ConstantInt>(callInst.getOperand(0))->getZExtValue(); LLVM_DEBUG(dbgs() << "Find output import call: builtin = " << isBuiltInOutputImport << " value = " << value << "\n"); m_importCalls.push_back(&callInst); if (isBuiltInOutputImport) { const unsigned builtInId = value; assert(callInst.arg_size() == 3); Value *elemIdx = isDontCareValue(callInst.getOperand(1)) ? nullptr : callInst.getOperand(1); Value *vertexIdx = isDontCareValue(callInst.getOperand(2)) ? nullptr : callInst.getOperand(2); output = patchTcsBuiltInOutputImport(outputTy, builtInId, elemIdx, vertexIdx, &callInst); } else { assert(isGenericOutputImport); unsigned loc = InvalidValue; // NOTE: If location offset is a constant, we have to add it to the unmapped location before querying // the mapped location. Meanwhile, we have to adjust the location offset to 0 (rebase it). Value *locOffset = callInst.getOperand(1); if (isa<ConstantInt>(locOffset)) { value += cast<ConstantInt>(locOffset)->getZExtValue(); locOffset = ConstantInt::get(Type::getInt32Ty(*m_context), 0); } // NOTE: For generic outputs of tessellation control shader, they could be per-patch ones. InOutLocationInfo origLocInfo; origLocInfo.setLocation(value); auto locInfoMapIt = resUsage->inOutUsage.outputLocInfoMap.find(origLocInfo); if (locInfoMapIt != resUsage->inOutUsage.outputLocInfoMap.end()) { loc = locInfoMapIt->second.getLocation(); } else { assert(resUsage->inOutUsage.perPatchOutputLocMap.find(value) != resUsage->inOutUsage.perPatchOutputLocMap.end()); loc = resUsage->inOutUsage.perPatchOutputLocMap[value]; } assert(loc != InvalidValue); assert(callInst.arg_size() == 4); auto elemIdx = callInst.getOperand(2); assert(isDontCareValue(elemIdx) == false); auto vertexIdx = isDontCareValue(callInst.getOperand(3)) ? nullptr : callInst.getOperand(3); output = patchTcsGenericOutputImport(outputTy, loc, locOffset, elemIdx, vertexIdx, &callInst); } callInst.replaceAllUsesWith(output); } else if (isExport) { // Output exports assert(isOutput); Value *output = callInst.getOperand(callInst.arg_size() - 1); // Last argument // Generic value (location or SPIR-V built-in ID or XFB buffer ID) unsigned value = cast<ConstantInt>(callInst.getOperand(0))->getZExtValue(); LLVM_DEBUG(dbgs() << "Find output export call: builtin = " << isBuiltInOutputExport << " value = " << value << "\n"); m_exportCalls.push_back(&callInst); if (isXfbOutputExport) { unsigned xfbBuffer = value; assert(xfbBuffer < MaxTransformFeedbackBuffers); unsigned xfbOffset = cast<ConstantInt>(callInst.getOperand(1))->getZExtValue(); unsigned streamId = cast<ConstantInt>(callInst.getOperand(2))->getZExtValue(); // NOTE: Transform feedback output will be done in last vertex-processing shader stage. switch (m_shaderStage) { case ShaderStageVertex: { // No TS/GS pipeline, VS is the last stage if (!m_hasGs && !m_hasTs) patchXfbOutputExport(output, xfbBuffer, xfbOffset, streamId, &callInst); break; } case ShaderStageTessEval: { // TS-only pipeline, TES is the last stage if (!m_hasGs) patchXfbOutputExport(output, xfbBuffer, xfbOffset, streamId, &callInst); break; } case ShaderStageGeometry: { // Do nothing, transform feedback output is done in copy shader break; } case ShaderStageCopyShader: { // TS-GS or GS-only pipeline, copy shader is the last stage patchXfbOutputExport(output, xfbBuffer, xfbOffset, streamId, &callInst); break; } default: { llvm_unreachable("Should never be called!"); break; } } } else if (isBuiltInOutputExport) { const unsigned builtInId = value; switch (m_shaderStage) { case ShaderStageVertex: { patchVsBuiltInOutputExport(output, builtInId, &callInst); break; } case ShaderStageTessControl: { assert(callInst.arg_size() == 4); Value *elemIdx = isDontCareValue(callInst.getOperand(1)) ? nullptr : callInst.getOperand(1); Value *vertexIdx = isDontCareValue(callInst.getOperand(2)) ? nullptr : callInst.getOperand(2); patchTcsBuiltInOutputExport(output, builtInId, elemIdx, vertexIdx, &callInst); break; } case ShaderStageTessEval: { patchTesBuiltInOutputExport(output, builtInId, &callInst); break; } case ShaderStageGeometry: { patchGsBuiltInOutputExport(output, builtInId, resUsage->inOutUsage.gs.rasterStream, &callInst); break; } case ShaderStageFragment: { patchFsBuiltInOutputExport(output, builtInId, &callInst); break; } case ShaderStageCopyShader: { patchCopyShaderBuiltInOutputExport(output, builtInId, &callInst); break; } case ShaderStageCompute: { llvm_unreachable("Should never be called!"); break; } default: { llvm_unreachable("Should never be called!"); break; } } } else { assert(isGenericOutputExport); bool exist = false; unsigned loc = InvalidValue; Value *locOffset = nullptr; unsigned elemIdx = InvalidValue; InOutLocationInfo origLocInfo; origLocInfo.setLocation(value); if (m_shaderStage == ShaderStageGeometry) origLocInfo.setStreamId(cast<ConstantInt>(callInst.getOperand(2))->getZExtValue()); auto locInfoMapIt = resUsage->inOutUsage.outputLocInfoMap.find(origLocInfo); if (m_shaderStage == ShaderStageTessControl) { // NOTE: If location offset is a constant, we have to add it to the unmapped location before querying // the mapped location. Meanwhile, we have to adjust the location offset to 0 (rebase it). locOffset = callInst.getOperand(1); if (isa<ConstantInt>(locOffset)) { value += cast<ConstantInt>(locOffset)->getZExtValue(); locOffset = ConstantInt::get(Type::getInt32Ty(*m_context), 0); } // NOTE: For generic outputs of tessellation control shader, they could be per-patch ones. if (locInfoMapIt != resUsage->inOutUsage.outputLocInfoMap.end()) { exist = true; loc = locInfoMapIt->second.getLocation(); } else if (resUsage->inOutUsage.perPatchOutputLocMap.find(value) != resUsage->inOutUsage.perPatchOutputLocMap.end()) { exist = true; loc = resUsage->inOutUsage.perPatchOutputLocMap[value]; } } else if (m_shaderStage == ShaderStageCopyShader) { exist = true; loc = value; } else { if (m_pipelineState->canPackOutput(m_shaderStage)) { assert(m_shaderStage == ShaderStageVertex || m_shaderStage == ShaderStageGeometry || m_shaderStage == ShaderStageTessEval); origLocInfo.setComponent(cast<ConstantInt>(callInst.getOperand(1))->getZExtValue()); locInfoMapIt = resUsage->inOutUsage.outputLocInfoMap.find(origLocInfo); bool relateDynIndex = false; const bool checkDynIndex = (m_shaderStage == ShaderStageVertex && m_pipelineState->hasShaderStage(ShaderStageTessControl)); if (checkDynIndex && locInfoMapIt == resUsage->inOutUsage.outputLocInfoMap.end()) { // The location in TCS may be used with dynamic indexing, try location as the key for a search origLocInfo.setComponent(0); locInfoMapIt = resUsage->inOutUsage.outputLocInfoMap.find(origLocInfo); relateDynIndex = true; } if (locInfoMapIt != resUsage->inOutUsage.outputLocInfoMap.end()) { loc = locInfoMapIt->second.getLocation(); // Dynamic indexing related locations just use the location for mapping if (!relateDynIndex) elemIdx = locInfoMapIt->second.getComponent(); exist = true; } else { exist = false; } } else if (locInfoMapIt != resUsage->inOutUsage.outputLocInfoMap.end()) { exist = true; loc = locInfoMapIt->second.getLocation(); } } if (exist) { // NOTE: Some outputs are not used by next shader stage. They must have been removed already. assert(loc != InvalidValue); switch (m_shaderStage) { case ShaderStageVertex: { assert(callInst.arg_size() == 3); if (elemIdx == InvalidValue) elemIdx = cast<ConstantInt>(callInst.getOperand(1))->getZExtValue(); patchVsGenericOutputExport(output, loc, elemIdx, &callInst); break; } case ShaderStageTessControl: { assert(callInst.arg_size() == 5); auto elemIdx = callInst.getOperand(2); assert(isDontCareValue(elemIdx) == false); auto vertexIdx = isDontCareValue(callInst.getOperand(3)) ? nullptr : callInst.getOperand(3); patchTcsGenericOutputExport(output, loc, locOffset, elemIdx, vertexIdx, &callInst); break; } case ShaderStageTessEval: { assert(callInst.arg_size() == 3); if (elemIdx == InvalidValue) elemIdx = cast<ConstantInt>(callInst.getOperand(1))->getZExtValue(); patchTesGenericOutputExport(output, loc, elemIdx, &callInst); break; } case ShaderStageGeometry: { assert(callInst.arg_size() == 4); if (elemIdx == InvalidValue) elemIdx = cast<ConstantInt>(callInst.getOperand(1))->getZExtValue(); const unsigned streamId = cast<ConstantInt>(callInst.getOperand(2))->getZExtValue(); patchGsGenericOutputExport(output, loc, elemIdx, streamId, &callInst); break; } case ShaderStageFragment: { assert(callInst.arg_size() == 3); llvm_unreachable("Fragment shader export should have been handled by the LowerFragColorExport pass"); break; } case ShaderStageCopyShader: { patchCopyShaderGenericOutputExport(output, loc, &callInst); break; } case ShaderStageCompute: { llvm_unreachable("Should never be called!"); break; } default: { llvm_unreachable("Should never be called!"); break; } } } } } else { // Other calls relevant to input/output import/export if (callee->isIntrinsic() && callee->getIntrinsicID() == Intrinsic::amdgcn_s_sendmsg) { // NOTE: Implicitly store the value of gl_ViewIndex to GS-VS ring buffer before emit calls. if (m_pipelineState->getInputAssemblyState().enableMultiView) { assert(m_shaderStage == ShaderStageGeometry); // Must be geometry shader auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageGeometry)->entryArgIdxs.gs; auto viewIndex = getFunctionArgument(m_entryPoint, entryArgIdxs.viewIndex); auto resUsage = m_pipelineState->getShaderResourceUsage(ShaderStageGeometry); auto &builtInOutLocMap = resUsage->inOutUsage.builtInOutputLocMap; assert(builtInOutLocMap.find(BuiltInViewIndex) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[BuiltInViewIndex]; auto rasterStream = resUsage->inOutUsage.gs.rasterStream; storeValueToGsVsRing(viewIndex, loc, 0, rasterStream, &callInst); } unsigned emitStream = InvalidValue; uint64_t message = cast<ConstantInt>(callInst.getArgOperand(0))->getZExtValue(); if (message == GsEmitStreaM0 || message == GsEmitStreaM1 || message == GsEmitStreaM2 || message == GsEmitStreaM3) { // NOTE: MSG[9:8] = STREAM_ID emitStream = (message & GsEmitCutStreamIdMask) >> GsEmitCutStreamIdShift; } if (emitStream != InvalidValue) { // Increment emit vertex counter auto emitCounterPtr = m_pipelineSysValues.get(m_entryPoint)->getEmitCounterPtr()[emitStream]; auto emitCounterTy = emitCounterPtr->getType()->getPointerElementType(); Value *emitCounter = new LoadInst(emitCounterTy, emitCounterPtr, "", &callInst); emitCounter = BinaryOperator::CreateAdd(emitCounter, ConstantInt::get(Type::getInt32Ty(*m_context), 1), "", &callInst); new StoreInst(emitCounter, emitCounterPtr, &callInst); } } } } // ===================================================================================================================== // Visits "ret" instruction. // // @param retInst : "Ret" instruction void PatchInOutImportExport::visitReturnInst(ReturnInst &retInst) { // We only handle the "ret" of shader entry point if (m_shaderStage == ShaderStageInvalid) return; const auto nextStage = m_pipelineState->getNextShaderStage(m_shaderStage); // Whether this shader stage has to use "exp" instructions to export outputs const bool useExpInst = ((m_shaderStage == ShaderStageVertex || m_shaderStage == ShaderStageTessEval || m_shaderStage == ShaderStageCopyShader) && (nextStage == ShaderStageInvalid || nextStage == ShaderStageFragment)); auto zero = ConstantFP::get(Type::getFloatTy(*m_context), 0.0); auto one = ConstantFP::get(Type::getFloatTy(*m_context), 1.0); auto undef = UndefValue::get(Type::getFloatTy(*m_context)); Instruction *insertPos = &retInst; const bool enableXfb = m_pipelineState->getShaderResourceUsage(m_shaderStage)->inOutUsage.enableXfb; if (m_shaderStage == ShaderStageCopyShader && enableXfb) { if (!m_pipelineState->getNggControl()->enableNgg) { // NOTE: For copy shader, if transform feedback is enabled for multiple streams, the following processing doesn't // happen in return block. Rather, they happen in the switch-case branch for the raster stream. See the following: // // copyShader() { // ... // switch(streamId) { // case 0: // export outputs of stream 0 // break // ... // case rasterStream: // export outputs of raster stream // break // ... // case 3: // export outputs of stream 3 // break // } // // return // } // // If NGG, the copy shader with stream-out is not a real HW VS and will be incorporated into NGG // primitive shader later. There is no mutiple HW executions. And it has the following structure similar to // single stream processing: // // copyShader() { // ... // export outputs of stream 0 // ... // export outputs of raster stream // ... // export outputs of stream 3 // // return // } // auto resUsage = m_pipelineState->getShaderResourceUsage(ShaderStageCopyShader); bool updated = false; for (auto &block : *m_entryPoint) { // Seach blocks to find the switch-case instruction auto switchInst = dyn_cast<SwitchInst>(block.getTerminator()); if (switchInst) { for (auto &caseBranch : switchInst->cases()) { if (caseBranch.getCaseValue()->getZExtValue() == resUsage->inOutUsage.gs.rasterStream) { // The insert position is updated to this case branch, before the terminator insertPos = caseBranch.getCaseSuccessor()->getTerminator(); updated = true; // We must go to return block from this case branch assert(caseBranch.getCaseSuccessor()->getSingleSuccessor() == retInst.getParent()); break; } } if (updated) break; // Early exit if we have updated the insert position } } } } if (useExpInst) { bool usePosition = false; bool usePointSize = false; bool usePrimitiveId = false; bool useLayer = false; bool useViewportIndex = false; bool useShadingRate = false; unsigned clipDistanceCount = 0; unsigned cullDistanceCount = 0; auto &inOutUsage = m_pipelineState->getShaderResourceUsage(m_shaderStage)->inOutUsage; const auto enableMultiView = m_pipelineState->getInputAssemblyState().enableMultiView; if (m_shaderStage == ShaderStageVertex) { auto &builtInUsage = m_pipelineState->getShaderResourceUsage(ShaderStageVertex)->builtInUsage.vs; auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageVertex)->entryArgIdxs.vs; usePosition = builtInUsage.position; usePointSize = builtInUsage.pointSize; usePrimitiveId = builtInUsage.primitiveId; useLayer = builtInUsage.layer; useViewportIndex = builtInUsage.viewportIndex; useShadingRate = builtInUsage.primitiveShadingRate; clipDistanceCount = builtInUsage.clipDistance; cullDistanceCount = builtInUsage.cullDistance; if (enableMultiView) { // NOTE: If multi-view is enabled, the exported value of gl_Layer is from gl_ViewIndex. m_layer = getFunctionArgument(m_entryPoint, entryArgIdxs.viewIndex); } } else if (m_shaderStage == ShaderStageTessEval) { auto &builtInUsage = m_pipelineState->getShaderResourceUsage(ShaderStageTessEval)->builtInUsage.tes; auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageTessEval)->entryArgIdxs.tes; usePosition = builtInUsage.position; usePointSize = builtInUsage.pointSize; usePrimitiveId = builtInUsage.primitiveId; useLayer = builtInUsage.layer; useViewportIndex = builtInUsage.viewportIndex; clipDistanceCount = builtInUsage.clipDistance; cullDistanceCount = builtInUsage.cullDistance; if (enableMultiView) { // NOTE: If multi-view is enabled, the exported value of gl_Layer is from gl_ViewIndex. m_layer = getFunctionArgument(m_entryPoint, entryArgIdxs.viewIndex); } } else { assert(m_shaderStage == ShaderStageCopyShader); auto &builtInUsage = m_pipelineState->getShaderResourceUsage(ShaderStageCopyShader)->builtInUsage.gs; usePosition = builtInUsage.position; usePointSize = builtInUsage.pointSize; usePrimitiveId = builtInUsage.primitiveId; useLayer = builtInUsage.layer; useViewportIndex = builtInUsage.viewportIndex; useShadingRate = builtInUsage.primitiveShadingRate; clipDistanceCount = builtInUsage.clipDistance; cullDistanceCount = builtInUsage.cullDistance; } useLayer = enableMultiView || useLayer; // NOTE: If gl_Position is not present in this shader stage, we have to export a dummy one. if (!usePosition) { Value *args[] = { ConstantInt::get(Type::getInt32Ty(*m_context), EXP_TARGET_POS_0), // tgt ConstantInt::get(Type::getInt32Ty(*m_context), 0xF), // en zero, // src0 zero, // src1 zero, // src2 one, // src3 ConstantInt::get(Type::getInt1Ty(*m_context), false), // done ConstantInt::get(Type::getInt1Ty(*m_context), false) // vm }; emitCall("llvm.amdgcn.exp.f32", Type::getVoidTy(*m_context), args, {}, insertPos); } // Export gl_ClipDistance[] and gl_CullDistance[] before entry-point returns if (clipDistanceCount > 0 || cullDistanceCount > 0) { assert(clipDistanceCount + cullDistanceCount <= MaxClipCullDistanceCount); assert(clipDistanceCount == 0 || (clipDistanceCount > 0 && m_clipDistance)); assert(cullDistanceCount == 0 || (cullDistanceCount > 0 && m_cullDistance)); // Extract elements of gl_ClipDistance[] and gl_CullDistance[] std::vector<Value *> clipDistance; for (unsigned i = 0; i < clipDistanceCount; ++i) clipDistance.push_back(ExtractValueInst::Create(m_clipDistance, {i}, "", insertPos)); std::vector<Value *> cullDistance; for (unsigned i = 0; i < cullDistanceCount; ++i) cullDistance.push_back(ExtractValueInst::Create(m_cullDistance, {i}, "", insertPos)); // Merge gl_ClipDistance[] and gl_CullDistance[] std::vector<Value *> clipCullDistance; for (auto clipDistanceElement : clipDistance) clipCullDistance.push_back(clipDistanceElement); for (auto cullDistanceElement : cullDistance) clipCullDistance.push_back(cullDistanceElement); // Do array padding if (clipCullDistance.size() <= 4) { while (clipCullDistance.size() < 4) // [4 x float] clipCullDistance.push_back(undef); } else { while (clipCullDistance.size() < 8) // [8 x float] clipCullDistance.push_back(undef); } bool miscExport = usePointSize || useLayer || useViewportIndex; miscExport |= useShadingRate; // NOTE: When misc. export is present, gl_ClipDistance[] or gl_CullDistance[] should start from pos2. unsigned pos = miscExport ? EXP_TARGET_POS_2 : EXP_TARGET_POS_1; Value *args[] = { ConstantInt::get(Type::getInt32Ty(*m_context), pos), // tgt ConstantInt::get(Type::getInt32Ty(*m_context), 0xF), // en clipCullDistance[0], // src0 clipCullDistance[1], // src1 clipCullDistance[2], // src2 clipCullDistance[3], // src3 ConstantInt::get(Type::getInt1Ty(*m_context), false), // done ConstantInt::get(Type::getInt1Ty(*m_context), false) // vm }; emitCall("llvm.amdgcn.exp.f32", Type::getVoidTy(*m_context), args, {}, insertPos); if (clipCullDistance.size() > 4) { // Do the second exporting Value *args[] = { ConstantInt::get(Type::getInt32Ty(*m_context), pos + 1), // tgt ConstantInt::get(Type::getInt32Ty(*m_context), 0xF), // en clipCullDistance[4], // src0 clipCullDistance[5], // src1 clipCullDistance[6], // src2 clipCullDistance[7], // src3 ConstantInt::get(Type::getInt1Ty(*m_context), false), // done ConstantInt::get(Type::getInt1Ty(*m_context), false) // vm }; emitCall("llvm.amdgcn.exp.f32", Type::getVoidTy(*m_context), args, {}, insertPos); } // NOTE: We have to export gl_ClipDistance[] or gl_CullDistancep[] via generic outputs as well. assert(nextStage == ShaderStageInvalid || nextStage == ShaderStageFragment); bool hasClipCullExport = true; if (nextStage == ShaderStageFragment) { const auto &nextBuiltInUsage = m_pipelineState->getShaderResourceUsage(ShaderStageFragment)->builtInUsage.fs; hasClipCullExport = (nextBuiltInUsage.clipDistance > 0 || nextBuiltInUsage.cullDistance > 0); if (hasClipCullExport) { // NOTE: We adjust the array size of gl_ClipDistance[] and gl_CullDistance[] according to their // usages in fragment shader. clipDistanceCount = std::min(nextBuiltInUsage.clipDistance, clipDistanceCount); cullDistanceCount = std::min(nextBuiltInUsage.cullDistance, cullDistanceCount); clipCullDistance.clear(); for (unsigned i = 0; i < clipDistanceCount; ++i) clipCullDistance.push_back(clipDistance[i]); for (unsigned i = clipDistanceCount; i < nextBuiltInUsage.clipDistance; ++i) clipCullDistance.push_back(undef); for (unsigned i = 0; i < cullDistanceCount; ++i) clipCullDistance.push_back(cullDistance[i]); // Do array padding if (clipCullDistance.size() <= 4) { while (clipCullDistance.size() < 4) // [4 x float] clipCullDistance.push_back(undef); } else { while (clipCullDistance.size() < 8) // [8 x float] clipCullDistance.push_back(undef); } } } if (hasClipCullExport) { unsigned loc = InvalidValue; if (m_shaderStage == ShaderStageCopyShader) { if (inOutUsage.gs.builtInOutLocs.find(BuiltInClipDistance) != inOutUsage.gs.builtInOutLocs.end()) loc = inOutUsage.gs.builtInOutLocs[BuiltInClipDistance]; else { assert(inOutUsage.gs.builtInOutLocs.find(BuiltInCullDistance) != inOutUsage.gs.builtInOutLocs.end()); loc = inOutUsage.gs.builtInOutLocs[BuiltInCullDistance]; } } else { if (inOutUsage.builtInOutputLocMap.find(BuiltInClipDistance) != inOutUsage.builtInOutputLocMap.end()) loc = inOutUsage.builtInOutputLocMap[BuiltInClipDistance]; else { assert(inOutUsage.builtInOutputLocMap.find(BuiltInCullDistance) != inOutUsage.builtInOutputLocMap.end()); loc = inOutUsage.builtInOutputLocMap[BuiltInCullDistance]; } } recordVertexAttribExport(loc, {clipCullDistance[0], clipCullDistance[1], clipCullDistance[2], clipCullDistance[3]}); if (clipCullDistance.size() > 4) { // Do the second exporting recordVertexAttribExport( loc + 1, {clipCullDistance[4], clipCullDistance[5], clipCullDistance[6], clipCullDistance[7]}); } } } // Export gl_PrimitiveID before entry-point returns if (usePrimitiveId) { bool hasPrimitiveIdExport = false; if (nextStage == ShaderStageFragment) { hasPrimitiveIdExport = m_pipelineState->getShaderResourceUsage(ShaderStageFragment)->builtInUsage.fs.primitiveId; } else if (nextStage == ShaderStageInvalid) { if (m_shaderStage == ShaderStageCopyShader) { hasPrimitiveIdExport = m_pipelineState->getShaderResourceUsage(ShaderStageGeometry)->builtInUsage.gs.primitiveId; } } if (hasPrimitiveIdExport) { unsigned loc = InvalidValue; if (m_shaderStage == ShaderStageCopyShader) { assert(inOutUsage.gs.builtInOutLocs.find(BuiltInPrimitiveId) != inOutUsage.gs.builtInOutLocs.end()); loc = inOutUsage.gs.builtInOutLocs[BuiltInPrimitiveId]; } else { assert(inOutUsage.builtInOutputLocMap.find(BuiltInPrimitiveId) != inOutUsage.builtInOutputLocMap.end()); loc = inOutUsage.builtInOutputLocMap[BuiltInPrimitiveId]; } assert(m_primitiveId); Value *primitiveId = new BitCastInst(m_primitiveId, Type::getFloatTy(*m_context), "", insertPos); recordVertexAttribExport(loc, {primitiveId, undef, undef, undef}); } } // NOTE: If multi-view is enabled, always do exporting for gl_Layer. if (m_gfxIp.major <= 8 && enableMultiView) { assert(m_layer); addExportInstForBuiltInOutput(m_layer, BuiltInLayer, insertPos); } // Export gl_Layer and gl_ViewportIndex before entry-point returns if (m_gfxIp.major >= 9 && (useLayer || useViewportIndex)) { Value *viewportIndexAndLayer = ConstantInt::get(Type::getInt32Ty(*m_context), 0); if (useViewportIndex) { assert(m_viewportIndex); viewportIndexAndLayer = BinaryOperator::CreateShl( m_viewportIndex, ConstantInt::get(Type::getInt32Ty(*m_context), 16), "", insertPos); } if (useLayer) { assert(m_layer); viewportIndexAndLayer = BinaryOperator::CreateOr(viewportIndexAndLayer, m_layer, "", insertPos); } viewportIndexAndLayer = new BitCastInst(viewportIndexAndLayer, Type::getFloatTy(*m_context), "", insertPos); Value *args[] = { ConstantInt::get(Type::getInt32Ty(*m_context), EXP_TARGET_POS_1), // tgt ConstantInt::get(Type::getInt32Ty(*m_context), 0x4), // en undef, // src0 undef, // src1 viewportIndexAndLayer, // src2 undef, // src3 ConstantInt::get(Type::getInt1Ty(*m_context), false), // done ConstantInt::get(Type::getInt1Ty(*m_context), false) // vm }; emitCall("llvm.amdgcn.exp.f32", Type::getVoidTy(*m_context), args, {}, insertPos); // NOTE: We have to export gl_ViewportIndex via generic outputs as well. if (useViewportIndex) { bool hasViewportIndexExport = true; if (nextStage == ShaderStageFragment) { const auto &nextBuiltInUsage = m_pipelineState->getShaderResourceUsage(ShaderStageFragment)->builtInUsage.fs; hasViewportIndexExport = nextBuiltInUsage.viewportIndex; } if (hasViewportIndexExport) { unsigned loc = InvalidValue; if (m_shaderStage == ShaderStageCopyShader) { assert(inOutUsage.gs.builtInOutLocs.find(BuiltInViewportIndex) != inOutUsage.gs.builtInOutLocs.end()); loc = inOutUsage.gs.builtInOutLocs[BuiltInViewportIndex]; } else { assert(inOutUsage.builtInOutputLocMap.find(BuiltInViewportIndex) != inOutUsage.builtInOutputLocMap.end()); loc = inOutUsage.builtInOutputLocMap[BuiltInViewportIndex]; } Value *viewportIndex = new BitCastInst(m_viewportIndex, Type::getFloatTy(*m_context), "", insertPos); recordVertexAttribExport(loc, {viewportIndex, undef, undef, undef}); } } // NOTE: We have to export gl_Layer via generic outputs as well. if (useLayer) { bool hasLayerExport = true; if (nextStage == ShaderStageFragment) { const auto &nextBuiltInUsage = m_pipelineState->getShaderResourceUsage(ShaderStageFragment)->builtInUsage.fs; hasLayerExport = nextBuiltInUsage.layer || nextBuiltInUsage.viewIndex; } if (hasLayerExport) { unsigned loc = InvalidValue; if (m_shaderStage == ShaderStageCopyShader) { assert(inOutUsage.gs.builtInOutLocs.find(BuiltInLayer) != inOutUsage.gs.builtInOutLocs.end() || inOutUsage.gs.builtInOutLocs.find(BuiltInViewIndex) != inOutUsage.gs.builtInOutLocs.end()); loc = enableMultiView ? inOutUsage.gs.builtInOutLocs[BuiltInViewIndex] : inOutUsage.gs.builtInOutLocs[BuiltInLayer]; } else { assert(inOutUsage.builtInOutputLocMap.find(BuiltInLayer) != inOutUsage.builtInOutputLocMap.end() || inOutUsage.builtInOutputLocMap.find(BuiltInViewIndex) != inOutUsage.builtInOutputLocMap.end()); loc = enableMultiView ? inOutUsage.builtInOutputLocMap[BuiltInViewIndex] : inOutUsage.builtInOutputLocMap[BuiltInLayer]; } Value *layer = new BitCastInst(m_layer, Type::getFloatTy(*m_context), "", insertPos); recordVertexAttribExport(loc, {layer, undef, undef, undef}); } } } // NOTE: For GFX10+, dummy generic output is no longer needed. Field NO_PC_EXPORT of SPI_VS_OUT_CONFIG // will control the behavior. if (m_gfxIp.major <= 9) { // NOTE: If no generic outputs is present in this shader, we have to export a dummy one if (inOutUsage.expCount == 0) recordVertexAttribExport(0, {undef, undef, undef, undef}); } // Export vertex attributes that were recorded previously exportVertexAttribs(insertPos); if (m_pipelineState->isUnlinked()) { // If we are building unlinked relocatable shaders, it is possible there are // generic outputs that are not written to. We need to count them in // the export count. auto resUsage = m_pipelineState->getShaderResourceUsage(m_shaderStage); for (const auto &locInfoPair : resUsage->inOutUsage.outputLocInfoMap) { const unsigned newLoc = locInfoPair.second.getLocation(); if (m_expLocs.count(newLoc) != 0) continue; inOutUsage.expCount = std::max(inOutUsage.expCount, newLoc + 1); // Update export count } } } else if (m_shaderStage == ShaderStageGeometry) { if (!m_pipelineState->isGsOnChip() && m_gfxIp.major >= 10) { // NOTE: This is a workaround because backend compiler does not provide s_waitcnt_vscnt intrinsic, so we // use fence release to generate s_waitcnt vmcnt/s_waitcnt_vscnt before s_sendmsg(MSG_GS_DONE) new FenceInst(*m_context, AtomicOrdering::Release, SyncScope::System, insertPos); } auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageGeometry)->entryArgIdxs.gs; auto waveId = getFunctionArgument(m_entryPoint, entryArgIdxs.waveId); Value *args[] = {ConstantInt::get(Type::getInt32Ty(*m_context), GsDone), waveId}; emitCall("llvm.amdgcn.s.sendmsg", Type::getVoidTy(*m_context), args, {}, insertPos); } else if (m_shaderStage == ShaderStageFragment) { // Fragment shader export are handled in LowerFragColorExport. return; } } // ===================================================================================================================== // Patches import calls for generic inputs of tessellation control shader. // // @param inputTy : Type of input value // @param location : Base location of the input // @param locOffset : Relative location offset // @param compIdx : Index used for vector element indexing // @param vertexIdx : Input array outermost index used for vertex indexing // @param insertPos : Where to insert the patch instruction Value *PatchInOutImportExport::patchTcsGenericInputImport(Type *inputTy, unsigned location, Value *locOffset, Value *compIdx, Value *vertexIdx, Instruction *insertPos) { assert(compIdx && vertexIdx); auto ldsOffset = calcLdsOffsetForTcsInput(inputTy, location, locOffset, compIdx, vertexIdx, insertPos); return readValueFromLds(false, inputTy, ldsOffset, insertPos); } // ===================================================================================================================== // Patches import calls for generic inputs of tessellation evaluation shader. // // @param inputTy : Type of input value // @param location : Base location of the input // @param locOffset : Relative location offset // @param compIdx : Index used for vector element indexing // @param vertexIdx : Input array outermost index used for vertex indexing (could be null) // @param insertPos : Where to insert the patch instruction Value *PatchInOutImportExport::patchTesGenericInputImport(Type *inputTy, unsigned location, Value *locOffset, Value *compIdx, Value *vertexIdx, Instruction *insertPos) { assert(compIdx); auto ldsOffset = calcLdsOffsetForTesInput(inputTy, location, locOffset, compIdx, vertexIdx, insertPos); return readValueFromLds(false, inputTy, ldsOffset, insertPos); } // ===================================================================================================================== // Patches import calls for generic inputs of geometry shader. // // @param inputTy : Type of input value // @param location : Location of the input // @param compIdx : Index used for vector element indexing // @param vertexIdx : Input array outermost index used for vertex indexing // @param insertPos : Where to insert the patch instruction Value *PatchInOutImportExport::patchGsGenericInputImport(Type *inputTy, unsigned location, unsigned compIdx, Value *vertexIdx, Instruction *insertPos) { assert(vertexIdx); const unsigned compCount = inputTy->isVectorTy() ? cast<FixedVectorType>(inputTy)->getNumElements() : 1; const unsigned bitWidth = inputTy->getScalarSizeInBits(); Type *origInputTy = inputTy; if (bitWidth == 64) { compIdx *= 2; // For 64-bit data type, the component indexing must multiply by 2 // Cast 64-bit data type to float vector inputTy = FixedVectorType::get(Type::getFloatTy(*m_context), compCount * 2); } else assert(bitWidth == 8 || bitWidth == 16 || bitWidth == 32); Value *input = loadValueFromEsGsRing(inputTy, location, compIdx, vertexIdx, insertPos); if (inputTy != origInputTy) { // Cast back to oringinal input type assert(canBitCast(inputTy, origInputTy)); assert(inputTy->isVectorTy()); input = new BitCastInst(input, origInputTy, "", insertPos); } return input; } // ===================================================================================================================== // Translate float type interpolation into corresponding LLVM intrinsics // // @param builder : The IR builder to to create and insert IR instruction // @param attr : The attribute location to access // @param channel: The specific attribute channel to access // @param coordI: Value of I coordinate // @param coordJ: Value of J coordinate // @param primMask: Value to fill into m0 register Value *PatchInOutImportExport::performFsFloatInterpolation(BuilderBase &builder, Value *attr, Value *channel, Value *coordI, Value *coordJ, Value *primMask) { Value *result = nullptr; Attribute::AttrKind attribs[] = {Attribute::ReadNone}; { // llvm.amdgcn.interp.p1(coordI, attr_channel, attr, m0) result = builder.CreateNamedCall("llvm.amdgcn.interp.p1", builder.getFloatTy(), {coordI, channel, attr, primMask}, attribs); // llvm.amdgcn.interp.p2(p1, coordJ, attr_channel, attr, m0) result = builder.CreateNamedCall("llvm.amdgcn.interp.p2", builder.getFloatTy(), {result, coordJ, channel, attr, primMask}, attribs); } return result; } // ===================================================================================================================== // Translate half type interpolation into corresponding LLVM intrinsics // // @param builder : The IR builder to to create and insert IR instruction // @param attr : The attribute location to access // @param channel: The specific attribute channel to access // @param coordI: Value of I coordinate // @param coordJ: Value of J coordinate // @param primMask: Value to fill into m0 register Value *PatchInOutImportExport::performFsHalfInterpolation(BuilderBase &builder, Value *attr, Value *channel, Value *coordI, Value *coordJ, Value *primMask, Value *highHalf) { Value *result = nullptr; Attribute::AttrKind attribs[] = {Attribute::ReadNone}; { // llvm.amdgcn.interp.p1.f16(coordI, attr_channel, attr, highhalf, m0) result = builder.CreateNamedCall("llvm.amdgcn.interp.p1.f16", builder.getFloatTy(), {coordI, channel, attr, highHalf, primMask}, attribs); // llvm.amdgcn.interp.p2.f16(p1, coordJ, attr_channel, attr, highhalf, m0) result = builder.CreateNamedCall("llvm.amdgcn.interp.p2.f16", builder.getHalfTy(), {result, coordJ, channel, attr, highHalf, primMask}, attribs); } return result; } // ===================================================================================================================== // Load a specified FS parameter (used under flat/custom interpolation). // // @param builder : The IR builder to create and insert IR instruction // @param attr : The attribute location to access // @param channel : The specific attribute channel to access // @param interpParam : The parameter to load // @param primMask : Value to fill into m0 register // @param bitWidth : The bitwidth of required data type // @param highHalf : Whether it is a high half in a 16-bit attribute Value *PatchInOutImportExport::performFsParameterLoad(BuilderBase &builder, Value *attr, Value *channel, InterpParam interpParam, Value *primMask, unsigned bitWidth, bool highHalf) { Value *compValue = nullptr; { Value *args[] = { builder.getInt32(interpParam), // param channel, // attr_chan attr, // attr primMask // m0 }; compValue = builder.CreateNamedCall("llvm.amdgcn.interp.mov", builder.getFloatTy(), args, {Attribute::ReadNone}); } // Two int8s are also packed like 16-bit in a 32-bit channel in previous export stage if (bitWidth == 8 || bitWidth == 16) { compValue = builder.CreateBitCast(compValue, builder.getInt32Ty()); if (highHalf) compValue = builder.CreateLShr(compValue, 16); if (bitWidth == 8) { compValue = builder.CreateTrunc(compValue, builder.getInt8Ty()); } else { compValue = builder.CreateTrunc(compValue, builder.getInt16Ty()); compValue = builder.CreateBitCast(compValue, builder.getHalfTy()); } } return compValue; } // ===================================================================================================================== // Patches import calls for generic inputs of fragment shader. // // @param inputTy : Type of input value // @param location : Base location of the input // @param locOffset : Relative location offset // @param compIdx : Index used for vector element indexing (could be null) // @param auxInterpValue : Auxiliary value of interpolation: for non "custom" interpolation, it is the explicitly // calculated I/J; for "custom" interpolation, it is vertex no. (could be null) // @param interpMode : Interpolation mode // @param interpLoc : Interpolation location // @param highHalf : Whether it is a high half in a 16-bit attribute // @param insertPos : Where to insert the patch instruction Value *PatchInOutImportExport::patchFsGenericInputImport(Type *inputTy, unsigned location, Value *locOffset, Value *compIdx, Value *auxInterpValue, unsigned interpMode, unsigned interpLoc, bool highHalf, Instruction *insertPos) { BuilderBase builder(*m_context); builder.SetInsertPoint(insertPos); Value *input = UndefValue::get(inputTy); auto resUsage = m_pipelineState->getShaderResourceUsage(ShaderStageFragment); auto &interpInfo = resUsage->inOutUsage.fs.interpInfo; const unsigned locCount = inputTy->getPrimitiveSizeInBits() / 8 > SizeOfVec4 ? 2 : 1; while (interpInfo.size() <= location + locCount - 1) interpInfo.push_back(InvalidFsInterpInfo); // Set the fields of FsInterpInfo except attr1Valid at location when it is not a high half if (!highHalf) { auto &interpInfoAtLoc = interpInfo[location]; interpInfoAtLoc.loc = location; interpInfoAtLoc.flat = interpMode == InOutInfo::InterpModeFlat; interpInfoAtLoc.custom = interpMode == InOutInfo::InterpModeCustom; interpInfoAtLoc.is16bit = inputTy->getScalarSizeInBits() == 16; interpInfoAtLoc.attr0Valid = true; } else { // attr1Valid is false by default and set it true when it is realy a high half interpInfo[location].attr1Valid = true; } if (locCount > 1) { // The input occupies two consecutive locations assert(locCount == 2); interpInfo[location + 1] = { location + 1, (interpMode == InOutInfo::InterpModeFlat), (interpMode == InOutInfo::InterpModeCustom), false, }; } auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageFragment)->entryArgIdxs.fs; auto primMask = getFunctionArgument(m_entryPoint, entryArgIdxs.primMask); Value *coordI = nullptr; Value *coordJ = nullptr; // Not "flat" and "custom" interpolation if (interpMode != InOutInfo::InterpModeFlat && interpMode != InOutInfo::InterpModeCustom) { auto ij = auxInterpValue; if (!ij) { if (interpMode == InOutInfo::InterpModeSmooth) { if (interpLoc == InOutInfo::InterpLocCentroid) { ij = adjustCentroidIj(getFunctionArgument(m_entryPoint, entryArgIdxs.perspInterp.centroid), getFunctionArgument(m_entryPoint, entryArgIdxs.perspInterp.center), insertPos); } else if (interpLoc == InOutInfo::InterpLocSample) ij = getFunctionArgument(m_entryPoint, entryArgIdxs.perspInterp.sample); else { assert(interpLoc == InOutInfo::InterpLocCenter); ij = getFunctionArgument(m_entryPoint, entryArgIdxs.perspInterp.center); } } else { assert(interpMode == InOutInfo::InterpModeNoPersp); if (interpLoc == InOutInfo::InterpLocCentroid) { ij = adjustCentroidIj(getFunctionArgument(m_entryPoint, entryArgIdxs.linearInterp.centroid), getFunctionArgument(m_entryPoint, entryArgIdxs.linearInterp.center), insertPos); } else if (interpLoc == InOutInfo::InterpLocSample) ij = getFunctionArgument(m_entryPoint, entryArgIdxs.linearInterp.sample); else { assert(interpLoc == InOutInfo::InterpLocCenter); ij = getFunctionArgument(m_entryPoint, entryArgIdxs.linearInterp.center); } } } coordI = ExtractElementInst::Create(ij, ConstantInt::get(Type::getInt32Ty(*m_context), 0), "", insertPos); coordJ = ExtractElementInst::Create(ij, ConstantInt::get(Type::getInt32Ty(*m_context), 1), "", insertPos); } Type *basicTy = inputTy->isVectorTy() ? cast<VectorType>(inputTy)->getElementType() : inputTy; const unsigned compCout = inputTy->isVectorTy() ? cast<FixedVectorType>(inputTy)->getNumElements() : 1; const unsigned bitWidth = inputTy->getScalarSizeInBits(); assert(bitWidth == 8 || bitWidth == 16 || bitWidth == 32 || bitWidth == 64); const unsigned numChannels = (bitWidth == 64 ? 2 : 1) * compCout; Type *interpTy = nullptr; if (bitWidth == 8) { assert(inputTy->isIntOrIntVectorTy()); interpTy = Type::getInt8Ty(*m_context); } else if (bitWidth == 16) interpTy = Type::getHalfTy(*m_context); else interpTy = Type::getFloatTy(*m_context); if (numChannels > 1) interpTy = FixedVectorType::get(interpTy, numChannels); Value *interp = UndefValue::get(interpTy); unsigned startChannel = 0; if (compIdx) startChannel = cast<ConstantInt>(compIdx)->getZExtValue(); Value *loc = ConstantInt::get(Type::getInt32Ty(*m_context), location); if (locOffset) { loc = BinaryOperator::CreateAdd(loc, locOffset, "", insertPos); assert((startChannel + numChannels) <= 4); } for (unsigned i = startChannel; i < startChannel + numChannels; ++i) { Value *compValue = nullptr; if (interpMode != InOutInfo::InterpModeFlat && interpMode != InOutInfo::InterpModeCustom) { assert((basicTy->isHalfTy() || basicTy->isFloatTy()) && numChannels <= 4); (void(basicTy)); // unused if (bitWidth == 16) { compValue = performFsHalfInterpolation(builder, loc, builder.getInt32(i), coordI, coordJ, primMask, builder.getInt1(highHalf)); } else { compValue = performFsFloatInterpolation(builder, loc, builder.getInt32(i), coordI, coordJ, primMask); } } else { InterpParam interpParam = INTERP_PARAM_P0; if (interpMode == InOutInfo::InterpModeCustom) { assert(isa<ConstantInt>(auxInterpValue)); unsigned vertexNo = cast<ConstantInt>(auxInterpValue)->getZExtValue(); switch (vertexNo) { case 0: interpParam = INTERP_PARAM_P0; break; case 1: interpParam = INTERP_PARAM_P10; break; case 2: interpParam = INTERP_PARAM_P20; break; default: llvm_unreachable("Should never be called!"); break; } } else { assert(interpMode == InOutInfo::InterpModeFlat); } Value *attr = locOffset ? loc : builder.getInt32(location + i / 4); compValue = performFsParameterLoad(builder, attr, builder.getInt32(i % 4), interpParam, primMask, bitWidth, highHalf); } if (numChannels == 1) interp = compValue; else { interp = InsertElementInst::Create( interp, compValue, ConstantInt::get(Type::getInt32Ty(*m_context), i - startChannel), "", insertPos); } } // Store interpolation results to inputs if (interpTy == inputTy) input = interp; else { assert(canBitCast(interpTy, inputTy)); input = new BitCastInst(interp, inputTy, "", insertPos); } return input; } // ===================================================================================================================== // Patches import calls for generic outputs of tessellation control shader. // // @param outputTy : Type of output value // @param location : Base location of the output // @param locOffset : Relative location offset // @param compIdx : Index used for vector element indexing // @param vertexIdx : Input array outermost index used for vertex indexing (could be null) // @param insertPos : Where to insert the patch instruction Value *PatchInOutImportExport::patchTcsGenericOutputImport(Type *outputTy, unsigned location, Value *locOffset, Value *compIdx, Value *vertexIdx, Instruction *insertPos) { assert(compIdx); auto ldsOffset = calcLdsOffsetForTcsOutput(outputTy, location, locOffset, compIdx, vertexIdx, insertPos); return readValueFromLds(true, outputTy, ldsOffset, insertPos); } // ===================================================================================================================== // Patches export calls for generic outputs of vertex shader. // // @param output : Output value // @param location : Location of the output // @param compIdx : Index used for vector element indexing // @param insertPos : Where to insert the patch instruction void PatchInOutImportExport::patchVsGenericOutputExport(Value *output, unsigned location, unsigned compIdx, Instruction *insertPos) { auto outputTy = output->getType(); if (m_hasTs) { auto ldsOffset = calcLdsOffsetForVsOutput(outputTy, location, compIdx, insertPos); writeValueToLds(output, ldsOffset, insertPos); } else { if (m_hasGs) { assert(outputTy->isIntOrIntVectorTy() || outputTy->isFPOrFPVectorTy()); const unsigned bitWidth = outputTy->getScalarSizeInBits(); if (bitWidth == 64) { // For 64-bit data type, the component indexing must multiply by 2 compIdx *= 2; unsigned compCount = outputTy->isVectorTy() ? cast<FixedVectorType>(outputTy)->getNumElements() * 2 : 2; outputTy = FixedVectorType::get(Type::getFloatTy(*m_context), compCount); output = new BitCastInst(output, outputTy, "", insertPos); } else assert(bitWidth == 8 || bitWidth == 16 || bitWidth == 32); storeValueToEsGsRing(output, location, compIdx, insertPos); } else addExportInstForGenericOutput(output, location, compIdx, insertPos); } } // ===================================================================================================================== // Patches export calls for generic outputs of tessellation control shader. // // @param output : Output value // @param location : Base location of the output // @param locOffset : Relative location offset // @param compIdx : Index used for vector element indexing // @param vertexIdx : Input array outermost index used for vertex indexing (could be null) // @param insertPos : Where to insert the patch instruction void PatchInOutImportExport::patchTcsGenericOutputExport(Value *output, unsigned location, Value *locOffset, Value *compIdx, Value *vertexIdx, Instruction *insertPos) { assert(compIdx); Type *outputTy = output->getType(); auto ldsOffset = calcLdsOffsetForTcsOutput(outputTy, location, locOffset, compIdx, vertexIdx, insertPos); writeValueToLds(output, ldsOffset, insertPos); } // ===================================================================================================================== // Patches export calls for generic outputs of tessellation evaluation shader. // // @param output : Output value // @param location : Location of the output // @param compIdx : Index used for vector element indexing // @param insertPos : Where to insert the patch instruction void PatchInOutImportExport::patchTesGenericOutputExport(Value *output, unsigned location, unsigned compIdx, Instruction *insertPos) { if (m_hasGs) { auto outputTy = output->getType(); assert(outputTy->isIntOrIntVectorTy() || outputTy->isFPOrFPVectorTy()); const unsigned bitWidth = outputTy->getScalarSizeInBits(); if (bitWidth == 64) { // For 64-bit data type, the component indexing must multiply by 2 compIdx *= 2; unsigned compCount = outputTy->isVectorTy() ? cast<FixedVectorType>(outputTy)->getNumElements() * 2 : 2; outputTy = FixedVectorType::get(Type::getFloatTy(*m_context), compCount); output = new BitCastInst(output, outputTy, "", insertPos); } else assert(bitWidth == 8 || bitWidth == 16 || bitWidth == 32); storeValueToEsGsRing(output, location, compIdx, insertPos); } else addExportInstForGenericOutput(output, location, compIdx, insertPos); } // ===================================================================================================================== // Patches export calls for generic outputs of geometry shader. // // @param output : Output value // @param location : Location of the output // @param compIdx : Index used for vector element indexing // @param streamId : ID of output vertex stream // @param insertPos : Where to insert the patch instruction void PatchInOutImportExport::patchGsGenericOutputExport(Value *output, unsigned location, unsigned compIdx, unsigned streamId, Instruction *insertPos) { auto outputTy = output->getType(); // Cast double or double vector to float vector. const unsigned bitWidth = outputTy->getScalarSizeInBits(); if (bitWidth == 64) { // For 64-bit data type, the component indexing must multiply by 2 compIdx *= 2; if (outputTy->isVectorTy()) outputTy = FixedVectorType::get(Type::getFloatTy(*m_context), cast<FixedVectorType>(outputTy)->getNumElements() * 2); else outputTy = FixedVectorType::get(Type::getFloatTy(*m_context), 2); output = new BitCastInst(output, outputTy, "", insertPos); } else assert(bitWidth == 8 || bitWidth == 16 || bitWidth == 32); const unsigned compCount = outputTy->isVectorTy() ? cast<FixedVectorType>(outputTy)->getNumElements() : 1; // NOTE: Currently, to simplify the design of load/store data from GS-VS ring, we always extend byte/word to dword and // store dword to GS-VS ring. So for 8-bit/16-bit data type, the actual byte size is based on number of dwords. unsigned byteSize = (outputTy->getScalarSizeInBits() / 8) * compCount; if (bitWidth == 8 || bitWidth == 16) byteSize *= (32 / bitWidth); assert(compIdx <= 4); storeValueToGsVsRing(output, location, compIdx, streamId, insertPos); } // ===================================================================================================================== // Patches import calls for built-in inputs of vertex shader. // // @param inputTy : Type of input value // @param builtInId : ID of the built-in variable // @param insertPos : Where to insert the patch instruction Value *PatchInOutImportExport::patchVsBuiltInInputImport(Type *inputTy, unsigned builtInId, Instruction *insertPos) { auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageVertex)->entryArgIdxs.vs; switch (builtInId) { // BuiltInVertexIndex, BuiltInInstanceIndex, BuiltInBaseVertex, BuiltInBaseInstance, BuiltInDrawIndex // now handled in InOutBuilder. case BuiltInViewIndex: return getFunctionArgument(m_entryPoint, entryArgIdxs.viewIndex); default: llvm_unreachable("Should never be called!"); return UndefValue::get(inputTy); } } // ===================================================================================================================== // Patches import calls for built-in inputs of tessellation control shader. // // @param inputTy : Type of input value // @param builtInId : ID of the built-in variable // @param elemIdx : Index used for array/vector element indexing (could be null) // @param vertexIdx : Input array outermost index used for vertex indexing (could be null) // @param insertPos : Where to insert the patch instruction Value *PatchInOutImportExport::patchTcsBuiltInInputImport(Type *inputTy, unsigned builtInId, Value *elemIdx, Value *vertexIdx, Instruction *insertPos) { Value *input = UndefValue::get(inputTy); auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageTessControl)->entryArgIdxs.tcs; auto resUsage = m_pipelineState->getShaderResourceUsage(ShaderStageTessControl); auto &inoutUsage = resUsage->inOutUsage; auto &builtInInLocMap = inoutUsage.builtInInputLocMap; switch (builtInId) { case BuiltInPosition: { assert(builtInInLocMap.find(builtInId) != builtInInLocMap.end()); const unsigned loc = builtInInLocMap[builtInId]; auto ldsOffset = calcLdsOffsetForTcsInput(inputTy, loc, nullptr, elemIdx, vertexIdx, insertPos); input = readValueFromLds(false, inputTy, ldsOffset, insertPos); break; } case BuiltInPointSize: { assert(!elemIdx); assert(builtInInLocMap.find(builtInId) != builtInInLocMap.end()); const unsigned loc = builtInInLocMap[builtInId]; auto ldsOffset = calcLdsOffsetForTcsInput(inputTy, loc, nullptr, nullptr, vertexIdx, insertPos); input = readValueFromLds(false, inputTy, ldsOffset, insertPos); break; } case BuiltInClipDistance: case BuiltInCullDistance: { assert(builtInInLocMap.find(builtInId) != builtInInLocMap.end()); const unsigned loc = builtInInLocMap[builtInId]; if (!elemIdx) { // gl_ClipDistanceIn[]/gl_CullDistanceIn[] is treated as 2 x vec4 assert(inputTy->isArrayTy()); auto elemTy = inputTy->getArrayElementType(); for (unsigned i = 0; i < inputTy->getArrayNumElements(); ++i) { auto elemIdx = ConstantInt::get(Type::getInt32Ty(*m_context), i); auto ldsOffset = calcLdsOffsetForTcsInput(elemTy, loc, nullptr, elemIdx, vertexIdx, insertPos); auto elem = readValueFromLds(false, elemTy, ldsOffset, insertPos); input = InsertValueInst::Create(input, elem, {i}, "", insertPos); } } else { auto ldsOffset = calcLdsOffsetForTcsInput(inputTy, loc, nullptr, elemIdx, vertexIdx, insertPos); input = readValueFromLds(false, inputTy, ldsOffset, insertPos); } break; } case BuiltInPatchVertices: { input = ConstantInt::get(Type::getInt32Ty(*m_context), m_pipelineState->getInputAssemblyState().patchControlPoints); break; } case BuiltInPrimitiveId: { input = m_pipelineSysValues.get(m_entryPoint)->getPrimitiveId(); break; } case BuiltInInvocationId: { input = m_pipelineSysValues.get(m_entryPoint)->getInvocationId(); break; } case BuiltInViewIndex: { input = getFunctionArgument(m_entryPoint, entryArgIdxs.viewIndex); break; } default: { llvm_unreachable("Should never be called!"); break; } } return input; } // ===================================================================================================================== // Patches import calls for built-in inputs of tessellation evaluation shader. // // @param inputTy : Type of input value // @param builtInId : ID of the built-in variable // @param elemIdx : Index used for array/vector element indexing (could be null) // @param vertexIdx : Input array outermost index used for vertex indexing (could be null) // @param insertPos : Where to insert the patch instruction Value *PatchInOutImportExport::patchTesBuiltInInputImport(Type *inputTy, unsigned builtInId, Value *elemIdx, Value *vertexIdx, Instruction *insertPos) { Value *input = UndefValue::get(inputTy); auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageTessEval)->entryArgIdxs.tes; auto resUsage = m_pipelineState->getShaderResourceUsage(ShaderStageTessEval); auto &inOutUsage = resUsage->inOutUsage; auto &builtInInLocMap = inOutUsage.builtInInputLocMap; auto &perPatchBuiltInInLocMap = inOutUsage.perPatchBuiltInInputLocMap; switch (builtInId) { case BuiltInPosition: { assert(builtInInLocMap.find(builtInId) != builtInInLocMap.end()); const unsigned loc = builtInInLocMap[builtInId]; auto ldsOffset = calcLdsOffsetForTesInput(inputTy, loc, nullptr, elemIdx, vertexIdx, insertPos); input = readValueFromLds(false, inputTy, ldsOffset, insertPos); break; } case BuiltInPointSize: { assert(!elemIdx); assert(builtInInLocMap.find(builtInId) != builtInInLocMap.end()); const unsigned loc = builtInInLocMap[builtInId]; auto ldsOffset = calcLdsOffsetForTesInput(inputTy, loc, nullptr, nullptr, vertexIdx, insertPos); input = readValueFromLds(false, inputTy, ldsOffset, insertPos); break; } case BuiltInClipDistance: case BuiltInCullDistance: { assert(builtInInLocMap.find(builtInId) != builtInInLocMap.end()); const unsigned loc = builtInInLocMap[builtInId]; if (!elemIdx) { // gl_ClipDistanceIn[]/gl_CullDistanceIn[] is treated as 2 x vec4 assert(inputTy->isArrayTy()); auto elemTy = inputTy->getArrayElementType(); for (unsigned i = 0; i < inputTy->getArrayNumElements(); ++i) { auto elemIdx = ConstantInt::get(Type::getInt32Ty(*m_context), i); auto ldsOffset = calcLdsOffsetForTesInput(elemTy, loc, nullptr, elemIdx, vertexIdx, insertPos); auto elem = readValueFromLds(false, elemTy, ldsOffset, insertPos); input = InsertValueInst::Create(input, elem, {i}, "", insertPos); } } else { auto ldsOffset = calcLdsOffsetForTesInput(inputTy, loc, nullptr, elemIdx, vertexIdx, insertPos); input = readValueFromLds(false, inputTy, ldsOffset, insertPos); } break; } case BuiltInPatchVertices: { unsigned patchVertices = MaxTessPatchVertices; const bool hasTcs = m_pipelineState->hasShaderStage(ShaderStageTessControl); if (hasTcs) patchVertices = m_pipelineState->getShaderModes()->getTessellationMode().outputVertices; input = ConstantInt::get(Type::getInt32Ty(*m_context), patchVertices); break; } case BuiltInPrimitiveId: { input = getFunctionArgument(m_entryPoint, entryArgIdxs.patchId); break; } case BuiltInTessCoord: { auto tessCoord = m_pipelineSysValues.get(m_entryPoint)->getTessCoord(); if (elemIdx) input = ExtractElementInst::Create(tessCoord, elemIdx, "", insertPos); else input = tessCoord; break; } case BuiltInTessLevelOuter: case BuiltInTessLevelInner: { assert(perPatchBuiltInInLocMap.find(builtInId) != perPatchBuiltInInLocMap.end()); unsigned loc = perPatchBuiltInInLocMap[builtInId]; if (!elemIdx) { // gl_TessLevelOuter[4] is treated as vec4 // gl_TessLevelInner[2] is treated as vec2 assert(inputTy->isArrayTy()); auto elemTy = inputTy->getArrayElementType(); for (unsigned i = 0; i < inputTy->getArrayNumElements(); ++i) { auto elemIdx = ConstantInt::get(Type::getInt32Ty(*m_context), i); auto ldsOffset = calcLdsOffsetForTesInput(elemTy, loc, nullptr, elemIdx, vertexIdx, insertPos); auto elem = readValueFromLds(false, elemTy, ldsOffset, insertPos); input = InsertValueInst::Create(input, elem, {i}, "", insertPos); } } else { auto ldsOffset = calcLdsOffsetForTesInput(inputTy, loc, nullptr, elemIdx, vertexIdx, insertPos); input = readValueFromLds(false, inputTy, ldsOffset, insertPos); } break; } case BuiltInViewIndex: { input = getFunctionArgument(m_entryPoint, entryArgIdxs.viewIndex); break; } default: { llvm_unreachable("Should never be called!"); break; } } return input; } // ===================================================================================================================== // Patches import calls for built-in inputs of geometry shader. // // @param inputTy : Type of input value // @param builtInId : ID of the built-in variable // @param vertexIdx : Input array outermost index used for vertex indexing (could be null) // @param insertPos : Where to insert the patch instruction Value *PatchInOutImportExport::patchGsBuiltInInputImport(Type *inputTy, unsigned builtInId, Value *vertexIdx, Instruction *insertPos) { Value *input = nullptr; auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageGeometry)->entryArgIdxs.gs; auto &inOutUsage = m_pipelineState->getShaderResourceUsage(ShaderStageGeometry)->inOutUsage; unsigned loc = inOutUsage.builtInInputLocMap[builtInId]; assert(loc != InvalidValue); switch (builtInId) { case BuiltInPosition: case BuiltInPointSize: case BuiltInClipDistance: case BuiltInCullDistance: { input = loadValueFromEsGsRing(inputTy, loc, 0, vertexIdx, insertPos); break; } case BuiltInPrimitiveId: { input = getFunctionArgument(m_entryPoint, entryArgIdxs.primitiveId); break; } case BuiltInInvocationId: { input = getFunctionArgument(m_entryPoint, entryArgIdxs.invocationId); break; } case BuiltInViewIndex: { input = getFunctionArgument(m_entryPoint, entryArgIdxs.viewIndex); break; } // Handle internal-use built-ins case BuiltInWaveId: { input = getFunctionArgument(m_entryPoint, entryArgIdxs.waveId); break; } default: { llvm_unreachable("Should never be called!"); break; } } return input; } // ===================================================================================================================== // Patches import calls for built-in inputs of fragment shader. // // @param inputTy : Type of input value // @param builtInId : ID of the built-in variable // @param sampleId : Sample ID; only needed for BuiltInSamplePosOffset // @param insertPos : Where to insert the patch instruction Value *PatchInOutImportExport::patchFsBuiltInInputImport(Type *inputTy, unsigned builtInId, Value *sampleId, Instruction *insertPos) { Value *input = UndefValue::get(inputTy); auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageFragment)->entryArgIdxs.fs; auto &builtInUsage = m_pipelineState->getShaderResourceUsage(ShaderStageFragment)->builtInUsage.fs; auto &inOutUsage = m_pipelineState->getShaderResourceUsage(ShaderStageFragment)->inOutUsage; Attribute::AttrKind attribs[] = {Attribute::ReadNone}; BuilderBase builder(*m_context); builder.SetInsertPoint(insertPos); switch (builtInId) { case BuiltInSampleMask: { assert(inputTy->isArrayTy()); auto sampleCoverage = getFunctionArgument(m_entryPoint, entryArgIdxs.sampleCoverage); auto ancillary = getFunctionArgument(m_entryPoint, entryArgIdxs.ancillary); // gl_SampleID = Ancillary[11:8] Value *args[] = {ancillary, ConstantInt::get(Type::getInt32Ty(*m_context), 8), ConstantInt::get(Type::getInt32Ty(*m_context), 4)}; auto sampleId = emitCall("llvm.amdgcn.ubfe.i32", Type::getInt32Ty(*m_context), args, {}, insertPos); Value *sampleMaskIn = sampleCoverage; if (m_pipelineState->getRasterizerState().perSampleShading) { // gl_SampleMaskIn[0] = (SampleCoverage & (1 << gl_SampleID)) sampleMaskIn = BinaryOperator::CreateShl(ConstantInt::get(Type::getInt32Ty(*m_context), 1), sampleId, "", insertPos); sampleMaskIn = BinaryOperator::CreateAnd(sampleCoverage, sampleMaskIn, "", insertPos); } // NOTE: Only gl_SampleMaskIn[0] is valid for us. input = InsertValueInst::Create(input, sampleMaskIn, {0}, "", insertPos); break; } case BuiltInFragCoord: { // TODO: Support layout qualifiers "pixel_center_integer" and "origin_upper_left". Value *fragCoord[4] = { getFunctionArgument(m_entryPoint, entryArgIdxs.fragCoord.x), getFunctionArgument(m_entryPoint, entryArgIdxs.fragCoord.y), getFunctionArgument(m_entryPoint, entryArgIdxs.fragCoord.z), getFunctionArgument(m_entryPoint, entryArgIdxs.fragCoord.w), }; // Adjust gl_FragCoord.z value for the shading rate X, // // adjustedFragCoordZ = gl_FragCood.z + dFdxFine(gl_FragCood.z) * 1/16 // adjustedFragCoordZ = gl_ShadingRate.x == 1? adjustedFragCoordZ : gl_FragCood.z if (m_pipelineState->getTargetInfo().getGpuWorkarounds().gfx10.waAdjustDepthImportVrs && m_pipelineState->getShaderOptions(ShaderStageFragment).adjustDepthImportVrs) { const unsigned firstDppCtrl = 0xF5; // FineX: [0,1,2,3]->[1,1,3,3] const unsigned secondDppCtrl = 0xA0; // FineX: [0,1,2,3]->[0,0,2,2] Value *fragCoordZAsInt = builder.CreateBitCast(fragCoord[2], builder.getInt32Ty()); Value *firstDppValue = builder.CreateIntrinsic(Intrinsic::amdgcn_mov_dpp, builder.getInt32Ty(), {fragCoordZAsInt, builder.getInt32(firstDppCtrl), builder.getInt32(15), builder.getInt32(15), builder.getTrue()}); firstDppValue = builder.CreateBitCast(firstDppValue, builder.getFloatTy()); Value *secondDppValue = builder.CreateIntrinsic(Intrinsic::amdgcn_mov_dpp, builder.getInt32Ty(), {fragCoordZAsInt, builder.getInt32(secondDppCtrl), builder.getInt32(15), builder.getInt32(15), builder.getTrue()}); secondDppValue = builder.CreateBitCast(secondDppValue, builder.getFloatTy()); Value *adjustedFragCoordZ = builder.CreateFSub(firstDppValue, secondDppValue); adjustedFragCoordZ = builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_wqm, adjustedFragCoordZ, nullptr); Value *sixteenth = ConstantFP::get(builder.getFloatTy(), 1.0 / 16.0f); adjustedFragCoordZ = builder.CreateIntrinsic(Intrinsic::fma, builder.getFloatTy(), {adjustedFragCoordZ, sixteenth, fragCoord[2]}); auto ancillary = getFunctionArgument(m_entryPoint, entryArgIdxs.ancillary); Value *xRate = builder.CreateAnd(ancillary, 0xC); xRate = builder.CreateLShr(xRate, 2); // xRate = xRate == 0x1 ? Horizontal2Pixels : None auto xRate2Pixels = builder.CreateICmpEQ(xRate, builder.getInt32(1)); adjustedFragCoordZ = builder.CreateSelect(xRate2Pixels, adjustedFragCoordZ, fragCoord[2]); fragCoord[2] = adjustedFragCoordZ; } fragCoord[3] = emitCall("llvm.amdgcn.rcp.f32", Type::getFloatTy(*m_context), {fragCoord[3]}, attribs, insertPos); for (unsigned i = 0; i < 4; ++i) { input = InsertElementInst::Create(input, fragCoord[i], ConstantInt::get(Type::getInt32Ty(*m_context), i), "", insertPos); } break; } case BuiltInFrontFacing: { auto frontFacing = getFunctionArgument(m_entryPoint, entryArgIdxs.frontFacing); input = new ICmpInst(insertPos, ICmpInst::ICMP_NE, frontFacing, ConstantInt::get(Type::getInt32Ty(*m_context), 0)); input = CastInst::CreateIntegerCast(input, inputTy, false, "", insertPos); break; } case BuiltInPointCoord: { assert(inOutUsage.builtInInputLocMap.find(BuiltInPointCoord) != inOutUsage.builtInInputLocMap.end()); const unsigned loc = inOutUsage.builtInInputLocMap[BuiltInPointCoord]; auto &interpInfo = inOutUsage.fs.interpInfo; while (interpInfo.size() <= loc) interpInfo.push_back(InvalidFsInterpInfo); interpInfo[loc] = {loc, false, false, false}; // Emulation for "in vec2 gl_PointCoord" const bool perSampleShading = m_pipelineState->getRasterizerState().perSampleShading; input = patchFsGenericInputImport(inputTy, loc, nullptr, nullptr, nullptr, InOutInfo::InterpModeSmooth, perSampleShading ? InOutInfo::InterpLocSample : InOutInfo::InterpLocCenter, false, insertPos); break; } case BuiltInHelperInvocation: { input = emitCall("llvm.amdgcn.ps.live", Type::getInt1Ty(*m_context), {}, Attribute::ReadNone, insertPos); input = BinaryOperator::CreateNot(input, "", insertPos); input = CastInst::CreateIntegerCast(input, inputTy, false, "", insertPos); break; } case BuiltInPrimitiveId: case BuiltInLayer: case BuiltInViewportIndex: case BuiltInViewIndex: { unsigned loc = InvalidValue; if (builtInId == BuiltInPrimitiveId) { assert(inOutUsage.builtInInputLocMap.find(BuiltInPrimitiveId) != inOutUsage.builtInInputLocMap.end()); loc = inOutUsage.builtInInputLocMap[BuiltInPrimitiveId]; } else if (builtInId == BuiltInLayer) { assert(inOutUsage.builtInInputLocMap.find(BuiltInLayer) != inOutUsage.builtInInputLocMap.end()); loc = inOutUsage.builtInInputLocMap[BuiltInLayer]; } else if (builtInId == BuiltInViewIndex) { assert(inOutUsage.builtInInputLocMap.find(BuiltInViewIndex) != inOutUsage.builtInInputLocMap.end()); loc = inOutUsage.builtInInputLocMap[BuiltInViewIndex]; } else { assert(builtInId == BuiltInViewportIndex); assert(inOutUsage.builtInInputLocMap.find(BuiltInViewportIndex) != inOutUsage.builtInInputLocMap.end()); loc = inOutUsage.builtInInputLocMap[BuiltInViewportIndex]; } auto &interpInfo = inOutUsage.fs.interpInfo; while (interpInfo.size() <= loc) interpInfo.push_back(InvalidFsInterpInfo); interpInfo[loc] = {loc, true, false}; // Flat interpolation // Emulation for "in int gl_PrimitiveID" or "in int gl_Layer" or "in int gl_ViewportIndex" // or "in int gl_ViewIndex" input = patchFsGenericInputImport(inputTy, loc, nullptr, nullptr, nullptr, InOutInfo::InterpModeFlat, InOutInfo::InterpLocCenter, false, insertPos); break; } case BuiltInClipDistance: case BuiltInCullDistance: { assert(inputTy->isArrayTy()); unsigned loc = InvalidValue; unsigned locCount = 0; unsigned startChannel = 0; if (builtInId == BuiltInClipDistance) { assert(inOutUsage.builtInInputLocMap.find(BuiltInClipDistance) != inOutUsage.builtInInputLocMap.end()); loc = inOutUsage.builtInInputLocMap[BuiltInClipDistance]; locCount = builtInUsage.clipDistance > 4 ? 2 : 1; startChannel = 0; } else { assert(builtInId == BuiltInCullDistance); assert(inOutUsage.builtInInputLocMap.find(BuiltInCullDistance) != inOutUsage.builtInInputLocMap.end()); loc = inOutUsage.builtInInputLocMap[BuiltInCullDistance]; locCount = builtInUsage.clipDistance + builtInUsage.cullDistance > 4 ? 2 : 1; startChannel = builtInUsage.clipDistance % 4; } auto &interpInfo = inOutUsage.fs.interpInfo; while (interpInfo.size() <= loc + locCount - 1) interpInfo.push_back(InvalidFsInterpInfo); interpInfo[loc] = {loc, false, false}; if (locCount > 1) interpInfo[loc + 1] = {loc + 1, false, false}; // Emulation for "in float gl_ClipDistance[]" or "in float gl_CullDistance[]" auto primMask = getFunctionArgument(m_entryPoint, entryArgIdxs.primMask); Value *ij = getFunctionArgument(m_entryPoint, entryArgIdxs.linearInterp.center); ij = new BitCastInst(ij, FixedVectorType::get(Type::getFloatTy(*m_context), 2), "", insertPos); auto coordI = ExtractElementInst::Create(ij, ConstantInt::get(Type::getInt32Ty(*m_context), 0), "", insertPos); auto coordJ = ExtractElementInst::Create(ij, ConstantInt::get(Type::getInt32Ty(*m_context), 1), "", insertPos); const unsigned elemCount = inputTy->getArrayNumElements(); assert(elemCount <= MaxClipCullDistanceCount); for (unsigned i = 0; i < elemCount; ++i) { auto compValue = performFsFloatInterpolation(builder, builder.getInt32(loc + (startChannel + i) / 4) /* attr */, builder.getInt32((startChannel + i) % 4) /* attr_chan */, coordI, coordJ, primMask); input = InsertValueInst::Create(input, compValue, {i}, "", insertPos); } break; } case BuiltInSampleId: { auto ancillary = getFunctionArgument(m_entryPoint, entryArgIdxs.ancillary); // gl_SampleID = Ancillary[11:8] Value *args[] = {ancillary, ConstantInt::get(Type::getInt32Ty(*m_context), 8), ConstantInt::get(Type::getInt32Ty(*m_context), 4)}; input = emitCall("llvm.amdgcn.ubfe.i32", inputTy, args, {}, insertPos); break; } case BuiltInShadingRate: { // gl_ShadingRate is not supported on pre-GFX10.3 assert(m_gfxIp >= GfxIpVersion({10, 3})); input = getShadingRate(insertPos); break; } // Handle internal-use built-ins for sample position emulation case BuiltInNumSamples: { if (m_pipelineState->isUnlinked()) { input = builder.CreateRelocationConstant(reloc::NumSamples); } else { input = ConstantInt::get(Type::getInt32Ty(*m_context), m_pipelineState->getRasterizerState().numSamples); } break; } case BuiltInSamplePatternIdx: { if (m_pipelineState->isUnlinked()) { input = builder.CreateRelocationConstant(reloc::SamplePatternIdx); } else { input = ConstantInt::get(Type::getInt32Ty(*m_context), m_pipelineState->getRasterizerState().samplePatternIdx); } break; } // Handle internal-use built-ins for interpolation functions and AMD extension (AMD_shader_explicit_vertex_parameter) case BuiltInInterpPerspSample: case BuiltInBaryCoordSmoothSample: { assert(entryArgIdxs.perspInterp.sample != 0); input = getFunctionArgument(m_entryPoint, entryArgIdxs.perspInterp.sample); break; } case BuiltInInterpPerspCenter: case BuiltInBaryCoordSmooth: { assert(entryArgIdxs.perspInterp.center != 0); input = getFunctionArgument(m_entryPoint, entryArgIdxs.perspInterp.center); break; } case BuiltInInterpPerspCentroid: case BuiltInBaryCoordSmoothCentroid: { assert(entryArgIdxs.perspInterp.centroid != 0); input = adjustCentroidIj(getFunctionArgument(m_entryPoint, entryArgIdxs.perspInterp.centroid), getFunctionArgument(m_entryPoint, entryArgIdxs.perspInterp.center), insertPos); break; } case BuiltInInterpPullMode: case BuiltInBaryCoordPullModel: { assert(entryArgIdxs.perspInterp.pullMode != 0); input = getFunctionArgument(m_entryPoint, entryArgIdxs.perspInterp.pullMode); break; } case BuiltInInterpLinearSample: case BuiltInBaryCoordNoPerspSample: { assert(entryArgIdxs.linearInterp.sample != 0); input = getFunctionArgument(m_entryPoint, entryArgIdxs.linearInterp.sample); break; } case BuiltInInterpLinearCenter: case BuiltInBaryCoordNoPersp: { assert(entryArgIdxs.linearInterp.center != 0); input = getFunctionArgument(m_entryPoint, entryArgIdxs.linearInterp.center); break; } case BuiltInInterpLinearCentroid: case BuiltInBaryCoordNoPerspCentroid: { assert(entryArgIdxs.linearInterp.centroid != 0); input = adjustCentroidIj(getFunctionArgument(m_entryPoint, entryArgIdxs.linearInterp.centroid), getFunctionArgument(m_entryPoint, entryArgIdxs.linearInterp.center), insertPos); break; } case BuiltInSamplePosOffset: { input = getSamplePosOffset(inputTy, sampleId, insertPos); break; } case BuiltInSamplePosition: { input = getSamplePosition(inputTy, insertPos); break; } case BuiltInBaryCoord: case BuiltInBaryCoordNoPerspKHR: { unsigned int idx = 0; if (BuiltInBaryCoord == builtInId) { assert(entryArgIdxs.perspInterp.center != 0); idx = entryArgIdxs.perspInterp.center; } else { assert(entryArgIdxs.linearInterp.center != 0); idx = entryArgIdxs.linearInterp.center; } auto iJCoord = getFunctionArgument(m_entryPoint, idx); builder.SetInsertPoint(insertPos); auto iCoord = builder.CreateExtractElement(iJCoord, uint64_t(0)); auto jCoord = builder.CreateExtractElement(iJCoord, 1); unsigned vertsPerPrim = m_pipelineState->getVerticesPerPrimitive(); switch (vertsPerPrim) { case 1: { // Points input = builder.CreateInsertElement(input, ConstantFP::get(Type::getFloatTy(*m_context), 1.0), uint64_t(0)); input = builder.CreateInsertElement(input, ConstantFP::get(Type::getFloatTy(*m_context), 0.0), 1); input = builder.CreateInsertElement(input, ConstantFP::get(Type::getFloatTy(*m_context), 0.0), 2); break; } case 2: { // Lines // The weight of vertex0 is (1 - i - j), the weight of vertex1 is (i + j). auto kCoord = builder.CreateFSub(ConstantFP::get(Type::getFloatTy(*m_context), 1.0), iCoord); kCoord = builder.CreateFSub(kCoord, jCoord); jCoord = builder.CreateFAdd(iCoord, jCoord); input = builder.CreateInsertElement(input, kCoord, uint64_t(0)); input = builder.CreateInsertElement(input, jCoord, 1); break; } case 3: { // Triangles // V0 ==> Attr_indx2 // V1 ==> Attr_indx0 // V2 ==> Attr_indx1 auto kCoord = builder.CreateFSub(ConstantFP::get(Type::getFloatTy(*m_context), 1.0), iCoord); kCoord = builder.CreateFSub(kCoord, jCoord); input = builder.CreateInsertElement(input, iCoord, uint64_t(2)); input = builder.CreateInsertElement(input, jCoord, uint64_t(0)); input = builder.CreateInsertElement(input, kCoord, uint64_t(1)); break; } default: { llvm_unreachable("Should never be called!"); break; } } break; } default: { llvm_unreachable("Should never be called!"); break; } } return input; } // ===================================================================================================================== // Generate code to read BuiltInSamplePosOffset // // @param inputTy : Type of BuiltInSamplePosOffset // @param sampleId : Sample ID // @param insertPos : Insert position Value *PatchInOutImportExport::getSamplePosOffset(Type *inputTy, Value *sampleId, Instruction *insertPos) { // Gets the offset of sample position relative to the pixel center for the specified sample ID BuilderBase builder(*m_context); builder.SetInsertPoint(insertPos); Value *numSamples = patchFsBuiltInInputImport(builder.getInt32Ty(), BuiltInNumSamples, nullptr, insertPos); Value *patternIdx = patchFsBuiltInInputImport(builder.getInt32Ty(), BuiltInSamplePatternIdx, nullptr, insertPos); Value *validOffset = builder.CreateAdd(patternIdx, sampleId); // offset = (sampleCount > sampleId) ? (samplePatternOffset + sampleId) : 0 Value *sampleValid = builder.CreateICmpUGT(numSamples, sampleId); Value *offset = builder.CreateSelect(sampleValid, validOffset, builder.getInt32(0)); // Load sample position descriptor. Value *desc = m_pipelineSysValues.get(m_entryPoint)->loadDescFromDriverTable(SiDrvTableSamplepos, builder); // Load the value using the descriptor. offset = builder.CreateShl(offset, builder.getInt32(4)); return builder.CreateIntrinsic(Intrinsic::amdgcn_raw_buffer_load, inputTy, {desc, offset, builder.getInt32(0), builder.getInt32(0)}); } // ===================================================================================================================== // Generate code to read BuiltInSamplePosition // // @param inputTy : Type of BuiltInSamplePosition // @param insertPos : Insert position Value *PatchInOutImportExport::getSamplePosition(Type *inputTy, Instruction *insertPos) { IRBuilder<> builder(*m_context); builder.SetInsertPoint(insertPos); Value *sampleId = patchFsBuiltInInputImport(builder.getInt32Ty(), BuiltInSampleId, nullptr, insertPos); Value *input = patchFsBuiltInInputImport(inputTy, BuiltInSamplePosOffset, sampleId, insertPos); return builder.CreateFAdd(input, ConstantFP::get(inputTy, 0.5)); } // ===================================================================================================================== // Patches import calls for built-in outputs of tessellation control shader. // // @param outputTy : Type of output value // @param builtInId : ID of the built-in variable // @param elemIdx : Index used for array/vector element indexing (could be null) // @param vertexIdx : Input array outermost index used for vertex indexing (could be null) // @param insertPos : Where to insert the patch instruction Value *PatchInOutImportExport::patchTcsBuiltInOutputImport(Type *outputTy, unsigned builtInId, Value *elemIdx, Value *vertexIdx, Instruction *insertPos) { Value *output = UndefValue::get(outputTy); auto resUsage = m_pipelineState->getShaderResourceUsage(ShaderStageTessControl); auto &builtInUsage = resUsage->builtInUsage.tcs; auto &builtInOutLocMap = resUsage->inOutUsage.builtInOutputLocMap; auto &perPatchBuiltInOutLocMap = resUsage->inOutUsage.perPatchBuiltInOutputLocMap; switch (builtInId) { case BuiltInPosition: { assert(builtInUsage.position); (void(builtInUsage)); // unused assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; auto ldsOffset = calcLdsOffsetForTcsOutput(outputTy, loc, nullptr, elemIdx, vertexIdx, insertPos); output = readValueFromLds(true, outputTy, ldsOffset, insertPos); break; } case BuiltInPointSize: { assert(builtInUsage.pointSize); (void(builtInUsage)); // unused assert(!elemIdx); assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; auto ldsOffset = calcLdsOffsetForTcsOutput(outputTy, loc, nullptr, nullptr, vertexIdx, insertPos); output = readValueFromLds(true, outputTy, ldsOffset, insertPos); break; } case BuiltInClipDistance: case BuiltInCullDistance: { if (builtInId == BuiltInClipDistance) { assert(builtInUsage.clipDistance > 0); (void(builtInUsage)); // unused } else { assert(builtInId == BuiltInCullDistance); assert(builtInUsage.cullDistance > 0); (void(builtInUsage)); // unused } assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; if (!elemIdx) { // gl_ClipDistance[]/gl_CullDistance[] is treated as 2 x vec4 assert(outputTy->isArrayTy()); auto elemTy = outputTy->getArrayElementType(); for (unsigned i = 0; i < outputTy->getArrayNumElements(); ++i) { auto elemIdx = ConstantInt::get(Type::getInt32Ty(*m_context), i); auto ldsOffset = calcLdsOffsetForTcsOutput(elemTy, loc, nullptr, elemIdx, vertexIdx, insertPos); auto elem = readValueFromLds(true, elemTy, ldsOffset, insertPos); output = InsertValueInst::Create(output, elem, {i}, "", insertPos); } } else { auto ldsOffset = calcLdsOffsetForTcsOutput(outputTy, loc, nullptr, elemIdx, vertexIdx, insertPos); output = readValueFromLds(true, outputTy, ldsOffset, insertPos); } break; } case BuiltInTessLevelOuter: case BuiltInTessLevelInner: { if (builtInId == BuiltInTessLevelOuter) { assert(builtInUsage.tessLevelOuter); (void(builtInUsage)); // unused } else { assert(builtInId == BuiltInTessLevelInner); assert(builtInUsage.tessLevelInner); (void(builtInUsage)); // unused } assert(perPatchBuiltInOutLocMap.find(builtInId) != perPatchBuiltInOutLocMap.end()); unsigned loc = perPatchBuiltInOutLocMap[builtInId]; if (!elemIdx) { // gl_TessLevelOuter[4] is treated as vec4 // gl_TessLevelInner[2] is treated as vec2 assert(outputTy->isArrayTy()); auto elemTy = outputTy->getArrayElementType(); for (unsigned i = 0; i < outputTy->getArrayNumElements(); ++i) { auto elemIdx = ConstantInt::get(Type::getInt32Ty(*m_context), i); auto ldsOffset = calcLdsOffsetForTcsOutput(elemTy, loc, nullptr, elemIdx, vertexIdx, insertPos); auto elem = readValueFromLds(true, elemTy, ldsOffset, insertPos); output = InsertValueInst::Create(output, elem, {i}, "", insertPos); } } else { auto ldsOffset = calcLdsOffsetForTcsOutput(outputTy, loc, nullptr, elemIdx, vertexIdx, insertPos); output = readValueFromLds(true, outputTy, ldsOffset, insertPos); } break; } default: { llvm_unreachable("Should never be called!"); break; } } return output; } // ===================================================================================================================== // Patches export calls for built-in outputs of vertex shader. // // @param output : Output value // @param builtInId : ID of the built-in variable // @param insertPos : Where to insert the patch instruction void PatchInOutImportExport::patchVsBuiltInOutputExport(Value *output, unsigned builtInId, Instruction *insertPos) { auto outputTy = output->getType(); auto resUsage = m_pipelineState->getShaderResourceUsage(ShaderStageVertex); auto &builtInUsage = resUsage->builtInUsage.vs; auto &builtInOutLocMap = resUsage->inOutUsage.builtInOutputLocMap; switch (builtInId) { case BuiltInPosition: { if (!static_cast<bool>(builtInUsage.position)) return; if (m_hasTs) { unsigned loc = builtInOutLocMap[builtInId]; auto ldsOffset = calcLdsOffsetForVsOutput(outputTy, loc, 0, insertPos); writeValueToLds(output, ldsOffset, insertPos); } else { if (m_hasGs) { assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; storeValueToEsGsRing(output, loc, 0, insertPos); } else addExportInstForBuiltInOutput(output, builtInId, insertPos); } break; } case BuiltInPointSize: { if (!static_cast<bool>(builtInUsage.pointSize)) return; if (isa<UndefValue>(output)) { // NOTE: gl_PointSize is always declared as a field of gl_PerVertex. We have to check the output // value to determine if it is actually referenced in shader. builtInUsage.pointSize = false; return; } if (m_hasTs) { unsigned loc = builtInOutLocMap[builtInId]; auto ldsOffset = calcLdsOffsetForVsOutput(outputTy, loc, 0, insertPos); writeValueToLds(output, ldsOffset, insertPos); } else { if (m_hasGs) { assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; storeValueToEsGsRing(output, loc, 0, insertPos); } else addExportInstForBuiltInOutput(output, builtInId, insertPos); } break; } case BuiltInClipDistance: { if (builtInUsage.clipDistance == 0) return; if (isa<UndefValue>(output)) { // NOTE: gl_ClipDistance[] is always declared as a field of gl_PerVertex. We have to check the output // value to determine if it is actually referenced in shader. builtInUsage.clipDistance = 0; return; } if (m_hasTs) { assert(outputTy->isArrayTy()); unsigned loc = builtInOutLocMap[builtInId]; auto ldsOffset = calcLdsOffsetForVsOutput(outputTy->getArrayElementType(), loc, 0, insertPos); for (unsigned i = 0; i < outputTy->getArrayNumElements(); ++i) { auto elem = ExtractValueInst::Create(output, {i}, "", insertPos); writeValueToLds(elem, ldsOffset, insertPos); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 1), "", insertPos); } } else { if (m_hasGs) { assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; storeValueToEsGsRing(output, loc, 0, insertPos); } else { // NOTE: The export of gl_ClipDistance[] is delayed and is done before entry-point returns. m_clipDistance = output; } } break; } case BuiltInCullDistance: { if (builtInUsage.cullDistance == 0) return; if (isa<UndefValue>(output)) { // NOTE: gl_CullDistance[] is always declared as a field of gl_PerVertex. We have to check the output // value to determine if it is actually referenced in shader. builtInUsage.cullDistance = 0; return; } if (m_hasTs) { assert(outputTy->isArrayTy()); unsigned loc = builtInOutLocMap[builtInId]; auto ldsOffset = calcLdsOffsetForVsOutput(outputTy->getArrayElementType(), loc, 0, insertPos); for (unsigned i = 0; i < outputTy->getArrayNumElements(); ++i) { auto elem = ExtractValueInst::Create(output, {i}, "", insertPos); writeValueToLds(elem, ldsOffset, insertPos); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 1), "", insertPos); } } else { if (m_hasGs) { assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; storeValueToEsGsRing(output, loc, 0, insertPos); } else { // NOTE: The export of gl_CullDistance[] is delayed and is done before entry-point returns. m_cullDistance = output; } } break; } case BuiltInLayer: { if (!static_cast<bool>(builtInUsage.layer)) return; const auto enableMultiView = m_pipelineState->getInputAssemblyState().enableMultiView; // NOTE: Only last non-fragment shader stage has to export the value of gl_Layer. if (!m_hasTs && !m_hasGs && !static_cast<bool>(enableMultiView)) { if (m_gfxIp.major <= 8) addExportInstForBuiltInOutput(output, builtInId, insertPos); else { // NOTE: The export of gl_Layer is delayed and is done before entry-point returns. m_layer = output; } } break; } case BuiltInViewportIndex: { if (!static_cast<bool>(builtInUsage.viewportIndex)) return; // NOTE: Only last non-fragment shader stage has to export the value of gl_ViewportIndex. if (!m_hasTs && !m_hasGs) { if (m_gfxIp.major <= 8) addExportInstForBuiltInOutput(output, builtInId, insertPos); else { // NOTE: The export of gl_ViewportIndex is delayed and is done before entry-point returns. m_viewportIndex = output; } } break; } case BuiltInPrimitiveShadingRate: { if (!static_cast<bool>(builtInUsage.primitiveShadingRate)) return; // NOTE: Only last non-fragment shader stage has to export the value of gl_PrimitiveShadingRate. if (!m_hasTs && !m_hasGs) { // gl_PrimitiveShadingRate is not supported on pre-GFX10.3 assert(m_gfxIp >= GfxIpVersion({10, 3})); addExportInstForBuiltInOutput(output, builtInId, insertPos); } break; } default: { llvm_unreachable("Should never be called!"); break; } } } // ===================================================================================================================== // Patches export calls for built-in outputs of tessellation control shader. // // @param output : Output value // @param builtInId : ID of the built-in variable // @param elemIdx : Index used for array/vector element indexing (could be null) // @param vertexIdx : Input array outermost index used for vertex indexing (could be null) // @param insertPos : Where to insert the patch instruction void PatchInOutImportExport::patchTcsBuiltInOutputExport(Value *output, unsigned builtInId, Value *elemIdx, Value *vertexIdx, Instruction *insertPos) { auto outputTy = output->getType(); auto resUsage = m_pipelineState->getShaderResourceUsage(ShaderStageTessControl); auto &builtInUsage = resUsage->builtInUsage.tcs; auto &builtInOutLocMap = resUsage->inOutUsage.builtInOutputLocMap; switch (builtInId) { case BuiltInPosition: { if (!static_cast<bool>(builtInUsage.position)) return; assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; auto ldsOffset = calcLdsOffsetForTcsOutput(outputTy, loc, nullptr, elemIdx, vertexIdx, insertPos); writeValueToLds(output, ldsOffset, insertPos); break; } case BuiltInPointSize: { if (!static_cast<bool>(builtInUsage.pointSize)) return; assert(!elemIdx); assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; auto ldsOffset = calcLdsOffsetForTcsOutput(outputTy, loc, nullptr, nullptr, vertexIdx, insertPos); writeValueToLds(output, ldsOffset, insertPos); break; } case BuiltInClipDistance: case BuiltInCullDistance: { if ((builtInId == BuiltInClipDistance && builtInUsage.clipDistance == 0) || (builtInId == BuiltInCullDistance && builtInUsage.cullDistance == 0)) return; assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; if (!elemIdx) { // gl_ClipDistance[]/gl_CullDistance[] is treated as 2 x vec4 assert(outputTy->isArrayTy()); for (unsigned i = 0; i < outputTy->getArrayNumElements(); ++i) { auto elem = ExtractValueInst::Create(output, {i}, "", insertPos); auto elemIdx = ConstantInt::get(Type::getInt32Ty(*m_context), i); auto ldsOffset = calcLdsOffsetForTcsOutput(elem->getType(), loc, nullptr, elemIdx, vertexIdx, insertPos); writeValueToLds(elem, ldsOffset, insertPos); } } else { auto ldsOffset = calcLdsOffsetForTcsOutput(outputTy, loc, nullptr, elemIdx, vertexIdx, insertPos); writeValueToLds(output, ldsOffset, insertPos); } break; } case BuiltInTessLevelOuter: m_tessLevelOuterInsts.push_back(insertPos); break; case BuiltInTessLevelInner: m_tessLevelInnerInsts.push_back(insertPos); break; default: { llvm_unreachable("Should never be called!"); break; } } } // ===================================================================================================================== // Patches export calls for built-in outputs of tessellation evaluation shader. // // @param output : Output value // @param builtInId : ID of the built-in variable // @param insertPos : Where to insert the patch instruction void PatchInOutImportExport::patchTesBuiltInOutputExport(Value *output, unsigned builtInId, Instruction *insertPos) { auto resUsage = m_pipelineState->getShaderResourceUsage(ShaderStageTessEval); auto &builtInUsage = resUsage->builtInUsage.tes; auto &builtInOutLocMap = resUsage->inOutUsage.builtInOutputLocMap; switch (builtInId) { case BuiltInPosition: { if (!static_cast<bool>(builtInUsage.position)) return; if (m_hasGs) { assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; storeValueToEsGsRing(output, loc, 0, insertPos); } else addExportInstForBuiltInOutput(output, builtInId, insertPos); break; } case BuiltInPointSize: { if (!static_cast<bool>(builtInUsage.pointSize)) return; if (isa<UndefValue>(output)) { // NOTE: gl_PointSize is always declared as a field of gl_PerVertex. We have to check the output // value to determine if it is actually referenced in shader. builtInUsage.pointSize = false; return; } if (m_hasGs) { assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; storeValueToEsGsRing(output, loc, 0, insertPos); } else addExportInstForBuiltInOutput(output, builtInId, insertPos); break; } case BuiltInClipDistance: { if (builtInUsage.clipDistance == 0) return; if (isa<UndefValue>(output)) { // NOTE: gl_ClipDistance[] is always declared as a field of gl_PerVertex. We have to check the output // value to determine if it is actually referenced in shader. builtInUsage.clipDistance = 0; return; } if (m_hasGs) { assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; storeValueToEsGsRing(output, loc, 0, insertPos); } else { // NOTE: The export of gl_ClipDistance[] is delayed and is done before entry-point returns. m_clipDistance = output; } break; } case BuiltInCullDistance: { if (builtInUsage.cullDistance == 0) return; if (isa<UndefValue>(output)) { // NOTE: gl_CullDistance[] is always declared as a field of gl_PerVertex. We have to check the output // value to determine if it is actually referenced in shader. builtInUsage.cullDistance = 0; return; } if (m_hasGs) { assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; storeValueToEsGsRing(output, loc, 0, insertPos); } else { // NOTE: The export of gl_CullDistance[] is delayed and is done before entry-point returns. m_cullDistance = output; } break; } case BuiltInLayer: { if (!static_cast<bool>(builtInUsage.layer)) return; const auto enableMultiView = m_pipelineState->getInputAssemblyState().enableMultiView; // NOTE: Only last non-fragment shader stage has to export the value of gl_Layer. if (!m_hasGs && !static_cast<bool>(enableMultiView)) { if (m_gfxIp.major <= 8) addExportInstForBuiltInOutput(output, builtInId, insertPos); else { // NOTE: The export of gl_Layer is delayed and is done before entry-point returns. m_layer = output; } } break; } case BuiltInViewportIndex: { if (!static_cast<bool>(builtInUsage.viewportIndex)) return; // NOTE: Only last non-fragment shader stage has to export the value of gl_ViewportIndex. if (!m_hasGs) { if (m_gfxIp.major <= 8) addExportInstForBuiltInOutput(output, builtInId, insertPos); else { // NOTE: The export of gl_ViewportIndex is delayed and is done before entry-point returns. m_viewportIndex = output; } } break; } default: { llvm_unreachable("Should never be called!"); break; } } } // ===================================================================================================================== // Patches export calls for built-in outputs of geometry shader. // // @param output : Output value // @param builtInId : ID of the built-in variable // @param streamId : ID of output vertex stream // @param insertPos : Where to insert the patch instruction void PatchInOutImportExport::patchGsBuiltInOutputExport(Value *output, unsigned builtInId, unsigned streamId, Instruction *insertPos) { auto resUsage = m_pipelineState->getShaderResourceUsage(ShaderStageGeometry); auto &builtInUsage = resUsage->builtInUsage.gs; auto &builtInOutLocMap = resUsage->inOutUsage.builtInOutputLocMap; assert(builtInOutLocMap.find(builtInId) != builtInOutLocMap.end()); unsigned loc = builtInOutLocMap[builtInId]; switch (builtInId) { case BuiltInPosition: assert(builtInUsage.position); break; case BuiltInPointSize: assert(builtInUsage.pointSize); break; case BuiltInClipDistance: assert(builtInUsage.clipDistance); break; case BuiltInCullDistance: assert(builtInUsage.cullDistance); break; case BuiltInPrimitiveId: assert(builtInUsage.primitiveId); break; case BuiltInLayer: assert(builtInUsage.layer); break; case BuiltInViewportIndex: assert(builtInUsage.viewportIndex); break; case BuiltInPrimitiveShadingRate: assert(builtInUsage.primitiveShadingRate); break; default: llvm_unreachable("Should never be called!"); break; } (void(builtInUsage)); // unused storeValueToGsVsRing(output, loc, 0, streamId, insertPos); } // ===================================================================================================================== // Patches export calls for built-in outputs of fragment shader. // // @param output : Output value // @param builtInId : ID of the built-in variable // @param insertPos : Where to insert the patch instruction void PatchInOutImportExport::patchFsBuiltInOutputExport(Value *output, unsigned builtInId, Instruction *insertPos) { switch (builtInId) { case BuiltInFragDepth: { m_fragDepth = output; break; } case BuiltInSampleMask: { assert(output->getType()->isArrayTy()); // NOTE: Only gl_SampleMask[0] is valid for us. m_sampleMask = ExtractValueInst::Create(output, {0}, "", insertPos); m_sampleMask = new BitCastInst(m_sampleMask, Type::getFloatTy(*m_context), "", insertPos); break; } case BuiltInFragStencilRef: { m_fragStencilRef = new BitCastInst(output, Type::getFloatTy(*m_context), "", insertPos); break; } default: { llvm_unreachable("Should never be called!"); break; } } } // ===================================================================================================================== // Patches export calls for generic outputs of copy shader. // // @param output : Output value // @param location : Location of the output // @param insertPos : Where to insert the patch instruction void PatchInOutImportExport::patchCopyShaderGenericOutputExport(Value *output, unsigned location, Instruction *insertPos) { addExportInstForGenericOutput(output, location, 0, insertPos); } // ===================================================================================================================== // Patches export calls for built-in outputs of copy shader. // // @param output : Output value // @param builtInId : ID of the built-in variable // @param insertPos : Where to insert the patch instruction void PatchInOutImportExport::patchCopyShaderBuiltInOutputExport(Value *output, unsigned builtInId, Instruction *insertPos) { switch (builtInId) { case BuiltInPosition: case BuiltInPointSize: { addExportInstForBuiltInOutput(output, builtInId, insertPos); break; } case BuiltInClipDistance: { // NOTE: The export of gl_ClipDistance[] is delayed and is done before entry-point returns. m_clipDistance = output; break; } case BuiltInCullDistance: { // NOTE: The export of gl_CullDistance[] is delayed and is done before entry-point returns. m_cullDistance = output; break; } case BuiltInPrimitiveId: { // NOTE: The export of gl_PrimitiveID is delayed and is done before entry-point returns. m_primitiveId = output; break; } case BuiltInLayer: { const auto enableMultiView = m_pipelineState->getInputAssemblyState().enableMultiView; if (m_gfxIp.major <= 8 && !static_cast<bool>(enableMultiView)) addExportInstForBuiltInOutput(output, builtInId, insertPos); else { // NOTE: The export of gl_Layer is delayed and is done before entry-point returns. m_layer = output; } break; } case BuiltInViewportIndex: { if (m_gfxIp.major <= 8) addExportInstForBuiltInOutput(output, builtInId, insertPos); else { // NOTE: The export of gl_ViewportIndex is delayed and is done before entry-point returns. m_viewportIndex = output; } break; } case BuiltInPrimitiveShadingRate: { // gl_PrimitiveShadingRate is not supported on pre-GFX10.3 assert(m_gfxIp >= GfxIpVersion({10, 3})); addExportInstForBuiltInOutput(output, builtInId, insertPos); break; } default: { llvm_unreachable("Should never be called!"); break; } } } // ===================================================================================================================== // Patch export calls for transform feedback outputs of vertex shader and tessellation evaluation shader. // // @param output : Output value // @param xfbBuffer : Transform feedback buffer ID // @param xfbOffset : Transform feedback offset // @param streamId : Output stream ID // @param insertPos : Where to insert the store instruction void PatchInOutImportExport::patchXfbOutputExport(Value *output, unsigned xfbBuffer, unsigned xfbOffset, unsigned streamId, Instruction *insertPos) { assert(m_shaderStage == ShaderStageVertex || m_shaderStage == ShaderStageTessEval || m_shaderStage == ShaderStageCopyShader); Value *streamOutBufDesc = m_pipelineSysValues.get(m_entryPoint)->getStreamOutBufDesc(xfbBuffer); const auto &xfbStrides = m_pipelineState->getShaderResourceUsage(m_shaderStage)->inOutUsage.xfbStrides; unsigned xfbStride = xfbStrides[xfbBuffer]; auto outputTy = output->getType(); unsigned compCount = outputTy->isVectorTy() ? cast<FixedVectorType>(outputTy)->getNumElements() : 1; unsigned bitWidth = outputTy->getScalarSizeInBits(); if (bitWidth == 64) { // Cast 64-bit output to 32-bit compCount *= 2; bitWidth = 32; outputTy = FixedVectorType::get(Type::getFloatTy(*m_context), compCount); output = new BitCastInst(output, outputTy, "", insertPos); } assert(bitWidth == 16 || bitWidth == 32); if (compCount == 8) { // vec8 -> vec4 + vec4 assert(bitWidth == 32); Constant *shuffleMask0123[] = { ConstantInt::get(Type::getInt32Ty(*m_context), 0), ConstantInt::get(Type::getInt32Ty(*m_context), 1), ConstantInt::get(Type::getInt32Ty(*m_context), 2), ConstantInt::get(Type::getInt32Ty(*m_context), 3)}; Value *compX4 = new ShuffleVectorInst(output, output, ConstantVector::get(shuffleMask0123), "", insertPos); storeValueToStreamOutBuffer(compX4, xfbBuffer, xfbOffset, xfbStride, streamId, streamOutBufDesc, insertPos); Constant *shuffleMask4567[] = { ConstantInt::get(Type::getInt32Ty(*m_context), 4), ConstantInt::get(Type::getInt32Ty(*m_context), 5), ConstantInt::get(Type::getInt32Ty(*m_context), 6), ConstantInt::get(Type::getInt32Ty(*m_context), 7)}; compX4 = new ShuffleVectorInst(output, output, ConstantVector::get(shuffleMask4567), "", insertPos); xfbOffset += 4 * (bitWidth / 8); storeValueToStreamOutBuffer(compX4, xfbBuffer, xfbOffset, xfbStride, streamId, streamOutBufDesc, insertPos); } else if (compCount == 6) { // vec6 -> vec4 + vec2 assert(bitWidth == 32); // NOTE: This case is generated by copy shader, which casts 64-bit outputs to float. Constant *shuffleMask0123[] = { ConstantInt::get(Type::getInt32Ty(*m_context), 0), ConstantInt::get(Type::getInt32Ty(*m_context), 1), ConstantInt::get(Type::getInt32Ty(*m_context), 2), ConstantInt::get(Type::getInt32Ty(*m_context), 3)}; Value *compX4 = new ShuffleVectorInst(output, output, ConstantVector::get(shuffleMask0123), "", insertPos); storeValueToStreamOutBuffer(compX4, xfbBuffer, xfbOffset, xfbStride, streamId, streamOutBufDesc, insertPos); Constant *shuffleMask45[] = {ConstantInt::get(Type::getInt32Ty(*m_context), 4), ConstantInt::get(Type::getInt32Ty(*m_context), 5)}; Value *compX2 = new ShuffleVectorInst(output, output, ConstantVector::get(shuffleMask45), "", insertPos); xfbOffset += 4 * (bitWidth / 8); storeValueToStreamOutBuffer(compX2, xfbBuffer, xfbOffset, xfbStride, streamId, streamOutBufDesc, insertPos); } else { // 16vec4, 16vec3, 16vec2, 16scalar // vec4, vec3, vec2, scalar if (outputTy->isVectorTy() && compCount == 1) { // NOTE: We translate vec1 to scalar. SPIR-V translated from DX has such usage. output = ExtractElementInst::Create(output, ConstantInt::get(Type::getInt32Ty(*m_context), 0), "", insertPos); } storeValueToStreamOutBuffer(output, xfbBuffer, xfbOffset, xfbStride, streamId, streamOutBufDesc, insertPos); } } // ===================================================================================================================== // Creates the LLPC intrinsic "llpc.streamoutbuffer.store.f32" to store value to to stream-out buffer. // // @param storeValue : Value to store // @param xfbStride : Transform feedback stride // @param [out] funcName : Function name to add mangling to void PatchInOutImportExport::createStreamOutBufferStoreFunction(Value *storeValue, unsigned xfbStride, std::string &funcName) { addTypeMangling(nullptr, {storeValue}, funcName); // define void @llpc.streamoutbuffer.store.f32( // float %storeValue, <4 x i32> %streamOutBufDesc, i32 %writeIndex, i32 %threadId, // i32 %vertexCount, i32 %xfbOffset, i32 %streamOffset) // { // .entry // %1 = icmp ult i32 %threadId, %vtxCount // br i1 %1, label %.store, label %.end // // .store: // call void llvm.amdgcn.struct.tbuffer.store.f32( // float %storeValue, <4 x i32> %streamOutBufDesc, i32 %writeIndex, // i32 %xfbOffset, i32 %streamOffset, i32 %format, i32 %coherent) // br label %.end // // .end: // ret void // } Type *argTys[] = { storeValue->getType(), // %storeValue FixedVectorType::get(Type::getInt32Ty(*m_context), 4), // %streamOutBufDesc Type::getInt32Ty(*m_context), // %writeIndex Type::getInt32Ty(*m_context), // %threadId Type::getInt32Ty(*m_context), // %vertexCount Type::getInt32Ty(*m_context), // %xfbOffset Type::getInt32Ty(*m_context) // %streamOffset }; auto funcTy = FunctionType::get(Type::getVoidTy(*m_context), argTys, false); auto func = Function::Create(funcTy, GlobalValue::InternalLinkage, funcName, m_module); func->setCallingConv(CallingConv::C); func->addFnAttr(Attribute::NoUnwind); func->addFnAttr(Attribute::AlwaysInline); auto argIt = func->arg_begin(); Value *storedValue = argIt++; Value *streamOutBufDesc = argIt++; Value *writeIndex = argIt++; Value *threadId = argIt++; Value *vertexCount = argIt++; Value *xfbOffset = argIt++; Value *streamOffset = argIt; // Create ".end" block BasicBlock *endBlock = BasicBlock::Create(*m_context, ".end", func); ReturnInst::Create(*m_context, endBlock); // Create ".store" block BasicBlock *storeBlock = BasicBlock::Create(*m_context, ".store", func, endBlock); // Create entry block BasicBlock *entryBlock = BasicBlock::Create(*m_context, "", func, storeBlock); auto threadValid = new ICmpInst(*entryBlock, ICmpInst::ICMP_ULT, threadId, vertexCount); if (m_shaderStage != ShaderStageCopyShader) { // Setup out-of-range value. GPU will drop stream-out buffer writing when the thread is invalid. unsigned outofRangeValue = 0xFFFFFFFF; // Divide outofRangeValue by xfbStride only for GFX8. if (m_gfxIp.major == 8) outofRangeValue /= xfbStride; outofRangeValue -= (m_pipelineState->getShaderWaveSize(m_shaderStage) - 1); writeIndex = SelectInst::Create(threadValid, writeIndex, ConstantInt::get(Type::getInt32Ty(*m_context), outofRangeValue), "", entryBlock); BranchInst::Create(storeBlock, entryBlock); } else BranchInst::Create(storeBlock, endBlock, threadValid, entryBlock); auto storeTy = storeValue->getType(); unsigned compCount = storeTy->isVectorTy() ? cast<FixedVectorType>(storeTy)->getNumElements() : 1; assert(compCount <= 4); const uint64_t bitWidth = storeTy->getScalarSizeInBits(); assert(bitWidth == 16 || bitWidth == 32); static const char *const callNames[4][2] = { {"llvm.amdgcn.struct.tbuffer.store.f16", "llvm.amdgcn.struct.tbuffer.store.f32"}, {"llvm.amdgcn.struct.tbuffer.store.v2f16", "llvm.amdgcn.struct.tbuffer.store.v2f32"}, {nullptr, "llvm.amdgcn.struct.tbuffer.store.v3f32"}, {"llvm.amdgcn.struct.tbuffer.store.v4f16", "llvm.amdgcn.struct.tbuffer.store.v4f32"}, }; StringRef callName(callNames[compCount - 1][bitWidth == 32]); unsigned format = 0; switch (m_gfxIp.major) { default: { CombineFormat formatOprd = {}; formatOprd.bits.nfmt = BUF_NUM_FORMAT_FLOAT; static const unsigned char dfmtTable[4][2] = { {BUF_DATA_FORMAT_16, BUF_DATA_FORMAT_32}, {BUF_DATA_FORMAT_16_16, BUF_DATA_FORMAT_32_32}, {BUF_DATA_FORMAT_INVALID, BUF_DATA_FORMAT_32_32_32}, {BUF_DATA_FORMAT_16_16_16_16, BUF_DATA_FORMAT_32_32_32_32}, }; formatOprd.bits.dfmt = dfmtTable[compCount - 1][bitWidth == 32]; format = formatOprd.u32All; break; } case 10: { static unsigned char formatTable[4][2] = { {BUF_FORMAT_16_FLOAT, BUF_FORMAT_32_FLOAT}, {BUF_FORMAT_16_16_FLOAT, BUF_FORMAT_32_32_FLOAT_GFX10}, {BUF_FORMAT_INVALID, BUF_FORMAT_32_32_32_FLOAT_GFX10}, {BUF_FORMAT_16_16_16_16_FLOAT_GFX10, BUF_FORMAT_32_32_32_32_FLOAT_GFX10}, }; format = formatTable[compCount - 1][bitWidth == 32]; break; } } // byteOffset = streamOffsets[xfbBuffer] * 4 + // (writeIndex + threadId) * bufferStride[bufferId] + // xfbOffset CoherentFlag coherent = {}; coherent.bits.glc = true; coherent.bits.slc = true; Value *args[] = { storedValue, // value streamOutBufDesc, // desc writeIndex, // vindex xfbOffset, // offset streamOffset, // soffset ConstantInt::get(Type::getInt32Ty(*m_context), format), // format ConstantInt::get(Type::getInt32Ty(*m_context), coherent.u32All) // glc, slc }; emitCall(callName, Type::getVoidTy(*m_context), args, {}, storeBlock); BranchInst::Create(endBlock, storeBlock); } // ===================================================================================================================== // Combines scalar values store to vector store // // @param storeValues : Values to store // @param startIdx : Starting index for load operation in the load value array // @param valueOffset : Value offset as a bias of buffer store offset // @param bufDesc : Buffer descriptor // @param storeOffset : Buffer store offset // @param bufBase : Buffer base offset // @param coherent : Buffer coherency // @param insertPos : Where to insert write instructions unsigned PatchInOutImportExport::combineBufferStore(const std::vector<Value *> &storeValues, unsigned startIdx, unsigned valueOffset, Value *bufDesc, Value *storeOffset, Value *bufBase, CoherentFlag coherent, Instruction *insertPos) { Type *storeTys[4] = { Type::getInt32Ty(*m_context), FixedVectorType::get(Type::getInt32Ty(*m_context), 2), FixedVectorType::get(Type::getInt32Ty(*m_context), 3), FixedVectorType::get(Type::getInt32Ty(*m_context), 4), }; std::string funcName = "llvm.amdgcn.raw.tbuffer.store."; // Start from 4-component combination unsigned compCount = 4; for (; compCount > 0; compCount--) { // GFX6 does not support 3-component combination if (m_gfxIp.major == 6 && compCount == 3) continue; if (startIdx + compCount <= storeValues.size()) { funcName += getTypeName(storeTys[compCount - 1]); Value *storeValue = nullptr; if (compCount > 1) { auto storeTy = FixedVectorType::get(Type::getInt32Ty(*m_context), compCount); storeValue = UndefValue::get(storeTy); for (unsigned i = 0; i < compCount; ++i) { storeValue = InsertElementInst::Create(storeValue, storeValues[startIdx + i], ConstantInt::get(Type::getInt32Ty(*m_context), i), "", insertPos); } } else storeValue = storeValues[startIdx]; auto writeOffset = BinaryOperator::CreateAdd( storeOffset, ConstantInt::get(Type::getInt32Ty(*m_context), valueOffset * 4), "", insertPos); Value *args[] = { storeValue, // vdata bufDesc, // rsrc writeOffset, // voffset bufBase, // soffset ConstantInt::get(Type::getInt32Ty(*m_context), (*m_buffFormats)[compCount - 1]), // format ConstantInt::get(Type::getInt32Ty(*m_context), coherent.u32All) // glc }; emitCall(funcName, Type::getVoidTy(*m_context), args, {}, insertPos); break; } } return compCount; } // ===================================================================================================================== // Combines scalar values load to vector load // // @param [in/out] loadValues : Values to load // @param startIdx : Starting index for load operation in the load value array // @param bufDesc : Buffer descriptor // @param loadOffset : Buffer load offset // @param bufBase : Buffer base offset // @param coherent : Buffer coherency // @param insertPos : Where to insert write instructions unsigned PatchInOutImportExport::combineBufferLoad(std::vector<Value *> &loadValues, unsigned startIdx, Value *bufDesc, Value *loadOffset, Value *bufBase, CoherentFlag coherent, Instruction *insertPos) { Type *loadTyps[4] = { Type::getInt32Ty(*m_context), FixedVectorType::get(Type::getInt32Ty(*m_context), 2), FixedVectorType::get(Type::getInt32Ty(*m_context), 3), FixedVectorType::get(Type::getInt32Ty(*m_context), 4), }; std::string funcName = "llvm.amdgcn.raw.tbuffer.load."; assert(loadValues.size() > 0); // 4-component combination unsigned compCount = 4; for (; compCount > 0; compCount--) { // GFX6 does not support 3-component combination if (m_gfxIp.major == 6 && compCount == 3) continue; if (startIdx + compCount <= loadValues.size()) { funcName += getTypeName(loadTyps[compCount - 1]); Value *loadValue = nullptr; auto writeOffset = BinaryOperator::CreateAdd( loadOffset, ConstantInt::get(Type::getInt32Ty(*m_context), startIdx * 4), "", insertPos); Value *args[] = { bufDesc, // rsrc writeOffset, // voffset bufBase, // soffset ConstantInt::get(Type::getInt32Ty(*m_context), (*m_buffFormats)[compCount - 1]), // format ConstantInt::get(Type::getInt32Ty(*m_context), coherent.u32All) // glc }; loadValue = emitCall(funcName, loadTyps[compCount - 1], args, {}, insertPos); assert(loadValue); if (compCount > 1) { for (unsigned i = 0; i < compCount; i++) { loadValues[startIdx + i] = ExtractElementInst::Create(loadValue, ConstantInt::get(Type::getInt32Ty(*m_context), i), "", insertPos); } } else loadValues[startIdx] = loadValue; break; } } return compCount; } // ===================================================================================================================== // Store value to stream-out buffer // // @param storeValue : Value to store // @param xfbBuffer : Transform feedback buffer // @param xfbOffset : Offset of the store value within transform feedback buffer // @param xfbStride : Transform feedback stride // @param streamId : Output stream ID // @param streamOutBufDesc : Transform feedback buffer descriptor // @param insertPos : Where to insert the store instruction void PatchInOutImportExport::storeValueToStreamOutBuffer(Value *storeValue, unsigned xfbBuffer, unsigned xfbOffset, unsigned xfbStride, unsigned streamId, Value *streamOutBufDesc, Instruction *insertPos) { auto storeTy = storeValue->getType(); unsigned compCount = storeTy->isVectorTy() ? cast<FixedVectorType>(storeTy)->getNumElements() : 1; assert(compCount <= 4); const uint64_t bitWidth = storeTy->getScalarSizeInBits(); assert(bitWidth == 16 || bitWidth == 32); if (storeTy->isIntOrIntVectorTy()) { Type *bitCastTy = bitWidth == 32 ? Type::getFloatTy(*m_context) : Type::getHalfTy(*m_context); if (compCount > 1) bitCastTy = FixedVectorType::get(bitCastTy, compCount); storeValue = new BitCastInst(storeValue, bitCastTy, "", insertPos); } // NOTE: For 16vec3, HW doesn't have a corresponding buffer store instruction. We have to split it to 16vec2 and // 16scalar. if (bitWidth == 16 && compCount == 3) { // 16vec3 -> 16vec2 + 16scalar Constant *shuffleMask01[] = {ConstantInt::get(Type::getInt32Ty(*m_context), 0), ConstantInt::get(Type::getInt32Ty(*m_context), 1)}; Value *compX2 = new ShuffleVectorInst(storeValue, storeValue, ConstantVector::get(shuffleMask01), "", insertPos); storeValueToStreamOutBuffer(compX2, xfbBuffer, xfbOffset, xfbStride, streamId, streamOutBufDesc, insertPos); Value *comp = ExtractElementInst::Create(storeValue, ConstantInt::get(Type::getInt32Ty(*m_context), 2), "", insertPos); xfbOffset += 2 * (bitWidth / 8); storeValueToStreamOutBuffer(comp, xfbBuffer, xfbOffset, xfbStride, streamId, streamOutBufDesc, insertPos); return; } const auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(m_shaderStage)->entryArgIdxs; unsigned streamOffsets[MaxTransformFeedbackBuffers] = {}; unsigned writeIndex = 0; unsigned streamInfo = 0; if (m_shaderStage == ShaderStageVertex) { memcpy(streamOffsets, entryArgIdxs.vs.streamOutData.streamOffsets, sizeof(streamOffsets)); writeIndex = entryArgIdxs.vs.streamOutData.writeIndex; streamInfo = entryArgIdxs.vs.streamOutData.streamInfo; } else if (m_shaderStage == ShaderStageTessEval) { memcpy(streamOffsets, entryArgIdxs.tes.streamOutData.streamOffsets, sizeof(streamOffsets)); writeIndex = entryArgIdxs.tes.streamOutData.writeIndex; streamInfo = entryArgIdxs.tes.streamOutData.streamInfo; } else { assert(m_shaderStage == ShaderStageCopyShader); writeIndex = CopyShaderUserSgprIdxWriteIndex; streamInfo = CopyShaderUserSgprIdxStreamInfo; auto &inoutUsage = m_pipelineState->getShaderResourceUsage(ShaderStageGeometry)->inOutUsage; unsigned streamOffset = CopyShaderUserSgprIdxStreamOffset; for (unsigned i = 0; i < MaxTransformFeedbackBuffers; ++i) { if (inoutUsage.xfbStrides[i] > 0) streamOffsets[i] = streamOffset++; } } assert(xfbBuffer < MaxTransformFeedbackBuffers); assert(streamOffsets[xfbBuffer] != 0); Value *streamOffset = getFunctionArgument(m_entryPoint, streamOffsets[xfbBuffer]); streamOffset = BinaryOperator::CreateMul(streamOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 4), "", insertPos); // vertexCount = streamInfo[22:16] Value *ubfeArgs[] = {getFunctionArgument(m_entryPoint, streamInfo), ConstantInt::get(Type::getInt32Ty(*m_context), 16), ConstantInt::get(Type::getInt32Ty(*m_context), 7)}; Value *vertexCount = emitCall("llvm.amdgcn.ubfe.i32", Type::getInt32Ty(*m_context), ubfeArgs, {}, &*insertPos); // Setup write index for stream-out Value *writeIndexVal = getFunctionArgument(m_entryPoint, writeIndex); if (m_gfxIp.major >= 9) writeIndexVal = BinaryOperator::CreateAdd(writeIndexVal, m_threadId, "", insertPos); std::string funcName = lgcName::StreamOutBufferStore; createStreamOutBufferStoreFunction(storeValue, xfbStride, funcName); Value *args[] = {storeValue, streamOutBufDesc, writeIndexVal, m_threadId, vertexCount, ConstantInt::get(Type::getInt32Ty(*m_context), xfbOffset), streamOffset}; emitCall(funcName, Type::getVoidTy(*m_context), args, {}, insertPos); } // ===================================================================================================================== // Stores value to ES-GS ring (buffer or LDS). // // @param storeValue : Value to store // @param location : Output location // @param compIdx : Output component index // @param insertPos : Where to insert the store instruction void PatchInOutImportExport::storeValueToEsGsRing(Value *storeValue, unsigned location, unsigned compIdx, Instruction *insertPos) { auto storeTy = storeValue->getType(); Type *elemTy = storeTy; if (storeTy->isArrayTy()) elemTy = cast<ArrayType>(storeTy)->getElementType(); else if (storeTy->isVectorTy()) elemTy = cast<VectorType>(storeTy)->getElementType(); const uint64_t bitWidth = elemTy->getScalarSizeInBits(); assert((elemTy->isFloatingPointTy() || elemTy->isIntegerTy()) && (bitWidth == 8 || bitWidth == 16 || bitWidth == 32)); if (storeTy->isArrayTy() || storeTy->isVectorTy()) { const unsigned elemCount = storeTy->isArrayTy() ? cast<ArrayType>(storeTy)->getNumElements() : cast<FixedVectorType>(storeTy)->getNumElements(); for (unsigned i = 0; i < elemCount; ++i) { Value *storeElem = nullptr; if (storeTy->isArrayTy()) storeElem = ExtractValueInst::Create(storeValue, {i}, "", insertPos); else { storeElem = ExtractElementInst::Create(storeValue, ConstantInt::get(Type::getInt32Ty(*m_context), i), "", insertPos); } storeValueToEsGsRing(storeElem, location + (compIdx + i) / 4, (compIdx + i) % 4, insertPos); } } else { if (bitWidth == 8 || bitWidth == 16) { if (storeTy->isFloatingPointTy()) { assert(bitWidth == 16); storeValue = new BitCastInst(storeValue, Type::getInt16Ty(*m_context), "", insertPos); } storeValue = new ZExtInst(storeValue, Type::getInt32Ty(*m_context), "", insertPos); } else { assert(bitWidth == 32); if (storeTy->isFloatingPointTy()) storeValue = new BitCastInst(storeValue, Type::getInt32Ty(*m_context), "", insertPos); } // Call buffer store intrinsic or LDS store const auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(m_shaderStage)->entryArgIdxs; Value *esGsOffset = nullptr; if (m_shaderStage == ShaderStageVertex) esGsOffset = getFunctionArgument(m_entryPoint, entryArgIdxs.vs.esGsOffset); else { assert(m_shaderStage == ShaderStageTessEval); esGsOffset = getFunctionArgument(m_entryPoint, entryArgIdxs.tes.esGsOffset); } auto ringOffset = calcEsGsRingOffsetForOutput(location, compIdx, esGsOffset, insertPos); if (m_pipelineState->isGsOnChip() || m_gfxIp.major >= 9) // ES -> GS ring is always on-chip on GFX9+ { Value *idxs[] = {ConstantInt::get(Type::getInt32Ty(*m_context), 0), ringOffset}; auto ldsType = m_lds->getType()->getPointerElementType(); Value *storePtr = GetElementPtrInst::Create(ldsType, m_lds, idxs, "", insertPos); new StoreInst(storeValue, storePtr, false, m_lds->getAlign().getValue(), insertPos); } else { Value *esGsRingBufDesc = m_pipelineSysValues.get(m_entryPoint)->getEsGsRingBufDesc(); // NOTE: Here we use tbuffer_store instruction instead of buffer_store because we have to do explicit control // of soffset. This is required by swizzle enabled mode when address range checking should be complied with. CombineFormat combineFormat = {}; combineFormat.bits.dfmt = BUF_DATA_FORMAT_32; combineFormat.bits.nfmt = BUF_NUM_FORMAT_UINT; CoherentFlag coherent = {}; coherent.bits.glc = true; coherent.bits.slc = true; coherent.bits.swz = true; Value *args[] = { storeValue, // vdata esGsRingBufDesc, // rsrc ringOffset, // voffset esGsOffset, // soffset ConstantInt::get(Type::getInt32Ty(*m_context), combineFormat.u32All), ConstantInt::get(Type::getInt32Ty(*m_context), coherent.u32All) // glc, slc, swz }; emitCall("llvm.amdgcn.raw.tbuffer.store.i32", Type::getVoidTy(*m_context), args, {}, insertPos); } } } // ===================================================================================================================== // Loads value from ES-GS ring (buffer or LDS). // // @param loadTy : Load value type // @param location : Input location // @param compIdx : Input component index // @param vertexIdx : Vertex index // @param insertPos : Where to insert the load instruction Value *PatchInOutImportExport::loadValueFromEsGsRing(Type *loadTy, unsigned location, unsigned compIdx, Value *vertexIdx, Instruction *insertPos) { Type *elemTy = loadTy; if (loadTy->isArrayTy()) elemTy = cast<ArrayType>(loadTy)->getElementType(); else if (loadTy->isVectorTy()) elemTy = cast<VectorType>(loadTy)->getElementType(); const uint64_t bitWidth = elemTy->getScalarSizeInBits(); assert((elemTy->isFloatingPointTy() || elemTy->isIntegerTy()) && (bitWidth == 8 || bitWidth == 16 || bitWidth == 32)); Value *loadValue = UndefValue::get(loadTy); if (loadTy->isArrayTy() || loadTy->isVectorTy()) { const unsigned elemCount = loadTy->isArrayTy() ? cast<ArrayType>(loadTy)->getNumElements() : cast<FixedVectorType>(loadTy)->getNumElements(); for (unsigned i = 0; i < elemCount; ++i) { auto loadElem = loadValueFromEsGsRing(elemTy, location + (compIdx + i) / 4, (compIdx + i) % 4, vertexIdx, insertPos); if (loadTy->isArrayTy()) loadValue = InsertValueInst::Create(loadValue, loadElem, {i}, "", insertPos); else { loadValue = InsertElementInst::Create(loadValue, loadElem, ConstantInt::get(Type::getInt32Ty(*m_context), i), "", insertPos); } } } else { Value *ringOffset = calcEsGsRingOffsetForInput(location, compIdx, vertexIdx, insertPos); if (m_pipelineState->isGsOnChip() || m_gfxIp.major >= 9) // ES -> GS ring is always on-chip on GFX9 { Value *idxs[] = {ConstantInt::get(Type::getInt32Ty(*m_context), 0), ringOffset}; auto ldsType = m_lds->getType()->getPointerElementType(); Value *loadPtr = GetElementPtrInst::Create(ldsType, m_lds, idxs, "", insertPos); auto loadInst = new LoadInst(loadPtr->getType()->getPointerElementType(), loadPtr, "", false, m_lds->getAlign().getValue(), insertPos); loadValue = loadInst; if (bitWidth == 8) loadValue = new TruncInst(loadValue, Type::getInt8Ty(*m_context), "", insertPos); else if (bitWidth == 16) loadValue = new TruncInst(loadValue, Type::getInt16Ty(*m_context), "", insertPos); if (loadTy->isFloatingPointTy()) loadValue = new BitCastInst(loadValue, loadTy, "", insertPos); } else { Value *esGsRingBufDesc = m_pipelineSysValues.get(m_entryPoint)->getEsGsRingBufDesc(); CoherentFlag coherent = {}; coherent.bits.glc = true; coherent.bits.slc = true; Value *args[] = { esGsRingBufDesc, // rsrc ringOffset, // offset ConstantInt::get(Type::getInt32Ty(*m_context), 0), // soffset ConstantInt::get(Type::getInt32Ty(*m_context), coherent.u32All) // glc slc }; loadValue = emitCall("llvm.amdgcn.raw.buffer.load.f32", Type::getFloatTy(*m_context), args, {}, insertPos); if (bitWidth == 8) { assert(loadTy->isIntegerTy()); loadValue = new BitCastInst(loadValue, Type::getInt32Ty(*m_context), "", insertPos); loadValue = new TruncInst(loadValue, Type::getInt8Ty(*m_context), "", insertPos); } else if (bitWidth == 16) { loadValue = new BitCastInst(loadValue, Type::getInt32Ty(*m_context), "", insertPos); loadValue = new TruncInst(loadValue, Type::getInt16Ty(*m_context), "", insertPos); if (loadTy->isFloatingPointTy()) loadValue = new BitCastInst(loadValue, loadTy, "", insertPos); } else { assert(bitWidth == 32); if (loadTy->isIntegerTy()) loadValue = new BitCastInst(loadValue, loadTy, "", insertPos); } } } return loadValue; } // ===================================================================================================================== // Stores value to GS-VS ring (buffer or LDS). // // @param storeValue : Value to store // @param location : Output location // @param compIdx : Output component index // @param streamId : Output stream ID // @param insertPos : Where to insert the store instruction void PatchInOutImportExport::storeValueToGsVsRing(Value *storeValue, unsigned location, unsigned compIdx, unsigned streamId, Instruction *insertPos) { auto storeTy = storeValue->getType(); Type *elemTy = storeTy; if (storeTy->isArrayTy()) elemTy = cast<ArrayType>(storeTy)->getElementType(); else if (storeTy->isVectorTy()) elemTy = cast<VectorType>(storeTy)->getElementType(); const unsigned bitWidth = elemTy->getScalarSizeInBits(); assert((elemTy->isFloatingPointTy() || elemTy->isIntegerTy()) && (bitWidth == 8 || bitWidth == 16 || bitWidth == 32)); if (m_pipelineState->getNggControl()->enableNgg) { // NOTE: For NGG, exporting GS output to GS-VS ring is represented by a call and the call is replaced with // real instructions when when NGG primitive shader is generated. Value *args[] = {ConstantInt::get(Type::getInt32Ty(*m_context), location), ConstantInt::get(Type::getInt32Ty(*m_context), compIdx), ConstantInt::get(Type::getInt32Ty(*m_context), streamId), storeValue}; std::string callName = lgcName::NggGsOutputExport + getTypeName(storeTy); emitCall(callName, Type::getVoidTy(*m_context), args, {}, insertPos); return; } if (storeTy->isArrayTy() || storeTy->isVectorTy()) { const unsigned elemCount = storeTy->isArrayTy() ? cast<ArrayType>(storeTy)->getNumElements() : cast<FixedVectorType>(storeTy)->getNumElements(); for (unsigned i = 0; i < elemCount; ++i) { Value *storeElem = nullptr; if (storeTy->isArrayTy()) storeElem = ExtractValueInst::Create(storeValue, {i}, "", insertPos); else { storeElem = ExtractElementInst::Create(storeValue, ConstantInt::get(Type::getInt32Ty(*m_context), i), "", insertPos); } storeValueToGsVsRing(storeElem, location + (compIdx + i) / 4, (compIdx + i) % 4, streamId, insertPos); } } else { if (bitWidth == 8 || bitWidth == 16) { // NOTE: Currently, to simplify the design of load/store data from GS-VS ring, we always extend byte/word // to dword. This is because copy shader does not know the actual data type. It only generates output // export calls based on number of dwords. if (storeTy->isFloatingPointTy()) { assert(bitWidth == 16); storeValue = new BitCastInst(storeValue, Type::getInt16Ty(*m_context), "", insertPos); } storeValue = new ZExtInst(storeValue, Type::getInt32Ty(*m_context), "", insertPos); } else { assert(bitWidth == 32); if (storeTy->isFloatingPointTy()) storeValue = new BitCastInst(storeValue, Type::getInt32Ty(*m_context), "", insertPos); } const auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(m_shaderStage)->entryArgIdxs; Value *gsVsOffset = getFunctionArgument(m_entryPoint, entryArgIdxs.gs.gsVsOffset); auto emitCounterPtr = m_pipelineSysValues.get(m_entryPoint)->getEmitCounterPtr()[streamId]; auto emitCounterTy = emitCounterPtr->getType()->getPointerElementType(); auto emitCounter = new LoadInst(emitCounterTy, emitCounterPtr, "", insertPos); auto ringOffset = calcGsVsRingOffsetForOutput(location, compIdx, streamId, emitCounter, gsVsOffset, insertPos); if (m_pipelineState->isGsOnChip()) { Value *idxs[] = {ConstantInt::get(Type::getInt32Ty(*m_context), 0), ringOffset}; auto ldsType = m_lds->getType()->getPointerElementType(); Value *storePtr = GetElementPtrInst::Create(ldsType, m_lds, idxs, "", insertPos); new StoreInst(storeValue, storePtr, false, m_lds->getAlign().getValue(), insertPos); } else { // NOTE: Here we use tbuffer_store instruction instead of buffer_store because we have to do explicit // control of soffset. This is required by swizzle enabled mode when address range checking should be // complied with. if (m_gfxIp.major <= 9) { CombineFormat combineFormat = {}; combineFormat.bits.dfmt = BUF_DATA_FORMAT_32; combineFormat.bits.nfmt = BUF_NUM_FORMAT_UINT; CoherentFlag coherent = {}; coherent.bits.glc = true; coherent.bits.slc = true; coherent.bits.swz = true; Value *args[] = { storeValue, // vdata m_pipelineSysValues.get(m_entryPoint)->getGsVsRingBufDesc(streamId), // rsrc ringOffset, // voffset gsVsOffset, // soffset ConstantInt::get(Type::getInt32Ty(*m_context), combineFormat.u32All), ConstantInt::get(Type::getInt32Ty(*m_context), coherent.u32All) // glc, slc, swz }; emitCall("llvm.amdgcn.raw.tbuffer.store.i32", Type::getVoidTy(*m_context), args, {}, insertPos); } else { CoherentFlag coherent = {}; coherent.bits.glc = true; coherent.bits.slc = true; coherent.bits.swz = true; Value *args[] = { storeValue, // vdata m_pipelineSysValues.get(m_entryPoint)->getGsVsRingBufDesc(streamId), // rsrc ringOffset, // voffset gsVsOffset, // soffset ConstantInt::get(Type::getInt32Ty(*m_context), BUF_FORMAT_32_UINT), // format ConstantInt::get(Type::getInt32Ty(*m_context), coherent.u32All) // glc, slc, swz }; emitCall("llvm.amdgcn.raw.tbuffer.store.i32", Type::getVoidTy(*m_context), args, {}, insertPos); } } } } // ===================================================================================================================== // Calculates the byte offset to store the output value to ES-GS ring based on the specified output info. // // @param location : Output location // @param compIdx : Output component index // @param esGsOffset : ES-GS ring offset in bytes // @param insertPos : Where to insert the instruction Value *PatchInOutImportExport::calcEsGsRingOffsetForOutput(unsigned location, unsigned compIdx, Value *esGsOffset, Instruction *insertPos) { Value *ringOffset = nullptr; if (m_pipelineState->isGsOnChip() || m_gfxIp.major >= 9) // ES -> GS ring is always on-chip on GFX9 { // ringOffset = esGsOffset + threadId * esGsRingItemSize + location * 4 + compIdx assert(m_pipelineState->hasShaderStage(ShaderStageGeometry)); const auto &calcFactor = m_pipelineState->getShaderResourceUsage(ShaderStageGeometry)->inOutUsage.gs.calcFactor; esGsOffset = BinaryOperator::CreateLShr(esGsOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 2), "", insertPos); ringOffset = BinaryOperator::CreateMul( m_threadId, ConstantInt::get(Type::getInt32Ty(*m_context), calcFactor.esGsRingItemSize), "", insertPos); ringOffset = BinaryOperator::CreateAdd(ringOffset, esGsOffset, "", insertPos); ringOffset = BinaryOperator::CreateAdd( ringOffset, ConstantInt::get(Type::getInt32Ty(*m_context), (location * 4 + compIdx)), "", insertPos); } else { // ringOffset = (location * 4 + compIdx) * 4 ringOffset = ConstantInt::get(Type::getInt32Ty(*m_context), (location * 4 + compIdx) * 4); } return ringOffset; } // ===================================================================================================================== // Calculates the byte offset to load the input value from ES-GS ring based on the specified input info. // // @param location : Input location // @param compIdx : Input Component index // @param vertexIdx : Vertex index // @param insertPos : Where to insert the instruction Value *PatchInOutImportExport::calcEsGsRingOffsetForInput(unsigned location, unsigned compIdx, Value *vertexIdx, Instruction *insertPos) { Value *ringOffset = nullptr; auto esGsOffsets = m_pipelineSysValues.get(m_entryPoint)->getEsGsOffsets(); if (m_pipelineState->isGsOnChip() || m_gfxIp.major >= 9) // ES -> GS ring is always on-chip on GFX9 { Value *vertexOffset = ExtractElementInst::Create(esGsOffsets, vertexIdx, "", insertPos); // ringOffset = vertexOffset[N] + (location * 4 + compIdx); ringOffset = BinaryOperator::CreateAdd( vertexOffset, ConstantInt::get(Type::getInt32Ty(*m_context), (location * 4 + compIdx)), "", insertPos); } else { Value *vertexOffset = ExtractElementInst::Create(esGsOffsets, vertexIdx, "", insertPos); // ringOffset = vertexOffset[N] * 4 + (location * 4 + compIdx) * 64 * 4; ringOffset = BinaryOperator::CreateMul(vertexOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 4), "", insertPos); ringOffset = BinaryOperator::CreateAdd( ringOffset, ConstantInt::get(Type::getInt32Ty(*m_context), (location * 4 + compIdx) * 64 * 4), "", insertPos); } return ringOffset; } // ===================================================================================================================== // Calculates the offset to store the output value to GS-VS ring based on the specified output info. // // @param location : Output location // @param compIdx : Output component // @param streamId : Output stream ID // @param vertexIdx : Vertex index // @param gsVsOffset : ES-GS ring offset in bytes // @param insertPos : Where to insert the instruction Value *PatchInOutImportExport::calcGsVsRingOffsetForOutput(unsigned location, unsigned compIdx, unsigned streamId, Value *vertexIdx, Value *gsVsOffset, Instruction *insertPos) { auto resUsage = m_pipelineState->getShaderResourceUsage(ShaderStageGeometry); Value *ringOffset = nullptr; unsigned streamBases[MaxGsStreams]; unsigned streamBase = 0; for (int i = 0; i < MaxGsStreams; ++i) { streamBases[i] = streamBase; streamBase += (resUsage->inOutUsage.gs.outLocCount[i] * m_pipelineState->getShaderModes()->getGeometryShaderMode().outputVertices * 4); } if (m_pipelineState->isGsOnChip()) { // ringOffset = esGsLdsSize + // gsVsOffset + // threadId * gsVsRingItemSize + // (vertexIdx * vertexSizePerStream) + location * 4 + compIdx + streamBase (in dwords) auto esGsLdsSize = ConstantInt::get(Type::getInt32Ty(*m_context), resUsage->inOutUsage.gs.calcFactor.esGsLdsSize); gsVsOffset = BinaryOperator::CreateExact(Instruction::LShr, gsVsOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 2), "", insertPos); auto ringItemOffset = BinaryOperator::CreateMul( m_threadId, ConstantInt::get(Type::getInt32Ty(*m_context), resUsage->inOutUsage.gs.calcFactor.gsVsRingItemSize), "", insertPos); // VertexSize is stream output vertexSize x 4 (in dwords) unsigned vertexSize = resUsage->inOutUsage.gs.outLocCount[streamId] * 4; auto vertexItemOffset = BinaryOperator::CreateMul(vertexIdx, ConstantInt::get(Type::getInt32Ty(*m_context), vertexSize), "", insertPos); ringOffset = BinaryOperator::CreateAdd(esGsLdsSize, gsVsOffset, "", insertPos); ringOffset = BinaryOperator::CreateAdd(ringOffset, ringItemOffset, "", insertPos); ringOffset = BinaryOperator::CreateAdd(ringOffset, vertexItemOffset, "", insertPos); unsigned attribOffset = (location * 4) + compIdx + streamBases[streamId]; ringOffset = BinaryOperator::CreateAdd(ringOffset, ConstantInt::get(Type::getInt32Ty(*m_context), attribOffset), "", insertPos); } else { // ringOffset = ((location * 4 + compIdx) * maxVertices + vertexIdx) * 4 (in bytes); unsigned outputVertices = m_pipelineState->getShaderModes()->getGeometryShaderMode().outputVertices; ringOffset = BinaryOperator::CreateAdd( ConstantInt::get(Type::getInt32Ty(*m_context), (location * 4 + compIdx) * outputVertices), vertexIdx, "", insertPos); ringOffset = BinaryOperator::CreateMul(ringOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 4), "", insertPos); } return ringOffset; } // ===================================================================================================================== // Reads value from LDS. // // @param isOutput : Is the value from output variable // @param readTy : Type of value read from LDS // @param ldsOffset : Start offset to do LDS read operations // @param insertPos : Where to insert read instructions Value *PatchInOutImportExport::readValueFromLds(bool isOutput, Type *readTy, Value *ldsOffset, Instruction *insertPos) { assert(m_lds); assert(readTy->isSingleValueType()); // Read dwords from LDS const unsigned compCount = readTy->isVectorTy() ? cast<FixedVectorType>(readTy)->getNumElements() : 1; const unsigned bitWidth = readTy->getScalarSizeInBits(); assert(bitWidth == 8 || bitWidth == 16 || bitWidth == 32 || bitWidth == 64); const unsigned numChannels = compCount * (bitWidth == 64 ? 2 : 1); std::vector<Value *> loadValues(numChannels); const bool isTcsOutput = (isOutput && m_shaderStage == ShaderStageTessControl); const bool isTesInput = (!isOutput && m_shaderStage == ShaderStageTessEval); if (m_pipelineState->isTessOffChip() && (isTcsOutput || isTesInput)) // Read from off-chip LDS buffer { const auto &offChipLdsBaseArgIdx = m_shaderStage == ShaderStageTessEval ? m_pipelineState->getShaderInterfaceData(m_shaderStage)->entryArgIdxs.tes.offChipLdsBase : m_pipelineState->getShaderInterfaceData(m_shaderStage)->entryArgIdxs.tcs.offChipLdsBase; auto offChipLdsDesc = m_pipelineSysValues.get(m_entryPoint)->getOffChipLdsDesc(); auto offChipLdsBase = getFunctionArgument(m_entryPoint, offChipLdsBaseArgIdx); // Convert dword off-chip LDS offset to byte offset ldsOffset = BinaryOperator::CreateMul(ldsOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 4), "", insertPos); CoherentFlag coherent = {}; if (m_gfxIp.major <= 9) coherent.bits.glc = true; else if (m_gfxIp.major == 10) { coherent.bits.glc = true; coherent.bits.dlc = true; } else llvm_unreachable("Not implemented!"); for (unsigned i = 0, combineCount = 0; i < numChannels; i += combineCount) { combineCount = combineBufferLoad(loadValues, i, offChipLdsDesc, ldsOffset, offChipLdsBase, coherent, insertPos); for (unsigned j = i; j < i + combineCount; ++j) { if (bitWidth == 8) loadValues[j] = new TruncInst(loadValues[j], Type::getInt8Ty(*m_context), "", insertPos); else if (bitWidth == 16) loadValues[j] = new TruncInst(loadValues[j], Type::getInt16Ty(*m_context), "", insertPos); } } } else // Read from on-chip LDS { for (unsigned i = 0; i < numChannels; ++i) { Value *idxs[] = {ConstantInt::get(Type::getInt32Ty(*m_context), 0), ldsOffset}; auto ldsType = m_lds->getType()->getPointerElementType(); Value *loadPtr = GetElementPtrInst::Create(ldsType, m_lds, idxs, "", insertPos); auto loadTy = loadPtr->getType()->getPointerElementType(); auto loadInst = new LoadInst(loadTy, loadPtr, "", false, m_lds->getAlign().getValue(), insertPos); loadValues[i] = loadInst; if (bitWidth == 8) loadValues[i] = new TruncInst(loadValues[i], Type::getInt8Ty(*m_context), "", insertPos); else if (bitWidth == 16) loadValues[i] = new TruncInst(loadValues[i], Type::getInt16Ty(*m_context), "", insertPos); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 1), "", insertPos); } } // Construct <n x i8>, <n x i16>, or <n x i32> vector from load values (dwords) Value *castValue = nullptr; if (numChannels > 1) { auto intTy = bitWidth == 32 || bitWidth == 64 ? Type::getInt32Ty(*m_context) : (bitWidth == 16 ? Type::getInt16Ty(*m_context) : Type::getInt8Ty(*m_context)); auto castTy = FixedVectorType::get(intTy, numChannels); castValue = UndefValue::get(castTy); for (unsigned i = 0; i < numChannels; ++i) { castValue = InsertElementInst::Create(castValue, loadValues[i], ConstantInt::get(Type::getInt32Ty(*m_context), i), "", insertPos); } } else castValue = loadValues[0]; // Cast <n x i8>, <n x i16> or <n x i32> vector to read value return new BitCastInst(castValue, readTy, "", insertPos); } // ===================================================================================================================== // Writes value to LDS. // // @param writeValue : Value written to LDS // @param ldsOffset : Start offset to do LDS write operations // @param insertPos : Where to insert write instructions void PatchInOutImportExport::writeValueToLds(Value *writeValue, Value *ldsOffset, Instruction *insertPos) { assert(m_lds); auto writeTy = writeValue->getType(); assert(writeTy->isSingleValueType()); const unsigned compCout = writeTy->isVectorTy() ? cast<FixedVectorType>(writeTy)->getNumElements() : 1; const unsigned bitWidth = writeTy->getScalarSizeInBits(); assert(bitWidth == 8 || bitWidth == 16 || bitWidth == 32 || bitWidth == 64); const unsigned numChannels = compCout * (bitWidth == 64 ? 2 : 1); // Cast write value to <n x i32> vector Type *intTy = bitWidth == 32 || bitWidth == 64 ? Type::getInt32Ty(*m_context) : (bitWidth == 16 ? Type::getInt16Ty(*m_context) : Type::getInt8Ty(*m_context)); Type *castTy = numChannels > 1 ? cast<Type>(FixedVectorType::get(intTy, numChannels)) : intTy; Value *castValue = new BitCastInst(writeValue, castTy, "", insertPos); // Extract store values (dwords) from <n x i8>, <n x i16> or <n x i32> vector std::vector<Value *> storeValues(numChannels); if (numChannels > 1) { for (unsigned i = 0; i < numChannels; ++i) { storeValues[i] = ExtractElementInst::Create(castValue, ConstantInt::get(Type::getInt32Ty(*m_context), i), "", insertPos); if (bitWidth == 8 || bitWidth == 16) storeValues[i] = new ZExtInst(storeValues[i], Type::getInt32Ty(*m_context), "", insertPos); } } else { storeValues[0] = castValue; if (bitWidth == 8 || bitWidth == 16) storeValues[0] = new ZExtInst(storeValues[0], Type::getInt32Ty(*m_context), "", insertPos); } if (m_pipelineState->isTessOffChip() && m_shaderStage == ShaderStageTessControl) // Write to off-chip LDS buffer { auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(m_shaderStage)->entryArgIdxs.tcs; auto offChipLdsBase = getFunctionArgument(m_entryPoint, entryArgIdxs.offChipLdsBase); // Convert dword off-chip LDS offset to byte offset ldsOffset = BinaryOperator::CreateMul(ldsOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 4), "", insertPos); auto offChipLdsDesc = m_pipelineSysValues.get(m_entryPoint)->getOffChipLdsDesc(); CoherentFlag coherent = {}; coherent.bits.glc = true; for (unsigned i = 0, combineCount = 0; i < numChannels; i += combineCount) { combineCount = combineBufferStore(storeValues, i, i, offChipLdsDesc, ldsOffset, offChipLdsBase, coherent, insertPos); } } else // Write to on-chip LDS { for (unsigned i = 0; i < numChannels; ++i) { Value *idxs[] = {ConstantInt::get(Type::getInt32Ty(*m_context), 0), ldsOffset}; auto ldsType = m_lds->getType()->getPointerElementType(); Value *storePtr = GetElementPtrInst::Create(ldsType, m_lds, idxs, "", insertPos); new StoreInst(storeValues[i], storePtr, false, m_lds->getAlign().getValue(), insertPos); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 1), "", insertPos); } } } // ===================================================================================================================== // Calculates start offset of tessellation factors in the TF buffer. // // @param isOuter : Whether the calculation is for tessellation outer factors // @param elemIdxVal : Index used for array element indexing (could be null) // @param insertPos : Where to insert store instructions Value *PatchInOutImportExport::calcTessFactorOffset(bool isOuter, Value *elemIdxVal, Instruction *insertPos) { assert(m_shaderStage == ShaderStageTessControl); // NOTE: Tessellation factors are from tessellation level array and we have: // (1) Isoline // tessFactor[0] = gl_TessLevelOuter[1] // tessFactor[1] = gl_TessLevelOuter[0] // (2) Triangle // tessFactor[0] = gl_TessLevelOuter[0] // tessFactor[1] = gl_TessLevelOuter[1] // tessFactor[2] = gl_TessLevelOuter[2] // tessFactor[3] = gl_TessLevelInner[0] // (3) Quad // tessFactor[0] = gl_TessLevelOuter[0] // tessFactor[1] = gl_TessLevelOuter[1] // tessFactor[2] = gl_TessLevelOuter[2] // tessFactor[3] = gl_TessLevelOuter[3] // tessFactor[4] = gl_TessLevelInner[0] // tessFactor[5] = gl_TessLevelInner[1] unsigned tessFactorCount = 0; unsigned tessFactorStart = 0; auto primitiveMode = m_pipelineState->getShaderModes()->getTessellationMode().primitiveMode; switch (primitiveMode) { case PrimitiveMode::Isolines: tessFactorCount = isOuter ? 2 : 0; tessFactorStart = isOuter ? 0 : 2; break; case PrimitiveMode::Triangles: tessFactorCount = isOuter ? 3 : 1; tessFactorStart = isOuter ? 0 : 3; break; case PrimitiveMode::Quads: tessFactorCount = isOuter ? 4 : 2; tessFactorStart = isOuter ? 0 : 4; break; default: llvm_unreachable("Should never be called!"); break; } Value *tessFactorOffset = ConstantInt::get(Type::getInt32Ty(*m_context), tessFactorStart); if (elemIdxVal) { if (primitiveMode == PrimitiveMode::Isolines && isOuter) { // NOTE: In case of the isoline, hardware wants two tessellation factor: the first is detail // TF, the second is density TF. The order is reversed, different from GLSL spec. assert(tessFactorCount == 2); // elemIdx = (elemIdx <= 1) ? 1 - elemIdx : elemIdx auto cond = new ICmpInst(insertPos, ICmpInst::ICMP_ULE, elemIdxVal, ConstantInt::get(Type::getInt32Ty(*m_context), 1), ""); auto swapElemIdx = BinaryOperator::CreateSub(ConstantInt::get(Type::getInt32Ty(*m_context), 1), elemIdxVal, "", insertPos); elemIdxVal = SelectInst::Create(cond, swapElemIdx, elemIdxVal, "", insertPos); } // tessFactorOffset = (elemIdx < tessFactorCount) ? (tessFactorStart + elemIdx) : invalidValue tessFactorOffset = BinaryOperator::CreateAdd(tessFactorOffset, elemIdxVal, "", insertPos); auto cond = new ICmpInst(insertPos, ICmpInst::ICMP_ULT, elemIdxVal, ConstantInt::get(Type::getInt32Ty(*m_context), tessFactorCount), ""); tessFactorOffset = SelectInst::Create(cond, tessFactorOffset, ConstantInt::get(Type::getInt32Ty(*m_context), InvalidValue), "", insertPos); } return tessFactorOffset; } // ===================================================================================================================== // Stores tessellation factors (outer/inner) to corresponding tessellation factor (TF) buffer. // // @param tessFactors : Tessellation factors to be stored // @param tessFactorOffsetVal : Start offset to store the specified tessellation factors // @param insertPos : Where to insert store instructions void PatchInOutImportExport::storeTessFactorToBuffer(ArrayRef<Value *> tessFactors, Value *tessFactorOffsetVal, Instruction *insertPos) { assert(m_shaderStage == ShaderStageTessControl); if (tessFactors.size() == 0) { // No tessellation factor should be stored return; } const auto &inOutUsage = m_pipelineState->getShaderResourceUsage(ShaderStageTessControl)->inOutUsage.tcs; const auto &calcFactor = inOutUsage.calcFactor; auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageTessControl)->entryArgIdxs.tcs; Value *tfBufferBase = getFunctionArgument(m_entryPoint, entryArgIdxs.tfBufferBase); auto tessFactorStride = ConstantInt::get(Type::getInt32Ty(*m_context), calcFactor.tessFactorStride); BuilderBase builder(*m_context); builder.SetInsertPoint(insertPos); // Mangle the call name according t the count of tessellation factors. std::string callName(lgcName::TfBufferStore); const unsigned compCount = tessFactors.size(); Value *tfValue = nullptr; if (compCount == 1) { tfValue = tessFactors[0]; } else { tfValue = UndefValue::get(FixedVectorType::get(builder.getFloatTy(), compCount)); for (unsigned compIdx = 0; compIdx < compCount; ++compIdx) tfValue = builder.CreateInsertElement(tfValue, tessFactors[compIdx], compIdx); } callName += getTypeName(tfValue->getType()); if (!m_module->getFunction(callName)) createTessBufferStoreFunction(callName, compCount, tfValue->getType()); if (m_pipelineState->isTessOffChip()) { if (m_gfxIp.major <= 8) { // NOTE: Additional 4-byte offset is required for tessellation off-chip mode (pre-GFX9). tfBufferBase = BinaryOperator::CreateAdd(tfBufferBase, ConstantInt::get(Type::getInt32Ty(*m_context), 4), "", insertPos); } } Value *args[] = { m_pipelineSysValues.get(m_entryPoint)->getTessFactorBufDesc(), // tfBufferDesc tfBufferBase, // tfBufferBase m_pipelineSysValues.get(m_entryPoint)->getRelativeId(), // relPatchId tessFactorStride, // tfStride tessFactorOffsetVal, // tfOffset tfValue // tfValue }; builder.CreateNamedCall(callName, builder.getVoidTy(), args, {}); } // ===================================================================================================================== // Creates the LLPC intrinsic "llpc.tfbuffer.store.%tfValueType" to store tessellation factor. // // param@ funcName : The internal function name // param@ compCount : The component count of the store value // param@ tfValueTy : The type of the store value void PatchInOutImportExport::createTessBufferStoreFunction(StringRef funcName, unsigned compCount, Type *tfValueTy) { // %tfValueType could be one of {f32, v2f32, v3f32, v4f32} // define void @llpc.tfbuffer.store.%tfValueType( // <4 x i32> %tfBufferDesc, i32 %tfBufferBase, i32 %relPatchId, i32 %tfStride, i32 %tfOffset, %tfValueType // %tfValue) // { // %1 = icmp ne i32 %tfOffset, -1 (invalidValue) // br i1 %1, label %.tfstore, label %.end // // .tfstore: // %2 = mul i32 %tfStride, 4 // %3 = mul i32 %relPatchId, %2 // %4 = mul i32 %tfOffset, 4 // %5 = add i32 %3, %4 // call void @llvm.amdgcn.raw.tbuffer.store.%tfValueType( // tfValueType %tfValue, <4 x i32> %tfBufferDesc, i32 %5, i32 %tfBufferBase, i32 1) // br label %.end // // .end: // ret void // } assert(tfValueTy->getScalarType()->isFloatTy()); BuilderBase builder(*m_context); Type *argTys[] = { FixedVectorType::get(Type::getInt32Ty(*m_context), 4), // TF buffer descriptor builder.getInt32Ty(), // TF buffer base builder.getInt32Ty(), // Relative patch ID builder.getInt32Ty(), // TF stride builder.getInt32Ty(), // TF offset tfValueTy // TF value }; auto funcTy = FunctionType::get(Type::getVoidTy(*m_context), argTys, false); auto func = Function::Create(funcTy, GlobalValue::InternalLinkage, funcName, m_module); func->setCallingConv(CallingConv::C); func->addFnAttr(Attribute::NoUnwind); func->addFnAttr(Attribute::AlwaysInline); auto argIt = func->arg_begin(); Value *tfBufferDesc = argIt++; tfBufferDesc->setName("tfBufferDesc"); Value *tfBufferBase = argIt++; tfBufferBase->setName("tfBufferBase"); Value *relPatchId = argIt++; relPatchId->setName("relPatchId"); Value *tfStride = argIt++; tfStride->setName("tfStride"); Value *tfOffset = argIt++; tfOffset->setName("tfOffset"); Value *tfValue = argIt++; tfValue->setName("tfValue"); // Create ".end" block BasicBlock *endBlock = BasicBlock::Create(*m_context, ".end", func); ReturnInst::Create(*m_context, endBlock); // Create ".tfstore" block BasicBlock *tfStoreBlock = BasicBlock::Create(*m_context, ".tfstore", func, endBlock); Value *tfByteOffset = BinaryOperator::CreateMul(tfOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 4), "", tfStoreBlock); Value *tfByteStride = BinaryOperator::CreateMul(tfStride, ConstantInt::get(Type::getInt32Ty(*m_context), 4), "", tfStoreBlock); Value *tfBufferOffset = BinaryOperator::CreateMul(relPatchId, tfByteStride, "", tfStoreBlock); tfBufferOffset = BinaryOperator::CreateAdd(tfBufferOffset, tfByteOffset, "", tfStoreBlock); auto branch = BranchInst::Create(endBlock, tfStoreBlock); // Create llvm.amdgcn.raw.tbuffer.store. CoherentFlag coherent = {}; coherent.bits.glc = true; Value *args[] = { tfValue, // vdata tfBufferDesc, // rsrc tfBufferOffset, // voffset tfBufferBase, // soffset builder.getInt32((*m_buffFormats)[compCount - 1]), // format builder.getInt32(coherent.u32All) // glc }; builder.SetInsertPoint(branch); builder.CreateNamedCall((Twine("llvm.amdgcn.raw.tbuffer.store.") + getTypeName(tfValueTy)).str(), builder.getVoidTy(), args, {}); // Create entry block BasicBlock *entryBlock = BasicBlock::Create(*m_context, "", func, tfStoreBlock); Value *cond = new ICmpInst(*entryBlock, ICmpInst::ICMP_NE, tfOffset, ConstantInt::get(Type::getInt32Ty(*m_context), InvalidValue), ""); BranchInst::Create(tfStoreBlock, endBlock, cond, entryBlock); } // ===================================================================================================================== // Calculates the dword offset to write value to LDS based on the specified VS output info. // // @param outputTy : Type of the output // @param location : Base location of the output // @param compIdx : Index used for vector element indexing // @param insertPos : Where to insert calculation instructions Value *PatchInOutImportExport::calcLdsOffsetForVsOutput(Type *outputTy, unsigned location, unsigned compIdx, Instruction *insertPos) { assert(m_shaderStage == ShaderStageVertex); // attribOffset = location * 4 + compIdx Value *attribOffset = ConstantInt::get(Type::getInt32Ty(*m_context), location * 4); const unsigned bitWidth = outputTy->getScalarSizeInBits(); assert(bitWidth == 8 || bitWidth == 16 || bitWidth == 32 || bitWidth == 64); if (bitWidth == 64) { // For 64-bit data type, the component indexing must multiply by 2 compIdx *= 2; } attribOffset = BinaryOperator::CreateAdd(attribOffset, ConstantInt::get(Type::getInt32Ty(*m_context), compIdx), "", insertPos); const auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageVertex)->entryArgIdxs.vs; auto relVertexId = getFunctionArgument(m_entryPoint, entryArgIdxs.relVertexId); const auto &calcFactor = m_pipelineState->getShaderResourceUsage(ShaderStageTessControl)->inOutUsage.tcs.calcFactor; auto vertexStride = ConstantInt::get(Type::getInt32Ty(*m_context), calcFactor.inVertexStride); // dwordOffset = relVertexId * vertexStride + attribOffset auto ldsOffset = BinaryOperator::CreateMul(relVertexId, vertexStride, "", insertPos); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, attribOffset, "", insertPos); return ldsOffset; } // ===================================================================================================================== // Calculates the dword offset to read value from LDS based on the specified TCS input info. // // @param inputTy : Type of the input // @param location : Base location of the input // @param locOffset : Relative location offset // @param compIdx : Index used for vector element indexing (could be null) // @param vertexIdx : Vertex indexing // @param insertPos : Where to insert calculation instructions Value *PatchInOutImportExport::calcLdsOffsetForTcsInput(Type *inputTy, unsigned location, Value *locOffset, Value *compIdx, Value *vertexIdx, Instruction *insertPos) { assert(m_shaderStage == ShaderStageTessControl); const auto &inOutUsage = m_pipelineState->getShaderResourceUsage(ShaderStageTessControl)->inOutUsage.tcs; const auto &calcFactor = inOutUsage.calcFactor; // attribOffset = (location + locOffset) * 4 + compIdx Value *attribOffset = ConstantInt::get(Type::getInt32Ty(*m_context), location); if (locOffset) attribOffset = BinaryOperator::CreateAdd(attribOffset, locOffset, "", insertPos); attribOffset = BinaryOperator::CreateMul(attribOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 4), "", insertPos); if (compIdx) { const unsigned bitWidth = inputTy->getScalarSizeInBits(); assert(bitWidth == 8 || bitWidth == 16 || bitWidth == 32 || bitWidth == 64); if (bitWidth == 64) { // For 64-bit data type, the component indexing must multiply by 2 compIdx = BinaryOperator::CreateMul(compIdx, ConstantInt::get(Type::getInt32Ty(*m_context), 2), "", insertPos); } attribOffset = BinaryOperator::CreateAdd(attribOffset, compIdx, "", insertPos); } // dwordOffset = (relativeId * inVertexCount + vertexId) * inVertexStride + attribOffset auto inVertexCount = m_pipelineState->getInputAssemblyState().patchControlPoints; auto inVertexCountVal = ConstantInt::get(Type::getInt32Ty(*m_context), inVertexCount); auto relativeId = m_pipelineSysValues.get(m_entryPoint)->getRelativeId(); Value *ldsOffset = BinaryOperator::CreateMul(relativeId, inVertexCountVal, "", insertPos); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, vertexIdx, "", insertPos); auto inVertexStride = ConstantInt::get(Type::getInt32Ty(*m_context), calcFactor.inVertexStride); ldsOffset = BinaryOperator::CreateMul(ldsOffset, inVertexStride, "", insertPos); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, attribOffset, "", insertPos); return ldsOffset; } // ===================================================================================================================== // Calculates the dword offset to read/write value from/to LDS based on the specified TCS output info. // // @param outputTy : Type of the output // @param location : Base location of the output // @param locOffset : Relative location offset (could be null) // @param compIdx : Index used for vector element indexing (could be null) // @param vertexIdx : Vertex indexing // @param insertPos : Where to insert calculation instructions Value *PatchInOutImportExport::calcLdsOffsetForTcsOutput(Type *outputTy, unsigned location, Value *locOffset, Value *compIdx, Value *vertexIdx, Instruction *insertPos) { assert(m_shaderStage == ShaderStageTessControl); const auto &inOutUsage = m_pipelineState->getShaderResourceUsage(ShaderStageTessControl)->inOutUsage.tcs; const auto &calcFactor = inOutUsage.calcFactor; auto outPatchStart = m_pipelineState->isTessOffChip() ? calcFactor.offChip.outPatchStart : calcFactor.onChip.outPatchStart; auto patchConstStart = m_pipelineState->isTessOffChip() ? calcFactor.offChip.patchConstStart : calcFactor.onChip.patchConstStart; // attribOffset = (location + locOffset) * 4 + compIdx * bitWidth / 32 Value *attibOffset = ConstantInt::get(Type::getInt32Ty(*m_context), location); if (locOffset) attibOffset = BinaryOperator::CreateAdd(attibOffset, locOffset, "", insertPos); attibOffset = BinaryOperator::CreateMul(attibOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 4), "", insertPos); if (compIdx) { const unsigned bitWidth = outputTy->getScalarSizeInBits(); assert(bitWidth == 8 || bitWidth == 16 || bitWidth == 32 || bitWidth == 64); if (bitWidth == 64) { // For 64-bit data type, the component indexing must multiply by 2 compIdx = BinaryOperator::CreateMul(compIdx, ConstantInt::get(Type::getInt32Ty(*m_context), 2), "", insertPos); } attibOffset = BinaryOperator::CreateAdd(attibOffset, compIdx, "", insertPos); } Value *ldsOffset = nullptr; const bool perPatch = (!vertexIdx); // Vertex indexing is unavailable for per-patch output auto relativeId = m_pipelineSysValues.get(m_entryPoint)->getRelativeId(); if (perPatch) { // dwordOffset = patchConstStart + relativeId * patchConstSize + attribOffset auto patchConstSize = ConstantInt::get(Type::getInt32Ty(*m_context), calcFactor.patchConstSize); ldsOffset = BinaryOperator::CreateMul(relativeId, patchConstSize, "", insertPos); auto patchConstStartVal = ConstantInt::get(Type::getInt32Ty(*m_context), patchConstStart); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, patchConstStartVal, "", insertPos); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, attibOffset, "", insertPos); } else { // dwordOffset = outPatchStart + (relativeId * outVertexCount + vertexId) * outVertexStride + attribOffset // = outPatchStart + relativeId * outPatchSize + vertexId * outVertexStride + attribOffset auto outPatchSize = ConstantInt::get(Type::getInt32Ty(*m_context), calcFactor.outPatchSize); ldsOffset = BinaryOperator::CreateMul(relativeId, outPatchSize, "", insertPos); auto outPatchStartVal = ConstantInt::get(Type::getInt32Ty(*m_context), outPatchStart); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, outPatchStartVal, "", insertPos); auto outVertexStride = ConstantInt::get(Type::getInt32Ty(*m_context), calcFactor.outVertexStride); ldsOffset = BinaryOperator::CreateAdd( ldsOffset, BinaryOperator::CreateMul(vertexIdx, outVertexStride, "", insertPos), "", insertPos); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, attibOffset, "", insertPos); } return ldsOffset; } // ===================================================================================================================== // Calculates the dword offset to read/write value from/to LDS based on the specified TES input info. // // @param inputTy : Type of the input // @param location : Base location of the input // @param locOffset : Relative location offset // @param compIdx : Index used for vector element indexing (could be null) // @param vertexIdx : Vertex indexing // @param insertPos : Where to insert calculation instructions Value *PatchInOutImportExport::calcLdsOffsetForTesInput(Type *inputTy, unsigned location, Value *locOffset, Value *compIdx, Value *vertexIdx, Instruction *insertPos) { assert(m_shaderStage == ShaderStageTessEval); const auto &calcFactor = m_pipelineState->getShaderResourceUsage(ShaderStageTessControl)->inOutUsage.tcs.calcFactor; auto outPatchStart = m_pipelineState->isTessOffChip() ? calcFactor.offChip.outPatchStart : calcFactor.onChip.outPatchStart; auto patchConstStart = m_pipelineState->isTessOffChip() ? calcFactor.offChip.patchConstStart : calcFactor.onChip.patchConstStart; const auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(m_shaderStage)->entryArgIdxs.tes; auto relPatchId = getFunctionArgument(m_entryPoint, entryArgIdxs.relPatchId); // attribOffset = (location + locOffset) * 4 + compIdx Value *attibOffset = ConstantInt::get(Type::getInt32Ty(*m_context), location); if (locOffset) attibOffset = BinaryOperator::CreateAdd(attibOffset, locOffset, "", insertPos); attibOffset = BinaryOperator::CreateMul(attibOffset, ConstantInt::get(Type::getInt32Ty(*m_context), 4), "", insertPos); if (compIdx) { const unsigned bitWidth = inputTy->getScalarSizeInBits(); assert(bitWidth == 8 || bitWidth == 16 || bitWidth == 32 || bitWidth == 64); if (bitWidth == 64) { // For 64-bit data type, the component indexing must multiply by 2 compIdx = BinaryOperator::CreateMul(compIdx, ConstantInt::get(Type::getInt32Ty(*m_context), 2), "", insertPos); } attibOffset = BinaryOperator::CreateAdd(attibOffset, compIdx, "", insertPos); } Value *ldsOffset = nullptr; const bool perPatch = (!vertexIdx); // Vertex indexing is unavailable for per-patch input if (perPatch) { // dwordOffset = patchConstStart + relPatchId * patchConstSize + attribOffset auto patchConstSize = ConstantInt::get(Type::getInt32Ty(*m_context), calcFactor.patchConstSize); ldsOffset = BinaryOperator::CreateMul(relPatchId, patchConstSize, "", insertPos); auto patchConstStartVal = ConstantInt::get(Type::getInt32Ty(*m_context), patchConstStart); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, patchConstStartVal, "", insertPos); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, attibOffset, "", insertPos); } else { // dwordOffset = patchStart + (relPatchId * vertexCount + vertexId) * vertexStride + attribOffset // = patchStart + relPatchId * patchSize + vertexId * vertexStride + attribOffset auto patchSize = ConstantInt::get(Type::getInt32Ty(*m_context), calcFactor.outPatchSize); ldsOffset = BinaryOperator::CreateMul(relPatchId, patchSize, "", insertPos); auto patchStart = ConstantInt::get(Type::getInt32Ty(*m_context), outPatchStart); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, patchStart, "", insertPos); auto vertexStride = ConstantInt::get(Type::getInt32Ty(*m_context), calcFactor.outVertexStride); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, BinaryOperator::CreateMul(vertexIdx, vertexStride, "", insertPos), "", insertPos); ldsOffset = BinaryOperator::CreateAdd(ldsOffset, attibOffset, "", insertPos); } return ldsOffset; } // ===================================================================================================================== // Calculates the patch count for per-thread group. // // @param inVertexCount : Count of vertices of input patch // @param inVertexStride : Vertex stride of input patch in (dwords) // @param outVertexCount : Count of vertices of output patch // @param outVertexStride : Vertex stride of output patch in (dwords) // @param patchConstCount : Count of output patch constants // @param tessFactorStride : Stride of tessellation factors (dwords) unsigned PatchInOutImportExport::calcPatchCountPerThreadGroup(unsigned inVertexCount, unsigned inVertexStride, unsigned outVertexCount, unsigned outVertexStride, unsigned patchConstCount, unsigned tessFactorStride) const { const unsigned waveSize = m_pipelineState->getShaderWaveSize(m_shaderStage); // NOTE: The limit of thread count for tessellation control shader is 4 wavefronts per thread group. const unsigned maxThreadCountPerThreadGroup = (4 * waveSize); const unsigned maxThreadCountPerPatch = std::max(inVertexCount, outVertexCount); const unsigned patchCountLimitedByThread = maxThreadCountPerThreadGroup / maxThreadCountPerPatch; const unsigned inPatchSize = (inVertexCount * inVertexStride); const unsigned outPatchSize = (outVertexCount * outVertexStride); const unsigned patchConstSize = patchConstCount * 4; // Compute the required LDS size per patch, always include the space for VS vertex out unsigned ldsSizePerPatch = inPatchSize; unsigned patchCountLimitedByLds = (m_pipelineState->getTargetInfo().getGpuProperty().ldsSizePerThreadGroup / ldsSizePerPatch); unsigned patchCountPerThreadGroup = std::min(patchCountLimitedByThread, patchCountLimitedByLds); // NOTE: Performance analysis shows that 16 patches per thread group is an optimal upper-bound. The value is only // an experimental number. For GFX9. 64 is an optimal number instead. const unsigned optimalPatchCountPerThreadGroup = m_gfxIp.major >= 9 ? 64 : 16; patchCountPerThreadGroup = std::min(patchCountPerThreadGroup, optimalPatchCountPerThreadGroup); if (m_pipelineState->isTessOffChip()) { auto outPatchLdsBufferSize = (outPatchSize + patchConstSize) * 4; auto tessOffChipPatchCountPerThreadGroup = m_pipelineState->getTargetInfo().getGpuProperty().tessOffChipLdsBufferSize / outPatchLdsBufferSize; patchCountPerThreadGroup = std::min(patchCountPerThreadGroup, tessOffChipPatchCountPerThreadGroup); } // TF-Buffer-based limit for Patchers per Thread Group: // --------------------------------------------------------------------------------------------- // There is one TF Buffer per shader engine. We can do the below calculation on a per-SE basis. It is also safe to // assume that one thread-group could at most utilize all of the TF Buffer. const unsigned tfBufferSizeInBytes = sizeof(unsigned) * m_pipelineState->getTargetInfo().getGpuProperty().tessFactorBufferSizePerSe; unsigned tfBufferPatchCountLimit = tfBufferSizeInBytes / (tessFactorStride * sizeof(unsigned)); const auto workarounds = &m_pipelineState->getTargetInfo().getGpuWorkarounds(); if (workarounds->gfx10.waTessFactorBufferSizeLimitGeUtcl1Underflow) { tfBufferPatchCountLimit /= 2; } patchCountPerThreadGroup = std::min(patchCountPerThreadGroup, tfBufferPatchCountLimit); if (m_pipelineState->isTessOffChip()) { // For all-offchip tessellation, we need to write an additional 4-byte TCS control word to the TF buffer whenever // the patch-ID is zero. const unsigned offChipTfBufferPatchCountLimit = (tfBufferSizeInBytes - (patchCountPerThreadGroup * sizeof(unsigned))) / (tessFactorStride * sizeof(unsigned)); patchCountPerThreadGroup = std::min(patchCountPerThreadGroup, offChipTfBufferPatchCountLimit); } // Adjust the patches-per-thread-group based on hardware workarounds. if (m_pipelineState->getTargetInfo().getGpuWorkarounds().gfx6.miscLoadBalancePerWatt != 0) { const unsigned waveSize = m_pipelineState->getTargetInfo().getGpuProperty().waveSize; // Load balance per watt is a mechanism which monitors HW utilization (num waves active, instructions issued // per cycle, etc.) to determine if the HW can handle the workload with fewer CUs enabled. The SPI_LB_CU_MASK // register directs the SPI to stop launching waves to a CU so it will be clock-gated. There is a bug in the // SPI which where that register setting is applied immediately, which causes any pending LS/HS/CS waves on // that CU to never be launched. // // The workaround is to limit each LS/HS threadgroup to a single wavefront: if there's only one wave, then the // CU can safely be turned off afterwards. A microcode fix exists for CS but for GFX it was decided that the // cost in power efficiency wasn't worthwhile. // // Clamping to threads-per-wavefront / max(input control points, threads-per-patch) will make the hardware // launch a single LS/HS wave per thread-group. // For vulkan, threads-per-patch is always equal with outVertexCount. const unsigned maxThreadCountPerPatch = std::max(inVertexCount, outVertexCount); const unsigned maxPatchCount = waveSize / maxThreadCountPerPatch; patchCountPerThreadGroup = std::min(patchCountPerThreadGroup, maxPatchCount); } return patchCountPerThreadGroup; } // ===================================================================================================================== // Inserts "exp" instruction to export generic output. // // @param output : Output value // @param location : Location of the output // @param compIdx : Index used for vector element indexing // @param insertPos : Where to insert the "exp" instruction void PatchInOutImportExport::addExportInstForGenericOutput(Value *output, unsigned location, unsigned compIdx, Instruction *insertPos) { // Check if the shader stage is valid to use "exp" instruction to export output const auto nextStage = m_pipelineState->getNextShaderStage(m_shaderStage); const bool useExpInst = ((m_shaderStage == ShaderStageVertex || m_shaderStage == ShaderStageTessEval || m_shaderStage == ShaderStageCopyShader) && (nextStage == ShaderStageInvalid || nextStage == ShaderStageFragment)); assert(useExpInst); (void(useExpInst)); // unused auto outputTy = output->getType(); const unsigned compCount = outputTy->isVectorTy() ? cast<FixedVectorType>(outputTy)->getNumElements() : 1; const unsigned bitWidth = outputTy->getScalarSizeInBits(); assert(bitWidth == 8 || bitWidth == 16 || bitWidth == 32 || bitWidth == 64); // Convert the output value to floating-point export value Value *exportInst = nullptr; const unsigned numChannels = bitWidth == 64 ? compCount * 2 : compCount; unsigned startChannel = bitWidth == 64 ? compIdx * 2 : compIdx; Type *exportTy = numChannels > 1 ? FixedVectorType::get(Type::getFloatTy(*m_context), numChannels) : Type::getFloatTy(*m_context); if (outputTy != exportTy) { if (bitWidth == 8) { // NOTE: For 16-bit output export, we have to cast the 8-bit value to 32-bit floating-point value. assert(outputTy->isIntOrIntVectorTy()); Type *zExtTy = Type::getInt32Ty(*m_context); zExtTy = outputTy->isVectorTy() ? cast<Type>(FixedVectorType::get(zExtTy, compCount)) : zExtTy; exportInst = new ZExtInst(output, zExtTy, "", insertPos); exportInst = new BitCastInst(exportInst, exportTy, "", insertPos); } else if (bitWidth == 16) { // NOTE: For 16-bit output export, we have to cast the 16-bit value to 32-bit floating-point value. if (outputTy->isFPOrFPVectorTy()) { Type *bitCastTy = Type::getInt16Ty(*m_context); bitCastTy = outputTy->isVectorTy() ? cast<Type>(FixedVectorType::get(bitCastTy, compCount)) : bitCastTy; exportInst = new BitCastInst(output, bitCastTy, "", insertPos); } else { assert(outputTy->isIntOrIntVectorTy()); exportInst = output; } Type *zExtTy = Type::getInt32Ty(*m_context); zExtTy = outputTy->isVectorTy() ? cast<Type>(FixedVectorType::get(zExtTy, compCount)) : zExtTy; exportInst = new ZExtInst(exportInst, zExtTy, "", insertPos); exportInst = new BitCastInst(exportInst, exportTy, "", insertPos); } else { assert(canBitCast(outputTy, exportTy)); exportInst = new BitCastInst(output, exportTy, "", insertPos); } } else exportInst = output; assert(numChannels <= 8); Value *exportValues[8] = {nullptr}; if (numChannels == 1) exportValues[0] = exportInst; else { for (unsigned i = 0; i < numChannels; ++i) { exportValues[i] = ExtractElementInst::Create(exportInst, ConstantInt::get(Type::getInt32Ty(*m_context), i), "", insertPos); } } auto undef = UndefValue::get(Type::getFloatTy(*m_context)); if (numChannels <= 4) { assert(startChannel + numChannels <= 4); Value *attribValues[4] = {undef, undef, undef, undef}; for (unsigned i = startChannel; i < startChannel + numChannels; ++i) attribValues[i] = exportValues[i - startChannel]; m_expLocs.insert(location); recordVertexAttribExport(location, {attribValues[0], attribValues[1], attribValues[2], attribValues[3]}); } else { // We have to do exporting twice for this output assert(startChannel == 0); // Other values are disallowed according to GLSL spec assert(numChannels == 6 || numChannels == 8); Value *attribValues[8] = {undef, undef, undef, undef, undef, undef, undef, undef}; for (unsigned i = 0; i < numChannels; ++i) attribValues[i] = exportValues[i]; m_expLocs.insert(location); // First export recordVertexAttribExport(location, {attribValues[0], attribValues[1], attribValues[2], attribValues[3]}); m_expLocs.insert(location + 1); // Second export recordVertexAttribExport(location + 1, {attribValues[4], attribValues[5], attribValues[6], attribValues[7]}); } } // ===================================================================================================================== // Inserts "exp" instruction to export built-in output. // // @param output : Output value // @param builtInId : ID of the built-in variable // @param insertPos : Where to insert the "exp" instruction void PatchInOutImportExport::addExportInstForBuiltInOutput(Value *output, unsigned builtInId, Instruction *insertPos) { // Check if the shader stage is valid to use "exp" instruction to export output const auto nextStage = m_pipelineState->getNextShaderStage(m_shaderStage); const bool useExpInst = ((m_shaderStage == ShaderStageVertex || m_shaderStage == ShaderStageTessEval || m_shaderStage == ShaderStageCopyShader) && (nextStage == ShaderStageInvalid || nextStage == ShaderStageFragment)); assert(useExpInst); (void(useExpInst)); // unused auto &inOutUsage = m_pipelineState->getShaderResourceUsage(m_shaderStage)->inOutUsage; const auto undef = UndefValue::get(Type::getFloatTy(*m_context)); switch (builtInId) { case BuiltInPosition: { Value *args[] = { ConstantInt::get(Type::getInt32Ty(*m_context), EXP_TARGET_POS_0), // tgt ConstantInt::get(Type::getInt32Ty(*m_context), 0xF), // en nullptr, nullptr, nullptr, nullptr, ConstantInt::get(Type::getInt1Ty(*m_context), false), // done ConstantInt::get(Type::getInt1Ty(*m_context), false) // vm }; // src0 ~ src3 for (unsigned i = 0; i < 4; ++i) { auto compValue = ExtractElementInst::Create(output, ConstantInt::get(Type::getInt32Ty(*m_context), i), "", insertPos); args[2 + i] = compValue; } emitCall("llvm.amdgcn.exp.f32", Type::getVoidTy(*m_context), args, {}, insertPos); break; } case BuiltInPointSize: { Value *args[] = { ConstantInt::get(Type::getInt32Ty(*m_context), EXP_TARGET_POS_1), // tgt ConstantInt::get(Type::getInt32Ty(*m_context), 0x1), // en output, // src0 undef, // src1 undef, // src2 undef, // src3 ConstantInt::get(Type::getInt1Ty(*m_context), false), // done ConstantInt::get(Type::getInt1Ty(*m_context), false) // vm }; emitCall("llvm.amdgcn.exp.f32", Type::getVoidTy(*m_context), args, {}, insertPos); break; } case BuiltInLayer: { assert(m_gfxIp.major <= 8); // For GFX9, gl_ViewportIndex and gl_Layer are packed const auto enableMultiView = m_pipelineState->getInputAssemblyState().enableMultiView; Value *layer = new BitCastInst(output, Type::getFloatTy(*m_context), "", insertPos); Value *args[] = { ConstantInt::get(Type::getInt32Ty(*m_context), EXP_TARGET_POS_1), // tgt ConstantInt::get(Type::getInt32Ty(*m_context), 0x4), // en undef, // src0 undef, // src1 layer, // src2 undef, // src3 ConstantInt::get(Type::getInt1Ty(*m_context), false), // done ConstantInt::get(Type::getInt1Ty(*m_context), false) // vm }; emitCall("llvm.amdgcn.exp.f32", Type::getVoidTy(*m_context), args, {}, insertPos); // NOTE: We have to export gl_Layer via generic outputs as well. bool hasLayerExport = true; if (nextStage == ShaderStageFragment) { const auto &nextBuiltInUsage = m_pipelineState->getShaderResourceUsage(ShaderStageFragment)->builtInUsage.fs; hasLayerExport = nextBuiltInUsage.layer || nextBuiltInUsage.viewIndex; } if (hasLayerExport) { unsigned loc = InvalidValue; if (m_shaderStage == ShaderStageCopyShader) { assert(inOutUsage.gs.builtInOutLocs.find(BuiltInLayer) != inOutUsage.gs.builtInOutLocs.end() || inOutUsage.gs.builtInOutLocs.find(BuiltInViewIndex) != inOutUsage.gs.builtInOutLocs.end()); loc = enableMultiView ? inOutUsage.gs.builtInOutLocs[BuiltInViewIndex] : inOutUsage.gs.builtInOutLocs[BuiltInLayer]; } else { assert(inOutUsage.builtInOutputLocMap.find(BuiltInLayer) != inOutUsage.builtInOutputLocMap.end() || inOutUsage.builtInOutputLocMap.find(BuiltInViewIndex) != inOutUsage.builtInOutputLocMap.end()); loc = enableMultiView ? inOutUsage.builtInOutputLocMap[BuiltInViewIndex] : inOutUsage.builtInOutputLocMap[BuiltInLayer]; } recordVertexAttribExport(loc, {layer, undef, undef, undef}); } break; } case BuiltInViewportIndex: { assert(m_gfxIp.major <= 8); // For GFX9, gl_ViewportIndex and gl_Layer are packed Value *viewportIndex = new BitCastInst(output, Type::getFloatTy(*m_context), "", insertPos); Value *args[] = { ConstantInt::get(Type::getInt32Ty(*m_context), EXP_TARGET_POS_1), // tgt ConstantInt::get(Type::getInt32Ty(*m_context), 0x8), // en undef, // src0 undef, // src1 undef, // src2 viewportIndex, // src3 ConstantInt::get(Type::getInt1Ty(*m_context), false), // done ConstantInt::get(Type::getInt1Ty(*m_context), false) // vm }; emitCall("llvm.amdgcn.exp.f32", Type::getVoidTy(*m_context), args, {}, insertPos); // NOTE: We have to export gl_ViewportIndex via generic outputs as well. bool hasViewportIndexExport = true; if (nextStage == ShaderStageFragment) { const auto &nextBuiltInUsage = m_pipelineState->getShaderResourceUsage(ShaderStageFragment)->builtInUsage.fs; hasViewportIndexExport = nextBuiltInUsage.viewportIndex; } if (hasViewportIndexExport) { unsigned loc = InvalidValue; if (m_shaderStage == ShaderStageCopyShader) { assert(inOutUsage.gs.builtInOutLocs.find(BuiltInViewportIndex) != inOutUsage.gs.builtInOutLocs.end()); loc = inOutUsage.gs.builtInOutLocs[BuiltInViewportIndex]; } else { assert(inOutUsage.builtInOutputLocMap.find(BuiltInViewportIndex) != inOutUsage.builtInOutputLocMap.end()); loc = inOutUsage.builtInOutputLocMap[BuiltInViewportIndex]; } recordVertexAttribExport(loc, {viewportIndex, undef, undef, undef}); } break; } case BuiltInPrimitiveShadingRate: { // gl_PrimitiveShadingRate is not supported on pre-GFX10.3 assert(m_gfxIp >= GfxIpVersion({10, 3})); exportShadingRate(output, insertPos); break; } default: { llvm_unreachable("Should never be called!"); break; } } } // ===================================================================================================================== // Adjusts I/J calculation for "centroid" interpolation mode by taking "center" mode into account. // // @param centroidIj : Centroid I/J provided by hardware natively // @param centerIj : Center I/J provided by hardware natively // @param insertPos : Where to insert this call Value *PatchInOutImportExport::adjustCentroidIj(Value *centroidIj, Value *centerIj, Instruction *insertPos) { auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageFragment)->entryArgIdxs.fs; auto primMask = getFunctionArgument(m_entryPoint, entryArgIdxs.primMask); auto &builtInUsage = m_pipelineState->getShaderResourceUsage(ShaderStageFragment)->builtInUsage.fs; Value *ij = nullptr; if (builtInUsage.centroid && builtInUsage.center) { // NOTE: If both centroid and center are enabled, centroid I/J provided by hardware natively may be invalid. We have // to adjust it with center I/J on condition of bc_optimize flag. bc_optimize = pPrimMask[31], when bc_optimize is // on, pPrimMask is less than zero auto cond = new ICmpInst(insertPos, ICmpInst::ICMP_SLT, primMask, ConstantInt::get(Type::getInt32Ty(*m_context), 0), ""); ij = SelectInst::Create(cond, centerIj, centroidIj, "", insertPos); } else ij = centroidIj; return ij; } // ===================================================================================================================== // Get Subgroup local invocation Id // // @param insertPos : Where to insert this call Value *PatchInOutImportExport::getSubgroupLocalInvocationId(Instruction *insertPos) { Value *args[] = {ConstantInt::get(Type::getInt32Ty(*m_context), -1), ConstantInt::get(Type::getInt32Ty(*m_context), 0)}; Value *subgroupLocalInvocationId = emitCall("llvm.amdgcn.mbcnt.lo", Type::getInt32Ty(*m_context), args, {}, &*insertPos); unsigned waveSize = m_pipelineState->getShaderWaveSize(m_shaderStage); if (waveSize == 64) { Value *args[] = {ConstantInt::get(Type::getInt32Ty(*m_context), -1), subgroupLocalInvocationId}; subgroupLocalInvocationId = emitCall("llvm.amdgcn.mbcnt.hi", Type::getInt32Ty(*m_context), args, {}, &*insertPos); } return subgroupLocalInvocationId; } // ===================================================================================================================== // Do automatic workgroup size reconfiguration in a compute shader, to allow ReconfigWorkgroup // to apply optimizations. WorkgroupLayout PatchInOutImportExport::calculateWorkgroupLayout() { auto &resUsage = *m_pipelineState->getShaderResourceUsage(ShaderStageCompute); if (m_shaderStage == ShaderStageCompute) { bool reconfig = false; switch (static_cast<WorkgroupLayout>(resUsage.builtInUsage.cs.workgroupLayout)) { case WorkgroupLayout::Unknown: // If no configuration has been specified, apply a reconfigure if the compute shader uses images and the // pipeline option was enabled. if (resUsage.useImages) reconfig = m_pipelineState->getOptions().reconfigWorkgroupLayout; break; case WorkgroupLayout::Linear: // The hardware by default applies the linear rules, so just ban reconfigure and we're done. reconfig = false; break; case WorkgroupLayout::Quads: // 2x2 requested. reconfig = true; break; case WorkgroupLayout::SexagintiQuads: // 8x8 requested. reconfig = true; break; } if (reconfig) { auto &mode = m_pipelineState->getShaderModes()->getComputeShaderMode(); if ((mode.workgroupSizeX % 2) == 0 && (mode.workgroupSizeY % 2) == 0) { if ((mode.workgroupSizeX > 8 && mode.workgroupSizeY >= 8) || (mode.workgroupSizeX >= 8 && mode.workgroupSizeY > 8)) { // If our local size in the X & Y dimensions are greater than 8, we can reconfigure. resUsage.builtInUsage.cs.workgroupLayout = static_cast<unsigned>(WorkgroupLayout::SexagintiQuads); } else { // If our local size in the X & Y dimensions are multiples of 2, we can reconfigure. resUsage.builtInUsage.cs.workgroupLayout = static_cast<unsigned>(WorkgroupLayout::Quads); } } } } return static_cast<WorkgroupLayout>(resUsage.builtInUsage.cs.workgroupLayout); } // ===================================================================================================================== // Reconfigure the workgroup for optimization purposes. // // @param localInvocationId : The original workgroup ID. // @param insertPos : Where to insert instructions. Value *PatchInOutImportExport::reconfigWorkgroup(Value *localInvocationId, Instruction *insertPos) { auto &builtInUsage = m_pipelineState->getShaderResourceUsage(ShaderStageCompute)->builtInUsage.cs; auto workgroupLayout = static_cast<WorkgroupLayout>(builtInUsage.workgroupLayout); auto &mode = m_pipelineState->getShaderModes()->getComputeShaderMode(); // NOTE: Here, we implement "GDC 2018 Engine Optimization Hot Lap Workgroup Optimization " (slides 40-45, by // Timothy Lottes). // uvec2 Remap(uint a) { // uint y = bitfieldExtract(a,3,4); // v_bfe_u32 ---> {...0,y3,y2,y1,x2} // y = bitfieldInsert(y,a,0,1); // v_bfi_b32 ---> {...0,y3,y2,y1,y0} // uint x = bitfieldExtract(a,1,3); // v_bfe_u32 ---> {...0,x2,x1,x0} // a = bitfieldExtract(a,4,5); // v_bfe_u32 ---> {...0,x4,x3,y3,y2,y1} // x = bitfieldInsert(a,x,0,3); // v_bfi_b32 ---> {...0,x4,x3,x2,x1,x0} // return uvec2(x, y); // } // usage in shader // uvec2 xy = Remap(gl_LocalInvocationID.x); // xy.x += gl_WorkGroupID.x << 5; // v_lshl_add_u32 // xy.y += gl_WorkGroupID.y << 4; // v_lshl_add_u32 Type *const int16Ty = Type::getInt16Ty(*m_context); Type *const int32Ty = Type::getInt32Ty(*m_context); Value *remappedId = localInvocationId; // For a reconfigured workgroup, we map Y -> Z if (mode.workgroupSizeZ > 1) { Constant *shuffleMask[] = {ConstantInt::get(int32Ty, 0), UndefValue::get(int32Ty), ConstantInt::get(int32Ty, 1)}; remappedId = new ShuffleVectorInst(remappedId, UndefValue::get(remappedId->getType()), ConstantVector::get(shuffleMask), "", insertPos); } else { remappedId = InsertElementInst::Create(remappedId, ConstantInt::get(int32Ty, 0), ConstantInt::get(int32Ty, 2), "", insertPos); } Instruction *const x = ExtractElementInst::Create(remappedId, ConstantInt::get(int32Ty, 0), "", insertPos); Instruction *const bit0 = BinaryOperator::CreateAnd(x, ConstantInt::get(int32Ty, 0x1), "", insertPos); Instruction *bit1 = BinaryOperator::CreateAnd(x, ConstantInt::get(int32Ty, 0x2), "", insertPos); bit1 = BinaryOperator::CreateLShr(bit1, ConstantInt::get(int32Ty, 1), "", insertPos); Instruction *offset = nullptr; Instruction *maskedX = x; // Check if we are doing 8x8, as we need to calculate an offset and mask out the top bits of X if so. if (workgroupLayout == WorkgroupLayout::SexagintiQuads) { const unsigned workgroupSizeYMul8 = mode.workgroupSizeY * 8; if (isPowerOf2_32(workgroupSizeYMul8)) { // If we have a power of two, we can use a right shift to compute the division more efficiently. offset = BinaryOperator::CreateLShr(x, ConstantInt::get(int32Ty, Log2(workgroupSizeYMul8)), "", insertPos); } else { // Otherwise we truncate down to a 16-bit integer, do the division, and zero extend. This will // result in significantly less instructions to do the divide. offset = CastInst::CreateIntegerCast(x, int16Ty, false, "", insertPos); offset = BinaryOperator::CreateUDiv(offset, ConstantInt::get(int16Ty, workgroupSizeYMul8), "", insertPos); offset = CastInst::CreateIntegerCast(offset, int32Ty, false, "", insertPos); } Instruction *const mulOffset = BinaryOperator::CreateMul(offset, ConstantInt::get(int32Ty, workgroupSizeYMul8), "", insertPos); maskedX = BinaryOperator::CreateSub(x, mulOffset, "", insertPos); } Instruction *const remainingBits = BinaryOperator::CreateAnd(maskedX, ConstantInt::get(int32Ty, ~0x3), "", insertPos); Instruction *div = nullptr; Instruction *rem = nullptr; if (offset) { if ((mode.workgroupSizeX % 8) == 0 && (mode.workgroupSizeY % 8) == 0) { // Divide by 16. div = BinaryOperator::CreateLShr(remainingBits, ConstantInt::get(int32Ty, 4), "", insertPos); // Multiply by 16. rem = BinaryOperator::CreateShl(div, ConstantInt::get(int32Ty, 4), "", insertPos); // Subtract to get remainder. rem = BinaryOperator::CreateSub(remainingBits, rem, "", insertPos); } else { // Multiply by 8. Instruction *divideBy = BinaryOperator::CreateShl(offset, ConstantInt::get(int32Ty, 3), "", insertPos); divideBy = BinaryOperator::CreateSub(ConstantInt::get(int32Ty, mode.workgroupSizeX), divideBy, "", insertPos); Instruction *const cond = new ICmpInst(insertPos, ICmpInst::ICMP_ULT, divideBy, ConstantInt::get(int32Ty, 8), ""); // We do a minimum operation to ensure that we never divide by more than 8, which forces our // workgroup layout into 8x8 tiles. divideBy = SelectInst::Create(cond, divideBy, ConstantInt::get(int32Ty, 8), "", insertPos); // Multiply by 2. divideBy = BinaryOperator::CreateShl(divideBy, ConstantInt::get(int32Ty, 1), "", insertPos); Instruction *const divideByTrunc = CastInst::CreateIntegerCast(divideBy, int16Ty, false, "", insertPos); // Truncate down to a 16-bit integer, do the division, and zero extend. div = CastInst::CreateIntegerCast(maskedX, int16Ty, false, "", insertPos); div = BinaryOperator::CreateUDiv(div, divideByTrunc, "", insertPos); div = CastInst::CreateIntegerCast(div, int32Ty, false, "", insertPos); Instruction *const mulDiv = BinaryOperator::CreateMul(div, divideBy, "", insertPos); rem = BinaryOperator::CreateSub(remainingBits, mulDiv, "", insertPos); } } else { const unsigned workgroupSizeXMul2 = mode.workgroupSizeX * 2; if (isPowerOf2_32(workgroupSizeXMul2)) { // If we have a power of two, we can use a right shift to compute the division more efficiently. div = BinaryOperator::CreateLShr(maskedX, ConstantInt::get(int32Ty, Log2(workgroupSizeXMul2)), "", insertPos); } else { // Otherwise we truncate down to a 16-bit integer, do the division, and zero extend. This will // result in significantly less instructions to do the divide. div = CastInst::CreateIntegerCast(maskedX, int16Ty, false, "", insertPos); div = BinaryOperator::CreateUDiv(div, ConstantInt::get(int16Ty, workgroupSizeXMul2), "", insertPos); div = CastInst::CreateIntegerCast(div, int32Ty, false, "", insertPos); } Instruction *const mulDiv = BinaryOperator::CreateMul(div, ConstantInt::get(int32Ty, workgroupSizeXMul2), "", insertPos); rem = BinaryOperator::CreateSub(remainingBits, mulDiv, "", insertPos); } // Now we have all the components to reconstruct X & Y! Instruction *newX = BinaryOperator::CreateLShr(rem, ConstantInt::get(int32Ty, 1), "", insertPos); newX = BinaryOperator::CreateAdd(newX, bit0, "", insertPos); // If we have an offset, we need to incorporate this into X. if (offset) { const unsigned workgroupSizeYMin8 = std::min(mode.workgroupSizeY, 8u); Instruction *const mul = BinaryOperator::CreateMul(offset, ConstantInt::get(int32Ty, workgroupSizeYMin8), "", insertPos); newX = BinaryOperator::CreateAdd(newX, mul, "", insertPos); } remappedId = InsertElementInst::Create(remappedId, newX, ConstantInt::get(int32Ty, 0), "", insertPos); Instruction *newY = BinaryOperator::CreateShl(div, ConstantInt::get(int32Ty, 1), "", insertPos); newY = BinaryOperator::CreateAdd(newY, bit1, "", insertPos); remappedId = InsertElementInst::Create(remappedId, newY, ConstantInt::get(int32Ty, 1), "", insertPos); return remappedId; } // ===================================================================================================================== // Exports HW shading rate, extracting the values from LGC shading rate (a mask of ShadingRateFlags) // // @param shadingRate : LGC shading rate // @param insertPos : Where to insert instructions. void PatchInOutImportExport::exportShadingRate(Value *shadingRate, Instruction *insertPos) { IRBuilder<> builder(*m_context); builder.SetInsertPoint(insertPos); assert(m_gfxIp >= GfxIpVersion({10, 3})); // Must be GFX10.3+ Value* hwShadingRate = nullptr; { // NOTE: The shading rates have different meanings in HW and LGC interface. Current HW only supports 2-pixel mode // and 4-pixel mode is not supported. But the spec requires us to accept unsupported rates and clamp them to // maxFragmentSize of HW. The mapping is therefore as follow: // // VRS X rate: MaskNone -> 0b00, Horizontal2Pixels | Horizontal4Pixels -> 0b01 // VRS Y rate: MaskNone -> 0b00, Vertical2Pixels | Vertical4Pixels -> 0b01 // // xRate = (shadingRate & (Horizontal2Pixels | Horizontal4Pixels) ? 0x1 : 0x0 Value *xRate2Pixels = builder.CreateAnd(shadingRate, builder.getInt32(ShadingRateHorizontal2Pixels | ShadingRateHorizontal4Pixels)); xRate2Pixels = builder.CreateICmpNE(xRate2Pixels, builder.getInt32(0)); Value *xRate = builder.CreateSelect(xRate2Pixels, builder.getInt32(1), builder.getInt32(0)); // yRate = (shadingRate & (Vertical2Pixels | Vertical4Pixels)) ? 0x1 : 0x0 Value *yRate2Pixels = builder.CreateAnd(shadingRate, builder.getInt32(ShadingRateVertical2Pixels | ShadingRateVertical4Pixels)); yRate2Pixels = builder.CreateICmpNE(yRate2Pixels, builder.getInt32(0)); Value *yRate = builder.CreateSelect(yRate2Pixels, builder.getInt32(1), builder.getInt32(0)); // [5:4] = Y rate, [3:2] = X rate // hwShadingRate = (xRate << 2) | (yRate << 4) xRate = builder.CreateShl(xRate, 2); yRate = builder.CreateShl(yRate, 4); hwShadingRate = builder.CreateOr(xRate, yRate); hwShadingRate = builder.CreateBitCast(hwShadingRate, builder.getFloatTy()); } auto undef = UndefValue::get(builder.getFloatTy()); // "Done" flag is valid for exporting position 0 ~ 3 builder.CreateIntrinsic(Intrinsic::amdgcn_exp, builder.getFloatTy(), {builder.getInt32(EXP_TARGET_POS_1), // tgt builder.getInt32(0x2), // en undef, // src0 hwShadingRate, // src1 undef, // src2 undef, // src3 builder.getFalse(), // done builder.getFalse()}); // src0 } // ===================================================================================================================== // Gets HW shading rate and converts them to LGC definitions. // // @param insertPos : Where to insert instructions. Value *PatchInOutImportExport::getShadingRate(Instruction *insertPos) { IRBuilder<> builder(*m_context); builder.SetInsertPoint(insertPos); assert(m_gfxIp >= GfxIpVersion({10, 3})); // Must be GFX10.3+ assert(m_shaderStage == ShaderStageFragment); auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(ShaderStageFragment)->entryArgIdxs.fs; auto ancillary = getFunctionArgument(m_entryPoint, entryArgIdxs.ancillary); // Y rate = Ancillary[5:4], X rate = Ancillary[3:2] Value *xRate = builder.CreateAnd(ancillary, 0xC); xRate = builder.CreateLShr(xRate, 2); Value *yRate = builder.CreateAnd(ancillary, 0x30); yRate = builder.CreateLShr(yRate, 4); { // NOTE: The shading rates have different meanings in HW and LGC interface. Current HW only supports 2-pixel mode // and 4-pixel mode is not supported. The mapping is as follow: // // VRS X rate: 0b00 -> MaskNone, 0b01 -> Horizontal2Pixels // VRS Y rate: 0b00 -> MaskNone, 0b01 -> Vertical2Pixels // // xRate = xRate == 0x1 ? Horizontal2Pixels : None auto xRate2Pixels = builder.CreateICmpEQ(xRate, builder.getInt32(1)); xRate = builder.CreateSelect(xRate2Pixels, builder.getInt32(ShadingRateHorizontal2Pixels), builder.getInt32(ShadingRateNone)); // yRate = yRate == 0x1 ? Vertical2Pixels : None auto yRate2Pixels = builder.CreateICmpEQ(yRate, builder.getInt32(1)); yRate = builder.CreateSelect(yRate2Pixels, builder.getInt32(ShadingRateVertical2Pixels), builder.getInt32(ShadingRateNone)); } return builder.CreateOr(xRate, yRate); } // ===================================================================================================================== // Records export info of vertex attributes // // @param location : Vertex attribute location // @param attribValues : Values of this vertex attribute to export void PatchInOutImportExport::recordVertexAttribExport(unsigned location, ArrayRef<Value *> attribValues) { assert(m_shaderStage == ShaderStageVertex || m_shaderStage == ShaderStageTessEval || m_shaderStage == ShaderStageCopyShader); // Valid shader stages assert(location <= MaxInOutLocCount); // 32 attributes at most assert(attribValues.size() == 4); // Must have 4 elements, corresponds to <4 x float> auto undef = UndefValue::get(Type::getFloatTy(*m_context)); // Vertex attribute not existing, insert a new one and initialize it if (m_attribExports.count(location) == 0) { for (unsigned i = 0; i < 4; ++i) m_attribExports[location][i] = undef; } for (unsigned i = 0; i < 4; ++i) { assert(attribValues[i]); if (isa<UndefValue>(attribValues[i])) continue; // Here, we only record new attribute values that are valid (not undefined ones) // NOTE: The existing values must have been initialized to undefined ones already. Overlapping is disallowed (see // such cases): // - Valid: // Existing: attrib0, <1.0, 2.0, undef, undef> // New: attrib0, <undef, undef, 3.0, 4.0> // - Invalid: // Existing: attrib0, <1.0, 2.0, 3.0, undef> // New: attrib0, <undef, undef, 4.0, 5.0> assert(isa<UndefValue>(m_attribExports[location][i])); m_attribExports[location][i] = attribValues[i]; // Update values that are valid } auto &inOutUsage = m_pipelineState->getShaderResourceUsage(m_shaderStage)->inOutUsage; inOutUsage.expCount = std::max(inOutUsage.expCount, location + 1); // Update export count } // ===================================================================================================================== // Exports vertex attributes that were recorded previously // // @param insertPos : Where to insert instructions. void PatchInOutImportExport::exportVertexAttribs(Instruction *insertPos) { assert(m_shaderStage == ShaderStageVertex || m_shaderStage == ShaderStageTessEval || m_shaderStage == ShaderStageCopyShader); // Valid shader stages if (m_attribExports.empty()) { assert(m_pipelineState->getShaderResourceUsage(m_shaderStage)->inOutUsage.expCount == 0); return; } IRBuilder<> builder(*m_context); builder.SetInsertPoint(insertPos); for (auto &attribExport : m_attribExports) { if (m_gfxIp.major <= 10) { unsigned channelMask = 0; for (unsigned i = 0; i < 4; ++i) { assert(attribExport.second[i]); if (!isa<UndefValue>(attribExport.second[i])) channelMask |= (1u << i); // Update channel mask if the value is valid (not undef) } builder.CreateIntrinsic(Intrinsic::amdgcn_exp, builder.getFloatTy(), {builder.getInt32(EXP_TARGET_PARAM_0 + attribExport.first), // tgt builder.getInt32(channelMask), // en attribExport.second[0], // src0 attribExport.second[1], // src1 attribExport.second[2], // src2 attribExport.second[3], // src3 builder.getFalse(), // done builder.getFalse()}); // src0 } else { llvm_unreachable("Not implemented!"); } } } // ===================================================================================================================== // The process of handling the store of tessellation factors. // 1. Collect outer and inner tessellation factors from the corresponding callInst. // 2. Store TFs to LDS if they are read as input and write to TF buffer. void PatchInOutImportExport::storeTessFactors() { if (m_tessLevelOuterInsts.empty() && m_tessLevelInnerInsts.empty()) return; BuilderBase builder(*m_context); // Row 0 - Unknown, 1 - Triangle, 2 - Quad, 3 - Isoline. static const unsigned expTessFactorCount[][2] = {{0, 0}, {3, 1}, {4, 2}, {2, 0}}; const auto primitiveMode = static_cast<unsigned>(m_pipelineState->getShaderModes()->getTessellationMode().primitiveMode); // Collect outer and inner tessellation factors, respectively. SmallVector<Value *> outerTessFactors, innerTessFactors; SmallVector<Value *> *tessFactors = &outerTessFactors; ArrayRef<Instruction *> tessLevelInsts = m_tessLevelOuterInsts; bool isOutputArray[2] = {}; for (unsigned i = 0; i < 2; ++i) { // Fill the container for tessellation factors for (auto tessLevelInst : tessLevelInsts) { Value *output = tessLevelInst->getOperand(3); Type *outputTy = output->getType(); isOutputArray[i] = outputTy->isArrayTy(); if (isOutputArray[i]) { const unsigned tessFactorCount = expTessFactorCount[primitiveMode][i]; for (unsigned elemIdx = 0; elemIdx < tessFactorCount; ++elemIdx) { auto elem = builder.CreateExtractValue(output, elemIdx); tessFactors->push_back(elem); } if (static_cast<PrimitiveMode>(primitiveMode) == PrimitiveMode::Isolines && i == 0) std::swap(tessFactors[0], tessFactors[1]); } else { assert(outputTy->isFloatTy()); tessFactors->push_back(output); } } tessFactors = &innerTessFactors; tessLevelInsts = m_tessLevelInnerInsts; } bool optimizeTessFactors = false; if (!optimizeTessFactors) { // Write tessellation factors to LDS if they are used as input for TES or TCS. auto resUsage = m_pipelineState->getShaderResourceUsage(ShaderStageTessControl); auto &perPatchBuiltInOutLocMap = resUsage->inOutUsage.perPatchBuiltInOutputLocMap; unsigned builtInId = BuiltInTessLevelOuter; tessFactors = &outerTessFactors; tessLevelInsts = m_tessLevelOuterInsts; for (unsigned i = 0; i < 2; ++i) { // If tessellation factors are used as input of TES or TCS, they are required to write to LDS. const bool needWriteToLds = perPatchBuiltInOutLocMap.count(builtInId) == 1; if (needWriteToLds) { const unsigned loc = perPatchBuiltInOutLocMap[builtInId]; if (isOutputArray[i]) { // gl_TessLevelOuter[4] is treated as vec4 // gl_TessLevelInner[2] is treated as vec2 auto output = tessLevelInsts[0]->getOperand(3); auto outputTy = output->getType(); auto vertexIdx = tessLevelInsts[0]->getOperand(2); auto insertPos = tessLevelInsts[0]; for (unsigned idx = 0; idx < outputTy->getArrayNumElements(); ++idx) { auto elem = builder.CreateExtractValue(output, idx); auto elemIdx = builder.getInt32(idx); auto ldsOffset = calcLdsOffsetForTcsOutput(elem->getType(), loc, nullptr, elemIdx, vertexIdx, insertPos); writeValueToLds(elem, ldsOffset, insertPos); } } else { for (unsigned idx = 0; idx < tessFactors->size(); ++idx) { Value *elemIdx = tessLevelInsts[idx]->getOperand(1); Value *tessFactor = (*tessFactors)[idx]; auto ldsOffset = calcLdsOffsetForTcsOutput(tessFactor->getType(), loc, nullptr, elemIdx, nullptr, tessLevelInsts[idx]); writeValueToLds(tessFactor, ldsOffset, tessLevelInsts[idx]); } } } builtInId = BuiltInTessLevelInner; tessFactors = &innerTessFactors; tessLevelInsts = m_tessLevelInnerInsts; } doTessFactorBufferStore(outerTessFactors, innerTessFactors, nullptr); } } // ===================================================================================================================== // Write the collected tessellation factors of Outer and Inner to TF buffer in turn. // // @param outerTessFactors : The collected tessellation factors of Outer // @param innerTessFactors : The collected tessellation factors of Inner // @param inserPos : Where to insert instructions void PatchInOutImportExport::doTessFactorBufferStore(ArrayRef<Value *> outerTessFactors, ArrayRef<Value *> innerTessFactors, Instruction *insertPos) { ArrayRef<Instruction *> tessLevelInsts = m_tessLevelOuterInsts; ArrayRef<Value *> tessFactors = outerTessFactors; for (unsigned i = 0; i < 2; ++i) { const bool isOuter = i == 0; if (!tessFactors.empty()) { // NOTE: If the given insert point is null, the original tessLevel instruction is used as the insert point. const bool isArrayTessFactor = tessLevelInsts[0]->getOperand(3)->getType()->isArrayTy(); if (isArrayTessFactor) { auto insertPoint = insertPos ? insertPos : tessLevelInsts[0]; // The second argument for element index should be nullptr for array type. Value *tessFactorOffset = calcTessFactorOffset(isOuter, nullptr, insertPoint); storeTessFactorToBuffer(tessFactors, tessFactorOffset, insertPoint); } else { // We have to store each element in tessFactors seperately because they may not be in memory order. for (unsigned idx = 0; idx < tessFactors.size(); ++idx) { auto insertPoint = insertPos ? insertPos : tessLevelInsts[idx]; Value *elemIdx = tessLevelInsts[idx]->getOperand(1); Value *tessFactorOffset = calcTessFactorOffset(isOuter, elemIdx, insertPoint); SmallVector<Value *> singleTfVector; singleTfVector.push_back(tessFactors[idx]); storeTessFactorToBuffer(singleTfVector, tessFactorOffset, insertPoint); } } } tessLevelInsts = m_tessLevelInnerInsts; tessFactors = innerTessFactors; } } } // namespace lgc // ===================================================================================================================== // Initializes the pass of LLVM patching opertions for input import and output export. INITIALIZE_PASS(PatchInOutImportExport, DEBUG_TYPE, "Patch LLVM for input import and output export operations", false, false)
// #include <bits/stdc++.h> #include <iostream> #include <vector> #include <algorithm> using namespace std; #define ar array #define ll long long const int MAX_N = 1e5 + 1; const int MOD = 1e9 + 7; const int INF = 1e9; const ll LINF = 1e18; int solve(int n) { int d = n%100; return 100 - d; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int tc = 1; // cin >> tc; for (int t = 1; t <= tc; t++) { int n; cin >> n; cout << solve(n); } }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/common/permissions/settings_override_permission.h" #include "base/strings/utf_string_conversions.h" #include "extensions/common/permissions/api_permission_set.h" #include "grit/extensions_strings.h" #include "ui/base/l10n/l10n_util.h" namespace extensions { SettingsOverrideAPIPermission::SettingsOverrideAPIPermission( const APIPermissionInfo* permission, const std::string& setting_value) : APIPermission(permission), setting_value_(setting_value) {} SettingsOverrideAPIPermission::~SettingsOverrideAPIPermission() {} PermissionIDSet SettingsOverrideAPIPermission::GetPermissions() const { PermissionIDSet permissions; permissions.insert(info()->id(), base::UTF8ToUTF16(setting_value_)); return permissions; } bool SettingsOverrideAPIPermission::HasMessages() const { return info()->message_id() > PermissionMessage::kNone; } PermissionMessages SettingsOverrideAPIPermission::GetMessages() const { DCHECK(HasMessages()); int string_id = -1; // Warning: when modifying this function, be sure to modify the correct rule // in ChromePermissionMessageProvider. switch (id()) { case kHomepage: { // TODO(sashab): Add a parameter rule in ChromePermissionMessageProvider: // kHomepage -> IDS_EXTENSION_PROMPT_WARNING_HOME_PAGE_SETTING_OVERRIDE string_id = IDS_EXTENSION_PROMPT_WARNING_HOME_PAGE_SETTING_OVERRIDE; break; } case kStartupPages: { // TODO(sashab): Add a parameter rule in ChromePermissionMessageProvider: // kStartupPages -> // IDS_EXTENSION_PROMPT_WARNING_START_PAGE_SETTING_OVERRIDE string_id = IDS_EXTENSION_PROMPT_WARNING_START_PAGE_SETTING_OVERRIDE; break; } case kSearchProvider: { // TODO(sashab): Add a parameter rule in ChromePermissionMessageProvider: // kSearchProvider -> // IDS_EXTENSION_PROMPT_WARNING_SEARCH_SETTINGS_OVERRIDE string_id = IDS_EXTENSION_PROMPT_WARNING_SEARCH_SETTINGS_OVERRIDE; break; } default: NOTREACHED(); } PermissionMessages result; result.push_back( PermissionMessage(info()->message_id(), l10n_util::GetStringFUTF16( string_id, base::UTF8ToUTF16(setting_value_)))); return result; } bool SettingsOverrideAPIPermission::Check( const APIPermission::CheckParam* param) const { return (param == NULL); } bool SettingsOverrideAPIPermission::Contains(const APIPermission* rhs) const { CHECK_EQ(info(), rhs->info()); return true; } bool SettingsOverrideAPIPermission::Equal(const APIPermission* rhs) const { if (this != rhs) CHECK_EQ(info(), rhs->info()); return true; } bool SettingsOverrideAPIPermission::FromValue( const base::Value* value, std::string* /*error*/, std::vector<std::string>* unhandled_permissions) { return (value == NULL); } scoped_ptr<base::Value> SettingsOverrideAPIPermission::ToValue() const { return scoped_ptr<base::Value>(); } APIPermission* SettingsOverrideAPIPermission::Clone() const { return new SettingsOverrideAPIPermission(info(), setting_value_); } APIPermission* SettingsOverrideAPIPermission::Diff( const APIPermission* rhs) const { CHECK_EQ(info(), rhs->info()); return NULL; } APIPermission* SettingsOverrideAPIPermission::Union( const APIPermission* rhs) const { CHECK_EQ(info(), rhs->info()); return new SettingsOverrideAPIPermission(info(), setting_value_); } APIPermission* SettingsOverrideAPIPermission::Intersect( const APIPermission* rhs) const { CHECK_EQ(info(), rhs->info()); return new SettingsOverrideAPIPermission(info(), setting_value_); } void SettingsOverrideAPIPermission::Write(IPC::Message* m) const {} bool SettingsOverrideAPIPermission::Read(const IPC::Message* m, PickleIterator* iter) { return true; } void SettingsOverrideAPIPermission::Log(std::string* log) const {} } // namespace extensions
/**************************************************************************\ * Copyright (c) Kongsberg Oil & Gas Technologies AS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \**************************************************************************/ /*! \class SoTextureScalePolicyElement elements/SoTextureScalePolicyElement.h \brief The SoTextureScalePolicyElement class is yet to be documented. \ingroup elements This is currently an internal Coin element. The header file is not installed, and the API for this element might change without notice. */ #include "elements/SoTextureScalePolicyElement.h" #include <cassert> /*! \fn SoTextureScalePolicyElement::Policy FIXME: write doc. */ SO_ELEMENT_SOURCE(SoTextureScalePolicyElement); /*! This static method initializes static data for the SoTextureScalePolicyElement class. */ void SoTextureScalePolicyElement::initClass(void) { SO_ELEMENT_INIT_CLASS(SoTextureScalePolicyElement, inherited); } /*! The destructor. */ SoTextureScalePolicyElement::~SoTextureScalePolicyElement(void) { } //! FIXME: write doc. void SoTextureScalePolicyElement::set(SoState * const state, SoNode * const node, const Policy policy) { inherited::set(classStackIndex, state, node, static_cast<int>(policy)); } //! FIXME: write doc. void SoTextureScalePolicyElement::init(SoState * state) { inherited::init(state); this->data = getDefault(); } //! FIXME: write doc. void SoTextureScalePolicyElement::set(SoState * const state, const Policy policy) { SoTextureScalePolicyElement::set(state, NULL, policy); } //! FIXME: write doc. SoTextureScalePolicyElement::Policy SoTextureScalePolicyElement::get(SoState * const state) { return static_cast<Policy>(SoInt32Element::get(classStackIndex, state)); } //! FIXME: write doc. SoTextureScalePolicyElement::Policy SoTextureScalePolicyElement::getDefault(void) { return USE_TEXTURE_QUALITY; }
// Copyright Catch2 Authors // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // SPDX-License-Identifier: BSL-1.0 #include <catch2/internal/catch_random_number_generator.hpp> namespace Catch { namespace { #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4146) // we negate uint32 during the rotate #endif // Safe rotr implementation thanks to John Regehr uint32_t rotate_right(uint32_t val, uint32_t count) { const uint32_t mask = 31; count &= mask; return (val >> count) | (val << (-count & mask)); } #if defined(_MSC_VER) #pragma warning(pop) #endif } SimplePcg32::SimplePcg32(result_type seed_) { seed(seed_); } void SimplePcg32::seed(result_type seed_) { m_state = 0; (*this)(); m_state += seed_; (*this)(); } void SimplePcg32::discard(uint64_t skip) { // We could implement this to run in O(log n) steps, but this // should suffice for our use case. for (uint64_t s = 0; s < skip; ++s) { static_cast<void>((*this)()); } } SimplePcg32::result_type SimplePcg32::operator()() { // prepare the output value const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u); const auto output = rotate_right(xorshifted, m_state >> 59u); // advance state m_state = m_state * 6364136223846793005ULL + s_inc; return output; } bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) { return lhs.m_state == rhs.m_state; } bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) { return lhs.m_state != rhs.m_state; } }
//***************************************************************************** // Copyright 2017-2020 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. //***************************************************************************** #include "ngraph/op/equal.hpp" #include "ngraph/op/greater.hpp" #include "ngraph/op/greater_eq.hpp" #include "ngraph/op/less.hpp" #include "ngraph/op/less_eq.hpp" #include "ngraph/op/maximum.hpp" #include "ngraph/op/minimum.hpp" #include "ngraph/op/not_equal.hpp" #include "ngraph/runtime/plaidml/plaidml_impl.hpp" namespace ngraph { namespace runtime { namespace plaidml { NGRAPH_PLAIDML_OP_CLASS(ImplEqual, OpImpl<op::Equal>); NGRAPH_PLAIDML_OP_CLASS(ImplGreater, OpImpl<op::Greater>); NGRAPH_PLAIDML_OP_CLASS(ImplGreaterEq, OpImpl<op::GreaterEq>); NGRAPH_PLAIDML_OP_CLASS(ImplLess, OpImpl<op::Less>); NGRAPH_PLAIDML_OP_CLASS(ImplLessEq, OpImpl<op::LessEq>); NGRAPH_PLAIDML_OP_CLASS(ImplMaximum, OpImpl<op::Maximum>); NGRAPH_PLAIDML_OP_CLASS(ImplMinimum, OpImpl<op::Minimum>); NGRAPH_PLAIDML_OP_CLASS(ImplNotEqual, OpImpl<op::NotEqual>); } } } // Equal performs a simple elementwise equality. void ngraph::runtime::plaidml::ImplEqual::Apply() { check_inputs(2); check_outputs(1); set_output(start_tile_function() .add(builder::Input{op_input(0), "A"}) .add(builder::Input{op_input(1), "B"}) .add(builder::Output{"C"}) .add(builder::Elementwise{"C", "A == B"}) .finalize()); } // Greater performs a simple elementwise greater-than comparison. void ngraph::runtime::plaidml::ImplGreater::Apply() { check_inputs(2); check_outputs(1); set_output(start_tile_function() .add(builder::Input{op_input(0), "A"}) .add(builder::Input{op_input(1), "B"}) .add(builder::Output{"C"}) .add(builder::Elementwise{"C", "A > B"}) .finalize()); } // GreaterEq performs a simple elementwise greater-than-or-equal-to comparison. void ngraph::runtime::plaidml::ImplGreaterEq::Apply() { check_inputs(2); check_outputs(1); set_output(start_tile_function() .add(builder::Input{op_input(0), "A"}) .add(builder::Input{op_input(1), "B"}) .add(builder::Output{"C"}) .add(builder::Elementwise{"C", "A >= B"}) .finalize()); } // Less performs a simple elementwise less-than comparison. void ngraph::runtime::plaidml::ImplLess::Apply() { check_inputs(2); check_outputs(1); set_output(start_tile_function() .add(builder::Input{op_input(0), "A"}) .add(builder::Input{op_input(1), "B"}) .add(builder::Output{"C"}) .add(builder::Elementwise{"C", "A < B"}) .finalize()); } // LessEq performs a simple elementwise less-than-or-equal-to comparison. void ngraph::runtime::plaidml::ImplLessEq::Apply() { check_inputs(2); check_outputs(1); set_output(start_tile_function() .add(builder::Input{op_input(0), "A"}) .add(builder::Input{op_input(1), "B"}) .add(builder::Output{"C"}) .add(builder::Elementwise{"C", "A <= B"}) .finalize()); } // Maximum performs a simple elementwise maximum. void ngraph::runtime::plaidml::ImplMaximum::Apply() { check_inputs(2); check_outputs(1); set_output(start_tile_function() .add(builder::Input{op_input(0), "A"}) .add(builder::Input{op_input(1), "B"}) .add(builder::Output{"C"}) .add(builder::Elementwise{"C", "max(A, B)"}) .finalize()); } // Minimum performs a simple elementwise minimum. void ngraph::runtime::plaidml::ImplMinimum::Apply() { check_inputs(2); check_outputs(1); set_output(start_tile_function() .add(builder::Input{op_input(0), "A"}) .add(builder::Input{op_input(1), "B"}) .add(builder::Output{"C"}) .add(builder::Elementwise{"C", "min(A, B)"}) .finalize()); } // NotEqual performs a simple elementwise not-equality. void ngraph::runtime::plaidml::ImplNotEqual::Apply() { check_inputs(2); check_outputs(1); set_output(start_tile_function() .add(builder::Input{op_input(0), "A"}) .add(builder::Input{op_input(1), "B"}) .add(builder::Output{"C"}) .add(builder::Elementwise{"C", "A != B"}) .finalize()); }
/** @file @section license License 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 "ink_config.h" #include "libts.h" #include "I_Layout.h" #include "P_Net.h" #include <openssl/err.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/x509.h> #include <openssl/asn1.h> #include <openssl/rand.h> #if HAVE_OPENSSL_EVP_H #include <openssl/evp.h> #endif #if HAVE_OPENSSL_HMAC_H #include <openssl/hmac.h> #endif #if HAVE_OPENSSL_TS_H #include <openssl/ts.h> #endif #if HAVE_OPENSSL_EC_H #include <openssl/ec.h> #endif // ssl_multicert.config field names: #define SSL_IP_TAG "dest_ip" #define SSL_CERT_TAG "ssl_cert_name" #define SSL_PRIVATE_KEY_TAG "ssl_key_name" #define SSL_CA_TAG "ssl_ca_name" #define SSL_SESSION_TICKET_ENABLED "ssl_ticket_enabled" #define SSL_SESSION_TICKET_KEY_FILE_TAG "ticket_key_name" #ifndef evp_md_func #ifdef OPENSSL_NO_SHA256 #define evp_md_func EVP_sha1() #else #define evp_md_func EVP_sha256() #endif #endif #if (OPENSSL_VERSION_NUMBER >= 0x10000000L) // openssl returns a const SSL_METHOD typedef const SSL_METHOD * ink_ssl_method_t; #else typedef SSL_METHOD * ink_ssl_method_t; #endif static ink_mutex * sslMutexArray; static bool open_ssl_initialized = false; struct ssl_ticket_key_t { unsigned char key_name[16]; unsigned char hmac_secret[16]; unsigned char aes_key[16]; }; #if TS_USE_TLS_TICKETS static int ssl_callback_session_ticket(SSL *, unsigned char *, unsigned char *, EVP_CIPHER_CTX *, HMAC_CTX *, int); #endif /* TS_USE_TLS_TICKETS */ static int ssl_session_ticket_index = 0; struct ats_file_bio { ats_file_bio(const char * path, const char * mode) : bio(BIO_new_file(path, mode)) { } ~ats_file_bio() { (void)BIO_set_close(bio, BIO_CLOSE); BIO_free(bio); } operator bool() const { return bio != NULL; } BIO * bio; private: ats_file_bio(const ats_file_bio&); ats_file_bio& operator=(const ats_file_bio&); }; static unsigned long SSL_pthreads_thread_id() { EThread *eth = this_ethread(); return (unsigned long) (eth->id); } static void SSL_locking_callback(int mode, int type, const char * file, int line) { NOWARN_UNUSED(file); NOWARN_UNUSED(line); ink_debug_assert(type < CRYPTO_num_locks()); (mode & CRYPTO_LOCK) ? ink_mutex_acquire(&sslMutexArray[type]) : ink_mutex_release(&sslMutexArray[type]); } static bool SSL_CTX_add_extra_chain_cert_file(SSL_CTX * ctx, const char *chainfile) { X509 *cert; ats_file_bio bio(chainfile, "r"); if (!bio) { return false; } for (;;) { cert = PEM_read_bio_X509_AUX(bio.bio, NULL, NULL, NULL); if (!cert) { // No more the certificates in this file. break; } // This transfers ownership of the cert (X509) to the SSL context, if successful. if (!SSL_CTX_add_extra_chain_cert(ctx, cert)) { X509_free(cert); return false; } } return true; } #if TS_USE_TLS_SNI static int ssl_servername_callback(SSL * ssl, int * ad, void * arg) { SSL_CTX * ctx = NULL; SSLCertLookup * lookup = (SSLCertLookup *) arg; const char * servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); SSLNetVConnection * netvc = (SSLNetVConnection *)SSL_get_app_data(ssl); Debug("ssl", "ssl=%p ad=%d lookup=%p server=%s", ssl, *ad, lookup, servername); // The incoming SSL_CTX is either the one mapped from the inbound IP address or the default one. If we // don't find a name-based match at this point, we *do not* want to mess with the context because we've // already made a best effort to find the best match. if (likely(servername)) { ctx = lookup->findInfoInHash((char *)servername); } // If there's no match on the server name, try to match on the peer address. if (ctx == NULL) { IpEndpoint ip; int namelen = sizeof(ip); safe_getsockname(netvc->get_socket(), &ip.sa, &namelen); ctx = lookup->findInfoInHash(ip); } if (ctx != NULL) { SSL_set_SSL_CTX(ssl, ctx); } ctx = SSL_get_SSL_CTX(ssl); Debug("ssl", "found SSL context %p for requested name '%s'", ctx, servername); if (ctx == NULL) { return SSL_TLSEXT_ERR_NOACK; } // We need to return one of the SSL_TLSEXT_ERR constants. If we return an // error, we can fill in *ad with an alert code to propgate to the // client, see SSL_AD_*. return SSL_TLSEXT_ERR_OK; } #endif /* TS_USE_TLS_SNI */ static SSL_CTX * ssl_context_enable_sni(SSL_CTX * ctx, SSLCertLookup * lookup) { #if TS_USE_TLS_SNI Debug("ssl", "setting SNI callbacks with for ctx %p", ctx); if (ctx) { SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_callback); SSL_CTX_set_tlsext_servername_arg(ctx, lookup); } #else NOWARN_UNUSED(ctx); NOWARN_UNUSED(lookup); #endif /* TS_USE_TLS_SNI */ return ctx; } static SSL_CTX * ssl_context_enable_ecdh(SSL_CTX * ctx) { #if TS_USE_TLS_ECKEY #if defined(SSL_CTRL_SET_ECDH_AUTO) SSL_CTX_set_ecdh_auto(ctx, 1); #elif defined(HAVE_EC_KEY_NEW_BY_CURVE_NAME) && defined(NID_X9_62_prime256v1) EC_KEY * ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); if (ecdh) { SSL_CTX_set_tmp_ecdh(ctx, ecdh); EC_KEY_free(ecdh); } #endif #endif return ctx; } static SSL_CTX * ssl_context_enable_tickets(SSL_CTX * ctx, char * ticket_key_path) { #if TS_USE_TLS_TICKETS xptr<char> ticket_key_data; int ticket_key_len; ssl_ticket_key_t * ticket_key = NULL; ticket_key_data = readIntoBuffer(ticket_key_path, __func__, &ticket_key_len); if (!ticket_key_data) { Error("failed to read SSL session ticket key from %s", (const char *)ticket_key_path); goto fail; } if (ticket_key_len < 48) { Error("SSL session ticket key from %s is too short (48 bytes are required)", (const char *)ticket_key_path); goto fail; } ticket_key = NEW(new ssl_ticket_key_t()); memcpy(ticket_key->key_name, (const char *)ticket_key_data, 16); memcpy(ticket_key->hmac_secret, (const char *)ticket_key_data + 16, 16); memcpy(ticket_key->aes_key, (const char *)ticket_key_data + 32, 16); // Setting the callback can only fail if OpenSSL does not recognize the // SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB constant. we set the callback first // so that we don't leave a ticket_key pointer attached if it fails. if (SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_callback_session_ticket) == 0) { Error("failed to set session ticket callback"); goto fail; } if (SSL_CTX_set_ex_data(ctx, ssl_session_ticket_index, ticket_key) == 0) { Error ("failed to set session ticket data to ctx"); goto fail; } SSL_CTX_clear_options(ctx, SSL_OP_NO_TICKET); return ctx; fail: delete ticket_key; return ctx; #else /* TS_USE_TLS_TICKETS */ (void)ticket_key_path; return ctx; #endif /* TS_USE_TLS_TICKETS */ } void SSLInitializeLibrary() { if (!open_ssl_initialized) { CRYPTO_set_mem_functions(ats_malloc, ats_realloc, ats_free); SSL_load_error_strings(); SSL_library_init(); sslMutexArray = (ink_mutex *) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(ink_mutex)); for (int i = 0; i < CRYPTO_num_locks(); i++) { ink_mutex_init(&sslMutexArray[i], "sslMutexArray"); } CRYPTO_set_locking_callback(SSL_locking_callback); CRYPTO_set_id_callback(SSL_pthreads_thread_id); } int iRet = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL); if (iRet == -1) { SSLError("failed to create session ticket index"); } ssl_session_ticket_index = (iRet == -1 ? 0 : iRet); open_ssl_initialized = true; } void SSLError(const char *errStr, bool critical) { unsigned long l; char buf[256]; const char *file, *data; int line, flags; unsigned long es; if (!critical) { if (errStr) { Debug("ssl_error", "SSL ERROR: %s", errStr); } else { Debug("ssl_error", "SSL ERROR"); } } else { if (errStr) { Error("SSL ERROR: %s", errStr); } else { Error("SSL ERROR"); } } es = CRYPTO_thread_id(); while ((l = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0) { if (!critical) { Debug("ssl_error", "SSL::%lu:%s:%s:%d:%s", es, ERR_error_string(l, buf), file, line, (flags & ERR_TXT_STRING) ? data : ""); } else { Error("SSL::%lu:%s:%s:%d:%s", es, ERR_error_string(l, buf), file, line, (flags & ERR_TXT_STRING) ? data : ""); } } } void SSLDebugBufferPrint(const char * tag, const char * buffer, unsigned buflen, const char * message) { if (is_debug_tag_set(tag)) { if (message != NULL) { fprintf(stdout, "%s\n", message); } for (unsigned ii = 0; ii < buflen; ii++) { putc(buffer[ii], stdout); } putc('\n', stdout); } } SSL_CTX * SSLDefaultServerContext() { ink_ssl_method_t meth = NULL; meth = SSLv23_server_method(); return SSL_CTX_new(meth); } SSL_CTX * SSLInitServerContext( const SSLConfigParams * params, const char * serverCertPtr, const char * serverCaCertPtr, const char * serverKeyPtr) { int session_id_context; int server_verify_client; xptr<char> completeServerCertPath; SSL_CTX * ctx = SSLDefaultServerContext(); // disable selected protocols SSL_CTX_set_options(ctx, params->ssl_ctx_options); switch (params->ssl_session_cache) { case SSLConfigParams::SSL_SESSION_CACHE_MODE_OFF: SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF|SSL_SESS_CACHE_NO_INTERNAL); break; case SSLConfigParams::SSL_SESSION_CACHE_MODE_SERVER: SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER); SSL_CTX_sess_set_cache_size(ctx, params->ssl_session_cache_size); break; } #ifdef SSL_MODE_RELEASE_BUFFERS SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS); #endif SSL_CTX_set_quiet_shutdown(ctx, 1); // XXX OpenSSL recommends that we should use SSL_CTX_use_certificate_chain_file() here. That API // also loads only the first certificate, but it allows the intermediate CA certificate chain to // be in the same file. SSL_CTX_use_certificate_chain_file() was added in OpenSSL 0.9.3. completeServerCertPath = Layout::relative_to(params->serverCertPathOnly, serverCertPtr); if (SSL_CTX_use_certificate_file(ctx, completeServerCertPath, SSL_FILETYPE_PEM) <= 0) { Error ("SSL ERROR: Cannot use server certificate file: %s", (const char *)completeServerCertPath); goto fail; } // First, load any CA chains from the global chain file. if (params->serverCertChainFilename) { xptr<char> completeServerCaCertPath(Layout::relative_to(params->serverCertPathOnly, params->serverCertChainFilename)); if (!SSL_CTX_add_extra_chain_cert_file(ctx, completeServerCaCertPath)) { SSLError("failed to load global certificate chain from %s", (const char *)completeServerCaCertPath); goto fail; } } // Now, load any additional certificate chains specified in this entry. if (serverCaCertPtr) { xptr<char> completeServerCertChainPath(Layout::relative_to(params->serverCertPathOnly, serverCaCertPtr)); if (!SSL_CTX_add_extra_chain_cert_file(ctx, completeServerCertChainPath)) { SSLError ("Cannot use server certificate chain file: %s", (const char *)completeServerCertChainPath); goto fail; } } if (serverKeyPtr == NULL) { // assume private key is contained in cert obtained from multicert file. if (SSL_CTX_use_PrivateKey_file(ctx, completeServerCertPath, SSL_FILETYPE_PEM) <= 0) { SSLError("Cannot use server private key file: %s", (const char *)completeServerCertPath); goto fail; } } else if (params->serverKeyPathOnly != NULL) { xptr<char> completeServerKeyPath(Layout::get()->relative_to(params->serverKeyPathOnly, serverKeyPtr)); if (SSL_CTX_use_PrivateKey_file(ctx, completeServerKeyPath, SSL_FILETYPE_PEM) <= 0) { SSLError("Cannot use server private key file: %s", (const char *)completeServerKeyPath); goto fail; } } else { SSLError("Empty ssl private key path in records.config."); } if (!SSL_CTX_check_private_key(ctx)) { SSLError("Server private key does not match the certificate public key"); goto fail; } if (params->clientCertLevel != 0) { if (params->serverCACertFilename != NULL && params->serverCACertPath != NULL) { if ((!SSL_CTX_load_verify_locations(ctx, params->serverCACertFilename, params->serverCACertPath)) || (!SSL_CTX_set_default_verify_paths(ctx))) { SSLError("CA Certificate file or CA Certificate path invalid"); goto fail; } } if (params->clientCertLevel == 2) { server_verify_client = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE; } else if (params->clientCertLevel == 1) { server_verify_client = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE; } else { // disable client cert support server_verify_client = SSL_VERIFY_NONE; Error("Illegal Client Certification Level in records.config"); } session_id_context = 1; SSL_CTX_set_verify(ctx, server_verify_client, NULL); SSL_CTX_set_verify_depth(ctx, params->verify_depth); // might want to make configurable at some point. SSL_CTX_set_session_id_context(ctx, (const unsigned char *) &session_id_context, sizeof session_id_context); SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(params->serverCACertFilename)); } if (params->cipherSuite != NULL) { if (!SSL_CTX_set_cipher_list(ctx, params->cipherSuite)) { SSLError("Invalid Cipher Suite in records.config"); goto fail; } } return ssl_context_enable_ecdh(ctx); fail: SSL_CTX_free(ctx); return NULL; } SSL_CTX * SSLInitClientContext(const SSLConfigParams * params) { ink_ssl_method_t meth = NULL; SSL_CTX * client_ctx = NULL; char * clientKeyPtr = NULL; // Note that we do not call RAND_seed() explicitly here, we depend on OpenSSL // to do the seeding of the PRNG for us. This is the case for all platforms that // has /dev/urandom for example. meth = SSLv23_client_method(); client_ctx = SSL_CTX_new(meth); // disable selected protocols SSL_CTX_set_options(client_ctx, params->ssl_ctx_options); if (!client_ctx) { SSLError("Cannot create new client context"); return NULL; } // if no path is given for the client private key, // assume it is contained in the client certificate file. clientKeyPtr = params->clientKeyPath; if (clientKeyPtr == NULL) { clientKeyPtr = params->clientCertPath; } if (params->clientCertPath != 0) { if (SSL_CTX_use_certificate_file(client_ctx, params->clientCertPath, SSL_FILETYPE_PEM) <= 0) { Error ("SSL Error: Cannot use client certificate file: %s", params->clientCertPath); SSL_CTX_free(client_ctx); return NULL; } if (SSL_CTX_use_PrivateKey_file(client_ctx, clientKeyPtr, SSL_FILETYPE_PEM) <= 0) { Error ("SSL ERROR: Cannot use client private key file: %s", clientKeyPtr); SSL_CTX_free(client_ctx); return NULL; } if (!SSL_CTX_check_private_key(client_ctx)) { Error("SSL ERROR: Client private key (%s) does not match the certificate public key (%s)", clientKeyPtr, params->clientCertPath); SSL_CTX_free(client_ctx); return NULL; } } if (params->clientVerify) { int client_verify_server; client_verify_server = params->clientVerify ? SSL_VERIFY_PEER : SSL_VERIFY_NONE; SSL_CTX_set_verify(client_ctx, client_verify_server, NULL); SSL_CTX_set_verify_depth(client_ctx, params->client_verify_depth); if (params->clientCACertFilename != NULL && params->clientCACertPath != NULL) { if ((!SSL_CTX_load_verify_locations(client_ctx, params->clientCACertFilename, params->clientCACertPath)) || (!SSL_CTX_set_default_verify_paths(client_ctx))) { Error("SSL ERROR: Client CA Certificate file (%s) or CA Certificate path (%s) invalid", params->clientCACertFilename, params->clientCACertPath); SSL_CTX_free(client_ctx); return NULL; } } } return client_ctx; } static char * asn1_strdup(ASN1_STRING * s) { // Make sure we have an 8-bit encoding. ink_assert(ASN1_STRING_type(s) == V_ASN1_IA5STRING || ASN1_STRING_type(s) == V_ASN1_UTF8STRING || ASN1_STRING_type(s) == V_ASN1_PRINTABLESTRING || ASN1_STRING_type(s) == V_ASN1_T61STRING); return ats_strndup((const char *)ASN1_STRING_data(s), ASN1_STRING_length(s)); } // Given a certificate and it's corresponding SSL_CTX context, insert hash // table aliases for all of the subject and subjectAltNames. Note that we don't // deal with wildcards (yet). static void ssl_index_certificate(SSLCertLookup * lookup, SSL_CTX * ctx, const char * certfile) { X509_NAME * subject = NULL; ats_file_bio bio(certfile, "r"); X509* cert = PEM_read_bio_X509_AUX(bio.bio, NULL, NULL, NULL); // Insert a key for the subject CN. subject = X509_get_subject_name(cert); if (subject) { int pos = -1; for (;;) { pos = X509_NAME_get_index_by_NID(subject, NID_commonName, pos); if (pos == -1) { break; } X509_NAME_ENTRY * e = X509_NAME_get_entry(subject, pos); ASN1_STRING * cn = X509_NAME_ENTRY_get_data(e); xptr<char> name(asn1_strdup(cn)); Debug("ssl", "mapping '%s' to certificate %s", (const char *)name, certfile); lookup->insert(ctx, name); } } #if HAVE_OPENSSL_TS_H // Traverse the subjectAltNames (if any) and insert additional keys for the SSL context. GENERAL_NAMES * names = (GENERAL_NAMES *)X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL); if (names) { unsigned count = sk_GENERAL_NAME_num(names); for (unsigned i = 0; i < count; ++i) { GENERAL_NAME * name; name = sk_GENERAL_NAME_value(names, i); if (name->type == GEN_DNS) { xptr<char> dns(asn1_strdup(name->d.dNSName)); Debug("ssl", "mapping '%s' to certificate %s", (const char *)dns, certfile); lookup->insert(ctx, dns); } } GENERAL_NAMES_free(names); } #endif // HAVE_OPENSSL_TS_H X509_free(cert); } static void ssl_store_ssl_context( const SSLConfigParams * params, SSLCertLookup * lookup, xptr<char>& addr, xptr<char>& cert, xptr<char>& ca, xptr<char>& key, const int session_ticket_enabled, xptr<char>& ticket_key_filename) { SSL_CTX * ctx; xptr<char> certpath; xptr<char> session_key_path; ctx = ssl_context_enable_sni(SSLInitServerContext(params, cert, ca, key), lookup); if (!ctx) { SSLError("failed to create new SSL server context"); return; } #if TS_USE_TLS_NPN SSL_CTX_set_next_protos_advertised_cb(ctx, SSLNetVConnection::advertise_next_protocol, NULL); #endif /* TS_USE_TLS_NPN */ certpath = Layout::relative_to(params->serverCertPathOnly, cert); // Index this certificate by the specified IP(v6) address. If the address is "*", make it the default context. if (addr) { if (strcmp(addr, "*") == 0) { lookup->ssl_default = ctx; lookup->insert(ctx, addr); } else { IpEndpoint ep; if (ats_ip_pton(addr, &ep) == 0) { Debug("ssl", "mapping '%s' to certificate %s", (const char *)addr, (const char *)certpath); lookup->insert(ctx, ep); } else { Error("'%s' is not a valid IPv4 or IPv6 address", (const char *)addr); } } } #if defined(SSL_OP_NO_TICKET) // Session tickets are enabled by default. Disable if explicitly requested. if (session_ticket_enabled == 0) { SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET); Debug("ssl", "ssl session ticket is disabled"); } #endif // Load the session ticket key if session tickets are not disabled and we have key name. if (session_ticket_enabled != 0 && ticket_key_filename) { xptr<char> ticket_key_path(Layout::relative_to(params->serverCertPathOnly, ticket_key_filename)); ssl_context_enable_tickets(ctx, ticket_key_path); } // Insert additional mappings. Note that this maps multiple keys to the same value, so when // this code is updated to reconfigure the SSL certificates, it will need some sort of // refcounting or alternate way of avoiding double frees. ssl_index_certificate(lookup, ctx, certpath); } static bool ssl_extract_certificate( const matcher_line * line_info, xptr<char>& addr, // IPv[64] address to match xptr<char>& cert, // certificate xptr<char>& ca, // CA public certificate xptr<char>& key, // Private key int& session_ticket_enabled, // session ticket enabled xptr<char>& ticket_key_filename) // session key file. [key_name (16Byte) + HMAC_secret (16Byte) + AES_key (16Byte)] { for (int i = 0; i < MATCHER_MAX_TOKENS; ++i) { const char * label; const char * value; label = line_info->line[0][i]; value = line_info->line[1][i]; if (label == NULL) { continue; } if (strcasecmp(label, SSL_IP_TAG) == 0) { addr = ats_strdup(value); } if (strcasecmp(label, SSL_CERT_TAG) == 0) { cert = ats_strdup(value); } if (strcasecmp(label, SSL_CA_TAG) == 0) { ca = ats_strdup(value); } if (strcasecmp(label, SSL_PRIVATE_KEY_TAG) == 0) { key = ats_strdup(value); } if (strcasecmp(label, SSL_SESSION_TICKET_ENABLED) == 0) { session_ticket_enabled = atoi(value); } if (strcasecmp(label, SSL_SESSION_TICKET_KEY_FILE_TAG) == 0) { ticket_key_filename = ats_strdup(value); } } if (!cert) { Error("missing %s tag", SSL_CERT_TAG); return false; } return true; } bool SSLParseCertificateConfiguration( const SSLConfigParams * params, SSLCertLookup * lookup) { char * tok_state = NULL; char * line = NULL; xptr<char> file_buf; unsigned line_num = 0; matcher_line line_info; bool alarmAlready = false; char errBuf[1024]; const matcher_tags sslCertTags = { NULL, NULL, NULL, NULL, NULL, false }; Note("loading SSL certificate configuration from %s", params->configFilePath); if (params->configFilePath) { file_buf = readIntoBuffer(params->configFilePath, __func__, NULL); } if (!file_buf) { Error("%s: failed to read SSL certificate configuration from %s", __func__, params->configFilePath); return false; } line = tokLine(file_buf, &tok_state); while (line != NULL) { line_num++; // skip all blank spaces at beginning of line while (*line && isspace(*line)) { line++; } if (*line != '\0' && *line != '#') { xptr<char> addr; xptr<char> cert; xptr<char> ca; xptr<char> key; int session_ticket_enabled = -1; xptr<char> ticket_key_filename; const char * errPtr; errPtr = parseConfigLine(line, &line_info, &sslCertTags); if (errPtr != NULL) { snprintf(errBuf, sizeof(errBuf), "%s: discarding %s entry at line %d: %s", __func__, params->configFilePath, line_num, errPtr); IOCORE_SignalError(errBuf, alarmAlready); } else { if (ssl_extract_certificate(&line_info, addr, cert, ca, key, session_ticket_enabled, ticket_key_filename)) { ssl_store_ssl_context(params, lookup, addr, cert, ca, key, session_ticket_enabled, ticket_key_filename); } else { snprintf(errBuf, sizeof(errBuf), "%s: discarding invalid %s entry at line %u", __func__, params->configFilePath, line_num); IOCORE_SignalError(errBuf, alarmAlready); } } } line = tokLine(NULL, &tok_state); } // We *must* have a default context even if it can't possibly work. The default context is used to // bootstrap the SSL handshake so that we can subsequently do the SNI lookup to switch to the real // context. if (lookup->ssl_default == NULL) { lookup->ssl_default = ssl_context_enable_sni(SSLDefaultServerContext(), lookup); lookup->insert(lookup->ssl_default, "*"); } return true; } #if TS_USE_TLS_TICKETS /* * RFC 5077. Create session ticket to resume SSL session without requiring session-specific state at the TLS server. * Specifically, it distributes the encrypted session-state information to the client in the form of a ticket and * a mechanism to present the ticket back to the server. * */ int ssl_callback_session_ticket(SSL *ssl, unsigned char *keyname, unsigned char *iv, EVP_CIPHER_CTX *cipher_ctx, HMAC_CTX *hctx, int enc) { ssl_ticket_key_t* ssl_ticket_key = (ssl_ticket_key_t*) SSL_CTX_get_ex_data(SSL_get_SSL_CTX(ssl), ssl_session_ticket_index); if (NULL == ssl_ticket_key) { Error("ssl ticket key is null."); return -1; } if (enc == 1) { memcpy(keyname, ssl_ticket_key->key_name, 16); RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH); EVP_EncryptInit_ex(cipher_ctx, EVP_aes_128_cbc(), NULL, ssl_ticket_key->aes_key, iv); HMAC_Init_ex(hctx, ssl_ticket_key->hmac_secret, 16, evp_md_func, NULL); Note("create ticket for a new session"); return 0; } else if (enc == 0) { if (memcmp(keyname, ssl_ticket_key->key_name, 16)) { Error("keyname is not consistent."); return 0; } EVP_DecryptInit_ex(cipher_ctx, EVP_aes_128_cbc(), NULL, ssl_ticket_key->aes_key, iv); HMAC_Init_ex(hctx, ssl_ticket_key->hmac_secret, 16, evp_md_func, NULL); Note("verify the ticket for an existing session." ); return 1; } return -1; } #endif void SSLReleaseContext(SSL_CTX * ctx) { ssl_ticket_key_t * ssl_ticket_key = (ssl_ticket_key_t*)SSL_CTX_get_ex_data(ctx, ssl_session_ticket_index); // Free the ticket if this is the last reference. if (ctx->references == 1 && ssl_ticket_key) { delete ssl_ticket_key; } SSL_CTX_free(ctx); } const char * SSLErrorName(int ssl_error) { static const char * names[] = { "SSL_ERROR_NONE", "SSL_ERROR_SSL", "SSL_ERROR_WANT_READ", "SSL_ERROR_WANT_WRITE", "SSL_ERROR_WANT_X509_LOOKUP", "SSL_ERROR_SYSCALL", "SSL_ERROR_ZERO_RETURN", "SSL_ERROR_WANT_CONNECT", "SSL_ERROR_WANT_ACCEPT" }; if (ssl_error < 0 || ssl_error >= (int)SIZE(names)) { return "unknown SSL error"; } return names[ssl_error]; }
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/content/shortcut_customization_ui/backend/accelerator_configuration_provider.h" namespace ash { namespace shortcut_ui { AcceleratorConfigurationProvider::AcceleratorConfigurationProvider() = default; AcceleratorConfigurationProvider::~AcceleratorConfigurationProvider() = default; } // namespace shortcut_ui } // namespace ash
/* * JailLocation.hpp * * Created on: 9 Sep 2014 * Author: Ashley Davis (SgtCoDFish) */ #include "Ashley/core/Component.hpp" #ifndef JAILLOCATION_HPP_ #define JAILLOCATION_HPP_ namespace stinkingRich { class JailLocation : public ashley::Component { }; } #endif /* JAILLOCATION_HPP_ */
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "native_client/src/trusted/plugin/nexe_arch.h" #include "native_client/src/trusted/platform_qualify/nacl_os_qualify.h" namespace { // The list of supported ISA strings for x86. See issue: // http://code.google.com/p/nativeclient/issues/detail?id=1040 for more // information. Note that these string are to be case-insensitive compared. const char* const kNexeArchX86_32 = "x86-32"; const char* const kNexeArchX86_64 = "x86-64"; } // namespace namespace plugin { const char* GetSandboxISA() { #if (NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 && NACL_BUILD_SUBARCH == 64) && \ (defined(NACL_LINUX) || defined(NACL_OSX)) return kNexeArchX86_64; // 64-bit Linux or Mac. #else return NaClOsIs64BitWindows() == 1 ? kNexeArchX86_64 // 64-bit Windows (Chrome, Firefox) : kNexeArchX86_32; // everything else. #endif } } // namespace plugin
/* Copyright (c) DataStax, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "integration.hpp" /** * Basics integration tests; common operations */ class BasicsTests : public Integration { }; /** * Perform inserts and validate the timestamps from the server * * This test will perform multiple inserts using a simple statement and ensure * the timestamps between the inserts are valid and different based on a timed * tolerance against a single node cluster. * * @test_category queries:timestamp * @since core:1.0.0 * @expected_result Cassandra values are inserted and timestamps are validated */ CASSANDRA_INTEGRATION_TEST_F(BasicsTests, Timestamps) { CHECK_FAILURE; // Create the table, insert and select queries for the test session_.execute(format_string(CASSANDRA_KEY_VALUE_TABLE_FORMAT, table_name_.c_str(), "int", "int")); std::string insert_query = format_string(CASSANDRA_KEY_VALUE_INSERT_FORMAT, table_name_.c_str(), "?", "?"); Statement select_query = Statement("SELECT WRITETIME (value) FROM " + table_name_); // Insert a value and get the timestamp from the server Statement statement(insert_query, 2); statement.bind<Integer>(0, Integer(0)); statement.bind<Integer>(1, Integer(1)); session_.execute(statement); Result result = session_.execute(select_query); ASSERT_EQ(1u, result.row_count()); ASSERT_EQ(1u, result.column_count()); BigInteger timestamp_1 = result.first_row().next().as<BigInteger>(); // Wait five seconds before performing next insert and timestamp retrieval unsigned int pause_duration = 5000; msleep(pause_duration); // Overwrite the value and get the timestamp from the server statement = Statement(insert_query, 2); statement.bind<Integer>(0, Integer(0)); statement.bind<Integer>(1, Integer(2)); // Overwritten value session_.execute(statement); result = session_.execute(select_query); ASSERT_EQ(1u, result.row_count()); ASSERT_EQ(1u, result.column_count()); BigInteger timestamp_2 = result.first_row().next().as<BigInteger>(); // Validate the timestamps ASSERT_NE(timestamp_1, timestamp_2); ASSERT_LT(timestamp_2 - timestamp_1 - BigInteger(pause_duration * 1000), BigInteger(100000)); } /** * Perform inserts and validate counter value * * This test will perform multiple update/upserts using a simple statement and * ensure the counters are properly updated against a single node cluster. * * @test_category queries:counter * @since core:1.0.0 * @expected_result Cassandra values are inserted and counters are validated */ CASSANDRA_INTEGRATION_TEST_F(BasicsTests, Counters) { CHECK_FAILURE; // Create the table and update/upsert queries for the test session_.execute(format_string(CASSANDRA_KEY_VALUE_TABLE_FORMAT, table_name_.c_str(), "int", "counter")); std::string update_query = "UPDATE " + table_name_ + " SET value=value %s ? WHERE key=0"; // Perform multiple upserts against the counter value for (int step = 0; step < 100; ++step) { Statement statement(format_string(update_query.c_str(), (step % 2 == 0 ? "-" : "+")), 1); statement.bind<Counter>(0, Counter(step)); session_.execute(statement); } // Select the columns from the and ensure the counter and rows Statement statement(default_select_all()); Result result = session_.execute(statement); ASSERT_EQ(1u, result.row_count()); ASSERT_GT(result.column_count(), 0u); Row row = result.first_row(); ASSERT_EQ(Integer(0), row.next().as<Integer>()); ASSERT_EQ(Counter(50), row.next().as<Counter>()); } /** * Perform inserts and validate rows inserted is equal to rows selected * * This test will perform multiple inserts using a simple statement and ensure * that the number of rows inserted is equal to the number of rows selected * (along with data validation) against a single node cluster. * * @test_category queries:basic * @since core:1.0.0 * @expected_result Cassandra values are inserted and counters are validated */ CASSANDRA_INTEGRATION_TEST_F(BasicsTests, RowsInRowsOut) { CHECK_FAILURE; // Create the table, insert, and select statements for the test session_.execute("CREATE TABLE " + table_name_ + " (key bigint PRIMARY KEY, " \ "value_1 bigint, value_2 bigint, value_3 bigint)"); Statement insert_statement("INSERT INTO " + table_name_ + " (key, value_1, value_2, value_3) " \ "VALUES (?, ?, ?, ?)", 4); Statement select_statement("SELECT key, value_1, value_2, value_3 FROM " + table_name_ + " LIMIT 1000"); // Create multiple rows with varying data for (int i = 0; i < 1000; ++i) { insert_statement.bind<BigInteger>(0, BigInteger(i)); insert_statement.bind<BigInteger>(1, BigInteger(i + 1)); insert_statement.bind<BigInteger>(2, BigInteger(i + 2)); insert_statement.bind<BigInteger>(3, BigInteger(i + 3)); session_.execute(insert_statement); } // Validate the rows inserted are the rows selected Result result = session_.execute(select_statement); ASSERT_EQ(1000u, result.row_count()); ASSERT_EQ(4u, result.column_count()); Rows rows = result.rows(); int number_of_rows = 0; for (size_t i = 0; i < rows.row_count(); ++i) { Row row = rows.next(); BigInteger key = row.next().as<BigInteger>(); ASSERT_EQ(key + BigInteger(1), row.next().as<BigInteger>()); // value_1 ASSERT_EQ(key + BigInteger(2), row.next().as<BigInteger>()); // value_2 ASSERT_EQ(key + BigInteger(3), row.next().as<BigInteger>()); // value_3 ++number_of_rows; } // Ensure that all the rows were read ASSERT_EQ(1000, number_of_rows); } /** * Perform insert and validate columns by name * * This test will perform an insert using a simple statement and ensure * that the number of rows inserted is equal to the number of rows selected * (along with data validation) against a single node cluster. * * @test_category queries:basic * @since core:1.0.0 * @expected_result Cassandra values are inserted and counters are validated */ CASSANDRA_INTEGRATION_TEST_F(BasicsTests, ColumnNames) { CHECK_FAILURE; // Create the table for the test session_.execute("CREATE TABLE " + table_name_ + " (key bigint PRIMARY KEY, " \ "value_1 text, value_2 int, value_3 bigint, value_4 float)"); // Validate the column names Result result = session_.execute(default_select_all()); ASSERT_EQ(0u, result.row_count()); ASSERT_EQ(5u, result.column_count()); std::vector<std::string> column_names = result.column_names(); ASSERT_EQ("key", column_names[0]); ASSERT_EQ("value_1", column_names[1]); ASSERT_EQ("value_2", column_names[2]); ASSERT_EQ("value_3", column_names[3]); ASSERT_EQ("value_4", column_names[4]); } /** * Perform statement executions and ensure empty results * * This test will perform varying statement type executions using a simple * statement and ensure the result set is empty (row count == 0) when executing * these statement types that do not return values from the server. * * NOTE: This is run against a single node cluster. * * @test_category queries:basic * @since core:1.0.0-rc1 * @expected_result Statement execution queries will not contain value in result */ CASSANDRA_INTEGRATION_TEST_F(BasicsTests, EmptyResults) { CHECK_FAILURE; // Create the table Result result = session_.execute(format_string(CASSANDRA_KEY_VALUE_TABLE_FORMAT, table_name_.c_str(), "int", "int")); ASSERT_TRUE(result.is_empty()); // Insert data into the table result = session_.execute(format_string(CASSANDRA_KEY_VALUE_INSERT_FORMAT, table_name_.c_str(), "0", "0")); ASSERT_TRUE(result.is_empty()); // Delete data from the table result = session_.execute(format_string(CASSANDRA_DELETE_ROW_FORMAT, table_name_.c_str(), "0")); ASSERT_TRUE(result.is_empty()); // Select data from the table (all rows have been deleted) result = session_.execute(default_select_all()); ASSERT_TRUE(result.is_empty()); } /** * Perform insert and ensure UNSET parameter is set (Cassandra v2.2+) * * This test will perform an insert using a simple statement with set and unset * bound values while ensuring the proper error is returned for Cassandra <= * v2.1 against a single node cluster. The known values will be validated to * ensure they were properly inserted. * * @test_category error_codes * @test_category queries:basic * @since core:2.2.0-beta1 * @expected_result Known value inserts will complete and validated */ CASSANDRA_INTEGRATION_TEST_F(BasicsTests, UnsetParameters) { CHECK_FAILURE; // Create the table, insert a known value, and create insert statement for the test session_.execute(format_string(CASSANDRA_KEY_VALUE_TABLE_FORMAT, table_name_.c_str(), "int", "int")); session_.execute(format_string(CASSANDRA_KEY_VALUE_INSERT_FORMAT, table_name_.c_str(), "0", "1")); Prepared insert_prepared = session_.prepare(format_string(CASSANDRA_KEY_VALUE_INSERT_FORMAT, table_name_.c_str(), "?", "?")); // Bind a single value and leave one unset Statement insert_statement = insert_prepared.bind(); insert_statement.bind<Integer>(0, Integer(0)); // Execute the insert statement and validate the error code Result result = session_.execute(insert_statement, false); if (server_version_ >= "2.2.0") { // Cassandra v2.2+ uses the value UNSET; making this a no-op ASSERT_EQ(CASS_OK, result.error_code()); } else { ASSERT_EQ(CASS_ERROR_LIB_PARAMETER_UNSET, result.error_code()); } // Validate known values from previous insert result = session_.execute(default_select_all()); ASSERT_EQ(1u, result.row_count()); ASSERT_EQ(2u, result.column_count()); Row row = result.first_row(); ASSERT_EQ(Integer(0), row.next().as<Integer>()); ASSERT_EQ(Integer(1), row.next().as<Integer>()); } /** * Perform insert against a blob data type using a string (char*) * * This test will perform an insert using a simple statement by binding a string * to a blob data type and validate the result against a single node cluster. * * NOTE: Previous versions of the driver allowed for this * * @test_category data_types:primitive * @test_category queries:basic * @since core:2.3.0 * @expected_result String will be bound/inserted into blob and values will be * validated */ CASSANDRA_INTEGRATION_TEST_F(BasicsTests, BindBlobAsString) { CHECK_FAILURE; // Create the table, prepared and insert statement for the test session_.execute(format_string(CASSANDRA_KEY_VALUE_TABLE_FORMAT, table_name_.c_str(), "int", "blob")); // Prepared needed to validate bind type information Prepared insert_prepared = session_.prepare(format_string(CASSANDRA_KEY_VALUE_INSERT_FORMAT, table_name_.c_str(), "?", "?")); Statement insert_statement = insert_prepared.bind(); // Bind and insert the data into the table Blob data("blob_string"); insert_statement.bind<Integer>(0, Integer(0)); insert_statement.bind<Blob>(1, data); session_.execute(insert_statement); // Validate the inserted data Result result = session_.execute(default_select_all()); ASSERT_EQ(1u, result.row_count()); ASSERT_EQ(2u, result.column_count()); Row row = result.first_row(); ASSERT_EQ(Integer(0), row.next().as<Integer>()); ASSERT_EQ(data, row.next().as<Blob>()); } /** * Perform select against a table using COMPACT STORAGE in compatibility mode. * * This this will perform querying a table with COMPACT STORAGE applied and * queried using a separate session where the NO_COMPACT STARTUP_OPTIONS was * supplied. * * NOTE: This test can only be run using Apache Cassandra versions where * COMPACT STORAGE is still applicable and supports the NO_COMPACT * STARTUP OPTIONS (e.g. v3.0.16+, v3.11.2+; but must be less than v4.x) * * @jira_ticket CPP-578 * @test_category connection * @since core:2.9.0 * @cassandra_version 3.0.16 * @cassandra_version 3.11.2 * @expected_result Values inserted into the COMPACT STORAGE table will be * selectable and contain additional metadata (columns). */ CASSANDRA_INTEGRATION_TEST_F(BasicsTests, NoCompactEnabledConnection) { CHECK_FAILURE; CHECK_VERSION(3.0.16); CHECK_VERSION(3.11.2); CCM::CassVersion cass_version = server_version_; if (Options::is_dse()) { if (server_version_ >= "6.0.0") { SKIP_TEST("Unsupported for DataStax Enterprise Version " << server_version_.to_string() << ": Apache Cassandra server version must be used and less than" << " v4.0.0 and either 3.0.16+ or 3.11.2+ in order to execute"); } cass_version = static_cast<CCM::DseVersion>(cass_version).get_cass_version(); } if (cass_version >= "4.0.0") { SKIP_TEST("Unsupported for Apache Cassandra Version " << cass_version.to_string() << ": Server version must be less than v4.0.0 and either 3.0.16+" << " or 3.11.2+ in order to execute"); } // Create a session where the NO_COMPACT option is set Session no_compact_session = default_cluster() .with_no_compact() .connect(default_keyspace()); // Create the table and insert data using the NO_COMPACT session no_compact_session.execute(format_string( "CREATE TABLE %s (k int PRIMARY KEY, v int) WITH COMPACT STORAGE", table_name_.c_str())); no_compact_session.execute(format_string("INSERT INTO %s (k, v) VALUES(%s, %s)", table_name_.c_str(), "1", "1")); no_compact_session.execute(format_string("INSERT INTO %s (k, v) VALUES(%s, %s)", table_name_.c_str(), "2", "2")); no_compact_session.execute(format_string("INSERT INTO %s (k, v) VALUES(%s, %s)", table_name_.c_str(), "3", "3")); // Validate the default session with compact storage enabled Result result = session_.execute(default_select_all()); ASSERT_EQ(3u, result.row_count()); ASSERT_EQ(2u, result.column_count()); Rows rows = result.rows(); for (size_t i = 0; i < rows.row_count(); ++i) { Row row = rows.next(); Integer k = row.next().as<Integer>(); Integer v = row.next().as<Integer>(); ASSERT_EQ(k, Integer(i + 1)); ASSERT_EQ(v, Integer(i + 1)); } // Validate the default session with compact storage disabled (NO_COMPACT) result = no_compact_session.execute(default_select_all()); ASSERT_EQ(3u, result.row_count()); ASSERT_EQ(4u, result.column_count()); // Should contain extra columns (column and value) std::vector<std::string> column_names = result.column_names(); ASSERT_EQ("k", column_names[0]); ASSERT_EQ("column1", column_names[1]); ASSERT_EQ("v", column_names[2]); ASSERT_EQ("value", column_names[3]); rows = result.rows(); for (size_t i = 0; i < rows.row_count(); ++i) { Row row = rows.next(); Integer k = row.next().as<Integer>(); ASSERT_EQ(k, Integer(i + 1)); ASSERT_TRUE(row.next().as<Varchar>().is_null()); Integer v = row.next().as<Integer>(); ASSERT_EQ(v, Integer(i + 1)); ASSERT_TRUE(row.next().as<Blob>().is_null()); } }
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2019 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addresstablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "base58.h" #include "wallet/wallet.h" #include "askpassphrasedialog.h" #include <QDebug> #include <QFont> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; const QString AddressTableModel::Zerocoin = "X"; struct AddressTableEntry { enum Type { Sending, Receiving, Zerocoin, Hidden /* QSortFilterProxyModel will filter these out */ }; Type type; QString label; QString address; QString pubcoin; AddressTableEntry() {} AddressTableEntry(Type type, const QString &pubcoin): type(type), pubcoin(pubcoin) {} AddressTableEntry(Type type, const QString& label, const QString& address) : type(type), label(label), address(address) {} }; struct AddressTableEntryLessThan { bool operator()(const AddressTableEntry& a, const AddressTableEntry& b) const { return a.address < b.address; } bool operator()(const AddressTableEntry& a, const QString& b) const { return a.address < b; } bool operator()(const QString& a, const AddressTableEntry& b) const { return a < b.address; } }; /* Determine address type from address purpose */ static AddressTableEntry::Type translateTransactionType(const QString& strPurpose, bool isMine) { AddressTableEntry::Type addressType = AddressTableEntry::Hidden; // "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all. if (strPurpose == "send") addressType = AddressTableEntry::Sending; else if (strPurpose == "receive") addressType = AddressTableEntry::Receiving; else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending); return addressType; } // Private implementation class AddressTablePriv { public: CWallet* wallet; QList<AddressTableEntry> cachedAddressTable; AddressTableModel* parent; AddressTablePriv(CWallet* wallet, AddressTableModel* parent) : wallet(wallet), parent(parent) {} void refreshAddressTable() { cachedAddressTable.clear(); { LOCK(wallet->cs_wallet); for (const PAIRTYPE(CTxDestination, CAddressBookData) & item : wallet->mapAddressBook) { const CBitcoinAddress& address = item.first; bool fMine = IsMine(*wallet, address.Get()); AddressTableEntry::Type addressType = translateTransactionType( QString::fromStdString(item.second.purpose), fMine); const std::string& strName = item.second.name; cachedAddressTable.append(AddressTableEntry(addressType, QString::fromStdString(strName), QString::fromStdString(address.ToString()))); } } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order // Even though the map is already sorted this re-sorting step is needed because the originating map // is sorted by binary address, not by base58() address. qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); } void updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); int upperIndex = (upper - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine); switch (status) { case CT_NEW: if (inModel) { qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_NEW, but entry is already in model"; break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address)); parent->endInsertRows(); break; case CT_UPDATED: if (!inModel) { qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = label; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if (!inModel) { qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model"; break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1); cachedAddressTable.erase(lower, upper); parent->endRemoveRows(); break; } } void updateEntry(const QString &pubCoin, const QString &isUsed, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), pubCoin, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), pubCoin, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = AddressTableEntry::Zerocoin; switch(status) { case CT_NEW: if(inModel) { qWarning() << "AddressTablePriv_ZC::updateEntry : Warning: Got CT_NEW, but entry is already in model"; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, isUsed, pubCoin)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { qWarning() << "AddressTablePriv_ZC::updateEntry : Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = isUsed; parent->emitDataChanged(lowerIndex); break; } } int size() { return cachedAddressTable.size(); } AddressTableEntry* index(int idx) { if (idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent), walletModel(parent), wallet(wallet), priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(wallet, this); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer()); if (role == Qt::DisplayRole || role == Qt::EditRole) { switch (index.column()) { case Label: if (rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; } } else if (role == Qt::FontRole) { QFont font; if (index.column() == Address) { font = GUIUtil::bitcoinAddressFont(); } return font; } else if (role == TypeRole) { switch (rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex& index, const QVariant& value, int role) { if (!index.isValid()) return false; AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer()); std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive"); editStatus = OK; if (role == Qt::EditRole) { LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */ CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get(); if (index.column() == Label) { // Do nothing, if old label == new label if (rec->label == value.toString()) { editStatus = NO_CHANGES; return false; } wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose); } else if (index.column() == Address) { CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get(); // Refuse to set invalid address, set error status and return false if (boost::get<CNoDestination>(&newAddress)) { editStatus = INVALID_ADDRESS; return false; } // Do nothing, if old address == new address else if (newAddress == curAddress) { editStatus = NO_CHANGES; return false; } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) else if (wallet->mapAddressBook.count(newAddress)) { editStatus = DUPLICATE_ADDRESS; return false; } // Double-check that we're not overwriting a receiving address else if (rec->type == AddressTableEntry::Sending) { // Remove old entry wallet->DelAddressBook(curAddress); // Add new entry with new address wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose); } } return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal) { if (role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AddressTableModel::flags(const QModelIndex& index) const { if (!index.isValid()) return 0; AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if (rec->type == AddressTableEntry::Sending || (rec->type == AddressTableEntry::Receiving && index.column() == Label)) { retval |= Qt::ItemIsEditable; } return retval; } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex& parent) const { Q_UNUSED(parent); AddressTableEntry* data = priv->index(row); if (data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status) { // Update address book model from Streamies core priv->updateEntry(address, label, isMine, purpose, status); } void AddressTableModel::updateEntry(const QString &pubCoin, const QString &isUsed, int status) { // Update stealth address book model from Bitcoin core priv->updateEntry(pubCoin, isUsed, status); } QString AddressTableModel::addRow(const QString& type, const QString& label, const QString& address) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); editStatus = OK; if (type == Send) { if (!walletModel->validateAddress(address)) { editStatus = INVALID_ADDRESS; return QString(); } // Check for duplicate addresses { LOCK(wallet->cs_wallet); if (wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) { editStatus = DUPLICATE_ADDRESS; return QString(); } } } else if (type == Receive) { // Generate a new address to associate with given label CPubKey newKey; if (!wallet->GetKeyFromPool(newKey)) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Unlock_Full, true)); if (!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; return QString(); } if (!wallet->GetKeyFromPool(newKey)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } } strAddress = CBitcoinAddress(newKey.GetID()).ToString(); } else { return QString(); } // Add entry { LOCK(wallet->cs_wallet); wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel, (type == Send ? "send" : "receive")); } return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex& parent) { Q_UNUSED(parent); AddressTableEntry* rec = priv->index(row); if (count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } { LOCK(wallet->cs_wallet); wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get()); } return true; } /* Look up label for address in address book, if not found return empty string. */ QString AddressTableModel::labelForAddress(const QString& address) const { { LOCK(wallet->cs_wallet); CBitcoinAddress address_parsed(address.toStdString()); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get()); if (mi != wallet->mapAddressBook.end()) { return QString::fromStdString(mi->second.name); } } return QString(); } int AddressTableModel::lookupAddress(const QString& address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if (lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AddressTableModel::emitDataChanged(int idx) { emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length() - 1, QModelIndex())); }
/**************************************************************************** * * Copyright 2018 Samsung Electronics 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. * ****************************************************************************/ //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <iterator> // template <class T, size_t N> T* begin(T (&array)[N]); #include <iterator> #include <cassert> #include "libcxx_tc_common.h" int tc_libcxx_iterators_iterator_range_begin_array(void) { int ia[] = {1, 2, 3}; int* i = std::begin(ia); TC_ASSERT_EXPR(*i == 1); *i = 2; TC_ASSERT_EXPR(ia[0] == 2); TC_SUCCESS_RESULT(); return 0; }
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 100; const int INF = 10000; int n,a,b; int g[maxn][maxn],dis[maxn]; bool vis[maxn]; int main() {     int i,j,k,d;     while (scanf("%d%d%d",&n,&a,&b)==3)     {         a--; b--;         for (i=0;i<n;i++)             for (j=0;j<n;j++)                 g[i][j]=INF;         for (i=0;i<n;i++)             g[i][i]=0;         for (i=0;i<n;i++)         {             scanf("%d",&k);             if (!k) continue;             scanf("%d",&j); g[i][j-1]=0;             while (--k) {scanf("%d",&j); g[i][j-1]=1;}         }         for (i=0;i<n;i++) {dis[i]=g[a][i]; vis[i]=0;}         dis[a]=0; vis[a]=1;         for (i=0;i<n;i++)         {             if (vis[i]) continue;             j=i; d=INF;             for (k=0;k<n;k++)                 if (!vis[k] && dis[k]<d) {d=dis[k]; j=k;}             vis[j]=1;             for (k=0;k<n;k++)                 if (!vis[k] && dis[k]>dis[j]+g[j][k]) dis[k]=dis[j]+g[j][k];         }         if (dis[b]>=INF) printf("KK can not find his friend.\n");         else printf("%d\n",dis[b]);     }     return 0; }
// Copyright (c) 2012-2013 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "consensus/merkle.h" #include "merkleblock.h" #include "serialize.h" #include "streams.h" #include "uint256.h" #include "arith_uint256.h" #include "version.h" #include "random.h" #include "test/test_syscoin.h" #include <vector> #include <boost/assign/list_of.hpp> #include <boost/test/unit_test.hpp> using namespace std; class CPartialMerkleTreeTester : public CPartialMerkleTree { public: // flip one bit in one of the hashes - this should break the authentication void Damage() { unsigned int n = insecure_rand() % vHash.size(); int bit = insecure_rand() % 256; *(vHash[n].begin() + (bit>>3)) ^= 1<<(bit&7); } }; BOOST_FIXTURE_TEST_SUITE(pmt_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(pmt_test1) { seed_insecure_rand(false); static const unsigned int nTxCounts[] = {1, 4, 7, 17, 56, 100, 127, 256, 312, 513, 1000, 4095}; for (int n = 0; n < 12; n++) { unsigned int nTx = nTxCounts[n]; // build a block with some dummy transactions CBlock block; for (unsigned int j=0; j<nTx; j++) { CMutableTransaction tx; tx.nLockTime = j; // actual transaction data doesn't matter; just make the nLockTime's unique block.vtx.push_back(CTransaction(tx)); } // calculate actual merkle root and height uint256 merkleRoot1 = BlockMerkleRoot(block); std::vector<uint256> vTxid(nTx, uint256()); for (unsigned int j=0; j<nTx; j++) vTxid[j] = block.vtx[j].GetHash(); int nHeight = 1, nTx_ = nTx; while (nTx_ > 1) { nTx_ = (nTx_+1)/2; nHeight++; } // check with random subsets with inclusion chances 1, 1/2, 1/4, ..., 1/128 for (int att = 1; att < 15; att++) { // build random subset of txid's std::vector<bool> vMatch(nTx, false); std::vector<uint256> vMatchTxid1; for (unsigned int j=0; j<nTx; j++) { bool fInclude = (insecure_rand() & ((1 << (att/2)) - 1)) == 0; vMatch[j] = fInclude; if (fInclude) vMatchTxid1.push_back(vTxid[j]); } // build the partial merkle tree CPartialMerkleTree pmt1(vTxid, vMatch); // serialize CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << pmt1; // verify CPartialMerkleTree's size guarantees unsigned int n = std::min<unsigned int>(nTx, 1 + vMatchTxid1.size()*nHeight); BOOST_CHECK(ss.size() <= 10 + (258*n+7)/8); // deserialize into a tester copy CPartialMerkleTreeTester pmt2; ss >> pmt2; // extract merkle root and matched txids from copy std::vector<uint256> vMatchTxid2; uint256 merkleRoot2 = pmt2.ExtractMatches(vMatchTxid2); // check that it has the same merkle root as the original, and a valid one BOOST_CHECK(merkleRoot1 == merkleRoot2); BOOST_CHECK(!merkleRoot2.IsNull()); // check that it contains the matched transactions (in the same order!) BOOST_CHECK(vMatchTxid1 == vMatchTxid2); // check that random bit flips break the authentication for (int j=0; j<4; j++) { CPartialMerkleTreeTester pmt3(pmt2); pmt3.Damage(); std::vector<uint256> vMatchTxid3; uint256 merkleRoot3 = pmt3.ExtractMatches(vMatchTxid3); BOOST_CHECK(merkleRoot3 != merkleRoot1); } } } } BOOST_AUTO_TEST_CASE(pmt_malleability) { std::vector<uint256> vTxid = boost::assign::list_of (ArithToUint256(1))(ArithToUint256(2)) (ArithToUint256(3))(ArithToUint256(4)) (ArithToUint256(5))(ArithToUint256(6)) (ArithToUint256(7))(ArithToUint256(8)) (ArithToUint256(9))(ArithToUint256(10)) (ArithToUint256(9))(ArithToUint256(10)); std::vector<bool> vMatch = boost::assign::list_of(false)(false)(false)(false)(false)(false)(false)(false)(false)(true)(true)(false); CPartialMerkleTree tree(vTxid, vMatch); std::vector<uint256> vTxid2; BOOST_CHECK(tree.ExtractMatches(vTxid).IsNull()); } BOOST_AUTO_TEST_SUITE_END()
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2015 Benoit Steiner <benoit.steiner.goog@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" #include <Eigen/CXX11/Tensor> #if EIGEN_COMP_MSVC #define EIGEN_NO_INT128 #else typedef __uint128_t uint128_t; #endif // Only run the test on compilers that support 128bit integers natively #ifndef EIGEN_NO_INT128 using Eigen::internal::TensorUInt128; using Eigen::internal::static_val; void VERIFY_EQUAL(TensorUInt128<uint64_t, uint64_t> actual, uint128_t expected) { bool matchl = actual.lower() == static_cast<uint64_t>(expected); bool matchh = actual.upper() == static_cast<uint64_t>(expected >> 64); if (!matchl || !matchh) { const char* testname = g_test_stack.back().c_str(); std::cerr << "Test " << testname << " failed in " << __FILE__ << " (" << __LINE__ << ")" << std::endl; abort(); } } void test_add() { uint64_t incr = internal::random<uint64_t>(1, 9999999999); for (uint64_t i1 = 0; i1 < 100; ++i1) { for (uint64_t i2 = 1; i2 < 100 * incr; i2 += incr) { TensorUInt128<uint64_t, uint64_t> i(i1, i2); uint128_t a = (static_cast<uint128_t>(i1) << 64) + static_cast<uint128_t>(i2); for (uint64_t j1 = 0; j1 < 100; ++j1) { for (uint64_t j2 = 1; j2 < 100 * incr; j2 += incr) { TensorUInt128<uint64_t, uint64_t> j(j1, j2); uint128_t b = (static_cast<uint128_t>(j1) << 64) + static_cast<uint128_t>(j2); TensorUInt128<uint64_t, uint64_t> actual = i + j; uint128_t expected = a + b; VERIFY_EQUAL(actual, expected); } } } } } void test_sub() { uint64_t incr = internal::random<uint64_t>(1, 9999999999); for (uint64_t i1 = 0; i1 < 100; ++i1) { for (uint64_t i2 = 1; i2 < 100 * incr; i2 += incr) { TensorUInt128<uint64_t, uint64_t> i(i1, i2); uint128_t a = (static_cast<uint128_t>(i1) << 64) + static_cast<uint128_t>(i2); for (uint64_t j1 = 0; j1 < 100; ++j1) { for (uint64_t j2 = 1; j2 < 100 * incr; j2 += incr) { TensorUInt128<uint64_t, uint64_t> j(j1, j2); uint128_t b = (static_cast<uint128_t>(j1) << 64) + static_cast<uint128_t>(j2); TensorUInt128<uint64_t, uint64_t> actual = i - j; uint128_t expected = a - b; VERIFY_EQUAL(actual, expected); } } } } } void test_mul() { uint64_t incr = internal::random<uint64_t>(1, 9999999999); for (uint64_t i1 = 0; i1 < 100; ++i1) { for (uint64_t i2 = 1; i2 < 100 * incr; i2 += incr) { TensorUInt128<uint64_t, uint64_t> i(i1, i2); uint128_t a = (static_cast<uint128_t>(i1) << 64) + static_cast<uint128_t>(i2); for (uint64_t j1 = 0; j1 < 100; ++j1) { for (uint64_t j2 = 1; j2 < 100 * incr; j2 += incr) { TensorUInt128<uint64_t, uint64_t> j(j1, j2); uint128_t b = (static_cast<uint128_t>(j1) << 64) + static_cast<uint128_t>(j2); TensorUInt128<uint64_t, uint64_t> actual = i * j; uint128_t expected = a * b; VERIFY_EQUAL(actual, expected); } } } } } void test_div() { uint64_t incr = internal::random<uint64_t>(1, 9999999999); for (uint64_t i1 = 0; i1 < 100; ++i1) { for (uint64_t i2 = 1; i2 < 100 * incr; i2 += incr) { TensorUInt128<uint64_t, uint64_t> i(i1, i2); uint128_t a = (static_cast<uint128_t>(i1) << 64) + static_cast<uint128_t>(i2); for (uint64_t j1 = 0; j1 < 100; ++j1) { for (uint64_t j2 = 1; j2 < 100 * incr; j2 += incr) { TensorUInt128<uint64_t, uint64_t> j(j1, j2); uint128_t b = (static_cast<uint128_t>(j1) << 64) + static_cast<uint128_t>(j2); TensorUInt128<uint64_t, uint64_t> actual = i / j; uint128_t expected = a / b; VERIFY_EQUAL(actual, expected); } } } } } void test_misc1() { uint64_t incr = internal::random<uint64_t>(1, 9999999999); for (uint64_t i2 = 1; i2 < 100 * incr; i2 += incr) { TensorUInt128<static_val<0>, uint64_t> i(0, i2); uint128_t a = static_cast<uint128_t>(i2); for (uint64_t j2 = 1; j2 < 100 * incr; j2 += incr) { TensorUInt128<static_val<0>, uint64_t> j(0, j2); uint128_t b = static_cast<uint128_t>(j2); uint64_t actual = (i * j).upper(); uint64_t expected = (a * b) >> 64; VERIFY_IS_EQUAL(actual, expected); } } } void test_misc2() { int64_t incr = internal::random<int64_t>(1, 100); for (int64_t log_div = 0; log_div < 63; ++log_div) { for (int64_t divider = 1; divider <= 1000000 * incr; divider += incr) { uint64_t expected = (static_cast<uint128_t>(1) << (64+log_div)) / static_cast<uint128_t>(divider) - (static_cast<uint128_t>(1) << 64) + 1; uint64_t shift = 1ULL << log_div; TensorUInt128<uint64_t, uint64_t> result = (TensorUInt128<uint64_t, static_val<0> >(shift, 0) / TensorUInt128<static_val<0>, uint64_t>(divider) - TensorUInt128<static_val<1>, static_val<0> >(1, 0) + TensorUInt128<static_val<0>, static_val<1> >(1)); uint64_t actual = static_cast<uint64_t>(result); VERIFY_IS_EQUAL(actual, expected); } } } #endif void test_cxx11_tensor_uint128() { #ifdef EIGEN_NO_INT128 // Skip the test on compilers that don't support 128bit integers natively return; #else CALL_SUBTEST_1(test_add()); CALL_SUBTEST_2(test_sub()); CALL_SUBTEST_3(test_mul()); CALL_SUBTEST_4(test_div()); CALL_SUBTEST_5(test_misc1()); CALL_SUBTEST_6(test_misc2()); #endif }
/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2015 The Khronos Group Inc. * Copyright (c) 2015 Samsung Electronics Co., Ltd. * Copyright (c) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*--------------------------------------------------------------------*/ #include "vkDefs.hpp" #include "vktTestCaseUtil.hpp" #include "vkBuilderUtil.hpp" #include "vkPlatform.hpp" #include "vkRefUtil.hpp" #include "vkQueryUtil.hpp" #include "vkMemUtil.hpp" #include "vkDeviceUtil.hpp" #include "vkCmdUtil.hpp" #include "vkObjUtil.hpp" #include "tcuTextureUtil.hpp" #include "vkImageUtil.hpp" #include "vkPrograms.hpp" #include "vkTypeUtil.hpp" #include "vkAllocationCallbackUtil.hpp" #include "vkCmdUtil.hpp" #include "vktApiCommandBuffersTests.hpp" #include "vktApiBufferComputeInstance.hpp" #include "vktApiComputeInstanceResultBuffer.hpp" #include "deSharedPtr.hpp" #include <sstream> namespace vkt { namespace api { namespace { using namespace vk; typedef de::SharedPtr<vk::Unique<vk::VkEvent> > VkEventSp; // Global variables const deUint64 INFINITE_TIMEOUT = ~(deUint64)0u; template <deUint32 NumBuffers> class CommandBufferBareTestEnvironment { public: CommandBufferBareTestEnvironment (Context& context, VkCommandPoolCreateFlags commandPoolCreateFlags); VkCommandPool getCommandPool (void) const { return *m_commandPool; } VkCommandBuffer getCommandBuffer (deUint32 bufferIndex) const; protected: Context& m_context; const VkDevice m_device; const DeviceInterface& m_vkd; const VkQueue m_queue; const deUint32 m_queueFamilyIndex; Allocator& m_allocator; // \note All VkCommandBuffers are allocated from m_commandPool so there is no need // to free them separately as the auto-generated dtor will do that through // destroying the pool. Move<VkCommandPool> m_commandPool; VkCommandBuffer m_primaryCommandBuffers[NumBuffers]; }; template <deUint32 NumBuffers> CommandBufferBareTestEnvironment<NumBuffers>::CommandBufferBareTestEnvironment(Context& context, VkCommandPoolCreateFlags commandPoolCreateFlags) : m_context (context) , m_device (context.getDevice()) , m_vkd (context.getDeviceInterface()) , m_queue (context.getUniversalQueue()) , m_queueFamilyIndex (context.getUniversalQueueFamilyIndex()) , m_allocator (context.getDefaultAllocator()) { m_commandPool = createCommandPool(m_vkd, m_device, commandPoolCreateFlags, m_queueFamilyIndex); const VkCommandBufferAllocateInfo cmdBufferAllocateInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *m_commandPool, // VkCommandPool commandPool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; NumBuffers // deUint32 commandBufferCount; }; VK_CHECK(m_vkd.allocateCommandBuffers(m_device, &cmdBufferAllocateInfo, m_primaryCommandBuffers)); } template <deUint32 NumBuffers> VkCommandBuffer CommandBufferBareTestEnvironment<NumBuffers>::getCommandBuffer(deUint32 bufferIndex) const { DE_ASSERT(bufferIndex < NumBuffers); return m_primaryCommandBuffers[bufferIndex]; } class CommandBufferRenderPassTestEnvironment : public CommandBufferBareTestEnvironment<1> { public: CommandBufferRenderPassTestEnvironment (Context& context, VkCommandPoolCreateFlags commandPoolCreateFlags); VkRenderPass getRenderPass (void) const { return *m_renderPass; } VkFramebuffer getFrameBuffer (void) const { return *m_frameBuffer; } VkCommandBuffer getPrimaryCommandBuffer (void) const { return getCommandBuffer(0); } VkCommandBuffer getSecondaryCommandBuffer (void) const { return *m_secondaryCommandBuffer; } void beginPrimaryCommandBuffer (VkCommandBufferUsageFlags usageFlags); void beginSecondaryCommandBuffer (VkCommandBufferUsageFlags usageFlags); void beginRenderPass (VkSubpassContents content); void submitPrimaryCommandBuffer (void); de::MovePtr<tcu::TextureLevel> readColorAttachment (void); static const VkImageType DEFAULT_IMAGE_TYPE; static const VkFormat DEFAULT_IMAGE_FORMAT; static const VkExtent3D DEFAULT_IMAGE_SIZE; static const VkRect2D DEFAULT_IMAGE_AREA; protected: Move<VkImage> m_colorImage; Move<VkImageView> m_colorImageView; Move<VkRenderPass> m_renderPass; Move<VkFramebuffer> m_frameBuffer; de::MovePtr<Allocation> m_colorImageMemory; Move<VkCommandBuffer> m_secondaryCommandBuffer; }; const VkImageType CommandBufferRenderPassTestEnvironment::DEFAULT_IMAGE_TYPE = VK_IMAGE_TYPE_2D; const VkFormat CommandBufferRenderPassTestEnvironment::DEFAULT_IMAGE_FORMAT = VK_FORMAT_R8G8B8A8_UINT; const VkExtent3D CommandBufferRenderPassTestEnvironment::DEFAULT_IMAGE_SIZE = {255, 255, 1}; const VkRect2D CommandBufferRenderPassTestEnvironment::DEFAULT_IMAGE_AREA = { { 0u, 0u, }, // VkOffset2D offset; { DEFAULT_IMAGE_SIZE.width, DEFAULT_IMAGE_SIZE.height }, // VkExtent2D extent; }; CommandBufferRenderPassTestEnvironment::CommandBufferRenderPassTestEnvironment(Context& context, VkCommandPoolCreateFlags commandPoolCreateFlags) : CommandBufferBareTestEnvironment<1> (context, commandPoolCreateFlags) { m_renderPass = makeRenderPass(m_vkd, m_device, DEFAULT_IMAGE_FORMAT); { const VkImageCreateInfo imageCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkImageCreateFlags flags; DEFAULT_IMAGE_TYPE, // VkImageType imageType; DEFAULT_IMAGE_FORMAT, // VkFormat format; DEFAULT_IMAGE_SIZE, // VkExtent3D extent; 1, // deUint32 mipLevels; 1, // deUint32 arrayLayers; VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples; VK_IMAGE_TILING_OPTIMAL, // VkImageTiling tiling; VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, // VkImageUsageFlags usage; VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode; 1, // deUint32 queueFamilyIndexCount; &m_queueFamilyIndex, // const deUint32* pQueueFamilyIndices; VK_IMAGE_LAYOUT_UNDEFINED // VkImageLayout initialLayout; }; m_colorImage = createImage(m_vkd, m_device, &imageCreateInfo, DE_NULL); } m_colorImageMemory = m_allocator.allocate(getImageMemoryRequirements(m_vkd, m_device, *m_colorImage), MemoryRequirement::Any); VK_CHECK(m_vkd.bindImageMemory(m_device, *m_colorImage, m_colorImageMemory->getMemory(), m_colorImageMemory->getOffset())); { const VkImageViewCreateInfo imageViewCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkImageViewCreateFlags flags; *m_colorImage, // VkImage image; VK_IMAGE_VIEW_TYPE_2D, // VkImageViewType viewType; DEFAULT_IMAGE_FORMAT, // VkFormat format; { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A }, // VkComponentMapping components; { VK_IMAGE_ASPECT_COLOR_BIT, // VkImageAspectFlags aspectMask; 0u, // deUint32 baseMipLevel; 1u, // deUint32 mipLevels; 0u, // deUint32 baseArrayLayer; 1u, // deUint32 arraySize; }, // VkImageSubresourceRange subresourceRange; }; m_colorImageView = createImageView(m_vkd, m_device, &imageViewCreateInfo, DE_NULL); } { const VkImageView attachmentViews[1] = { *m_colorImageView }; const VkFramebufferCreateInfo framebufferCreateInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkFramebufferCreateFlags flags; *m_renderPass, // VkRenderPass renderPass; 1, // deUint32 attachmentCount; attachmentViews, // const VkImageView* pAttachments; DEFAULT_IMAGE_SIZE.width, // deUint32 width; DEFAULT_IMAGE_SIZE.height, // deUint32 height; 1u, // deUint32 layers; }; m_frameBuffer = createFramebuffer(m_vkd, m_device, &framebufferCreateInfo, DE_NULL); } { const VkCommandBufferAllocateInfo cmdBufferAllocateInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *m_commandPool, // VkCommandPool commandPool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // VkCommandBufferLevel level; 1u // deUint32 commandBufferCount; }; m_secondaryCommandBuffer = allocateCommandBuffer(m_vkd, m_device, &cmdBufferAllocateInfo); } } void CommandBufferRenderPassTestEnvironment::beginRenderPass(VkSubpassContents content) { vk::beginRenderPass(m_vkd, m_primaryCommandBuffers[0], *m_renderPass, *m_frameBuffer, DEFAULT_IMAGE_AREA, tcu::UVec4(17, 59, 163, 251), content); } void CommandBufferRenderPassTestEnvironment::beginPrimaryCommandBuffer(VkCommandBufferUsageFlags usageFlags) { beginCommandBuffer(m_vkd, m_primaryCommandBuffers[0], usageFlags); } void CommandBufferRenderPassTestEnvironment::beginSecondaryCommandBuffer(VkCommandBufferUsageFlags usageFlags) { const VkCommandBufferInheritanceInfo commandBufferInheritanceInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *m_renderPass, // VkRenderPass renderPass; 0u, // deUint32 subpass; *m_frameBuffer, // VkFramebuffer framebuffer; VK_FALSE, // VkBool32 occlusionQueryEnable; 0u, // VkQueryControlFlags queryFlags; 0u // VkQueryPipelineStatisticFlags pipelineStatistics; }; const VkCommandBufferBeginInfo commandBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; usageFlags, // VkCommandBufferUsageFlags flags; &commandBufferInheritanceInfo // const VkCommandBufferInheritanceInfo* pInheritanceInfo; }; VK_CHECK(m_vkd.beginCommandBuffer(*m_secondaryCommandBuffer, &commandBufferBeginInfo)); } void CommandBufferRenderPassTestEnvironment::submitPrimaryCommandBuffer(void) { submitCommandsAndWait(m_vkd, m_device, m_queue, *m_primaryCommandBuffers); } de::MovePtr<tcu::TextureLevel> CommandBufferRenderPassTestEnvironment::readColorAttachment () { Move<VkBuffer> buffer; de::MovePtr<Allocation> bufferAlloc; const tcu::TextureFormat tcuFormat = mapVkFormat(DEFAULT_IMAGE_FORMAT); const VkDeviceSize pixelDataSize = DEFAULT_IMAGE_SIZE.height * DEFAULT_IMAGE_SIZE.height * tcuFormat.getPixelSize(); de::MovePtr<tcu::TextureLevel> resultLevel (new tcu::TextureLevel(tcuFormat, DEFAULT_IMAGE_SIZE.width, DEFAULT_IMAGE_SIZE.height)); // Create destination buffer { const VkBufferCreateInfo bufferParams = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkBufferCreateFlags flags; pixelDataSize, // VkDeviceSize size; VK_BUFFER_USAGE_TRANSFER_DST_BIT, // VkBufferUsageFlags usage; VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode; 0u, // deUint32 queueFamilyIndexCount; DE_NULL // const deUint32* pQueueFamilyIndices; }; buffer = createBuffer(m_vkd, m_device, &bufferParams); bufferAlloc = m_allocator.allocate(getBufferMemoryRequirements(m_vkd, m_device, *buffer), MemoryRequirement::HostVisible); VK_CHECK(m_vkd.bindBufferMemory(m_device, *buffer, bufferAlloc->getMemory(), bufferAlloc->getOffset())); } // Barriers for copying image to buffer const VkImageMemoryBarrier imageBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType; DE_NULL, // const void* pNext; VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags srcAccessMask; VK_ACCESS_TRANSFER_READ_BIT, // VkAccessFlags dstAccessMask; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout oldLayout; VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, // VkImageLayout newLayout; VK_QUEUE_FAMILY_IGNORED, // deUint32 srcQueueFamilyIndex; VK_QUEUE_FAMILY_IGNORED, // deUint32 dstQueueFamilyIndex; *m_colorImage, // VkImage image; { // VkImageSubresourceRange subresourceRange; VK_IMAGE_ASPECT_COLOR_BIT, // VkImageAspectFlags aspectMask; 0u, // deUint32 baseMipLevel; 1u, // deUint32 mipLevels; 0u, // deUint32 baseArraySlice; 1u // deUint32 arraySize; } }; const VkBufferMemoryBarrier bufferBarrier = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, // VkStructureType sType; DE_NULL, // const void* pNext; VK_ACCESS_TRANSFER_WRITE_BIT, // VkAccessFlags srcAccessMask; VK_ACCESS_HOST_READ_BIT, // VkAccessFlags dstAccessMask; VK_QUEUE_FAMILY_IGNORED, // deUint32 srcQueueFamilyIndex; VK_QUEUE_FAMILY_IGNORED, // deUint32 dstQueueFamilyIndex; *buffer, // VkBuffer buffer; 0u, // VkDeviceSize offset; pixelDataSize // VkDeviceSize size; }; // Copy image to buffer const VkBufferImageCopy copyRegion = { 0u, // VkDeviceSize bufferOffset; DEFAULT_IMAGE_SIZE.width, // deUint32 bufferRowLength; DEFAULT_IMAGE_SIZE.height, // deUint32 bufferImageHeight; { VK_IMAGE_ASPECT_COLOR_BIT, 0u, 0u, 1u }, // VkImageSubresourceLayers imageSubresource; { 0, 0, 0 }, // VkOffset3D imageOffset; DEFAULT_IMAGE_SIZE // VkExtent3D imageExtent; }; beginPrimaryCommandBuffer(0); m_vkd.cmdPipelineBarrier(m_primaryCommandBuffers[0], VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &imageBarrier); m_vkd.cmdCopyImageToBuffer(m_primaryCommandBuffers[0], *m_colorImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, *buffer, 1, &copyRegion); m_vkd.cmdPipelineBarrier(m_primaryCommandBuffers[0], VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &bufferBarrier, 0, (const VkImageMemoryBarrier*)DE_NULL); endCommandBuffer(m_vkd, m_primaryCommandBuffers[0]); submitPrimaryCommandBuffer(); // Read buffer data invalidateMappedMemoryRange(m_vkd, m_device, bufferAlloc->getMemory(), bufferAlloc->getOffset(), pixelDataSize); tcu::copy(*resultLevel, tcu::ConstPixelBufferAccess(resultLevel->getFormat(), resultLevel->getSize(), bufferAlloc->getHostPtr())); return resultLevel; } // Testcases /********* 19.1. Command Pools (5.1 in VK 1.0 Spec) ***************************/ tcu::TestStatus createPoolNullParamsTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); createCommandPool(vk, vkDevice, 0u, queueFamilyIndex); return tcu::TestStatus::pass("Command Pool allocated correctly."); } tcu::TestStatus createPoolNonNullAllocatorTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkAllocationCallbacks* allocationCallbacks = getSystemAllocator(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; 0u, // flags; queueFamilyIndex, // queueFamilyIndex; }; createCommandPool(vk, vkDevice, &cmdPoolParams, allocationCallbacks); return tcu::TestStatus::pass("Command Pool allocated correctly."); } tcu::TestStatus createPoolTransientBitTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, // flags; queueFamilyIndex, // queueFamilyIndex; }; createCommandPool(vk, vkDevice, &cmdPoolParams, DE_NULL); return tcu::TestStatus::pass("Command Pool allocated correctly."); } tcu::TestStatus createPoolResetBitTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // flags; queueFamilyIndex, // queueFamilyIndex; }; createCommandPool(vk, vkDevice, &cmdPoolParams, DE_NULL); return tcu::TestStatus::pass("Command Pool allocated correctly."); } tcu::TestStatus resetPoolReleaseResourcesBitTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; 0u, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams, DE_NULL)); VK_CHECK(vk.resetCommandPool(vkDevice, *cmdPool, VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT)); return tcu::TestStatus::pass("Command Pool allocated correctly."); } tcu::TestStatus resetPoolNoFlagsTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; 0u, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams, DE_NULL)); VK_CHECK(vk.resetCommandPool(vkDevice, *cmdPool, 0u)); return tcu::TestStatus::pass("Command Pool allocated correctly."); } bool executeCommandBuffer (const VkDevice device, const DeviceInterface& vk, const VkQueue queue, const VkCommandBuffer commandBuffer, const bool exitBeforeEndCommandBuffer = false) { const Unique<VkEvent> event (createEvent(vk, device)); beginCommandBuffer(vk, commandBuffer, 0u); { const VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; vk.cmdSetEvent(commandBuffer, *event, stageMask); if (exitBeforeEndCommandBuffer) return exitBeforeEndCommandBuffer; } endCommandBuffer(vk, commandBuffer); submitCommandsAndWait(vk, device, queue, commandBuffer); // check if buffer has been executed const VkResult result = vk.getEventStatus(device, *event); return result == VK_EVENT_SET; } tcu::TestStatus resetPoolReuseTest (Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkQueue queue = context.getUniversalQueue(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; 0u, // flags; queueFamilyIndex // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams, DE_NULL)); const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // commandPool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level; 1u // bufferCount; }; const Move<VkCommandBuffer> commandBuffers[] = { allocateCommandBuffer(vk, vkDevice, &cmdBufParams), allocateCommandBuffer(vk, vkDevice, &cmdBufParams) }; if (!executeCommandBuffer(vkDevice, vk, queue, *(commandBuffers[0]))) return tcu::TestStatus::fail("Failed"); if (!executeCommandBuffer(vkDevice, vk, queue, *(commandBuffers[1]), true)) return tcu::TestStatus::fail("Failed"); VK_CHECK(vk.resetCommandPool(vkDevice, *cmdPool, VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT)); if (!executeCommandBuffer(vkDevice, vk, queue, *(commandBuffers[0]))) return tcu::TestStatus::fail("Failed"); if (!executeCommandBuffer(vkDevice, vk, queue, *(commandBuffers[1]))) return tcu::TestStatus::fail("Failed"); { const Unique<VkCommandBuffer> afterResetCommandBuffers(allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); if (!executeCommandBuffer(vkDevice, vk, queue, *afterResetCommandBuffers)) return tcu::TestStatus::fail("Failed"); } return tcu::TestStatus::pass("Passed"); } /******** 19.2. Command Buffer Lifetime (5.2 in VK 1.0 Spec) ******************/ tcu::TestStatus allocatePrimaryBufferTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // commandPool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level; 1u, // bufferCount; }; const Unique<VkCommandBuffer> cmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); return tcu::TestStatus::pass("Buffer was created correctly."); } tcu::TestStatus allocateManyPrimaryBuffersTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // \todo Determining the minimum number of command buffers should be a function of available system memory and driver capabilities. #if (DE_PTR_SIZE == 4) const unsigned minCommandBuffer = 1024; #else const unsigned minCommandBuffer = 10000; #endif // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; minCommandBuffer, // uint32_t bufferCount; }; // do not keep the handles to buffers, as they will be freed with command pool // allocate the minimum required amount of buffers VkCommandBuffer cmdBuffers[minCommandBuffer]; VK_CHECK(vk.allocateCommandBuffers(vkDevice, &cmdBufParams, cmdBuffers)); std::ostringstream out; out << "allocateManyPrimaryBuffersTest succeded: created " << minCommandBuffer << " command buffers"; return tcu::TestStatus::pass(out.str()); } tcu::TestStatus allocateSecondaryBufferTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // commandPool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // level; 1u, // bufferCount; }; const Unique<VkCommandBuffer> cmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); return tcu::TestStatus::pass("Buffer was created correctly."); } tcu::TestStatus allocateManySecondaryBuffersTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // \todo Determining the minimum number of command buffers should be a function of available system memory and driver capabilities. #if (DE_PTR_SIZE == 4) const unsigned minCommandBuffer = 1024; #else const unsigned minCommandBuffer = 10000; #endif // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // VkCommandBufferLevel level; minCommandBuffer, // uint32_t bufferCount; }; // do not keep the handles to buffers, as they will be freed with command pool // allocate the minimum required amount of buffers VkCommandBuffer cmdBuffers[minCommandBuffer]; VK_CHECK(vk.allocateCommandBuffers(vkDevice, &cmdBufParams, cmdBuffers)); std::ostringstream out; out << "allocateManySecondaryBuffersTest succeded: created " << minCommandBuffer << " command buffers"; return tcu::TestStatus::pass(out.str()); } tcu::TestStatus executePrimaryBufferTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); // create event that will be used to check if secondary command buffer has been executed const Unique<VkEvent> event (createEvent(vk, vkDevice)); // reset event VK_CHECK(vk.resetEvent(vkDevice, *event)); // record primary command buffer beginCommandBuffer(vk, *primCmdBuf, 0u); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // record setting event vk.cmdSetEvent(*primCmdBuf, *event,stageMask); } endCommandBuffer(vk, *primCmdBuf); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf.get()); // check if buffer has been executed VkResult result = vk.getEventStatus(vkDevice,*event); if (result == VK_EVENT_SET) return tcu::TestStatus::pass("Execute Primary Command Buffer succeeded"); return tcu::TestStatus::fail("Execute Primary Command Buffer FAILED"); } tcu::TestStatus executeLargePrimaryBufferTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const deUint32 LARGE_BUFFER_SIZE = 10000; const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); std::vector<VkEventSp> events; for (deUint32 ndx = 0; ndx < LARGE_BUFFER_SIZE; ++ndx) events.push_back(VkEventSp(new vk::Unique<VkEvent>(createEvent(vk, vkDevice)))); // record primary command buffer beginCommandBuffer(vk, *primCmdBuf, 0u); { // set all the events for (deUint32 ndx = 0; ndx < LARGE_BUFFER_SIZE; ++ndx) { vk.cmdSetEvent(*primCmdBuf, events[ndx]->get(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); } } endCommandBuffer(vk, *primCmdBuf); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf.get()); // check if the buffer was executed correctly - all events had their status // changed tcu::TestStatus testResult = tcu::TestStatus::incomplete(); for (deUint32 ndx = 0; ndx < LARGE_BUFFER_SIZE; ++ndx) { if (vk.getEventStatus(vkDevice, events[ndx]->get()) != VK_EVENT_SET) { testResult = tcu::TestStatus::fail("An event was not set."); break; } } if (!testResult.isComplete()) testResult = tcu::TestStatus::pass("All events set correctly."); return testResult; } tcu::TestStatus resetBufferImplicitlyTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level; 1u, // bufferCount; }; const Unique<VkCommandBuffer> cmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); const Unique<VkEvent> event (createEvent(vk, vkDevice)); // Put the command buffer in recording state. beginCommandBuffer(vk, *cmdBuf, 0u); { // Set the event vk.cmdSetEvent(*cmdBuf, *event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); } endCommandBuffer(vk, *cmdBuf); submitCommandsAndWait(vk, vkDevice, queue, cmdBuf.get()); // Check if the buffer was executed if (vk.getEventStatus(vkDevice, *event) != VK_EVENT_SET) return tcu::TestStatus::fail("Failed to set the event."); // Reset the event vk.resetEvent(vkDevice, *event); if(vk.getEventStatus(vkDevice, *event) != VK_EVENT_RESET) return tcu::TestStatus::fail("Failed to reset the event."); // Reset the command buffer by putting it in recording state again. This // should empty the command buffer. beginCommandBuffer(vk, *cmdBuf, 0u); endCommandBuffer(vk, *cmdBuf); // Submit the command buffer after resetting. It should have no commands // recorded, so the event should remain unsignaled. submitCommandsAndWait(vk, vkDevice, queue, cmdBuf.get()); // Check if the event remained unset. if(vk.getEventStatus(vkDevice, *event) == VK_EVENT_RESET) return tcu::TestStatus::pass("Buffer was reset correctly."); else return tcu::TestStatus::fail("Buffer was not reset correctly."); } using de::SharedPtr; typedef SharedPtr<Unique<VkEvent> > VkEventShared; template<typename T> inline SharedPtr<Unique<T> > makeSharedPtr (Move<T> move) { return SharedPtr<Unique<T> >(new Unique<T>(move)); } bool submitAndCheck (Context& context, std::vector<VkCommandBuffer>& cmdBuffers, std::vector <VkEventShared>& events) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const Unique<VkFence> fence (createFence(vk, vkDevice)); const VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores (const VkPipelineStageFlags*)DE_NULL, // pWaitDstStageMask static_cast<deUint32>(cmdBuffers.size()), // commandBufferCount &cmdBuffers[0], // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, fence.get())); VK_CHECK(vk.waitForFences(vkDevice, 1u, &fence.get(), 0u, INFINITE_TIMEOUT)); for(int eventNdx = 0; eventNdx < static_cast<int>(events.size()); ++eventNdx) { if (vk.getEventStatus(vkDevice, **events[eventNdx]) != VK_EVENT_SET) return false; vk.resetEvent(vkDevice, **events[eventNdx]); } return true; } void createCommadBuffers (const DeviceInterface& vk, const VkDevice vkDevice, deUint32 bufferCount, VkCommandPool pool, const VkCommandBufferLevel cmdBufferLevel, VkCommandBuffer* pCommandBuffers) { const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; pool, // VkCommandPool pool; cmdBufferLevel, // VkCommandBufferLevel level; bufferCount, // uint32_t bufferCount; }; VK_CHECK(vk.allocateCommandBuffers(vkDevice, &cmdBufParams, pCommandBuffers)); } void addCommandsToBuffer (const DeviceInterface& vk, std::vector<VkCommandBuffer>& cmdBuffers, std::vector <VkEventShared>& events) { const VkCommandBufferInheritanceInfo secCmdBufInheritInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, DE_NULL, (VkRenderPass)0u, // renderPass 0u, // subpass (VkFramebuffer)0u, // framebuffer VK_FALSE, // occlusionQueryEnable (VkQueryControlFlags)0u, // queryFlags (VkQueryPipelineStatisticFlags)0u, // pipelineStatistics }; const VkCommandBufferBeginInfo cmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags &secCmdBufInheritInfo, // pInheritanceInfo; }; for(int bufferNdx = 0; bufferNdx < static_cast<int>(cmdBuffers.size()); ++bufferNdx) { VK_CHECK(vk.beginCommandBuffer(cmdBuffers[bufferNdx], &cmdBufBeginInfo)); vk.cmdSetEvent(cmdBuffers[bufferNdx], **events[bufferNdx % events.size()], VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); endCommandBuffer(vk, cmdBuffers[bufferNdx]); } } bool executeSecondaryCmdBuffer (Context& context, VkCommandPool pool, std::vector<VkCommandBuffer>& cmdBuffersSecondary, std::vector <VkEventShared>& events) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); std::vector<VkCommandBuffer> cmdBuffer (1); createCommadBuffers(vk, vkDevice, 1u, pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, &cmdBuffer[0]); beginCommandBuffer(vk, cmdBuffer[0], 0u); vk.cmdExecuteCommands(cmdBuffer[0], static_cast<deUint32>(cmdBuffersSecondary.size()), &cmdBuffersSecondary[0]); endCommandBuffer(vk, cmdBuffer[0]); bool returnValue = submitAndCheck(context, cmdBuffer, events); vk.freeCommandBuffers(vkDevice, pool, 1u, &cmdBuffer[0]); return returnValue; } tcu::TestStatus trimCommandPoolTest (Context& context, const VkCommandBufferLevel cmdBufferLevel) { if (!isDeviceExtensionSupported(context.getUsedApiVersion(), context.getDeviceExtensions(), "VK_KHR_maintenance1")) TCU_THROW(NotSupportedError, "Extension VK_KHR_maintenance1 not supported"); const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); //test parameters const deUint32 cmdBufferIterationCount = 300u; const deUint32 cmdBufferCount = 10u; const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); std::vector <VkEventShared> events; for (deUint32 ndx = 0u; ndx < cmdBufferCount; ++ndx) events.push_back(makeSharedPtr(createEvent(vk, vkDevice))); { std::vector<VkCommandBuffer> cmdBuffers(cmdBufferCount); createCommadBuffers(vk, vkDevice, cmdBufferCount, *cmdPool, cmdBufferLevel, &cmdBuffers[0]); for (deUint32 cmdBufferIterationrNdx = 0; cmdBufferIterationrNdx < cmdBufferIterationCount; ++cmdBufferIterationrNdx) { addCommandsToBuffer(vk, cmdBuffers, events); //Peak, situation when we use a lot more command buffers if (cmdBufferIterationrNdx % 10u == 0) { std::vector<VkCommandBuffer> cmdBuffersPeak(cmdBufferCount * 10u); createCommadBuffers(vk, vkDevice, static_cast<deUint32>(cmdBuffersPeak.size()), *cmdPool, cmdBufferLevel, &cmdBuffersPeak[0]); addCommandsToBuffer(vk, cmdBuffersPeak, events); switch(cmdBufferLevel) { case VK_COMMAND_BUFFER_LEVEL_PRIMARY: if (!submitAndCheck(context, cmdBuffersPeak, events)) return tcu::TestStatus::fail("Fail"); break; case VK_COMMAND_BUFFER_LEVEL_SECONDARY: if (!executeSecondaryCmdBuffer(context, *cmdPool, cmdBuffersPeak, events)) return tcu::TestStatus::fail("Fail"); break; default: DE_ASSERT(0); } vk.freeCommandBuffers(vkDevice, *cmdPool, static_cast<deUint32>(cmdBuffersPeak.size()), &cmdBuffersPeak[0]); } vk.trimCommandPool(vkDevice, *cmdPool, (VkCommandPoolTrimFlags)0); switch(cmdBufferLevel) { case VK_COMMAND_BUFFER_LEVEL_PRIMARY: if (!submitAndCheck(context, cmdBuffers, events)) return tcu::TestStatus::fail("Fail"); break; case VK_COMMAND_BUFFER_LEVEL_SECONDARY: if (!executeSecondaryCmdBuffer(context, *cmdPool, cmdBuffers, events)) return tcu::TestStatus::fail("Fail"); break; default: DE_ASSERT(0); } for (deUint32 bufferNdx = cmdBufferIterationrNdx % 3u; bufferNdx < cmdBufferCount; bufferNdx+=2u) { vk.freeCommandBuffers(vkDevice, *cmdPool, 1u, &cmdBuffers[bufferNdx]); createCommadBuffers(vk, vkDevice, 1u, *cmdPool, cmdBufferLevel, &cmdBuffers[bufferNdx]); } } } return tcu::TestStatus::pass("Pass"); } /******** 19.3. Command Buffer Recording (5.3 in VK 1.0 Spec) *****************/ tcu::TestStatus recordSinglePrimaryBufferTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); // create event that will be used to check if secondary command buffer has been executed const Unique<VkEvent> event (createEvent(vk, vkDevice)); // record primary command buffer beginCommandBuffer(vk, *primCmdBuf, 0u); { // record setting event vk.cmdSetEvent(*primCmdBuf, *event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); } endCommandBuffer(vk, *primCmdBuf); return tcu::TestStatus::pass("Primary buffer recorded successfully."); } tcu::TestStatus recordLargePrimaryBufferTest(Context &context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); // create event that will be used to check if secondary command buffer has been executed const Unique<VkEvent> event (createEvent(vk, vkDevice)); // reset event VK_CHECK(vk.resetEvent(vkDevice, *event)); // record primary command buffer beginCommandBuffer(vk, *primCmdBuf, 0u); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // define minimal amount of commands to accept const long long unsigned minNumCommands = 10000llu; for ( long long unsigned currentCommands = 0; currentCommands < minNumCommands / 2; ++currentCommands ) { // record setting event vk.cmdSetEvent(*primCmdBuf, *event,stageMask); // record resetting event vk.cmdResetEvent(*primCmdBuf, *event,stageMask); }; } endCommandBuffer(vk, *primCmdBuf); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf.get()); return tcu::TestStatus::pass("hugeTest succeeded"); } tcu::TestStatus recordSingleSecondaryBufferTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> secCmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); const VkCommandBufferInheritanceInfo secCmdBufInheritInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, DE_NULL, (VkRenderPass)0u, // renderPass 0u, // subpass (VkFramebuffer)0u, // framebuffer VK_FALSE, // occlusionQueryEnable (VkQueryControlFlags)0u, // queryFlags (VkQueryPipelineStatisticFlags)0u, // pipelineStatistics }; const VkCommandBufferBeginInfo secCmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, DE_NULL, 0, // flags &secCmdBufInheritInfo, }; // create event that will be used to check if secondary command buffer has been executed const Unique<VkEvent> event (createEvent(vk, vkDevice)); // record primary command buffer VK_CHECK(vk.beginCommandBuffer(*secCmdBuf, &secCmdBufBeginInfo)); { // record setting event vk.cmdSetEvent(*secCmdBuf, *event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); } endCommandBuffer(vk, *secCmdBuf); return tcu::TestStatus::pass("Secondary buffer recorded successfully."); } tcu::TestStatus recordLargeSecondaryBufferTest(Context &context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); // create event that will be used to check if secondary command buffer has been executed const Unique<VkEvent> event (createEvent(vk, vkDevice)); // reset event VK_CHECK(vk.resetEvent(vkDevice, *event)); // record primary command buffer beginCommandBuffer(vk, *primCmdBuf, 0u); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // define minimal amount of commands to accept const long long unsigned minNumCommands = 10000llu; for ( long long unsigned currentCommands = 0; currentCommands < minNumCommands / 2; ++currentCommands ) { // record setting event vk.cmdSetEvent(*primCmdBuf, *event,stageMask); // record resetting event vk.cmdResetEvent(*primCmdBuf, *event,stageMask); }; } endCommandBuffer(vk, *primCmdBuf); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf.get()); return tcu::TestStatus::pass("hugeTest succeeded"); } tcu::TestStatus submitPrimaryBufferTwiceTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); // create event that will be used to check if secondary command buffer has been executed const Unique<VkEvent> event (createEvent(vk, vkDevice)); // reset event VK_CHECK(vk.resetEvent(vkDevice, *event)); // record primary command buffer beginCommandBuffer(vk, *primCmdBuf, 0u); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // record setting event vk.cmdSetEvent(*primCmdBuf, *event,stageMask); } endCommandBuffer(vk, *primCmdBuf); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf.get()); // check if buffer has been executed VkResult result = vk.getEventStatus(vkDevice,*event); if (result != VK_EVENT_SET) return tcu::TestStatus::fail("Submit Twice Test FAILED"); // reset event VK_CHECK(vk.resetEvent(vkDevice, *event)); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf.get()); // check if buffer has been executed result = vk.getEventStatus(vkDevice,*event); if (result != VK_EVENT_SET) return tcu::TestStatus::fail("Submit Twice Test FAILED"); else return tcu::TestStatus::pass("Submit Twice Test succeeded"); } tcu::TestStatus submitSecondaryBufferTwiceTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> primCmdBuf1 (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); const Unique<VkCommandBuffer> primCmdBuf2 (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); // Secondary Command buffer const VkCommandBufferAllocateInfo secCmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> secCmdBuf (allocateCommandBuffer(vk, vkDevice, &secCmdBufParams)); const VkCommandBufferInheritanceInfo secCmdBufInheritInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, DE_NULL, (VkRenderPass)0u, // renderPass 0u, // subpass (VkFramebuffer)0u, // framebuffer VK_FALSE, // occlusionQueryEnable (VkQueryControlFlags)0u, // queryFlags (VkQueryPipelineStatisticFlags)0u, // pipelineStatistics }; const VkCommandBufferBeginInfo secCmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, DE_NULL, 0u, // flags &secCmdBufInheritInfo, }; // create event that will be used to check if secondary command buffer has been executed const Unique<VkEvent> event (createEvent(vk, vkDevice)); // reset event VK_CHECK(vk.resetEvent(vkDevice, *event)); // record first primary command buffer beginCommandBuffer(vk, *primCmdBuf1, 0u); { // record secondary command buffer VK_CHECK(vk.beginCommandBuffer(*secCmdBuf, &secCmdBufBeginInfo)); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // record setting event vk.cmdSetEvent(*secCmdBuf, *event,stageMask); } // end recording of secondary buffers endCommandBuffer(vk, *secCmdBuf); // execute secondary buffer vk.cmdExecuteCommands(*primCmdBuf1, 1, &secCmdBuf.get()); } endCommandBuffer(vk, *primCmdBuf1); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf1.get()); // check if secondary buffer has been executed VkResult result = vk.getEventStatus(vkDevice,*event); if (result != VK_EVENT_SET) return tcu::TestStatus::fail("Submit Twice Secondary Command Buffer FAILED"); // reset first primary buffer vk.resetCommandBuffer( *primCmdBuf1, 0u); // reset event to allow receiving it again VK_CHECK(vk.resetEvent(vkDevice, *event)); // record second primary command buffer beginCommandBuffer(vk, *primCmdBuf2, 0u); { // execute secondary buffer vk.cmdExecuteCommands(*primCmdBuf2, 1, &secCmdBuf.get()); } // end recording endCommandBuffer(vk, *primCmdBuf2); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf2.get()); // check if secondary buffer has been executed result = vk.getEventStatus(vkDevice,*event); if (result != VK_EVENT_SET) return tcu::TestStatus::fail("Submit Twice Secondary Command Buffer FAILED"); else return tcu::TestStatus::pass("Submit Twice Secondary Command Buffer succeeded"); } tcu::TestStatus oneTimeSubmitFlagPrimaryBufferTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); // create event that will be used to check if secondary command buffer has been executed const Unique<VkEvent> event (createEvent(vk, vkDevice)); // reset event VK_CHECK(vk.resetEvent(vkDevice, *event)); // record primary command buffer beginCommandBuffer(vk, *primCmdBuf); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // record setting event vk.cmdSetEvent(*primCmdBuf, *event,stageMask); } endCommandBuffer(vk, *primCmdBuf); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf.get()); // check if buffer has been executed VkResult result = vk.getEventStatus(vkDevice,*event); if (result != VK_EVENT_SET) return tcu::TestStatus::fail("oneTimeSubmitFlagPrimaryBufferTest FAILED"); // record primary command buffer again - implicit reset because of VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT beginCommandBuffer(vk, *primCmdBuf); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // record setting event vk.cmdSetEvent(*primCmdBuf, *event,stageMask); } endCommandBuffer(vk, *primCmdBuf); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf.get()); // check if buffer has been executed result = vk.getEventStatus(vkDevice,*event); if (result != VK_EVENT_SET) return tcu::TestStatus::fail("oneTimeSubmitFlagPrimaryBufferTest FAILED"); else return tcu::TestStatus::pass("oneTimeSubmitFlagPrimaryBufferTest succeeded"); } tcu::TestStatus oneTimeSubmitFlagSecondaryBufferTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> primCmdBuf1 (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); const Unique<VkCommandBuffer> primCmdBuf2 (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); // Secondary Command buffer const VkCommandBufferAllocateInfo secCmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> secCmdBuf (allocateCommandBuffer(vk, vkDevice, &secCmdBufParams)); const VkCommandBufferInheritanceInfo secCmdBufInheritInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, DE_NULL, (VkRenderPass)0u, // renderPass 0u, // subpass (VkFramebuffer)0u, // framebuffer VK_FALSE, // occlusionQueryEnable (VkQueryControlFlags)0u, // queryFlags (VkQueryPipelineStatisticFlags)0u, // pipelineStatistics }; const VkCommandBufferBeginInfo secCmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, DE_NULL, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, // flags &secCmdBufInheritInfo, }; // create event that will be used to check if secondary command buffer has been executed const Unique<VkEvent> event (createEvent(vk, vkDevice)); // reset event VK_CHECK(vk.resetEvent(vkDevice, *event)); // record first primary command buffer beginCommandBuffer(vk, *primCmdBuf1, 0u); { // record secondary command buffer VK_CHECK(vk.beginCommandBuffer(*secCmdBuf, &secCmdBufBeginInfo)); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // record setting event vk.cmdSetEvent(*secCmdBuf, *event,stageMask); } // end recording of secondary buffers endCommandBuffer(vk, *secCmdBuf); // execute secondary buffer vk.cmdExecuteCommands(*primCmdBuf1, 1, &secCmdBuf.get()); } endCommandBuffer(vk, *primCmdBuf1); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf1.get()); // check if secondary buffer has been executed VkResult result = vk.getEventStatus(vkDevice,*event); if (result != VK_EVENT_SET) return tcu::TestStatus::fail("Submit Twice Secondary Command Buffer FAILED"); // reset first primary buffer vk.resetCommandBuffer( *primCmdBuf1, 0u); // reset event to allow receiving it again VK_CHECK(vk.resetEvent(vkDevice, *event)); // record secondary command buffer again VK_CHECK(vk.beginCommandBuffer(*secCmdBuf, &secCmdBufBeginInfo)); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // record setting event vk.cmdSetEvent(*secCmdBuf, *event,stageMask); } // end recording of secondary buffers endCommandBuffer(vk, *secCmdBuf); // record second primary command buffer beginCommandBuffer(vk, *primCmdBuf2, 0u); { // execute secondary buffer vk.cmdExecuteCommands(*primCmdBuf2, 1, &secCmdBuf.get()); } // end recording endCommandBuffer(vk, *primCmdBuf2); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf2.get()); // check if secondary buffer has been executed result = vk.getEventStatus(vkDevice,*event); if (result != VK_EVENT_SET) return tcu::TestStatus::fail("oneTimeSubmitFlagSecondaryBufferTest FAILED"); else return tcu::TestStatus::pass("oneTimeSubmitFlagSecondaryBufferTest succeeded"); } tcu::TestStatus renderPassContinueTest(Context& context) { const DeviceInterface& vkd = context.getDeviceInterface(); CommandBufferRenderPassTestEnvironment env (context, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT); VkCommandBuffer primaryCommandBuffer = env.getPrimaryCommandBuffer(); VkCommandBuffer secondaryCommandBuffer = env.getSecondaryCommandBuffer(); const deUint32 clearColor[4] = { 2, 47, 131, 211 }; const VkClearAttachment clearAttachment = { VK_IMAGE_ASPECT_COLOR_BIT, // VkImageAspectFlags aspectMask; 0, // deUint32 colorAttachment; makeClearValueColorU32(clearColor[0], clearColor[1], clearColor[2], clearColor[3]) // VkClearValue clearValue; }; const VkClearRect clearRect = { CommandBufferRenderPassTestEnvironment::DEFAULT_IMAGE_AREA, // VkRect2D rect; 0u, // deUint32 baseArrayLayer; 1u // deUint32 layerCount; }; env.beginSecondaryCommandBuffer(VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT); vkd.cmdClearAttachments(secondaryCommandBuffer, 1, &clearAttachment, 1, &clearRect); endCommandBuffer(vkd, secondaryCommandBuffer); env.beginPrimaryCommandBuffer(0); env.beginRenderPass(VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS); vkd.cmdExecuteCommands(primaryCommandBuffer, 1, &secondaryCommandBuffer); endRenderPass(vkd, primaryCommandBuffer); endCommandBuffer(vkd, primaryCommandBuffer); env.submitPrimaryCommandBuffer(); de::MovePtr<tcu::TextureLevel> result = env.readColorAttachment(); tcu::PixelBufferAccess pixelBufferAccess = result->getAccess(); for (deUint32 i = 0; i < (CommandBufferRenderPassTestEnvironment::DEFAULT_IMAGE_SIZE.width * CommandBufferRenderPassTestEnvironment::DEFAULT_IMAGE_SIZE.height); ++i) { deUint8* colorData = reinterpret_cast<deUint8*>(pixelBufferAccess.getDataPtr()); for (int colorComponent = 0; colorComponent < 4; ++colorComponent) if (colorData[i * 4 + colorComponent] != clearColor[colorComponent]) return tcu::TestStatus::fail("clear value mismatch"); } return tcu::TestStatus::pass("render pass continue test passed"); } tcu::TestStatus simultaneousUsePrimaryBufferTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); // create event that will be used to check if secondary command buffer has been executed const Unique<VkEvent> eventOne (createEvent(vk, vkDevice)); const Unique<VkEvent> eventTwo (createEvent(vk, vkDevice)); // reset event VK_CHECK(vk.resetEvent(vkDevice, *eventOne)); // record primary command buffer beginCommandBuffer(vk, *primCmdBuf, 0u); { // wait for event vk.cmdWaitEvents(*primCmdBuf, 1u, &eventOne.get(), VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0u, DE_NULL, 0u, DE_NULL, 0u, DE_NULL); // Set the second event vk.cmdSetEvent(*primCmdBuf, eventTwo.get(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); } endCommandBuffer(vk, *primCmdBuf); // create fence to wait for execution of queue const Unique<VkFence> fence1 (createFence(vk, vkDevice)); const Unique<VkFence> fence2 (createFence(vk, vkDevice)); const VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores (const VkPipelineStageFlags*)DE_NULL, // pWaitDstStageMask 1, // commandBufferCount &primCmdBuf.get(), // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; // submit first buffer VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, *fence1)); // submit second buffer VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, *fence2)); // wait for both buffer to stop at event for 100 microseconds vk.waitForFences(vkDevice, 1, &fence1.get(), 0u, 100000); vk.waitForFences(vkDevice, 1, &fence2.get(), 0u, 100000); // set event VK_CHECK(vk.setEvent(vkDevice, *eventOne)); // wait for end of execution of the first buffer VK_CHECK(vk.waitForFences(vkDevice, 1, &fence1.get(), 0u, INFINITE_TIMEOUT)); // wait for end of execution of the second buffer VK_CHECK(vk.waitForFences(vkDevice, 1, &fence2.get(), 0u, INFINITE_TIMEOUT)); // TODO: this will be true if the command buffer was executed only once // TODO: add some test that will say if it was executed twice // check if buffer has been executed VkResult result = vk.getEventStatus(vkDevice, *eventTwo); if (result == VK_EVENT_SET) return tcu::TestStatus::pass("simultaneous use - primary buffers test succeeded"); else return tcu::TestStatus::fail("simultaneous use - primary buffers test FAILED"); } tcu::TestStatus simultaneousUseSecondaryBufferTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); // Secondary Command buffer params const VkCommandBufferAllocateInfo secCmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> secCmdBuf (allocateCommandBuffer(vk, vkDevice, &secCmdBufParams)); const VkCommandBufferInheritanceInfo secCmdBufInheritInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, DE_NULL, (VkRenderPass)0u, // renderPass 0u, // subpass (VkFramebuffer)0u, // framebuffer VK_FALSE, // occlusionQueryEnable (VkQueryControlFlags)0u, // queryFlags (VkQueryPipelineStatisticFlags)0u, // pipelineStatistics }; const VkCommandBufferBeginInfo secCmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, DE_NULL, VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT, // flags &secCmdBufInheritInfo, }; // create event that will be used to check if secondary command buffer has been executed const Unique<VkEvent> eventOne (createEvent(vk, vkDevice)); const Unique<VkEvent> eventTwo (createEvent(vk, vkDevice)); // reset event VK_CHECK(vk.resetEvent(vkDevice, *eventOne)); VK_CHECK(vk.resetEvent(vkDevice, *eventTwo)); // record secondary command buffer VK_CHECK(vk.beginCommandBuffer(*secCmdBuf, &secCmdBufBeginInfo)); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // wait for event vk.cmdWaitEvents(*secCmdBuf, 1, &eventOne.get(), stageMask, stageMask, 0, DE_NULL, 0u, DE_NULL, 0u, DE_NULL); // reset event vk.cmdSetEvent(*secCmdBuf, *eventTwo, stageMask); } // end recording of secondary buffers endCommandBuffer(vk, *secCmdBuf); // record primary command buffer beginCommandBuffer(vk, *primCmdBuf, 0u); { // execute secondary buffer vk.cmdExecuteCommands(*primCmdBuf, 1, &secCmdBuf.get()); } endCommandBuffer(vk, *primCmdBuf); // create fence to wait for execution of queue const Unique<VkFence> fence (createFence(vk, vkDevice)); const VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores (const VkPipelineStageFlags*)DE_NULL, // pWaitDstStageMask 1, // commandBufferCount &primCmdBuf.get(), // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; // submit primary buffer, the secondary should be executed too VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, *fence)); // wait for both buffers to stop at event for 100 microseconds vk.waitForFences(vkDevice, 1, &fence.get(), 0u, 100000); // set event VK_CHECK(vk.setEvent(vkDevice, *eventOne)); // wait for end of execution of queue VK_CHECK(vk.waitForFences(vkDevice, 1, &fence.get(), 0u, INFINITE_TIMEOUT)); // TODO: this will be true if the command buffer was executed only once // TODO: add some test that will say if it was executed twice // check if secondary buffer has been executed VkResult result = vk.getEventStatus(vkDevice,*eventTwo); if (result == VK_EVENT_SET) return tcu::TestStatus::pass("Simulatous Secondary Command Buffer Execution succeeded"); else return tcu::TestStatus::fail("Simulatous Secondary Command Buffer Execution FAILED"); } tcu::TestStatus simultaneousUseSecondaryBufferOnePrimaryBufferTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); Allocator& allocator = context.getDefaultAllocator(); const ComputeInstanceResultBuffer result(vk, vkDevice, allocator, 0.0f); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool(createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> primCmdBuf(allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); // Secondary Command buffer params const VkCommandBufferAllocateInfo secCmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> secCmdBuf(allocateCommandBuffer(vk, vkDevice, &secCmdBufParams)); const VkCommandBufferInheritanceInfo secCmdBufInheritInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, DE_NULL, (VkRenderPass)0u, 0u, // subpass (VkFramebuffer)0u, VK_FALSE, // occlusionQueryEnable (VkQueryControlFlags)0u, (VkQueryPipelineStatisticFlags)0u, }; const VkCommandBufferBeginInfo secCmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, DE_NULL, VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT, // flags &secCmdBufInheritInfo, }; const deUint32 offset = (0u); const deUint32 addressableSize = 256; const deUint32 dataSize = 8; de::MovePtr<Allocation> bufferMem; const Unique<VkBuffer> buffer(createDataBuffer(context, offset, addressableSize, 0x00, dataSize, 0x5A, &bufferMem)); // Secondary command buffer will have a compute shader that does an atomic increment to make sure that all instances of secondary buffers execute const Unique<VkDescriptorSetLayout> descriptorSetLayout(createDescriptorSetLayout(context)); const Unique<VkDescriptorPool> descriptorPool(createDescriptorPool(context)); const Unique<VkDescriptorSet> descriptorSet(createDescriptorSet(context, *descriptorPool, *descriptorSetLayout, *buffer, offset, result.getBuffer())); const VkDescriptorSet descriptorSets[] = { *descriptorSet }; const int numDescriptorSets = DE_LENGTH_OF_ARRAY(descriptorSets); const VkPipelineLayoutCreateInfo layoutCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, // sType DE_NULL, // pNext (VkPipelineLayoutCreateFlags)0, numDescriptorSets, // setLayoutCount &descriptorSetLayout.get(), // pSetLayouts 0u, // pushConstantRangeCount DE_NULL, // pPushConstantRanges }; Unique<VkPipelineLayout> pipelineLayout(createPipelineLayout(vk, vkDevice, &layoutCreateInfo)); const Unique<VkShaderModule> computeModule(createShaderModule(vk, vkDevice, context.getBinaryCollection().get("compute_increment"), (VkShaderModuleCreateFlags)0u)); const VkPipelineShaderStageCreateInfo shaderCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, DE_NULL, (VkPipelineShaderStageCreateFlags)0, VK_SHADER_STAGE_COMPUTE_BIT, // stage *computeModule, // shader "main", DE_NULL, // pSpecializationInfo }; const VkComputePipelineCreateInfo pipelineCreateInfo = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, DE_NULL, 0u, // flags shaderCreateInfo, // cs *pipelineLayout, // layout (vk::VkPipeline)0, // basePipelineHandle 0u, // basePipelineIndex }; const Unique<VkPipeline> pipeline(createComputePipeline(vk, vkDevice, (VkPipelineCache)0u, &pipelineCreateInfo)); // record secondary command buffer VK_CHECK(vk.beginCommandBuffer(*secCmdBuf, &secCmdBufBeginInfo)); { vk.cmdBindPipeline(*secCmdBuf, VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline); vk.cmdBindDescriptorSets(*secCmdBuf, VK_PIPELINE_BIND_POINT_COMPUTE, *pipelineLayout, 0, numDescriptorSets, descriptorSets, 0, 0); vk.cmdDispatch(*secCmdBuf, 1u, 1u, 1u); } // end recording of secondary buffer endCommandBuffer(vk, *secCmdBuf); // record primary command buffer beginCommandBuffer(vk, *primCmdBuf, 0u); { // execute secondary buffer twice in same primary vk.cmdExecuteCommands(*primCmdBuf, 1, &secCmdBuf.get()); vk.cmdExecuteCommands(*primCmdBuf, 1, &secCmdBuf.get()); } endCommandBuffer(vk, *primCmdBuf); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf.get()); deUint32 resultCount; result.readResultContentsTo(&resultCount); // check if secondary buffer has been executed if (resultCount == 2) return tcu::TestStatus::pass("Simulatous Secondary Command Buffer Execution succeeded"); else return tcu::TestStatus::fail("Simulatous Secondary Command Buffer Execution FAILED"); } tcu::TestStatus simultaneousUseSecondaryBufferTwoPrimaryBuffersTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); Allocator& allocator = context.getDefaultAllocator(); const ComputeInstanceResultBuffer result(vk, vkDevice, allocator, 0.0f); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool(createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; // Two separate primary cmd buffers that will be executed with the same secondary cmd buffer const deUint32 numPrimCmdBufs = 2; const Unique<VkCommandBuffer> primCmdBufOne(allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); const Unique<VkCommandBuffer> primCmdBufTwo(allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); VkCommandBuffer primCmdBufs[numPrimCmdBufs]; primCmdBufs[0] = primCmdBufOne.get(); primCmdBufs[1] = primCmdBufTwo.get(); // Secondary Command buffer params const VkCommandBufferAllocateInfo secCmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> secCmdBuf(allocateCommandBuffer(vk, vkDevice, &secCmdBufParams)); const VkCommandBufferBeginInfo primCmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, DE_NULL, 0, // flags (const VkCommandBufferInheritanceInfo*)DE_NULL, }; const VkCommandBufferInheritanceInfo secCmdBufInheritInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, DE_NULL, (VkRenderPass)0u, // renderPass 0u, // subpass (VkFramebuffer)0u, // framebuffer VK_FALSE, // occlusionQueryEnable (VkQueryControlFlags)0u, // queryFlags (VkQueryPipelineStatisticFlags)0u, // pipelineStatistics }; const VkCommandBufferBeginInfo secCmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, DE_NULL, VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT, // flags &secCmdBufInheritInfo, }; const deUint32 offset = (0u); const deUint32 addressableSize = 256; const deUint32 dataSize = 8; de::MovePtr<Allocation> bufferMem; const Unique<VkBuffer> buffer(createDataBuffer(context, offset, addressableSize, 0x00, dataSize, 0x5A, &bufferMem)); // Secondary command buffer will have a compute shader that does an atomic increment to make sure that all instances of secondary buffers execute const Unique<VkDescriptorSetLayout> descriptorSetLayout(createDescriptorSetLayout(context)); const Unique<VkDescriptorPool> descriptorPool(createDescriptorPool(context)); const Unique<VkDescriptorSet> descriptorSet(createDescriptorSet(context, *descriptorPool, *descriptorSetLayout, *buffer, offset, result.getBuffer())); const VkDescriptorSet descriptorSets[] = { *descriptorSet }; const int numDescriptorSets = DE_LENGTH_OF_ARRAY(descriptorSets); const VkPipelineLayoutCreateInfo layoutCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, // sType DE_NULL, // pNext (VkPipelineLayoutCreateFlags)0, numDescriptorSets, // setLayoutCount &descriptorSetLayout.get(), // pSetLayouts 0u, // pushConstantRangeCount DE_NULL, // pPushConstantRanges }; Unique<VkPipelineLayout> pipelineLayout(createPipelineLayout(vk, vkDevice, &layoutCreateInfo)); const Unique<VkShaderModule> computeModule(createShaderModule(vk, vkDevice, context.getBinaryCollection().get("compute_increment"), (VkShaderModuleCreateFlags)0u)); const VkPipelineShaderStageCreateInfo shaderCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, DE_NULL, (VkPipelineShaderStageCreateFlags)0, VK_SHADER_STAGE_COMPUTE_BIT, // stage *computeModule, // shader "main", DE_NULL, // pSpecializationInfo }; const VkComputePipelineCreateInfo pipelineCreateInfo = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, DE_NULL, 0u, // flags shaderCreateInfo, // cs *pipelineLayout, // layout (vk::VkPipeline)0, // basePipelineHandle 0u, // basePipelineIndex }; const Unique<VkPipeline> pipeline(createComputePipeline(vk, vkDevice, (VkPipelineCache)0u, &pipelineCreateInfo)); // record secondary command buffer VK_CHECK(vk.beginCommandBuffer(*secCmdBuf, &secCmdBufBeginInfo)); { vk.cmdBindPipeline(*secCmdBuf, VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline); vk.cmdBindDescriptorSets(*secCmdBuf, VK_PIPELINE_BIND_POINT_COMPUTE, *pipelineLayout, 0, numDescriptorSets, descriptorSets, 0, 0); vk.cmdDispatch(*secCmdBuf, 1u, 1u, 1u); } // end recording of secondary buffer endCommandBuffer(vk, *secCmdBuf); // record primary command buffers // Insert one instance of same secondary command buffer into two separate primary command buffers VK_CHECK(vk.beginCommandBuffer(*primCmdBufOne, &primCmdBufBeginInfo)); { vk.cmdExecuteCommands(*primCmdBufOne, 1, &secCmdBuf.get()); } endCommandBuffer(vk, *primCmdBufOne); VK_CHECK(vk.beginCommandBuffer(*primCmdBufTwo, &primCmdBufBeginInfo)); { vk.cmdExecuteCommands(*primCmdBufTwo, 1, &secCmdBuf.get()); } endCommandBuffer(vk, *primCmdBufTwo); // create fence to wait for execution of queue const Unique<VkFence> fence(createFence(vk, vkDevice)); const VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores (const VkPipelineStageFlags*)DE_NULL, // pWaitDstStageMask numPrimCmdBufs, // commandBufferCount primCmdBufs, // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; // submit primary buffers, the secondary should be executed too VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, *fence)); // wait for end of execution of queue VK_CHECK(vk.waitForFences(vkDevice, 1, &fence.get(), 0u, INFINITE_TIMEOUT)); deUint32 resultCount; result.readResultContentsTo(&resultCount); // check if secondary buffer has been executed if (resultCount == 2) return tcu::TestStatus::pass("Simulatous Secondary Command Buffer Execution succeeded"); else return tcu::TestStatus::fail("Simulatous Secondary Command Buffer Execution FAILED"); } tcu::TestStatus recordBufferQueryPreciseWithFlagTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); if (!context.getDeviceFeatures().inheritedQueries) TCU_THROW(NotSupportedError, "Inherited queries feature is not supported"); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo primCmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level; 1u, // flags; }; const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &primCmdBufParams)); // Secondary Command buffer params const VkCommandBufferAllocateInfo secCmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // pool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // level; 1u, // flags; }; const Unique<VkCommandBuffer> secCmdBuf (allocateCommandBuffer(vk, vkDevice, &secCmdBufParams)); const VkCommandBufferBeginInfo primBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags (const VkCommandBufferInheritanceInfo*)DE_NULL, }; const VkCommandBufferInheritanceInfo secBufferInheritInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, DE_NULL, 0u, // renderPass 0u, // subpass 0u, // framebuffer VK_TRUE, // occlusionQueryEnable VK_QUERY_CONTROL_PRECISE_BIT, // queryFlags (VkQueryPipelineStatisticFlags)0u, // pipelineStatistics }; const VkCommandBufferBeginInfo secBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags &secBufferInheritInfo, }; const VkQueryPoolCreateInfo queryPoolCreateInfo = { VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO, // sType DE_NULL, // pNext (VkQueryPoolCreateFlags)0, // flags VK_QUERY_TYPE_OCCLUSION, // queryType 1u, // entryCount 0u, // pipelineStatistics }; Unique<VkQueryPool> queryPool (createQueryPool(vk, vkDevice, &queryPoolCreateInfo)); VK_CHECK(vk.beginCommandBuffer(secCmdBuf.get(), &secBufferBeginInfo)); endCommandBuffer(vk, secCmdBuf.get()); VK_CHECK(vk.beginCommandBuffer(primCmdBuf.get(), &primBufferBeginInfo)); { vk.cmdResetQueryPool(primCmdBuf.get(), queryPool.get(), 0u, 1u); vk.cmdBeginQuery(primCmdBuf.get(), queryPool.get(), 0u, VK_QUERY_CONTROL_PRECISE_BIT); { vk.cmdExecuteCommands(primCmdBuf.get(), 1u, &secCmdBuf.get()); } vk.cmdEndQuery(primCmdBuf.get(), queryPool.get(), 0u); } endCommandBuffer(vk, primCmdBuf.get()); return tcu::TestStatus::pass("Successfully recorded a secondary command buffer allowing a precise occlusion query."); } tcu::TestStatus recordBufferQueryImpreciseWithFlagTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); if (!context.getDeviceFeatures().inheritedQueries) TCU_THROW(NotSupportedError, "Inherited queries feature is not supported"); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo primCmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level; 1u, // flags; }; const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &primCmdBufParams)); // Secondary Command buffer params const VkCommandBufferAllocateInfo secCmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // pool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // level; 1u, // flags; }; const Unique<VkCommandBuffer> secCmdBuf (allocateCommandBuffer(vk, vkDevice, &secCmdBufParams)); const VkCommandBufferBeginInfo primBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags (const VkCommandBufferInheritanceInfo*)DE_NULL, }; const VkCommandBufferInheritanceInfo secBufferInheritInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, DE_NULL, 0u, // renderPass 0u, // subpass 0u, // framebuffer VK_TRUE, // occlusionQueryEnable VK_QUERY_CONTROL_PRECISE_BIT, // queryFlags (VkQueryPipelineStatisticFlags)0u, // pipelineStatistics }; const VkCommandBufferBeginInfo secBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags &secBufferInheritInfo, }; // Create an occlusion query with VK_QUERY_CONTROL_PRECISE_BIT set const VkQueryPoolCreateInfo queryPoolCreateInfo = { VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO, // sType DE_NULL, // pNext 0u, // flags VK_QUERY_TYPE_OCCLUSION, // queryType 1u, // entryCount 0u, // pipelineStatistics }; Unique<VkQueryPool> queryPool (createQueryPool(vk, vkDevice, &queryPoolCreateInfo)); VK_CHECK(vk.beginCommandBuffer(secCmdBuf.get(), &secBufferBeginInfo)); endCommandBuffer(vk, secCmdBuf.get()); VK_CHECK(vk.beginCommandBuffer(primCmdBuf.get(), &primBufferBeginInfo)); { vk.cmdResetQueryPool(primCmdBuf.get(), queryPool.get(), 0u, 1u); vk.cmdBeginQuery(primCmdBuf.get(), queryPool.get(), 0u, VK_QUERY_CONTROL_PRECISE_BIT); { vk.cmdExecuteCommands(primCmdBuf.get(), 1u, &secCmdBuf.get()); } vk.cmdEndQuery(primCmdBuf.get(), queryPool.get(), 0u); } endCommandBuffer(vk, primCmdBuf.get()); return tcu::TestStatus::pass("Successfully recorded a secondary command buffer allowing a precise occlusion query."); } tcu::TestStatus recordBufferQueryImpreciseWithoutFlagTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); if (!context.getDeviceFeatures().inheritedQueries) TCU_THROW(NotSupportedError, "Inherited queries feature is not supported"); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo primCmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level; 1u, // flags; }; const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &primCmdBufParams)); // Secondary Command buffer params const VkCommandBufferAllocateInfo secCmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // pool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // level; 1u, // flags; }; const Unique<VkCommandBuffer> secCmdBuf (allocateCommandBuffer(vk, vkDevice, &secCmdBufParams)); const VkCommandBufferBeginInfo primBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags (const VkCommandBufferInheritanceInfo*)DE_NULL, }; const VkCommandBufferInheritanceInfo secBufferInheritInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, DE_NULL, 0u, // renderPass 0u, // subpass 0u, // framebuffer VK_TRUE, // occlusionQueryEnable 0u, // queryFlags (VkQueryPipelineStatisticFlags)0u, // pipelineStatistics }; const VkCommandBufferBeginInfo secBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags &secBufferInheritInfo, }; // Create an occlusion query with VK_QUERY_CONTROL_PRECISE_BIT set const VkQueryPoolCreateInfo queryPoolCreateInfo = { VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO, // sType DE_NULL, // pNext (VkQueryPoolCreateFlags)0, VK_QUERY_TYPE_OCCLUSION, 1u, 0u, }; Unique<VkQueryPool> queryPool (createQueryPool(vk, vkDevice, &queryPoolCreateInfo)); VK_CHECK(vk.beginCommandBuffer(secCmdBuf.get(), &secBufferBeginInfo)); endCommandBuffer(vk, secCmdBuf.get()); VK_CHECK(vk.beginCommandBuffer(primCmdBuf.get(), &primBufferBeginInfo)); { vk.cmdResetQueryPool(primCmdBuf.get(), queryPool.get(), 0u, 1u); vk.cmdBeginQuery(primCmdBuf.get(), queryPool.get(), 0u, VK_QUERY_CONTROL_PRECISE_BIT); { vk.cmdExecuteCommands(primCmdBuf.get(), 1u, &secCmdBuf.get()); } vk.cmdEndQuery(primCmdBuf.get(), queryPool.get(), 0u); } endCommandBuffer(vk, primCmdBuf.get()); return tcu::TestStatus::pass("Successfully recorded a secondary command buffer allowing a precise occlusion query."); } /******** 19.4. Command Buffer Submission (5.4 in VK 1.0 Spec) ****************/ tcu::TestStatus submitBufferCountNonZero(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const deUint32 BUFFER_COUNT = 5u; const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; 0u, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level; BUFFER_COUNT, // bufferCount; }; VkCommandBuffer cmdBuffers[BUFFER_COUNT]; VK_CHECK(vk.allocateCommandBuffers(vkDevice, &cmdBufParams, cmdBuffers)); const VkCommandBufferBeginInfo cmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags (const VkCommandBufferInheritanceInfo*)DE_NULL, }; std::vector<VkEventSp> events; for (deUint32 ndx = 0; ndx < BUFFER_COUNT; ++ndx) { events.push_back(VkEventSp(new vk::Unique<VkEvent>(createEvent(vk, vkDevice)))); } // Record the command buffers for (deUint32 ndx = 0; ndx < BUFFER_COUNT; ++ndx) { VK_CHECK(vk.beginCommandBuffer(cmdBuffers[ndx], &cmdBufBeginInfo)); { vk.cmdSetEvent(cmdBuffers[ndx], events[ndx]->get(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); } endCommandBuffer(vk, cmdBuffers[ndx]); } // We'll use a fence to wait for the execution of the queue const Unique<VkFence> fence (createFence(vk, vkDevice)); const VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores (const VkPipelineStageFlags*)DE_NULL, // pWaitDstStageMask BUFFER_COUNT, // commandBufferCount cmdBuffers, // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; // Submit the alpha command buffer to the queue VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, fence.get())); // Wait for the queue VK_CHECK(vk.waitForFences(vkDevice, 1u, &fence.get(), VK_TRUE, INFINITE_TIMEOUT)); // Check if the buffers were executed tcu::TestStatus testResult = tcu::TestStatus::incomplete(); for (deUint32 ndx = 0; ndx < BUFFER_COUNT; ++ndx) { if (vk.getEventStatus(vkDevice, events[ndx]->get()) != VK_EVENT_SET) { testResult = tcu::TestStatus::fail("Failed to set the event."); break; } } if (!testResult.isComplete()) testResult = tcu::TestStatus::pass("All buffers were submitted and executed correctly."); return testResult; } tcu::TestStatus submitBufferCountEqualZero(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const deUint32 BUFFER_COUNT = 2u; const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; 0u, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level; BUFFER_COUNT, // bufferCount; }; VkCommandBuffer cmdBuffers[BUFFER_COUNT]; VK_CHECK(vk.allocateCommandBuffers(vkDevice, &cmdBufParams, cmdBuffers)); const VkCommandBufferBeginInfo cmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags (const VkCommandBufferInheritanceInfo*)DE_NULL, }; std::vector<VkEventSp> events; for (deUint32 ndx = 0; ndx < BUFFER_COUNT; ++ndx) events.push_back(VkEventSp(new vk::Unique<VkEvent>(createEvent(vk, vkDevice)))); // Record the command buffers for (deUint32 ndx = 0; ndx < BUFFER_COUNT; ++ndx) { VK_CHECK(vk.beginCommandBuffer(cmdBuffers[ndx], &cmdBufBeginInfo)); { vk.cmdSetEvent(cmdBuffers[ndx], events[ndx]->get(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); } endCommandBuffer(vk, cmdBuffers[ndx]); } // We'll use a fence to wait for the execution of the queue const Unique<VkFence> fenceZero (createFence(vk, vkDevice)); const Unique<VkFence> fenceOne (createFence(vk, vkDevice)); const VkSubmitInfo submitInfoCountZero = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores (const VkPipelineStageFlags*)DE_NULL, // pWaitDstStageMask 1u, // commandBufferCount &cmdBuffers[0], // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; const VkSubmitInfo submitInfoCountOne = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores (const VkPipelineStageFlags*)DE_NULL, // pWaitDstStageMask 1u, // commandBufferCount &cmdBuffers[1], // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; // Submit the command buffers to the queue // We're performing two submits to make sure that the first one has // a chance to be processed before we check the event's status VK_CHECK(vk.queueSubmit(queue, 0, &submitInfoCountZero, fenceZero.get())); VK_CHECK(vk.queueSubmit(queue, 1, &submitInfoCountOne, fenceOne.get())); const VkFence fences[] = { fenceZero.get(), fenceOne.get(), }; // Wait for the queue VK_CHECK(vk.waitForFences(vkDevice, (deUint32)DE_LENGTH_OF_ARRAY(fences), fences, VK_TRUE, INFINITE_TIMEOUT)); // Check if the first buffer was executed tcu::TestStatus testResult = tcu::TestStatus::incomplete(); if (vk.getEventStatus(vkDevice, events[0]->get()) == VK_EVENT_SET) testResult = tcu::TestStatus::fail("The first event was signaled."); else testResult = tcu::TestStatus::pass("The first submission was ignored."); return testResult; } tcu::TestStatus submitBufferWaitSingleSemaphore(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; // Create two command buffers const Unique<VkCommandBuffer> primCmdBuf1 (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); const Unique<VkCommandBuffer> primCmdBuf2 (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); const VkCommandBufferBeginInfo primCmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0, // flags DE_NULL // const VkCommandBufferInheritanceInfo* pInheritanceInfo; }; // create two events that will be used to check if command buffers has been executed const Unique<VkEvent> event1 (createEvent(vk, vkDevice)); const Unique<VkEvent> event2 (createEvent(vk, vkDevice)); // reset events VK_CHECK(vk.resetEvent(vkDevice, *event1)); VK_CHECK(vk.resetEvent(vkDevice, *event2)); // record first command buffer VK_CHECK(vk.beginCommandBuffer(*primCmdBuf1, &primCmdBufBeginInfo)); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // record setting event vk.cmdSetEvent(*primCmdBuf1, *event1,stageMask); } endCommandBuffer(vk, *primCmdBuf1); // record second command buffer VK_CHECK(vk.beginCommandBuffer(*primCmdBuf2, &primCmdBufBeginInfo)); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // record setting event vk.cmdSetEvent(*primCmdBuf2, *event2,stageMask); } endCommandBuffer(vk, *primCmdBuf2); // create fence to wait for execution of queue const Unique<VkFence> fence (createFence(vk, vkDevice)); // create semaphore for use in this test const Unique <VkSemaphore> semaphore (createSemaphore(vk, vkDevice)); // create submit info for first buffer - signalling semaphore const VkSubmitInfo submitInfo1 = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores DE_NULL, // pWaitDstStageMask 1, // commandBufferCount &primCmdBuf1.get(), // pCommandBuffers 1u, // signalSemaphoreCount &semaphore.get(), // pSignalSemaphores }; // Submit the command buffer to the queue VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo1, *fence)); // wait for end of execution of queue VK_CHECK(vk.waitForFences(vkDevice, 1, &fence.get(), 0u, INFINITE_TIMEOUT)); // check if buffer has been executed VkResult result = vk.getEventStatus(vkDevice,*event1); if (result != VK_EVENT_SET) return tcu::TestStatus::fail("Submit Buffer and Wait for Single Semaphore Test FAILED"); const VkPipelineStageFlags waitDstStageFlags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; // create submit info for second buffer - waiting for semaphore const VkSubmitInfo submitInfo2 = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 1u, // waitSemaphoreCount &semaphore.get(), // pWaitSemaphores &waitDstStageFlags, // pWaitDstStageMask 1, // commandBufferCount &primCmdBuf2.get(), // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; // reset fence, so it can be used again VK_CHECK(vk.resetFences(vkDevice, 1u, &fence.get())); // Submit the second command buffer to the queue VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo2, *fence)); // wait for end of execution of queue VK_CHECK(vk.waitForFences(vkDevice, 1, &fence.get(), 0u, INFINITE_TIMEOUT)); // check if second buffer has been executed // if it has been executed, it means that the semaphore was signalled - so test if passed result = vk.getEventStatus(vkDevice,*event1); if (result != VK_EVENT_SET) return tcu::TestStatus::fail("Submit Buffer and Wait for Single Semaphore Test FAILED"); return tcu::TestStatus::pass("Submit Buffer and Wait for Single Semaphore Test succeeded"); } tcu::TestStatus submitBufferWaitManySemaphores(Context& context) { // This test will create numSemaphores semaphores, and signal them in NUM_SEMAPHORES submits to queue // After that the numSubmissions queue submissions will wait for each semaphore const deUint32 numSemaphores = 10u; // it must be multiply of numSubmission const deUint32 numSubmissions = 2u; const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; // Create command buffer const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); const VkCommandBufferBeginInfo primCmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0, // flags DE_NULL // const VkCommandBufferInheritanceInfo* pInheritanceInfo; }; // create event that will be used to check if command buffers has been executed const Unique<VkEvent> event (createEvent(vk, vkDevice)); // reset event - at creation state is undefined VK_CHECK(vk.resetEvent(vkDevice, *event)); // record command buffer VK_CHECK(vk.beginCommandBuffer(*primCmdBuf, &primCmdBufBeginInfo)); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // record setting event vk.cmdSetEvent(*primCmdBuf, *event,stageMask); } endCommandBuffer(vk, *primCmdBuf); // create fence to wait for execution of queue const Unique<VkFence> fence (createFence(vk, vkDevice)); // numSemaphores is declared const, so this array can be static // the semaphores will be destroyed automatically at end of scope Move <VkSemaphore> semaphoreArray[numSemaphores]; VkSemaphore semaphores[numSemaphores]; for (deUint32 idx = 0; idx < numSemaphores; ++idx) { // create semaphores for use in this test semaphoreArray[idx] = createSemaphore(vk, vkDevice); semaphores[idx] = semaphoreArray[idx].get(); }; { // create submit info for buffer - signal semaphores const VkSubmitInfo submitInfo1 = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores DE_NULL, // pWaitDstStageMask 1, // commandBufferCount &primCmdBuf.get(), // pCommandBuffers numSemaphores, // signalSemaphoreCount semaphores // pSignalSemaphores }; // Submit the command buffer to the queue VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo1, *fence)); // wait for end of execution of queue VK_CHECK(vk.waitForFences(vkDevice, 1, &fence.get(), 0u, INFINITE_TIMEOUT)); // check if buffer has been executed VkResult result = vk.getEventStatus(vkDevice,*event); if (result != VK_EVENT_SET) return tcu::TestStatus::fail("Submit Buffer and Wait for Many Semaphores Test FAILED"); // reset event, so next buffers can set it again VK_CHECK(vk.resetEvent(vkDevice, *event)); // reset fence, so it can be used again VK_CHECK(vk.resetFences(vkDevice, 1u, &fence.get())); } const deUint32 numberOfSemaphoresToBeWaitedByOneSubmission = numSemaphores / numSubmissions; const std::vector<VkPipelineStageFlags> waitDstStageFlags (numberOfSemaphoresToBeWaitedByOneSubmission, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT); // the following code waits for the semaphores set above - numSubmissions queues will wait for each semaphore from above for (deUint32 idxSubmission = 0; idxSubmission < numSubmissions; ++idxSubmission) { // create submit info for buffer - waiting for semaphore const VkSubmitInfo submitInfo2 = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext numberOfSemaphoresToBeWaitedByOneSubmission, // waitSemaphoreCount semaphores + (numberOfSemaphoresToBeWaitedByOneSubmission * idxSubmission), // pWaitSemaphores waitDstStageFlags.data(), // pWaitDstStageMask 1, // commandBufferCount &primCmdBuf.get(), // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; // Submit the second command buffer to the queue VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo2, *fence)); // wait for 1 second. VK_CHECK(vk.waitForFences(vkDevice, 1, &fence.get(), 0u, 1000 * 1000 * 1000)); // check if second buffer has been executed // if it has been executed, it means that the semaphore was signalled - so test if passed VkResult result = vk.getEventStatus(vkDevice,*event); if (result != VK_EVENT_SET) return tcu::TestStatus::fail("Submit Buffer and Wait for Many Semaphores Test FAILED"); // reset fence, so it can be used again VK_CHECK(vk.resetFences(vkDevice, 1u, &fence.get())); // reset event, so next buffers can set it again VK_CHECK(vk.resetEvent(vkDevice, *event)); } return tcu::TestStatus::pass("Submit Buffer and Wait for Many Semaphores Test succeeded"); } tcu::TestStatus submitBufferNullFence(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const short BUFFER_COUNT = 2; const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; 0u, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level; 1u, // bufferCount; }; VkCommandBuffer cmdBuffers[BUFFER_COUNT]; for (deUint32 ndx = 0; ndx < BUFFER_COUNT; ++ndx) VK_CHECK(vk.allocateCommandBuffers(vkDevice, &cmdBufParams, &cmdBuffers[ndx])); const VkCommandBufferBeginInfo cmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags (const VkCommandBufferInheritanceInfo*)DE_NULL, }; std::vector<VkEventSp> events; for (deUint32 ndx = 0; ndx < BUFFER_COUNT; ++ndx) events.push_back(VkEventSp(new vk::Unique<VkEvent>(createEvent(vk, vkDevice)))); // Record the command buffers for (deUint32 ndx = 0; ndx < BUFFER_COUNT; ++ndx) { VK_CHECK(vk.beginCommandBuffer(cmdBuffers[ndx], &cmdBufBeginInfo)); { vk.cmdSetEvent(cmdBuffers[ndx], events[ndx]->get(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); } endCommandBuffer(vk, cmdBuffers[ndx]); } // We'll use a fence to wait for the execution of the queue const Unique<VkFence> fence (createFence(vk, vkDevice)); const VkSubmitInfo submitInfoNullFence = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores (const VkPipelineStageFlags*)DE_NULL, // pWaitDstStageMask 1u, // commandBufferCount &cmdBuffers[0], // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; const VkSubmitInfo submitInfoNonNullFence = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores (const VkPipelineStageFlags*)DE_NULL, // pWaitDstStageMask 1u, // commandBufferCount &cmdBuffers[1], // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; // Perform two submissions - one with no fence, the other one with a valid // fence Hoping submitting the other buffer will give the first one time to // execute VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfoNullFence, DE_NULL)); VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfoNonNullFence, fence.get())); // Wait for the queue VK_CHECK(vk.waitForFences(vkDevice, 1u, &fence.get(), VK_TRUE, INFINITE_TIMEOUT)); tcu::TestStatus testResult = tcu::TestStatus::incomplete(); //Fence guaranteed that all buffers submited before fence were executed if (vk.getEventStatus(vkDevice, events[0]->get()) != VK_EVENT_SET || vk.getEventStatus(vkDevice, events[1]->get()) != VK_EVENT_SET) { testResult = tcu::TestStatus::fail("One of the buffers was not executed."); } else { testResult = tcu::TestStatus::pass("Buffers have been submitted and executed correctly."); } vk.queueWaitIdle(queue); return testResult; } tcu::TestStatus submitTwoBuffersOneBufferNullWithFence(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const deUint32 BUFFER_COUNT = 2u; const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level; BUFFER_COUNT, // bufferCount; }; VkCommandBuffer cmdBuffers[BUFFER_COUNT]; VK_CHECK(vk.allocateCommandBuffers(vkDevice, &cmdBufParams, cmdBuffers)); const VkCommandBufferBeginInfo cmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags (const VkCommandBufferInheritanceInfo*)DE_NULL, // pInheritanceInfo }; std::vector<VkEventSp> events; for (deUint32 ndx = 0; ndx < BUFFER_COUNT; ++ndx) events.push_back(VkEventSp(new vk::Unique<VkEvent>(createEvent(vk, vkDevice)))); // Record the command buffers for (deUint32 ndx = 0; ndx < BUFFER_COUNT; ++ndx) { VK_CHECK(vk.beginCommandBuffer(cmdBuffers[ndx], &cmdBufBeginInfo)); { vk.cmdSetEvent(cmdBuffers[ndx], events[ndx]->get(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); } VK_CHECK(vk.endCommandBuffer(cmdBuffers[ndx])); } // First command buffer const VkSubmitInfo submitInfoNonNullFirst = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores (const VkPipelineStageFlags*)DE_NULL, // pWaitDstStageMask 1u, // commandBufferCount &cmdBuffers[0], // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; // Second command buffer const VkSubmitInfo submitInfoNonNullSecond = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores (const VkPipelineStageFlags*)DE_NULL, // pWaitDstStageMask 1u, // commandBufferCount &cmdBuffers[1], // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; // Fence will be submitted with the null queue const Unique<VkFence> fence (createFence(vk, vkDevice)); // Perform two separate queueSubmit calls on the same queue followed // by a third call with no submitInfos and with a valid fence VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfoNonNullFirst, DE_NULL)); VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfoNonNullSecond, DE_NULL)); VK_CHECK(vk.queueSubmit(queue, 0u, DE_NULL, fence.get())); // Wait for the queue VK_CHECK(vk.waitForFences(vkDevice, 1u, &fence.get(), VK_TRUE, INFINITE_TIMEOUT)); return tcu::TestStatus::pass("Buffers have been submitted correctly"); } /******** 19.5. Secondary Command Buffer Execution (5.6 in VK 1.0 Spec) *******/ tcu::TestStatus executeSecondaryBufferTest(Context& context) { const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // flags; queueFamilyIndex, // queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // commandPool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level; 1u, // bufferCount; }; const Unique<VkCommandBuffer> primCmdBuf (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); // Secondary Command buffer const VkCommandBufferAllocateInfo secCmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType; DE_NULL, // pNext; *cmdPool, // commandPool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // level; 1u, // bufferCount; }; const Unique<VkCommandBuffer> secCmdBuf (allocateCommandBuffer(vk, vkDevice, &secCmdBufParams)); const VkCommandBufferBeginInfo primCmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags (const VkCommandBufferInheritanceInfo*)DE_NULL, }; const VkCommandBufferInheritanceInfo secCmdBufInheritInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, DE_NULL, DE_NULL, // renderPass 0u, // subpass DE_NULL, // framebuffer VK_FALSE, // occlusionQueryEnable (VkQueryControlFlags)0u, // queryFlags (VkQueryPipelineStatisticFlags)0u, // pipelineStatistics }; const VkCommandBufferBeginInfo secCmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags &secCmdBufInheritInfo, }; // create event that will be used to check if secondary command buffer has been executed const Unique<VkEvent> event (createEvent(vk, vkDevice)); // reset event VK_CHECK(vk.resetEvent(vkDevice, *event)); // record secondary command buffer VK_CHECK(vk.beginCommandBuffer(*secCmdBuf, &secCmdBufBeginInfo)); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // record setting event vk.cmdSetEvent(*secCmdBuf, *event, stageMask); } // end recording of the secondary buffer endCommandBuffer(vk, *secCmdBuf); // record primary command buffer VK_CHECK(vk.beginCommandBuffer(*primCmdBuf, &primCmdBufBeginInfo)); { // execute secondary buffer vk.cmdExecuteCommands(*primCmdBuf, 1u, &secCmdBuf.get()); } endCommandBuffer(vk, *primCmdBuf); submitCommandsAndWait(vk, vkDevice, queue, primCmdBuf.get()); // check if secondary buffer has been executed VkResult result = vk.getEventStatus(vkDevice, *event); if (result == VK_EVENT_SET) return tcu::TestStatus::pass("executeSecondaryBufferTest succeeded"); return tcu::TestStatus::fail("executeSecondaryBufferTest FAILED"); } tcu::TestStatus executeSecondaryBufferTwiceTest(Context& context) { const deUint32 BUFFER_COUNT = 10u; const VkDevice vkDevice = context.getDevice(); const DeviceInterface& vk = context.getDeviceInterface(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkCommandPoolCreateInfo cmdPoolParams = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCommandPoolCreateFlags flags; queueFamilyIndex, // deUint32 queueFamilyIndex; }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, vkDevice, &cmdPoolParams)); // Command buffer const VkCommandBufferAllocateInfo cmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level; 1u, // uint32_t bufferCount; }; const Unique<VkCommandBuffer> primCmdBufOne (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); const Unique<VkCommandBuffer> primCmdBufTwo (allocateCommandBuffer(vk, vkDevice, &cmdBufParams)); // Secondary Command buffers params const VkCommandBufferAllocateInfo secCmdBufParams = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *cmdPool, // VkCommandPool pool; VK_COMMAND_BUFFER_LEVEL_SECONDARY, // VkCommandBufferLevel level; BUFFER_COUNT, // uint32_t bufferCount; }; VkCommandBuffer cmdBuffers[BUFFER_COUNT]; VK_CHECK(vk.allocateCommandBuffers(vkDevice, &secCmdBufParams, cmdBuffers)); const VkCommandBufferBeginInfo primCmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, DE_NULL, 0, // flags (const VkCommandBufferInheritanceInfo*)DE_NULL, }; const VkCommandBufferInheritanceInfo secCmdBufInheritInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, DE_NULL, (VkRenderPass)0u, // renderPass 0u, // subpass (VkFramebuffer)0u, // framebuffer VK_FALSE, // occlusionQueryEnable (VkQueryControlFlags)0u, // queryFlags (VkQueryPipelineStatisticFlags)0u, // pipelineStatistics }; const VkCommandBufferBeginInfo secCmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, DE_NULL, VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT, // flags &secCmdBufInheritInfo, }; // create event that will be used to check if secondary command buffer has been executed const Unique<VkEvent> eventOne (createEvent(vk, vkDevice)); // reset event VK_CHECK(vk.resetEvent(vkDevice, *eventOne)); for (deUint32 ndx = 0; ndx < BUFFER_COUNT; ++ndx) { // record secondary command buffer VK_CHECK(vk.beginCommandBuffer(cmdBuffers[ndx], &secCmdBufBeginInfo)); { // allow execution of event during every stage of pipeline VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; // wait for event vk.cmdWaitEvents(cmdBuffers[ndx], 1, &eventOne.get(), stageMask, stageMask, 0, DE_NULL, 0u, DE_NULL, 0u, DE_NULL); } // end recording of secondary buffers endCommandBuffer(vk, cmdBuffers[ndx]); }; // record primary command buffer one VK_CHECK(vk.beginCommandBuffer(*primCmdBufOne, &primCmdBufBeginInfo)); { // execute one secondary buffer vk.cmdExecuteCommands(*primCmdBufOne, 1, cmdBuffers ); } endCommandBuffer(vk, *primCmdBufOne); // record primary command buffer two VK_CHECK(vk.beginCommandBuffer(*primCmdBufTwo, &primCmdBufBeginInfo)); { // execute one secondary buffer with all buffers vk.cmdExecuteCommands(*primCmdBufTwo, BUFFER_COUNT, cmdBuffers ); } endCommandBuffer(vk, *primCmdBufTwo); // create fence to wait for execution of queue const Unique<VkFence> fenceOne (createFence(vk, vkDevice)); const Unique<VkFence> fenceTwo (createFence(vk, vkDevice)); const VkSubmitInfo submitInfoOne = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores (const VkPipelineStageFlags*)DE_NULL, // pWaitDstStageMask 1, // commandBufferCount &primCmdBufOne.get(), // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; // submit primary buffer, the secondary should be executed too VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfoOne, *fenceOne)); // wait for buffer to stop at event for 100 microseconds vk.waitForFences(vkDevice, 1, &fenceOne.get(), 0u, 100000); const VkSubmitInfo submitInfoTwo = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType DE_NULL, // pNext 0u, // waitSemaphoreCount DE_NULL, // pWaitSemaphores (const VkPipelineStageFlags*)DE_NULL, // pWaitDstStageMask 1, // commandBufferCount &primCmdBufTwo.get(), // pCommandBuffers 0u, // signalSemaphoreCount DE_NULL, // pSignalSemaphores }; // submit second primary buffer, the secondary should be executed too VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfoTwo, *fenceTwo)); // wait for all buffers to stop at event for 100 microseconds vk.waitForFences(vkDevice, 1, &fenceOne.get(), 0u, 100000); // now all buffers are waiting at eventOne // set event eventOne VK_CHECK(vk.setEvent(vkDevice, *eventOne)); // wait for end of execution of fenceOne VK_CHECK(vk.waitForFences(vkDevice, 1, &fenceOne.get(), 0u, INFINITE_TIMEOUT)); // wait for end of execution of second queue VK_CHECK(vk.waitForFences(vkDevice, 1, &fenceTwo.get(), 0u, INFINITE_TIMEOUT)); return tcu::TestStatus::pass("executeSecondaryBufferTwiceTest succeeded"); } /******** 19.6. Commands Allowed Inside Command Buffers (? in VK 1.0 Spec) **/ tcu::TestStatus orderBindPipelineTest(Context& context) { const DeviceInterface& vk = context.getDeviceInterface(); const VkDevice device = context.getDevice(); const VkQueue queue = context.getUniversalQueue(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); Allocator& allocator = context.getDefaultAllocator(); const ComputeInstanceResultBuffer result (vk, device, allocator); enum { ADDRESSABLE_SIZE = 256, // allocate a lot more than required }; const tcu::Vec4 colorA1 = tcu::Vec4(0.0f, 1.0f, 0.0f, 1.0f); const tcu::Vec4 colorA2 = tcu::Vec4(1.0f, 1.0f, 0.0f, 1.0f); const tcu::Vec4 colorB1 = tcu::Vec4(1.0f, 0.0f, 0.0f, 1.0f); const tcu::Vec4 colorB2 = tcu::Vec4(0.0f, 0.0f, 1.0f, 1.0f); const deUint32 dataOffsetA = (0u); const deUint32 dataOffsetB = (0u); const deUint32 viewOffsetA = (0u); const deUint32 viewOffsetB = (0u); const deUint32 bufferSizeA = dataOffsetA + ADDRESSABLE_SIZE; const deUint32 bufferSizeB = dataOffsetB + ADDRESSABLE_SIZE; de::MovePtr<Allocation> bufferMemA; const Unique<VkBuffer> bufferA (createColorDataBuffer(dataOffsetA, bufferSizeA, colorA1, colorA2, &bufferMemA, context)); de::MovePtr<Allocation> bufferMemB; const Unique<VkBuffer> bufferB (createColorDataBuffer(dataOffsetB, bufferSizeB, colorB1, colorB2, &bufferMemB, context)); const Unique<VkDescriptorSetLayout> descriptorSetLayout (createDescriptorSetLayout(context)); const Unique<VkDescriptorPool> descriptorPool (createDescriptorPool(context)); const Unique<VkDescriptorSet> descriptorSet (createDescriptorSet(*descriptorPool, *descriptorSetLayout, *bufferA, viewOffsetA, *bufferB, viewOffsetB, result.getBuffer(), context)); const VkDescriptorSet descriptorSets[] = { *descriptorSet }; const int numDescriptorSets = DE_LENGTH_OF_ARRAY(descriptorSets); const VkPipelineLayoutCreateInfo layoutCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, // sType DE_NULL, // pNext (VkPipelineLayoutCreateFlags)0, numDescriptorSets, // setLayoutCount &descriptorSetLayout.get(), // pSetLayouts 0u, // pushConstantRangeCount DE_NULL, // pPushConstantRanges }; Unique<VkPipelineLayout> pipelineLayout (createPipelineLayout(vk, device, &layoutCreateInfo)); const Unique<VkShaderModule> computeModuleGood (createShaderModule(vk, device, context.getBinaryCollection().get("compute_good"), (VkShaderModuleCreateFlags)0u)); const Unique<VkShaderModule> computeModuleBad (createShaderModule(vk, device, context.getBinaryCollection().get("compute_bad"), (VkShaderModuleCreateFlags)0u)); const VkPipelineShaderStageCreateInfo shaderCreateInfoGood = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, DE_NULL, (VkPipelineShaderStageCreateFlags)0, VK_SHADER_STAGE_COMPUTE_BIT, // stage *computeModuleGood, // shader "main", DE_NULL, // pSpecializationInfo }; const VkPipelineShaderStageCreateInfo shaderCreateInfoBad = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, DE_NULL, (vk::VkPipelineShaderStageCreateFlags)0, vk::VK_SHADER_STAGE_COMPUTE_BIT, // stage *computeModuleBad, // shader "main", DE_NULL, // pSpecializationInfo }; const VkComputePipelineCreateInfo createInfoGood = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, DE_NULL, 0u, // flags shaderCreateInfoGood, // cs *pipelineLayout, // layout (vk::VkPipeline)0, // basePipelineHandle 0u, // basePipelineIndex }; const VkComputePipelineCreateInfo createInfoBad = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, DE_NULL, 0u, // flags shaderCreateInfoBad, // cs *pipelineLayout, // descriptorSetLayout.get() (VkPipeline)0, // basePipelineHandle 0u, // basePipelineIndex }; const Unique<VkPipeline> pipelineGood (createComputePipeline(vk, device, (VkPipelineCache)0u, &createInfoGood)); const Unique<VkPipeline> pipelineBad (createComputePipeline(vk, device, (VkPipelineCache)0u, &createInfoBad)); const VkAccessFlags inputBit = (VK_ACCESS_UNIFORM_READ_BIT); const VkBufferMemoryBarrier bufferBarriers[] = { { VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, DE_NULL, VK_ACCESS_HOST_WRITE_BIT, // srcAccessMask inputBit, // dstAccessMask VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex VK_QUEUE_FAMILY_IGNORED, // destQueueFamilyIndex *bufferA, // buffer (VkDeviceSize)0u, // offset (VkDeviceSize)bufferSizeA, // size }, { VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, DE_NULL, VK_ACCESS_HOST_WRITE_BIT, // srcAccessMask inputBit, // dstAccessMask VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex VK_QUEUE_FAMILY_IGNORED, // destQueueFamilyIndex *bufferB, // buffer (VkDeviceSize)0u, // offset (VkDeviceSize)bufferSizeB, // size } }; const deUint32 numSrcBuffers = 1u; const deUint32* const dynamicOffsets = (DE_NULL); const deUint32 numDynamicOffsets = (0); const int numPreBarriers = numSrcBuffers; const vk::VkBufferMemoryBarrier* const postBarriers = result.getResultReadBarrier(); const int numPostBarriers = 1; const tcu::Vec4 refQuadrantValue14 = (colorA2); const tcu::Vec4 refQuadrantValue23 = (colorA1); const tcu::Vec4 references[4] = { refQuadrantValue14, refQuadrantValue23, refQuadrantValue23, refQuadrantValue14, }; tcu::Vec4 results[4]; // submit and wait begin const tcu::UVec3 numWorkGroups = tcu::UVec3(4, 1u, 1); const VkCommandPoolCreateInfo cmdPoolCreateInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType; DE_NULL, // pNext VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, // flags queueFamilyIndex, // queueFamilyIndex }; const Unique<VkCommandPool> cmdPool (createCommandPool(vk, device, &cmdPoolCreateInfo)); const VkCommandBufferAllocateInfo cmdBufCreateInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType DE_NULL, // pNext *cmdPool, // commandPool VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level 1u, // bufferCount; }; const VkCommandBufferBeginInfo cmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType DE_NULL, // pNext 0u, // flags (const VkCommandBufferInheritanceInfo*)DE_NULL, }; const Unique<VkCommandBuffer> cmd (allocateCommandBuffer(vk, device, &cmdBufCreateInfo)); VK_CHECK(vk.beginCommandBuffer(*cmd, &cmdBufBeginInfo)); vk.cmdBindPipeline(*cmd, VK_PIPELINE_BIND_POINT_COMPUTE, *pipelineBad); vk.cmdBindPipeline(*cmd, VK_PIPELINE_BIND_POINT_COMPUTE, *pipelineGood); vk.cmdBindDescriptorSets(*cmd, VK_PIPELINE_BIND_POINT_COMPUTE, *pipelineLayout, 0, numDescriptorSets, descriptorSets, numDynamicOffsets, dynamicOffsets); if (numPreBarriers) vk.cmdPipelineBarrier(*cmd, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, numPreBarriers, bufferBarriers, 0, (const VkImageMemoryBarrier*)DE_NULL); vk.cmdDispatch(*cmd, numWorkGroups.x(), numWorkGroups.y(), numWorkGroups.z()); vk.cmdPipelineBarrier(*cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, numPostBarriers, postBarriers, 0, (const VkImageMemoryBarrier*)DE_NULL); endCommandBuffer(vk, *cmd); // run // submit second primary buffer, the secondary should be executed too submitCommandsAndWait(vk, device, queue, cmd.get()); // submit and wait end result.readResultContentsTo(&results); // verify if (results[0] == references[0] && results[1] == references[1] && results[2] == references[2] && results[3] == references[3]) { return tcu::TestStatus::pass("Pass"); } else if (results[0] == tcu::Vec4(-1.0f) && results[1] == tcu::Vec4(-1.0f) && results[2] == tcu::Vec4(-1.0f) && results[3] == tcu::Vec4(-1.0f)) { context.getTestContext().getLog() << tcu::TestLog::Message << "Result buffer was not written to." << tcu::TestLog::EndMessage; return tcu::TestStatus::fail("Result buffer was not written to"); } else { context.getTestContext().getLog() << tcu::TestLog::Message << "Error expected [" << references[0] << ", " << references[1] << ", " << references[2] << ", " << references[3] << "], got [" << results[0] << ", " << results[1] << ", " << results[2] << ", " << results[3] << "]" << tcu::TestLog::EndMessage; return tcu::TestStatus::fail("Invalid result values"); } } // Shaders void genComputeSource (SourceCollections& programCollection) { const char* const versionDecl = glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_310_ES); std::ostringstream bufGood; bufGood << versionDecl << "\n" << "" << "layout(local_size_x = 1u, local_size_y = 1u, local_size_z = 1u) in;\n" << "layout(set = 0, binding = 1u, std140) uniform BufferName\n" << "{\n" << " highp vec4 colorA;\n" << " highp vec4 colorB;\n" << "} b_instance;\n" << "layout(set = 0, binding = 0, std140) writeonly buffer OutBuf\n" << "{\n" << " highp vec4 read_colors[4];\n" << "} b_out;\n" << "void main(void)\n" << "{\n" << " highp int quadrant_id = int(gl_WorkGroupID.x);\n" << " highp vec4 result_color;\n" << " if (quadrant_id == 1 || quadrant_id == 2)\n" << " result_color = b_instance.colorA;\n" << " else\n" << " result_color = b_instance.colorB;\n" << " b_out.read_colors[gl_WorkGroupID.x] = result_color;\n" << "}\n"; programCollection.glslSources.add("compute_good") << glu::ComputeSource(bufGood.str()); std::ostringstream bufBad; bufBad << versionDecl << "\n" << "" << "layout(local_size_x = 1u, local_size_y = 1u, local_size_z = 1u) in;\n" << "layout(set = 0, binding = 1u, std140) uniform BufferName\n" << "{\n" << " highp vec4 colorA;\n" << " highp vec4 colorB;\n" << "} b_instance;\n" << "layout(set = 0, binding = 0, std140) writeonly buffer OutBuf\n" << "{\n" << " highp vec4 read_colors[4];\n" << "} b_out;\n" << "void main(void)\n" << "{\n" << " highp int quadrant_id = int(gl_WorkGroupID.x);\n" << " highp vec4 result_color;\n" << " if (quadrant_id == 1 || quadrant_id == 2)\n" << " result_color = b_instance.colorA;\n" << " else\n" << " result_color = b_instance.colorB;\n" << " b_out.read_colors[gl_WorkGroupID.x] = vec4(0.0, 0.0, 0.0, 0.0);\n" << "}\n"; programCollection.glslSources.add("compute_bad") << glu::ComputeSource(bufBad.str()); } void genComputeIncrementSource (SourceCollections& programCollection) { const char* const versionDecl = glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_310_ES); std::ostringstream bufIncrement; bufIncrement << versionDecl << "\n" << "" << "layout(local_size_x = 1u, local_size_y = 1u, local_size_z = 1u) in;\n" << "layout(set = 0, binding = 0, std140) buffer InOutBuf\n" << "{\n" << " coherent uint count;\n" << "} b_in_out;\n" << "void main(void)\n" << "{\n" << " atomicAdd(b_in_out.count, 1u);\n" << "}\n"; programCollection.glslSources.add("compute_increment") << glu::ComputeSource(bufIncrement.str()); } } // anonymous tcu::TestCaseGroup* createCommandBuffersTests (tcu::TestContext& testCtx) { de::MovePtr<tcu::TestCaseGroup> commandBuffersTests (new tcu::TestCaseGroup(testCtx, "command_buffers", "Command Buffers Tests")); /* 19.1. Command Pools (5.1 in VK 1.0 Spec) */ addFunctionCase (commandBuffersTests.get(), "pool_create_null_params", "", createPoolNullParamsTest); addFunctionCase (commandBuffersTests.get(), "pool_create_non_null_allocator", "", createPoolNonNullAllocatorTest); addFunctionCase (commandBuffersTests.get(), "pool_create_transient_bit", "", createPoolTransientBitTest); addFunctionCase (commandBuffersTests.get(), "pool_create_reset_bit", "", createPoolResetBitTest); addFunctionCase (commandBuffersTests.get(), "pool_reset_release_res", "", resetPoolReleaseResourcesBitTest); addFunctionCase (commandBuffersTests.get(), "pool_reset_no_flags_res", "", resetPoolNoFlagsTest); addFunctionCase (commandBuffersTests.get(), "pool_reset_reuse", "", resetPoolReuseTest); /* 19.2. Command Buffer Lifetime (5.2 in VK 1.0 Spec) */ addFunctionCase (commandBuffersTests.get(), "allocate_single_primary", "", allocatePrimaryBufferTest); addFunctionCase (commandBuffersTests.get(), "allocate_many_primary", "", allocateManyPrimaryBuffersTest); addFunctionCase (commandBuffersTests.get(), "allocate_single_secondary", "", allocateSecondaryBufferTest); addFunctionCase (commandBuffersTests.get(), "allocate_many_secondary", "", allocateManySecondaryBuffersTest); addFunctionCase (commandBuffersTests.get(), "execute_small_primary", "", executePrimaryBufferTest); addFunctionCase (commandBuffersTests.get(), "execute_large_primary", "", executeLargePrimaryBufferTest); addFunctionCase (commandBuffersTests.get(), "reset_implicit", "", resetBufferImplicitlyTest); addFunctionCase (commandBuffersTests.get(), "trim_command_pool", "", trimCommandPoolTest, VK_COMMAND_BUFFER_LEVEL_PRIMARY); addFunctionCase (commandBuffersTests.get(), "trim_command_pool_secondary", "", trimCommandPoolTest, VK_COMMAND_BUFFER_LEVEL_SECONDARY); /* 19.3. Command Buffer Recording (5.3 in VK 1.0 Spec) */ addFunctionCase (commandBuffersTests.get(), "record_single_primary", "", recordSinglePrimaryBufferTest); addFunctionCase (commandBuffersTests.get(), "record_many_primary", "", recordLargePrimaryBufferTest); addFunctionCase (commandBuffersTests.get(), "record_single_secondary", "", recordSingleSecondaryBufferTest); addFunctionCase (commandBuffersTests.get(), "record_many_secondary", "", recordLargeSecondaryBufferTest); addFunctionCase (commandBuffersTests.get(), "submit_twice_primary", "", submitPrimaryBufferTwiceTest); addFunctionCase (commandBuffersTests.get(), "submit_twice_secondary", "", submitSecondaryBufferTwiceTest); addFunctionCase (commandBuffersTests.get(), "record_one_time_submit_primary", "", oneTimeSubmitFlagPrimaryBufferTest); addFunctionCase (commandBuffersTests.get(), "record_one_time_submit_secondary", "", oneTimeSubmitFlagSecondaryBufferTest); addFunctionCase (commandBuffersTests.get(), "render_pass_continue", "", renderPassContinueTest); addFunctionCase (commandBuffersTests.get(), "record_simul_use_primary", "", simultaneousUsePrimaryBufferTest); addFunctionCase (commandBuffersTests.get(), "record_simul_use_secondary", "", simultaneousUseSecondaryBufferTest); addFunctionCaseWithPrograms (commandBuffersTests.get(), "record_simul_use_secondary_one_primary", "", genComputeIncrementSource, simultaneousUseSecondaryBufferOnePrimaryBufferTest); addFunctionCaseWithPrograms (commandBuffersTests.get(), "record_simul_use_secondary_two_primary", "", genComputeIncrementSource, simultaneousUseSecondaryBufferTwoPrimaryBuffersTest); addFunctionCase (commandBuffersTests.get(), "record_query_precise_w_flag", "", recordBufferQueryPreciseWithFlagTest); addFunctionCase (commandBuffersTests.get(), "record_query_imprecise_w_flag", "", recordBufferQueryImpreciseWithFlagTest); addFunctionCase (commandBuffersTests.get(), "record_query_imprecise_wo_flag", "", recordBufferQueryImpreciseWithoutFlagTest); /* 19.4. Command Buffer Submission (5.4 in VK 1.0 Spec) */ addFunctionCase (commandBuffersTests.get(), "submit_count_non_zero", "", submitBufferCountNonZero); addFunctionCase (commandBuffersTests.get(), "submit_count_equal_zero", "", submitBufferCountEqualZero); addFunctionCase (commandBuffersTests.get(), "submit_wait_single_semaphore", "", submitBufferWaitSingleSemaphore); addFunctionCase (commandBuffersTests.get(), "submit_wait_many_semaphores", "", submitBufferWaitManySemaphores); addFunctionCase (commandBuffersTests.get(), "submit_null_fence", "", submitBufferNullFence); addFunctionCase (commandBuffersTests.get(), "submit_two_buffers_one_buffer_null_with_fence", "", submitTwoBuffersOneBufferNullWithFence); /* 19.5. Secondary Command Buffer Execution (5.6 in VK 1.0 Spec) */ addFunctionCase (commandBuffersTests.get(), "secondary_execute", "", executeSecondaryBufferTest); addFunctionCase (commandBuffersTests.get(), "secondary_execute_twice", "", executeSecondaryBufferTwiceTest); /* 19.6. Commands Allowed Inside Command Buffers (? in VK 1.0 Spec) */ addFunctionCaseWithPrograms (commandBuffersTests.get(), "order_bind_pipeline", "", genComputeSource, orderBindPipelineTest); return commandBuffersTests.release(); } } // api } // vkt
#include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "walletmodel.h" #include "freicoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "base58.h" #include "main.h" #include <QMessageBox> #include <QLocale> #include <QTextDocument> #include <QScrollBar> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; int nBlockheight = nBestHeight; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } if(model && model->getOptionsModel()) { setBalance(model->getBalance(nBlockheight), model->getUnconfirmedBalance(nBlockheight), model->getImmatureBalance(nBlockheight)); connect(model, SIGNAL(balanceChanged(const mpq&, const mpq&, const mpq&)), this, SLOT(setBalance(const mpq&, const mpq&, const mpq&))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { QList<SendCoinsRecipient> recipients; bool valid = true; if(!model) return; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { formatted.append(tr("<b>%1</b> to %2 (%3)").arg(FreicoinUnits::formatWithUnit(FreicoinUnits::FRC, rcp.amount), Qt::escape(rcp.label), rcp.address)); } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(FreicoinUnits::formatWithUnit(FreicoinUnits::FRC, sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { delete ui->entries->takeAt(0)->widget(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); QCoreApplication::instance()->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { delete entry; updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseFreicoinURI(uri, &rv)) { CFreicoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(const mpq& balance, const mpq& unconfirmedBalance, const mpq& immatureBalance) { Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(!model || !model->getOptionsModel()) return; int unit = model->getOptionsModel()->getDisplayUnit(); ui->labelBalance->setText(FreicoinUnits::formatWithUnit(unit, RoundAbsolute(balance, ROUND_TOWARDS_ZERO))); } void SendCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update labelBalance with the current balance and the current unit ui->labelBalance->setText(FreicoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), RoundAbsolute(model->getBalance(nBestHeight), ROUND_TOWARDS_ZERO))); } }
class Solution { public: int divide(int dividend, int divisor) { if (dividend == INT_MIN && divisor == -1) return INT_MAX; int sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1; long long a = labs(dividend); long long b = labs(divisor); int res = 0; while (a >= b) { long unit = b; long q = 1; while (a >= unit) { res += q; a -= unit; unit <<= 1; q <<= 1; } } return sign * res; } };
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Type namespace: UnityEngine.Rendering namespace UnityEngine::Rendering { // Forward declaring type: OnDemandRendering class OnDemandRendering; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityEngine::Rendering::OnDemandRendering); DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::Rendering::OnDemandRendering*, "UnityEngine.Rendering", "OnDemandRendering"); // Type namespace: UnityEngine.Rendering namespace UnityEngine::Rendering { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: UnityEngine.Rendering.OnDemandRendering // [TokenAttribute] Offset: FFFFFFFF // [RequiredByNativeCodeAttribute] Offset: 662EB8 class OnDemandRendering : public ::Il2CppObject { public: // Get static field: static private System.Int32 m_RenderFrameInterval static int _get_m_RenderFrameInterval(); // Set static field: static private System.Int32 m_RenderFrameInterval static void _set_m_RenderFrameInterval(int value); // static public System.Int32 get_renderFrameInterval() // Offset: 0xBC124C static int get_renderFrameInterval(); // static private System.Void .cctor() // Offset: 0xBC1314 static void _cctor(); // static System.Void GetRenderFrameInterval(out System.Int32 frameInterval) // Offset: 0xBC12B0 static void GetRenderFrameInterval(ByRef<int> frameInterval); }; // UnityEngine.Rendering.OnDemandRendering #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::Rendering::OnDemandRendering::get_renderFrameInterval // Il2CppName: get_renderFrameInterval template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)()>(&UnityEngine::Rendering::OnDemandRendering::get_renderFrameInterval)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::Rendering::OnDemandRendering*), "get_renderFrameInterval", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::Rendering::OnDemandRendering::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&UnityEngine::Rendering::OnDemandRendering::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::Rendering::OnDemandRendering*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::Rendering::OnDemandRendering::GetRenderFrameInterval // Il2CppName: GetRenderFrameInterval template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(ByRef<int>)>(&UnityEngine::Rendering::OnDemandRendering::GetRenderFrameInterval)> { static const MethodInfo* get() { static auto* frameInterval = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Rendering::OnDemandRendering*), "GetRenderFrameInterval", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{frameInterval}); } };
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__unsigned_int_max_multiply_82_goodG2B.cpp Label Definition File: CWE190_Integer_Overflow.label.xml Template File: sources-sinks-82_goodG2B.tmpl.cpp */ /* * @description * CWE: 190 Integer Overflow * BadSource: max Set data to the max value for unsigned int * GoodSource: Set data to a small, non-zero number (two) * Sinks: multiply * GoodSink: Ensure there will not be an overflow before multiplying data by 2 * BadSink : If data is positive, multiply by 2, which can cause an overflow * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE190_Integer_Overflow__unsigned_int_max_multiply_82.h" namespace CWE190_Integer_Overflow__unsigned_int_max_multiply_82 { void CWE190_Integer_Overflow__unsigned_int_max_multiply_82_goodG2B::action(unsigned int data) { if(data > 0) /* ensure we won't have an underflow */ { /* POTENTIAL FLAW: if (data*2) > UINT_MAX, this will overflow */ unsigned int result = data * 2; printUnsignedLine(result); } } } #endif /* OMITGOOD */
/* Copyright (C) 2009 Carlo de Falco 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 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <octave/oct.h> #include "low_level_functions.h" #include <iostream> DEFUN_DLD(surfderivcpts, args, nargout,"\ \nSURFDERIVCPTS: Compute control points of n-th derivatives of a NURBS surface.\n \ \n \ \nusage: pkl = surfderivcpts (n, p, U, m, q, V, P, d) \ \n \ \n INPUT: \ \n\ \n n+1, m+1 = number of control points \ \n p, q = spline order \ \n U, V = knots \ \n P = control points \ \n d = derivative order \ \n\ \n OUTPUT: \ \n\ \n pkl (k+1, l+1, i+1, j+1) = i,jth control point \ \n of the surface differentiated k \ \n times in the u direction and l \ \n times in the v direction \ \n \ \n Adaptation of algorithm A3.7 from the NURBS book\n") { //function pkl = surfderivcpts (n, p, U, m, q, V, P, d, r1, r2, s1, s2) octave_value_list retval; octave_idx_type n = args(0).idx_type_value (); octave_idx_type p = args(1).idx_type_value (); RowVector U = args(2).row_vector_value (false, true); octave_idx_type m = args(3).idx_type_value (); octave_idx_type q = args(4).idx_type_value (); RowVector V = args(5).row_vector_value (false, true); Matrix P = args(6).matrix_value (); octave_idx_type d = args(7).idx_type_value (); octave_idx_type r1(0), r2 (n), s1 (0), s2 (m); if (args.length () == 12) { r1 = args (8).idx_type_value (); r2 = args (9).idx_type_value (); s1 = args (10).idx_type_value (); s2 = args (11).idx_type_value (); } else if (args.length () > 8) print_usage (); if (! error_state) { NDArray pkl; surfderivcpts (n, p, U, m, q, V, P, d, r1, r2, s1, s2, pkl); retval(0) = octave_value (pkl); } return retval; } /* %!test %! plane = nrbdegelev(nrb4surf([0 0], [0 1], [1 0], [1 1]), [1, 1]); %! %! pkl = surfderivcpts (plane.number(1)-1, plane.order(1)-1, %! plane.knots{1}, plane.number(2)-1, %! plane.order(2)-1, plane.knots{2}, %! squeeze (plane.coefs(1,:,:)), 2); %! %! %! pkl2 = [ 0 0 0 1 0 0 0 0 0 0 0 0 1 0 ... %! 0 0 0 0 0 0 0 1 0 0 0 0 0 0.5 0 ... %! 0 1 0 0 0 0 0 0.5 0 0 1 0 0 0 0 ... %! 0 0.5 0 0 1 0 0 0 0 0 1 0 0 0 0 ... %! 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 ... %! 0 0 0 0 0 0 0]'; %! %! assert (pkl(:),pkl2); */