diff
stringlengths 41
2.03M
| msg
stringlengths 1
1.5k
⌀ | repo
stringlengths 5
40
| sha
stringlengths 40
40
| time
stringlengths 20
20
|
---|---|---|---|---|
mmm a / modules / ml / src / svm . cpp <nl> ppp b / modules / ml / src / svm . cpp <nl> class SVMImpl : public SVM <nl> < < " alpha " < < " [ : " ; <nl> fs . writeRaw ( " d " , ( const uchar * ) & df_alpha [ df . ofs ] , sv_count * sizeof ( df_alpha [ 0 ] ) ) ; <nl> fs < < " ] " ; <nl> - if ( class_count > 2 ) <nl> + if ( class_count > = 2 ) <nl> { <nl> fs < < " index " < < " [ : " ; <nl> fs . writeRaw ( " i " , ( const uchar * ) & df_index [ df . ofs ] , sv_count * sizeof ( df_index [ 0 ] ) ) ; <nl> class SVMImpl : public SVM <nl> df_index . resize ( ofs + sv_count ) ; <nl> df_alpha . resize ( ofs + sv_count ) ; <nl> dfi [ " alpha " ] . readRaw ( " d " , ( uchar * ) & df_alpha [ ofs ] , sv_count * sizeof ( df_alpha [ 0 ] ) ) ; <nl> - if ( class_count > 2 ) <nl> + if ( class_count > = 2 ) <nl> dfi [ " index " ] . readRaw ( " i " , ( uchar * ) & df_index [ ofs ] , sv_count * sizeof ( df_index [ 0 ] ) ) ; <nl> decision_func . push_back ( df ) ; <nl> } <nl> - if ( class_count < = 2 ) <nl> + if ( class_count < 2 ) <nl> setRangeVector ( df_index , sv_total ) ; <nl> if ( ( int ) fn [ " optimize_linear " ] ! = 0 ) <nl> optimize_linear_svm ( ) ; <nl> | Enforced DecisionFunction vector indexes to be saved on SVM save / load methods | opencv/opencv | d046602ea4e2f8a9b08bd632073816d32fef9ab9 | 2016-03-29T19:35:27Z |
mmm a / tensorflow / core / grappler / optimizers / function_optimizer . cc <nl> ppp b / tensorflow / core / grappler / optimizers / function_optimizer . cc <nl> Status FunctionOptimizer : : Optimize ( Cluster * cluster , const GrapplerItem & item , <nl> GraphDef * optimized_graph ) { <nl> std : : unordered_map < string , const FunctionDef * > functions ; <nl> for ( const FunctionDef & func : item . graph . library ( ) . function ( ) ) { <nl> - if ( func . attr ( ) . count ( " _noinline " ) = = 0 ) { <nl> - functions [ func . signature ( ) . name ( ) ] = & func ; <nl> + / / Don ' t inline functions marked as noinline <nl> + if ( func . attr ( ) . count ( " _noinline " ) ! = 0 ) { <nl> + continue ; <nl> } <nl> + / / Can ' t create IdentityN nodes with no input or output : skip these <nl> + / / functions for now . <nl> + if ( func . signature ( ) . input_arg_size ( ) = = 0 | | <nl> + func . signature ( ) . output_arg_size ( ) = = 0 ) { <nl> + continue ; <nl> + } <nl> + functions [ func . signature ( ) . name ( ) ] = & func ; <nl> } <nl> <nl> / / Nothing to do . <nl> mmm a / tensorflow / core / grappler / optimizers / function_optimizer_test . cc <nl> ppp b / tensorflow / core / grappler / optimizers / function_optimizer_test . cc <nl> TEST_F ( FunctionOptimizerTest , FunctionWithInputForwarding ) { <nl> test : : ExpectTensorEqual < int > ( tensors_expected [ 2 ] , tensors [ 2 ] ) ; <nl> } <nl> <nl> + TEST_F ( FunctionOptimizerTest , FunctionWithoutInput ) { <nl> + const Tensor kTwo = test : : AsScalar < int64 > ( 2 ) ; <nl> + FunctionDef func = FunctionDefHelper : : Define ( <nl> + / / Name <nl> + " GenerateTwo " , <nl> + / / Args <nl> + { } , <nl> + / / Return value <nl> + { " o : T " } , <nl> + / / Attr def <nl> + { " T : { float , double } " } , <nl> + / / Nodes <nl> + { { { " two " } , " Const " , { } , { { " value " , kTwo } , { " dtype " , DT_INT64 } } } , <nl> + { { " o " } , " Cast " , { " two " } , { { " SrcT " , DT_INT64 } , { " DstT " , " $ T " } } } } ) ; <nl> + <nl> + GrapplerItem item ; <nl> + constexpr char device [ ] = " / device : CPU : 0 " ; <nl> + item . graph = test : : function : : GDef ( <nl> + { test : : function : : NDef ( " y " , " GenerateTwo " , { } , { } , device ) , <nl> + test : : function : : NDef ( " z " , " Identity " , { " y " } , { { " T " , DT_FLOAT } } , device ) } , <nl> + / / FunctionLib <nl> + { <nl> + func , <nl> + } ) ; <nl> + <nl> + FunctionOptimizer optimizer ; <nl> + GraphDef output ; <nl> + Status status = optimizer . Optimize ( nullptr , item , & output ) ; <nl> + TF_EXPECT_OK ( status ) ; <nl> + <nl> + / / For now we won ' t inline the function . <nl> + EXPECT_EQ ( item . graph . DebugString ( ) , output . DebugString ( ) ) ; <nl> + } <nl> + <nl> } / / namespace <nl> } / / namespace grappler <nl> } / / namespace tensorflow <nl> mmm a / tensorflow / core / grappler / utils / functions_test . cc <nl> ppp b / tensorflow / core / grappler / utils / functions_test . cc <nl> TEST_F ( FunctionsTest , FromFunctionDefWithInputForwarding ) { <nl> } <nl> } <nl> <nl> + TEST_F ( FunctionsTest , FromFunctionDefWithoutInput ) { <nl> + const Tensor kTwo = test : : AsScalar < int64 > ( 2 ) ; <nl> + FunctionDef func = FunctionDefHelper : : Define ( <nl> + / / Name <nl> + " GenerateTwo " , <nl> + / / Args <nl> + { } , <nl> + / / Return value <nl> + { " o : T " } , <nl> + / / Attr def <nl> + { " T : { float , double } " } , <nl> + / / Nodes <nl> + { { { " two " } , " Const " , { } , { { " value " , kTwo } , { " dtype " , DT_INT64 } } } , <nl> + { { " o " } , " Cast " , { " two " } , { { " SrcT " , DT_INT64 } , { " DstT " , " $ T " } } } } ) ; <nl> + <nl> + std : : unordered_map < string , AttrValue > func_attr ; <nl> + func_attr [ " T " ] . set_type ( DT_FLOAT ) ; <nl> + FunctionDefLibrary library ; <nl> + std : : unique_ptr < GrapplerItem > item = <nl> + GrapplerItemFromFunctionDef ( func , func_attr , library ) ; <nl> + <nl> + EXPECT_EQ ( 0 , item - > feed . size ( ) ) ; <nl> + EXPECT_EQ ( 1 , item - > fetch . size ( ) ) ; <nl> + EXPECT_EQ ( " o : 0 " , item - > fetch [ 0 ] ) ; <nl> + <nl> + EXPECT_EQ ( 2 , item - > graph . node_size ( ) ) ; <nl> + const NodeDef & two = item - > graph . node ( 0 ) ; <nl> + EXPECT_EQ ( " two " , two . name ( ) ) ; <nl> + EXPECT_EQ ( 0 , two . input_size ( ) ) ; <nl> + const NodeDef & cast = item - > graph . node ( 1 ) ; <nl> + EXPECT_EQ ( " o " , cast . name ( ) ) ; <nl> + EXPECT_EQ ( 1 , cast . input_size ( ) ) ; <nl> + EXPECT_EQ ( " two : 0 " , cast . input ( 0 ) ) ; <nl> + <nl> + std : : cout < < item - > graph . DebugString ( ) < < std : : endl ; <nl> + } <nl> + <nl> } / / namespace <nl> } / / namespace grappler <nl> } / / namespace tensorflow <nl> | Properly handle the case of functions with no inputs | tensorflow/tensorflow | 0c92f574d18cd01134bb9f7a5a679866a0f92f7e | 2018-03-03T01:22:01Z |
mmm a / caffe2 / core / plan_executor . cc <nl> ppp b / caffe2 / core / plan_executor . cc <nl> std : : function < bool ( int64_t ) > getContinuationTest ( <nl> } ; <nl> <nl> / / if the blob doesn ' t exist or is not initiaized , return false <nl> - inline const bool getShouldStop ( const Blob * b ) { <nl> + inline bool getShouldStop ( const Blob * b ) { <nl> if ( ! b | | ! b - > meta ( ) . id ( ) ) { / / not exist or uninitialized <nl> return false ; <nl> } <nl> mmm a / caffe2 / operators / text_file_reader_utils . h <nl> ppp b / caffe2 / operators / text_file_reader_utils . h <nl> class TokenizedString { <nl> const std : : vector < Token > & tokens ( ) const { <nl> return tokens_ ; <nl> } <nl> - const int lastDelim ( ) const { <nl> + int lastDelim ( ) const { <nl> return lastDelim_ ; <nl> } <nl> friend class Tokenizer ; <nl> | Remove const modifier where it has no effect | pytorch/pytorch | 03829e55b3c2e4eec415d2902750b370bf55c300 | 2017-11-29T16:32:06Z |
mmm a / xbmc / GUIDialogAddonSettings . cpp <nl> ppp b / xbmc / GUIDialogAddonSettings . cpp <nl> <nl> # include " GUIDialogOK . h " <nl> # include " GUIControlGroupList . h " <nl> # include " Util . h " <nl> + # include " StringUtils . h " <nl> # include " MediaManager . h " <nl> # include " GUILabelControl . h " <nl> # include " GUIRadioButtonControl . h " <nl> bool CGUIDialogAddonSettings : : ShowVirtualKeyboard ( int iControl ) <nl> bool bUseFileDirectories = false ; <nl> if ( option ) <nl> { <nl> - bUseThumbs = ( strcmpi ( option , " usethumbs " ) = = 0 | | strcmpi ( option , " usethumbs | treatasfolder " ) = = 0 ) ; <nl> - bUseFileDirectories = ( strcmpi ( option , " treatasfolder " ) = = 0 | | strcmpi ( option , " usethumbs | treatasfolder " ) = = 0 ) ; <nl> + vector < CStdString > options ; <nl> + StringUtils : : SplitString ( option , " | " , options ) ; <nl> + bUseThumbs = find ( options . begin ( ) , options . end ( ) , " usethumbs " ) ! = options . end ( ) ; <nl> + bUseFileDirectories = find ( options . begin ( ) , options . end ( ) , " treatasfolder " ) ! = options . end ( ) ; <nl> } <nl> <nl> if ( CGUIDialogFileBrowser : : ShowAndGetFile ( * shares , strMask , ( ( CGUIButtonControl * ) control ) - > GetLabel ( ) , value ) ) <nl> | changed : AddonSettings - better parsing of options for file / folder browse | xbmc/xbmc | 06fdc7c3c78a3a618878d102a8ce8b927d88722d | 2010-05-30T08:19:45Z |
mmm a / imgui . cpp <nl> ppp b / imgui . cpp <nl> static void RenderCollapseTriangle ( ImVec2 p_min , bool opened , float scal <nl> <nl> static void SetFont ( ImFont * font ) ; <nl> static bool ItemAdd ( const ImGuiAabb & bb , const ImGuiID * id ) ; <nl> - static void ItemSize ( ImVec2 size ) ; <nl> - static void ItemSize ( const ImGuiAabb & bb ) ; <nl> + static void ItemSize ( ImVec2 size , float text_offset_y = 0 . 0f ) ; <nl> + static void ItemSize ( const ImGuiAabb & bb , float text_offset_y = 0 . 0f ) ; <nl> static void PushColumnClipRect ( int column_index = - 1 ) ; <nl> static bool IsClipped ( const ImGuiAabb & bb ) ; <nl> <nl> struct ImGuiDrawContext <nl> ImVec2 CursorPosPrevLine ; <nl> ImVec2 CursorStartPos ; <nl> float CurrentLineHeight ; <nl> + float CurrentLineTextBaseOffset ; <nl> float PrevLineHeight ; <nl> + float PrevLineTextBaseOffset ; <nl> float LogLinePosY ; <nl> int TreeDepth ; <nl> ImGuiID LastItemID ; <nl> struct ImGuiDrawContext <nl> { <nl> CursorPos = CursorPosPrevLine = CursorStartPos = ImVec2 ( 0 . 0f , 0 . 0f ) ; <nl> CurrentLineHeight = PrevLineHeight = 0 . 0f ; <nl> + CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0 . 0f ; <nl> LogLinePosY = - 1 . 0f ; <nl> TreeDepth = 0 ; <nl> LastItemID = 0 ; <nl> bool ImGui : : Begin ( const char * name , bool * p_opened , const ImVec2 & size , float bg <nl> window - > DC . CursorPos = window - > DC . CursorStartPos ; <nl> window - > DC . CursorPosPrevLine = window - > DC . CursorPos ; <nl> window - > DC . CurrentLineHeight = window - > DC . PrevLineHeight = 0 . 0f ; <nl> + window - > DC . CurrentLineTextBaseOffset = window - > DC . PrevLineTextBaseOffset = 0 . 0f ; <nl> window - > DC . LogLinePosY = window - > DC . CursorPos . y - 9999 . 0f ; <nl> window - > DC . ChildWindows . resize ( 0 ) ; <nl> window - > DC . ItemWidth . resize ( 0 ) ; <nl> void ImGui : : TextUnformatted ( const char * text , const char * text_end ) <nl> / / We also don ' t vertically center the text within the line full height , which is unlikely to matter because we are likely the biggest and only item on the line . <nl> const char * line = text ; <nl> const float line_height = ImGui : : GetTextLineHeight ( ) ; <nl> - const ImVec2 start_pos = window - > DC . CursorPos ; <nl> + const ImVec2 text_pos = window - > DC . CursorPos + ImVec2 ( 0 . 0f , window - > DC . CurrentLineTextBaseOffset ) ; <nl> const ImVec4 clip_rect = window - > ClipRectStack . back ( ) ; <nl> ImVec2 text_size ( 0 , 0 ) ; <nl> <nl> - if ( start_pos . y < = clip_rect . w ) <nl> + if ( text_pos . y < = clip_rect . w ) <nl> { <nl> - ImVec2 pos = start_pos ; <nl> + ImVec2 pos = text_pos ; <nl> <nl> / / Lines to skip ( can ' t skip when logging text ) <nl> if ( ! g . LogEnabled ) <nl> { <nl> - int lines_skippable = ( int ) ( ( clip_rect . y - start_pos . y ) / line_height ) - 1 ; <nl> + int lines_skippable = ( int ) ( ( clip_rect . y - text_pos . y ) / line_height ) - 1 ; <nl> if ( lines_skippable > 0 ) <nl> { <nl> int lines_skipped = 0 ; <nl> void ImGui : : TextUnformatted ( const char * text , const char * text_end ) <nl> pos . y + = lines_skipped * line_height ; <nl> } <nl> <nl> - text_size . y + = ( pos - start_pos ) . y ; <nl> + text_size . y + = ( pos - text_pos ) . y ; <nl> } <nl> - const ImGuiAabb bb ( window - > DC . CursorPos , window - > DC . CursorPos + text_size ) ; <nl> + <nl> + ImGuiAabb bb ( text_pos , text_pos + text_size ) ; <nl> ItemSize ( bb ) ; <nl> ItemAdd ( bb , NULL ) ; <nl> } <nl> void ImGui : : TextUnformatted ( const char * text , const char * text_end ) <nl> { <nl> const float wrap_width = wrap_enabled ? CalcWrapWidthForPos ( window - > DC . CursorPos , wrap_pos_x ) : 0 . 0f ; <nl> const ImVec2 text_size = CalcTextSize ( text_begin , text_end , false , wrap_width ) ; <nl> - ImVec2 text_pos = window - > DC . CursorPos ; <nl> <nl> - / / Vertical centering over our line height <nl> - / / FIXME <nl> - const float line_height = ImMax ( window - > DC . CurrentLineHeight , text_size . y ) ; <nl> - text_pos . y + = ( line_height - text_size . y ) * 0 . 5f ; <nl> + / / Account of baseline offset <nl> + ImVec2 text_pos = window - > DC . CursorPos ; <nl> + text_pos . y + = window - > DC . CurrentLineTextBaseOffset ; <nl> <nl> - ImGuiAabb bb ( text_pos , window - > DC . CursorPos + text_size ) ; <nl> + ImGuiAabb bb ( text_pos , text_pos + text_size ) ; <nl> ItemSize ( bb . GetSize ( ) ) ; <nl> if ( ! ItemAdd ( bb , NULL ) ) <nl> return ; <nl> void ImGui : : AlignFirstTextHeightToWidgets ( ) <nl> return ; <nl> <nl> / / Declare a dummy item size to that upcoming items that are smaller will center - align on the newly expanded line height . <nl> - ItemSize ( ImVec2 ( 0 , window - > FontSize ( ) + g . Style . FramePadding . y * 2 ) ) ; <nl> + ItemSize ( ImVec2 ( 0 , window - > FontSize ( ) + g . Style . FramePadding . y * 2 ) , g . Style . FramePadding . y ) ; <nl> ImGui : : SameLine ( 0 , 0 ) ; <nl> } <nl> <nl> void ImGui : : LabelTextV ( const char * label , const char * fmt , va_list args ) <nl> const char * value_text_end = value_text_begin + ImFormatStringV ( g . TempBuffer , IM_ARRAYSIZE ( g . TempBuffer ) , fmt , args ) ; <nl> <nl> const ImVec2 label_size = CalcTextSize ( label , NULL , true ) ; <nl> - const ImGuiAabb value_bb ( window - > DC . CursorPos , window - > DC . CursorPos + ImVec2 ( w + style . FramePadding . x * 2 , label_size . y ) ) ; <nl> - const ImGuiAabb bb ( window - > DC . CursorPos , window - > DC . CursorPos + ImVec2 ( w + style . FramePadding . x * 2 + ( label_size . x > 0 . 0f ? style . ItemInnerSpacing . x : 0 . 0f ) , 0 . 0f ) + label_size ) ; <nl> - ItemSize ( bb ) ; <nl> + const ImGuiAabb value_bb ( window - > DC . CursorPos , window - > DC . CursorPos + ImVec2 ( w + style . FramePadding . x * 2 , label_size . y + style . FramePadding . y * 2 ) ) ; <nl> + const ImGuiAabb bb ( window - > DC . CursorPos , window - > DC . CursorPos + ImVec2 ( w + style . FramePadding . x * 2 + ( label_size . x > 0 . 0f ? style . ItemInnerSpacing . x : 0 . 0f ) , style . FramePadding . y * 2 ) + label_size ) ; <nl> + ItemSize ( bb , style . FramePadding . y ) ; <nl> if ( ! ItemAdd ( value_bb , NULL ) ) <nl> return ; <nl> <nl> / / Render <nl> - RenderTextClipped ( value_bb . Min , value_text_begin , value_text_end , NULL , value_bb . Max ) ; <nl> - RenderText ( ImVec2 ( value_bb . Max . x + style . ItemInnerSpacing . x , value_bb . Min . y ) , label ) ; <nl> + RenderTextClipped ( ImVec2 ( value_bb . Min . x , value_bb . Min . y + style . FramePadding . y ) , value_text_begin , value_text_end , NULL , value_bb . Max ) ; <nl> + RenderText ( ImVec2 ( value_bb . Max . x + style . ItemInnerSpacing . x , value_bb . Min . y + style . FramePadding . y ) , label ) ; <nl> } <nl> <nl> void ImGui : : LabelText ( const char * label , const char * fmt , . . . ) <nl> bool ImGui : : Button ( const char * label , const ImVec2 & size_arg , bool repeat_when_h <nl> <nl> const ImVec2 size ( size_arg . x ! = 0 . 0f ? size_arg . x : label_size . x , size_arg . y ! = 0 . 0f ? size_arg . y : label_size . y ) ; <nl> const ImGuiAabb bb ( window - > DC . CursorPos , window - > DC . CursorPos + size + style . FramePadding * 2 . 0f ) ; <nl> - ItemSize ( bb ) ; <nl> + ItemSize ( bb , style . FramePadding . y ) ; <nl> if ( ! ItemAdd ( bb , & id ) ) <nl> return false ; <nl> <nl> bool ImGui : : SmallButton ( const char * label ) <nl> const ImGuiID id = window - > GetID ( label ) ; <nl> const ImVec2 label_size = CalcTextSize ( label , NULL , true ) ; <nl> <nl> - const ImGuiAabb bb ( window - > DC . CursorPos , window - > DC . CursorPos + label_size + ImVec2 ( style . FramePadding . x * 2 , 0 ) ) ; <nl> + ImVec2 text_pos = window - > DC . CursorPos ; <nl> + text_pos . y + = window - > DC . CurrentLineTextBaseOffset ; <nl> + ImGuiAabb bb ( text_pos , text_pos + label_size + ImVec2 ( style . FramePadding . x * 2 , 0 ) ) ; <nl> ItemSize ( bb ) ; <nl> if ( ! ItemAdd ( bb , & id ) ) <nl> return false ; <nl> bool ImGui : : CollapsingHeader ( const char * label , const char * str_id , bool display <nl> bb . Max . y + = style . FramePadding . y * 2 ; <nl> } <nl> <nl> + / / FIXME : we don ' t provide our width so that it doesn ' t get feed back into AutoFit . Should manage that better so we can still hover without extending ContentsSize <nl> const ImGuiAabb text_bb ( bb . Min , bb . Min + ImVec2 ( window - > FontSize ( ) + style . FramePadding . x * 2 * 2 , 0 ) + label_size ) ; <nl> - ItemSize ( ImVec2 ( text_bb . GetSize ( ) . x , bb . GetSize ( ) . y ) ) ; / / NB : we don ' t provide our width so that it doesn ' t get feed back into AutoFit <nl> + ItemSize ( ImVec2 ( text_bb . GetSize ( ) . x , bb . GetSize ( ) . y ) , display_frame ? style . FramePadding . y : 0 . 0f ) ; <nl> <nl> / / When logging is enabled , if automatically expand tree nodes ( but * NOT * collapsing headers . . seems like sensible behavior ) . <nl> / / NB - If we are above max depth we still allow manually opened nodes to be logged . <nl> bool ImGui : : SliderFloat ( const char * label , float * v , float v_min , float v_max , c <nl> / / NB - we don ' t call ItemSize ( ) yet becausae we may turn into a text edit box below <nl> if ( ! ItemAdd ( frame_bb , & id ) ) <nl> { <nl> - ItemSize ( bb ) ; <nl> + ItemSize ( bb , style . FramePadding . y ) ; <nl> return false ; <nl> } <nl> <nl> bool ImGui : : SliderFloat ( const char * label , float * v , float v_min , float v_max , c <nl> if ( start_text_input | | ( g . ActiveId = = id & & id = = g . SliderAsInputTextId ) ) <nl> return SliderFloatAsInputText ( label , v , id , decimal_precision ) ; <nl> <nl> - ItemSize ( bb ) ; <nl> + ItemSize ( bb , style . FramePadding . y ) ; <nl> <nl> / / Actual slider behavior + render grab <nl> bool value_changed = SliderBehavior ( frame_bb , slider_bb , id , v , v_min , v_max , power , decimal_precision , true ) ; <nl> bool ImGui : : VSliderFloat ( const char * label , const ImVec2 & size , float * v , float <nl> const ImGuiAabb slider_bb ( frame_bb . Min + style . FramePadding , frame_bb . Max - style . FramePadding ) ; <nl> const ImGuiAabb bb ( frame_bb . Min , frame_bb . Max + ImVec2 ( label_size . x > 0 . 0f ? style . ItemInnerSpacing . x + label_size . x : 0 . 0f , 0 . 0f ) ) ; <nl> <nl> - ItemSize ( bb ) ; <nl> + ItemSize ( bb , style . FramePadding . y ) ; <nl> if ( ! ItemAdd ( frame_bb , & id ) ) <nl> return false ; <nl> <nl> static void Plot ( ImGuiPlotType plot_type , const char * label , float ( * values_gett <nl> const ImGuiAabb frame_bb ( window - > DC . CursorPos , window - > DC . CursorPos + ImVec2 ( graph_size . x , graph_size . y ) ) ; <nl> const ImGuiAabb graph_bb ( frame_bb . Min + style . FramePadding , frame_bb . Max - style . FramePadding ) ; <nl> const ImGuiAabb bb ( frame_bb . Min , frame_bb . Max + ImVec2 ( label_size . x > 0 . 0f ? style . ItemInnerSpacing . x + label_size . x : 0 . 0f , 0 ) ) ; <nl> - ItemSize ( bb ) ; <nl> + ItemSize ( bb , style . FramePadding . y ) ; <nl> if ( ! ItemAdd ( bb , NULL ) ) <nl> return ; <nl> <nl> bool ImGui : : Checkbox ( const char * label , bool * v ) <nl> const ImVec2 label_size = CalcTextSize ( label , NULL , true ) ; <nl> <nl> const ImGuiAabb check_bb ( window - > DC . CursorPos , window - > DC . CursorPos + ImVec2 ( label_size . y + style . FramePadding . y * 2 , label_size . y + style . FramePadding . y * 2 ) ) ; <nl> - ItemSize ( check_bb ) ; <nl> + ItemSize ( check_bb , style . FramePadding . y ) ; <nl> <nl> ImGuiAabb total_bb = check_bb ; <nl> if ( label_size . x > 0 ) <nl> bool ImGui : : Checkbox ( const char * label , bool * v ) <nl> const ImGuiAabb text_bb ( window - > DC . CursorPos + ImVec2 ( 0 , style . FramePadding . y ) , window - > DC . CursorPos + ImVec2 ( 0 , style . FramePadding . y ) + label_size ) ; <nl> if ( label_size . x > 0 ) <nl> { <nl> - ItemSize ( ImVec2 ( text_bb . GetWidth ( ) , check_bb . GetHeight ( ) ) ) ; <nl> + ItemSize ( ImVec2 ( text_bb . GetWidth ( ) , check_bb . GetHeight ( ) ) , style . FramePadding . y ) ; <nl> total_bb = ImGuiAabb ( ImMin ( check_bb . Min , text_bb . Min ) , ImMax ( check_bb . Max , text_bb . Max ) ) ; <nl> } <nl> <nl> bool ImGui : : RadioButton ( const char * label , bool active ) <nl> const ImVec2 label_size = CalcTextSize ( label , NULL , true ) ; <nl> <nl> const ImGuiAabb check_bb ( window - > DC . CursorPos , window - > DC . CursorPos + ImVec2 ( label_size . y + style . FramePadding . y * 2 - 1 , label_size . y + style . FramePadding . y * 2 - 1 ) ) ; <nl> - ItemSize ( check_bb ) ; <nl> + ItemSize ( check_bb , style . FramePadding . y ) ; <nl> <nl> ImGuiAabb total_bb = check_bb ; <nl> if ( label_size . x > 0 ) <nl> bool ImGui : : RadioButton ( const char * label , bool active ) <nl> const ImGuiAabb text_bb ( window - > DC . CursorPos + ImVec2 ( 0 , style . FramePadding . y ) , window - > DC . CursorPos + ImVec2 ( 0 , style . FramePadding . y ) + label_size ) ; <nl> if ( label_size . x > 0 ) <nl> { <nl> - ItemSize ( ImVec2 ( text_bb . GetWidth ( ) , check_bb . GetHeight ( ) ) ) ; <nl> + ItemSize ( ImVec2 ( text_bb . GetWidth ( ) , check_bb . GetHeight ( ) ) , style . FramePadding . y ) ; <nl> total_bb . Add ( text_bb ) ; <nl> } <nl> <nl> bool ImGui : : InputFloat ( const char * label , float * v , float step , float step_fast , <nl> if ( label_size . x > 0 ) <nl> { <nl> ImGui : : SameLine ( 0 , ( int ) style . ItemInnerSpacing . x ) ; <nl> - ItemSize ( label_size ) ; <nl> + ItemSize ( label_size , style . FramePadding . y ) ; <nl> RenderText ( ImVec2 ( frame_bb . Max . x + style . ItemInnerSpacing . x , frame_bb . Min . y + style . FramePadding . y ) , label ) ; <nl> } <nl> <nl> bool ImGui : : InputText ( const char * label , char * buf , size_t buf_size , ImGuiInputT <nl> const ImVec2 label_size = CalcTextSize ( label , NULL , true ) ; <nl> const ImGuiAabb frame_bb ( window - > DC . CursorPos , window - > DC . CursorPos + ImVec2 ( w , label_size . y ) + style . FramePadding * 2 . 0f ) ; <nl> const ImGuiAabb bb ( frame_bb . Min , frame_bb . Max + ImVec2 ( label_size . x > 0 . 0f ? ( style . ItemInnerSpacing . x + label_size . x ) : 0 . 0f , 0 . 0f ) ) ; <nl> - ItemSize ( bb ) ; <nl> + ItemSize ( bb , style . FramePadding . y ) ; <nl> if ( ! ItemAdd ( frame_bb , & id ) ) <nl> return false ; <nl> <nl> bool ImGui : : Combo ( const char * label , int * current_item , bool ( * items_getter ) ( voi <nl> const ImVec2 label_size = CalcTextSize ( label , NULL , true ) ; <nl> const ImGuiAabb frame_bb ( window - > DC . CursorPos , window - > DC . CursorPos + ImVec2 ( w , label_size . y ) + style . FramePadding * 2 . 0f ) ; <nl> const ImGuiAabb bb ( frame_bb . Min , frame_bb . Max + ImVec2 ( style . ItemInnerSpacing . x + label_size . x , 0 ) ) ; <nl> - ItemSize ( bb ) ; <nl> + ItemSize ( bb , style . FramePadding . y ) ; <nl> if ( ! ItemAdd ( frame_bb , & id ) ) <nl> return false ; <nl> <nl> void ImGui : : ListBoxFooter ( ) <nl> { <nl> ImGuiWindow * parent_window = GetParentWindow ( ) ; <nl> const ImGuiAabb bb = parent_window - > DC . LastItemAabb ; <nl> + const ImGuiStyle & style = ImGui : : GetStyle ( ) ; <nl> <nl> ImGui : : EndChildFrame ( ) ; <nl> <nl> parent_window - > DC . CursorPos = bb . Min ; <nl> - ItemSize ( bb ) ; <nl> + ItemSize ( bb , style . FramePadding . y ) ; <nl> } <nl> <nl> bool ImGui : : ListBox ( const char * label , int * current_item , const char * * items , int items_count , int height_items ) <nl> bool ImGui : : ColorButton ( const ImVec4 & col , bool small_height , bool outline_borde <nl> const ImGuiID id = window - > GetID ( " # colorbutton " ) ; <nl> const float square_size = window - > FontSize ( ) ; <nl> const ImGuiAabb bb ( window - > DC . CursorPos , window - > DC . CursorPos + ImVec2 ( square_size + style . FramePadding . x * 2 , square_size + ( small_height ? 0 : style . FramePadding . y * 2 ) ) ) ; <nl> - ItemSize ( bb ) ; <nl> + ItemSize ( bb , small_height ? 0 . 0f : style . FramePadding . y ) ; <nl> if ( ! ItemAdd ( bb , & id ) ) <nl> return false ; <nl> <nl> void ImGui : : Spacing ( ) <nl> } <nl> <nl> / / Advance cursor given item size . <nl> - static void ItemSize ( ImVec2 size ) <nl> + static void ItemSize ( ImVec2 size , float text_offset_y ) <nl> { <nl> ImGuiState & g = * GImGui ; <nl> ImGuiWindow * window = GetCurrentWindow ( ) ; <nl> static void ItemSize ( ImVec2 size ) <nl> <nl> / / Always align ourselves on pixel boundaries <nl> const float line_height = ImMax ( window - > DC . CurrentLineHeight , size . y ) ; <nl> + const float text_base_offset = ImMax ( window - > DC . CurrentLineTextBaseOffset , text_offset_y ) ; <nl> window - > DC . CursorPosPrevLine = ImVec2 ( window - > DC . CursorPos . x + size . x , window - > DC . CursorPos . y ) ; <nl> window - > DC . CursorPos = ImVec2 ( ( float ) ( int ) ( window - > Pos . x + window - > DC . ColumnsStartX + window - > DC . ColumnsOffsetX ) , ( float ) ( int ) ( window - > DC . CursorPos . y + line_height + g . Style . ItemSpacing . y ) ) ; <nl> <nl> window - > SizeContentsCurrent = ImMax ( window - > SizeContentsCurrent , ImVec2 ( window - > DC . CursorPosPrevLine . x - window - > Pos . x , window - > DC . CursorPos . y + window - > ScrollY - window - > Pos . y ) ) ; <nl> <nl> window - > DC . PrevLineHeight = line_height ; <nl> - window - > DC . CurrentLineHeight = 0 . 0f ; <nl> + window - > DC . PrevLineTextBaseOffset = text_base_offset ; <nl> + window - > DC . CurrentLineHeight = window - > DC . CurrentLineTextBaseOffset = 0 . 0f ; <nl> } <nl> <nl> - static inline void ItemSize ( const ImGuiAabb & bb ) <nl> + static inline void ItemSize ( const ImGuiAabb & bb , float text_offset_y ) <nl> { <nl> - ItemSize ( bb . GetSize ( ) ) ; <nl> + ItemSize ( bb . GetSize ( ) , text_offset_y ) ; <nl> } <nl> <nl> static bool IsClipped ( const ImGuiAabb & bb ) <nl> void ImGui : : SameLine ( int column_x , int spacing_w ) <nl> y = window - > DC . CursorPosPrevLine . y ; <nl> } <nl> window - > DC . CurrentLineHeight = window - > DC . PrevLineHeight ; <nl> + window - > DC . CurrentLineTextBaseOffset = window - > DC . PrevLineTextBaseOffset ; <nl> window - > DC . CursorPos = ImVec2 ( x , y ) ; <nl> } <nl> <nl> void ImGui : : NextColumn ( ) <nl> window - > DC . CursorPos . x = ( float ) ( int ) ( window - > Pos . x + window - > DC . ColumnsStartX + window - > DC . ColumnsOffsetX ) ; <nl> window - > DC . CursorPos . y = window - > DC . ColumnsCellMinY ; <nl> window - > DC . CurrentLineHeight = 0 . 0f ; <nl> + window - > DC . CurrentLineTextBaseOffset = 0 . 0f ; <nl> <nl> PushColumnClipRect ( ) ; <nl> ImGui : : PushItemWidth ( ImGui : : GetColumnWidth ( ) * 0 . 65f ) ; <nl> void ImGui : : ShowTestWindow ( bool * opened ) <nl> <nl> ImGui : : Separator ( ) ; <nl> <nl> + ImGui : : LabelText ( " label " , " Value " ) ; <nl> + <nl> static int item = 1 ; <nl> ImGui : : Combo ( " combo " , & item , " aaaa \ 0bbbb \ 0cccc \ 0dddd \ 0eeee \ 0 \ 0 " ) ; <nl> <nl> void ImGui : : ShowTestWindow ( bool * opened ) <nl> } <nl> ImGui : : PopID ( ) ; <nl> <nl> + ImGui : : SameLine ( ) ; <nl> + ImGui : : Text ( " Label " ) ; <nl> + <nl> ImGui : : Indent ( ) ; <nl> ImGui : : TreePop ( ) ; <nl> } <nl> void ImGui : : ShowTestWindow ( bool * opened ) <nl> ImGui : : PlotHistogram ( " Histogram " , arr , IM_ARRAYSIZE ( arr ) , 0 , NULL , 0 . 0f , 1 . 0f , ImVec2 ( 0 , 80 ) ) ; <nl> } <nl> <nl> - if ( ImGui : : CollapsingHeader ( " Horizontal Layout " ) ) <nl> + if ( ImGui : : CollapsingHeader ( " Layout " ) ) <nl> { <nl> - / / Text <nl> - ImGui : : Text ( " Hello " ) ; <nl> - ImGui : : SameLine ( ) ; <nl> - ImGui : : Text ( " World " ) ; <nl> + if ( ImGui : : TreeNode ( " Text Baseline Alignment " ) ) <nl> + { <nl> + ImGui : : TextWrapped ( " This is testing the vertical alignment that occurs on text to keep it at the same baseline as widgets . Lines only composed of text or \ " small \ " widgets fit in less vertical spaces than lines with normal widgets . " ) ; <nl> <nl> - / / Button <nl> - ImGui : : AlignFirstTextHeightToWidgets ( ) ; <nl> - ImGui : : Text ( " Normal buttons " ) ; <nl> - ImGui : : SameLine ( ) ; <nl> - if ( ImGui : : Button ( " Banana " ) ) printf ( " Pressed ! \ n " ) ; <nl> - ImGui : : SameLine ( ) ; <nl> - ImGui : : Button ( " Apple " ) ; <nl> - ImGui : : SameLine ( ) ; <nl> - ImGui : : Button ( " Corniflower " ) ; <nl> + ImGui : : Text ( " One \ nTwo \ nThree " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Text ( " Hello \ nWorld " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Text ( " Banana " ) ; <nl> <nl> - / / Button <nl> - ImGui : : Text ( " Small buttons " ) ; <nl> - ImGui : : SameLine ( ) ; <nl> - ImGui : : SmallButton ( " Like this one " ) ; <nl> - ImGui : : SameLine ( ) ; <nl> - ImGui : : Text ( " can fit within a text block . " ) ; <nl> + ImGui : : Text ( " Banana " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Text ( " Hello \ nWorld " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Text ( " One \ nTwo \ nThree " ) ; <nl> <nl> - / / Checkbox <nl> - static bool c1 = false , c2 = false , c3 = false , c4 = false ; <nl> - ImGui : : Checkbox ( " My " , & c1 ) ; <nl> - ImGui : : SameLine ( ) ; <nl> - ImGui : : Checkbox ( " Tailor " , & c2 ) ; <nl> - ImGui : : SameLine ( ) ; <nl> - ImGui : : Checkbox ( " Is " , & c3 ) ; <nl> - ImGui : : SameLine ( ) ; <nl> - ImGui : : Checkbox ( " Rich " , & c4 ) ; <nl> - <nl> - / / Various <nl> - static float f0 = 1 . 0f , f1 = 2 . 0f , f2 = 3 . 0f ; <nl> - ImGui : : PushItemWidth ( 80 ) ; <nl> - const char * items [ ] = { " AAAA " , " BBBB " , " CCCC " , " DDDD " } ; <nl> - static int item = - 1 ; <nl> - ImGui : : Combo ( " Combo " , & item , items , IM_ARRAYSIZE ( items ) ) ; <nl> - ImGui : : SameLine ( ) ; <nl> - ImGui : : SliderFloat ( " X " , & f0 , 0 . 0f , 5 . 0f ) ; <nl> - ImGui : : SameLine ( ) ; <nl> - ImGui : : SliderFloat ( " Y " , & f1 , 0 . 0f , 5 . 0f ) ; <nl> - ImGui : : SameLine ( ) ; <nl> - ImGui : : SliderFloat ( " Z " , & f2 , 0 . 0f , 5 . 0f ) ; <nl> - ImGui : : PopItemWidth ( ) ; <nl> + ImGui : : Button ( " HOP " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Text ( " Banana " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Text ( " Hello \ nWorld " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Text ( " Banana " ) ; <nl> + <nl> + ImGui : : Button ( " HOP " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Text ( " Hello \ nWorld " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Text ( " Banana " ) ; <nl> <nl> - ImGui : : PushItemWidth ( 80 ) ; <nl> - ImGui : : Text ( " Lists : " ) ; <nl> - static int selection [ 4 ] = { 0 , 1 , 2 , 3 } ; <nl> - for ( int i = 0 ; i < 4 ; i + + ) <nl> + ImGui : : Button ( " TEST " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Text ( " TEST " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : SmallButton ( " TEST " ) ; <nl> + <nl> + ImGui : : AlignFirstTextHeightToWidgets ( ) ; / / If your line starts with text , call this to align it to upcoming widgets . <nl> + ImGui : : Text ( " Text aligned to Widget " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Button ( " Widget " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Text ( " Widget " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : SmallButton ( " Widget " ) ; <nl> + <nl> + ImGui : : TreePop ( ) ; <nl> + } <nl> + <nl> + if ( ImGui : : TreeNode ( " Horizontal Layout using SameLine ( ) " ) ) <nl> { <nl> - if ( i > 0 ) ImGui : : SameLine ( ) ; <nl> - ImGui : : PushID ( i ) ; <nl> - ImGui : : ListBox ( " " , & selection [ i ] , items , IM_ARRAYSIZE ( items ) ) ; <nl> - ImGui : : PopID ( ) ; <nl> - / / if ( ImGui : : IsItemHovered ( ) ) ImGui : : SetTooltip ( " ListBox % d hovered " , i ) ; <nl> + / / Text <nl> + ImGui : : Text ( " Hello " ) ; <nl> + ImGui : : SameLine ( ) ; <nl> + ImGui : : TextColored ( ImVec4 ( 1 , 1 , 0 , 1 ) , " World " ) ; <nl> + <nl> + / / Button <nl> + ImGui : : AlignFirstTextHeightToWidgets ( ) ; <nl> + ImGui : : Text ( " Normal buttons " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Button ( " Banana " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Button ( " Apple " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Button ( " Corniflower " ) ; <nl> + <nl> + / / Button <nl> + ImGui : : Text ( " Small buttons " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : SmallButton ( " Like this one " ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Text ( " can fit within a text block . " ) ; <nl> + <nl> + / / Checkbox <nl> + static bool c1 = false , c2 = false , c3 = false , c4 = false ; <nl> + ImGui : : Checkbox ( " My " , & c1 ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Checkbox ( " Tailor " , & c2 ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Checkbox ( " Is " , & c3 ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : Checkbox ( " Rich " , & c4 ) ; <nl> + <nl> + / / Various <nl> + static float f0 = 1 . 0f , f1 = 2 . 0f , f2 = 3 . 0f ; <nl> + ImGui : : PushItemWidth ( 80 ) ; <nl> + const char * items [ ] = { " AAAA " , " BBBB " , " CCCC " , " DDDD " } ; <nl> + static int item = - 1 ; <nl> + ImGui : : Combo ( " Combo " , & item , items , IM_ARRAYSIZE ( items ) ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : SliderFloat ( " X " , & f0 , 0 . 0f , 5 . 0f ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : SliderFloat ( " Y " , & f1 , 0 . 0f , 5 . 0f ) ; ImGui : : SameLine ( ) ; <nl> + ImGui : : SliderFloat ( " Z " , & f2 , 0 . 0f , 5 . 0f ) ; <nl> + ImGui : : PopItemWidth ( ) ; <nl> + <nl> + ImGui : : PushItemWidth ( 80 ) ; <nl> + ImGui : : Text ( " Lists : " ) ; <nl> + static int selection [ 4 ] = { 0 , 1 , 2 , 3 } ; <nl> + for ( int i = 0 ; i < 4 ; i + + ) <nl> + { <nl> + if ( i > 0 ) ImGui : : SameLine ( ) ; <nl> + ImGui : : PushID ( i ) ; <nl> + ImGui : : ListBox ( " " , & selection [ i ] , items , IM_ARRAYSIZE ( items ) ) ; <nl> + ImGui : : PopID ( ) ; <nl> + / / if ( ImGui : : IsItemHovered ( ) ) ImGui : : SetTooltip ( " ListBox % d hovered " , i ) ; <nl> + } <nl> + ImGui : : PopItemWidth ( ) ; <nl> + <nl> + ImGui : : TreePop ( ) ; <nl> } <nl> - ImGui : : PopItemWidth ( ) ; <nl> } <nl> <nl> if ( ImGui : : CollapsingHeader ( " Child regions " ) ) <nl> | Various fixes related to vertical alignment of text after widget of various sizes . Added demos . Toward | ocornut/imgui | fd7f50d269bfee3d08908be372848c5ae12b159e | 2015-03-17T20:17:53Z |
mmm a / caffe2 / contrib / tensorrt / tensorrt_tranformer . cc <nl> ppp b / caffe2 / contrib / tensorrt / tensorrt_tranformer . cc <nl> void BlobToTensorProto ( <nl> } <nl> <nl> / / Set values <nl> - if ( blob - > template IsType < TensorCPU > ( ) ) { <nl> + if ( blob - > template IsType < Tensor > ( CPU ) ) { <nl> const auto & cpu_tensor = blob - > template Get < TensorCPU > ( ) ; <nl> CPUTensorToTensorProto ( cpu_tensor , t ) ; <nl> - } else if ( blob - > template IsType < TensorCUDA > ( ) ) { <nl> + } else if ( blob - > template IsType < Tensor > ( CUDA ) ) { <nl> const auto & cuda_tensor = blob - > template Get < TensorCUDA > ( ) ; <nl> const auto cpu_tensor = TensorCPU ( cuda_tensor , context ) ; <nl> context - > FinishDeviceComputation ( ) ; <nl> mmm a / caffe2 / core / blob . h <nl> ppp b / caffe2 / core / blob . h <nl> class Blob { <nl> * Checks if the content stored in the blob is of type T . <nl> * / <nl> template < class T > <nl> - bool IsType ( ) const { return meta_ . Match < T > ( ) ; } <nl> + bool IsType ( ) const { <nl> + return meta_ . Match < T > ( ) ; <nl> + } <nl> <nl> / / TODO ( jerryzh ) : Remove template <nl> template < class T > <nl> class Blob { <nl> meta_ . name ( ) , <nl> " while caller expects " , <nl> TypeMeta : : TypeName < T > ( ) ) ; <nl> + / / TODO : after we add Get < Tensor > ( DeviceType ) <nl> + / / and changed all the callsites , we can add <nl> + / / a static assert here to enforce T ! = Tensor <nl> return * static_cast < const T * > ( pointer_ ) ; <nl> } <nl> <nl> class Blob { <nl> } <nl> <nl> inline Tensor * GetMutableTensor ( DeviceType device_type ) { <nl> - if ( IsType < Tensor > ( ) & & <nl> - static_cast < Tensor * > ( pointer_ ) - > GetDeviceType ( ) = = device_type ) { <nl> + if ( IsType < Tensor > ( device_type ) ) { <nl> return static_cast < Tensor * > ( pointer_ ) ; <nl> } else { <nl> VLOG ( 1 ) < < " Create new mutable object " < < TypeMeta : : TypeName < Tensor > ( ) <nl> mmm a / caffe2 / core / operator . h <nl> ppp b / caffe2 / core / operator . h <nl> class OperatorBase : public Observable < OperatorBase > { <nl> / / Get the inputs and outputs as specific types . <nl> template < typename T > <nl> inline const T & Input ( int idx ) { <nl> + static_assert ( <nl> + ! std : : is_same < T , Tensor > : : value , <nl> + " You should use Input < Tensor > ( int , DeviceType ) for " <nl> + " Tensor . " ) ; <nl> DCHECK_LT ( idx , inputs_ . size ( ) ) ; <nl> try { <nl> return inputs_ . at ( idx ) - > template Get < T > ( ) ; <nl> class OperatorBase : public Observable < OperatorBase > { <nl> <nl> template < typename T > <nl> inline T * Output ( int idx ) { <nl> + static_assert ( <nl> + ! std : : is_same < T , Tensor > : : value , <nl> + " You should use Output < Tensor > ( int , DeviceType ) for " <nl> + " Tensor . " ) ; <nl> return outputs_ . at ( idx ) - > template GetMutable < T > ( ) ; <nl> } <nl> <nl> class OperatorBase : public Observable < OperatorBase > { <nl> <nl> template < typename T > <nl> inline bool InputIsType ( int idx ) { <nl> + static_assert ( <nl> + ! std : : is_same < T , Tensor > : : value , <nl> + " You should use InputIsType < Tensor > ( int , DeviceType ) for " <nl> + " Tensor . " ) ; <nl> return inputs_ . at ( idx ) - > template IsType < T > ( ) ; <nl> } <nl> <nl> class OperatorBase : public Observable < OperatorBase > { <nl> <nl> template < typename T > <nl> inline bool OutputIsType ( int idx ) { <nl> + static_assert ( <nl> + ! std : : is_same < T , Tensor > : : value , <nl> + " You should use OutputIsType < Tensor > ( int , DeviceType ) for " <nl> + " Tensor . " ) ; <nl> return outputs_ . at ( idx ) - > template IsType < T > ( ) ; <nl> } <nl> <nl> mmm a / caffe2 / mpi / mpi_ops . h <nl> ppp b / caffe2 / mpi / mpi_ops . h <nl> class MPIBroadcastOp final : public Operator < Context > { <nl> bool RunOnDevice ( ) override { <nl> MPI_Comm comm = OperatorBase : : Input < MPICommonWorldWrapper > ( 0 ) . comm ( ) ; <nl> CAFFE_ENFORCE ( <nl> - OperatorBase : : OutputIsType < Tensor > ( 0 ) , " Output is of wrong type . " ) ; <nl> + OperatorBase : : OutputIsType < Tensor > ( 0 , Context : : GetDeviceType ( ) ) , <nl> + " Output is of wrong type . " ) ; <nl> auto * output = Output ( 0 ) ; <nl> / / Make sure that output is already allocated . <nl> CAFFE_ENFORCE ( <nl> mmm a / caffe2 / observers / profile_observer_gpu . cc <nl> ppp b / caffe2 / observers / profile_observer_gpu . cc <nl> void ProfileOperatorObserver : : Dump ( ) const { <nl> LOG ( INFO ) < < " mmmmmmmmm Starting operator " < < subject_ - > debug_def ( ) . type ( ) <nl> < < " op # " < < getId ( ) < < " mmmmmmmmm " ; <nl> for ( int i = 0 ; i < subject_ - > InputSize ( ) ; + + i ) { <nl> - const auto & tensor = subject_ - > Input < Tensor > ( i ) ; <nl> - const auto & name = subject_ - > debug_def ( ) . input ( i ) ; <nl> - TensorPrinter printer ( name ) ; <nl> - LOG ( INFO ) < < " Input " < < i < < " : " < < printer . MetaStr ( tensor ) ; <nl> + if ( subject_ - > InputIsType < Tensor > ( i , CPU ) ) { <nl> + const auto & tensor = subject_ - > Input < Tensor > ( i , CPU ) ; <nl> + const auto & name = subject_ - > debug_def ( ) . input ( i ) ; <nl> + TensorPrinter printer ( name ) ; <nl> + LOG ( INFO ) < < " Input " < < i < < " : " < < printer . MetaStr ( tensor ) ; <nl> + } else if ( subject_ - > InputIsType < Tensor > ( i , CUDA ) ) { <nl> + const auto & tensor = subject_ - > Input < Tensor > ( i , CUDA ) ; <nl> + const auto & name = subject_ - > debug_def ( ) . input ( i ) ; <nl> + TensorPrinter printer ( name ) ; <nl> + LOG ( INFO ) < < " Input " < < i < < " : " < < printer . MetaStr ( tensor ) ; <nl> + } <nl> } <nl> <nl> int a = 0 ; <nl> mmm a / caffe2 / operators / gather_op . cu <nl> ppp b / caffe2 / operators / gather_op . cu <nl> __global__ void GatherKernel ( <nl> template < > <nl> bool GatherOp < CUDAContext > : : RunOnDevice ( ) { <nl> return DispatchHelper < TensorTypes < int32_t , int64_t > > : : call ( <nl> - this , OperatorBase : : Input < TensorCUDA > ( INDICES ) ) ; <nl> + this , OperatorBase : : Input < Tensor > ( INDICES , CUDA ) ) ; <nl> } <nl> <nl> template < > <nl> mmm a / caffe2 / operators / gather_op . h <nl> ppp b / caffe2 / operators / gather_op . h <nl> class GatherOp : public Operator < Context > { <nl> <nl> bool RunOnDevice ( ) override { <nl> return DispatchHelper < TensorTypes < int32_t , int64_t > > : : call ( <nl> - this , OperatorBase : : Input < TensorCPU > ( INDICES ) ) ; <nl> + this , OperatorBase : : Input < Tensor > ( INDICES , CPU ) ) ; <nl> } <nl> <nl> template < typename Index > <nl> | IsType < TensorCPU > - > IsType < Tensor > ( CPU ) ( ) | pytorch/pytorch | 3b3aff2ed6daf4d86999faa12b91e1aa1f2d0ce2 | 2018-08-04T00:24:59Z |
mmm a / include / swift / AST / KnownProtocols . def <nl> ppp b / include / swift / AST / KnownProtocols . def <nl> PROTOCOL ( Hashable ) <nl> PROTOCOL ( Comparable ) <nl> <nl> PROTOCOL ( _ObjectiveCBridgeable ) <nl> + PROTOCOL ( _DestructorSafeContainer ) <nl> <nl> LITERAL_CONVERTIBLE_PROTOCOL ( ArrayLiteralConvertible ) <nl> LITERAL_CONVERTIBLE_PROTOCOL ( BooleanLiteralConvertible ) <nl> mmm a / include / swift / SILAnalysis / Analysis . h <nl> ppp b / include / swift / SILAnalysis / Analysis . h <nl> namespace swift { <nl> PostOrder , <nl> ClassHierarchyAnalysis , <nl> RCIdentity , <nl> + Destructor <nl> } ; <nl> <nl> / / / Stores the kind of derived class . <nl> namespace swift { <nl> SILAnalysis * createPostOrderAnalysis ( SILModule * M ) ; <nl> SILAnalysis * createClassHierarchyAnalysis ( SILModule * M ) ; <nl> SILAnalysis * createRCIdentityAnalysis ( SILModule * M , SILPassManager * PM ) ; <nl> + SILAnalysis * createDestructorAnalysis ( SILModule * M ) ; <nl> } / / end namespace swift <nl> <nl> # endif <nl> new file mode 100644 <nl> index 000000000000 . . 6dce3be785f2 <nl> mmm / dev / null <nl> ppp b / include / swift / SILAnalysis / DestructorAnalysis . h <nl> <nl> + / / = = = mmm DestructorAnalysis . h mmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * - C + + - * mmmmmm = = = / / <nl> + / / <nl> + / / This source file is part of the Swift . org open source project <nl> + / / <nl> + / / Copyright ( c ) 2014 - 2015 Apple Inc . and the Swift project authors <nl> + / / Licensed under Apache License v2 . 0 with Runtime Library Exception <nl> + / / <nl> + / / See http : / / swift . org / LICENSE . txt for license information <nl> + / / See http : / / swift . org / CONTRIBUTORS . txt for the list of Swift project authors <nl> + / / <nl> + / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + # ifndef SWIFT_SILANALYSIS_DESTRUCTORANALYSIS_H <nl> + # define SWIFT_SILANALYSIS_DESTRUCTORANALYSIS_H <nl> + <nl> + # include " swift / SIL / SILValue . h " <nl> + # include " swift / SILAnalysis / Analysis . h " <nl> + <nl> + namespace swift { <nl> + <nl> + / / / This analysis determines memory effects during destruction . <nl> + class DestructorAnalysis : public SILAnalysis { <nl> + SILModule * Mod ; <nl> + public : <nl> + <nl> + DestructorAnalysis ( SILModule * M ) <nl> + : SILAnalysis ( AnalysisKind : : Destructor ) , Mod ( M ) { } <nl> + <nl> + static bool classof ( const SILAnalysis * S ) { <nl> + return S - > getKind ( ) = = AnalysisKind : : Destructor ; <nl> + } <nl> + <nl> + / / / Returns true if destruction of T may store to memory . <nl> + bool mayStoreToMemoryOnDestruction ( SILType T ) ; <nl> + <nl> + protected : <nl> + bool isSafeType ( Type ) ; <nl> + bool implementsDestructorSafeContainerProtocol ( NominalTypeDecl * ) ; <nl> + bool areTypeParametersSafe ( CanType ) ; <nl> + ASTContext & getASTContext ( ) ; <nl> + } ; <nl> + } <nl> + # endif <nl> mmm a / lib / SILAnalysis / CMakeLists . txt <nl> ppp b / lib / SILAnalysis / CMakeLists . txt <nl> add_swift_library ( swiftSILAnalysis <nl> CallGraphAnalysis . cpp <nl> SimplifyInstruction . cpp <nl> RCIdentityAnalysis . cpp <nl> + DestructorAnalysis . cpp <nl> DEPENDS swiftSILPassesUtils ) <nl> new file mode 100644 <nl> index 000000000000 . . 3f0f8fbd5c83 <nl> mmm / dev / null <nl> ppp b / lib / SILAnalysis / DestructorAnalysis . cpp <nl> <nl> + # include " swift / SILAnalysis / DestructorAnalysis . h " <nl> + # include " swift / SIL / SILInstruction . h " <nl> + # include " swift / AST / ASTContext . h " <nl> + # include " swift / AST / Decl . h " <nl> + # include " swift / SIL / SILModule . h " <nl> + # include " llvm / Support / Debug . h " <nl> + <nl> + # define DEBUG_TYPE " destructor - analysis " <nl> + <nl> + using namespace swift ; <nl> + <nl> + / / / A type T ' s destructor does not store to memory if the type <nl> + / / / * is a trivial builtin type like builtin float or int types <nl> + / / / * is a value type with stored properties that are safe or <nl> + / / / * is a value type that implements the _DestructorSafeContainer protocol and <nl> + / / / whose type parameters are safe types T1 . . . Tn . <nl> + bool DestructorAnalysis : : mayStoreToMemoryOnDestruction ( SILType T ) { <nl> + bool IsSafe = isSafeType ( T . getSwiftRValueType ( ) ) ; <nl> + DEBUG ( llvm : : dbgs ( ) < < " DestructorAnalysis : : mayStoreToMemoryOnDestruction is " <nl> + < < ( IsSafe ? " false : " : " true : " ) ) ; <nl> + DEBUG ( T . getSwiftRValueType ( ) - > dump ( ) ) ; <nl> + return ! IsSafe ; <nl> + } <nl> + <nl> + bool DestructorAnalysis : : isSafeType ( Type Ty ) { <nl> + CanType Cannonical = Ty . getCanonicalTypeOrNull ( ) ; <nl> + if ( Cannonical . isNull ( ) ) <nl> + return false ; <nl> + <nl> + / / Trivial value types . <nl> + if ( Cannonical - > getKind ( ) = = TypeKind : : BuiltinInteger ) <nl> + return true ; <nl> + if ( Cannonical - > getKind ( ) = = TypeKind : : BuiltinFloat ) <nl> + return true ; <nl> + <nl> + / / A struct is safe if <nl> + / / * either it implements the _DestructorSafeContainer protocol and <nl> + / / all the type parameters are safe types . <nl> + / / * or all stored properties are safe types . <nl> + if ( auto * Struct = Cannonical - > getStructOrBoundGenericStruct ( ) ) { <nl> + <nl> + if ( implementsDestructorSafeContainerProtocol ( Struct ) & & <nl> + areTypeParametersSafe ( Cannonical ) ) <nl> + return true ; <nl> + <nl> + / / Check the stored properties . <nl> + for ( auto SP : Struct - > getStoredProperties ( ) ) <nl> + if ( ! isSafeType ( SP - > getType ( ) ) ) <nl> + return false ; <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + / / A tuple type is safe if its elements are safe . <nl> + if ( auto Tuple = dyn_cast < TupleType > ( Cannonical ) ) { <nl> + for ( auto & Elt : Tuple - > getFields ( ) ) <nl> + if ( ! isSafeType ( Elt . getType ( ) ) ) <nl> + return false ; <nl> + return true ; <nl> + } <nl> + <nl> + / / TODO : enum types . <nl> + <nl> + return false ; <nl> + } <nl> + <nl> + bool DestructorAnalysis : : implementsDestructorSafeContainerProtocol ( <nl> + NominalTypeDecl * NomDecl ) { <nl> + ProtocolDecl * DestructorSafeContainer = <nl> + getASTContext ( ) . getProtocol ( KnownProtocolKind : : _DestructorSafeContainer ) ; <nl> + <nl> + for ( auto Proto : NomDecl - > getProtocols ( ) ) <nl> + if ( Proto = = DestructorSafeContainer ) <nl> + return true ; <nl> + <nl> + return false ; <nl> + } <nl> + <nl> + bool DestructorAnalysis : : areTypeParametersSafe ( CanType Ty ) { <nl> + auto BGT = dyn_cast < BoundGenericType > ( Ty ) ; <nl> + if ( ! BGT ) <nl> + return false ; <nl> + <nl> + / / Make sure all type parameters are safe . <nl> + for ( auto TP : BGT - > getGenericArgs ( ) ) { <nl> + if ( ! isSafeType ( TP ) ) <nl> + return false ; <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> + ASTContext & DestructorAnalysis : : getASTContext ( ) { <nl> + return Mod - > getASTContext ( ) ; <nl> + } <nl> + <nl> + SILAnalysis * swift : : createDestructorAnalysis ( SILModule * M ) { <nl> + return new DestructorAnalysis ( M ) ; <nl> + } <nl> mmm a / lib / SILPasses / Passes . cpp <nl> ppp b / lib / SILPasses / Passes . cpp <nl> static void registerAnalysisPasses ( SILPassManager & PM ) { <nl> PM . registerAnalysis ( createPostOrderAnalysis ( Mod ) ) ; <nl> PM . registerAnalysis ( createClassHierarchyAnalysis ( Mod ) ) ; <nl> PM . registerAnalysis ( createRCIdentityAnalysis ( Mod , & PM ) ) ; <nl> + PM . registerAnalysis ( createDestructorAnalysis ( Mod ) ) ; <nl> } <nl> <nl> bool swift : : runSILDiagnosticPasses ( SILModule & Module , <nl> mmm a / stdlib / core / Arrays . swift . gyb <nl> ppp b / stdlib / core / Arrays . swift . gyb <nl> if True : <nl> } % <nl> <nl> $ { SelfDocComment } <nl> - public struct $ { Self } < T > : MutableCollectionType , Sliceable { <nl> + public struct $ { Self } < T > : MutableCollectionType , Sliceable , _DestructorSafeContainer { <nl> / / / The type of element stored by this ` $ { Self } ` <nl> public typealias Element = T <nl> <nl> mmm a / stdlib / core / CompilerProtocols . swift <nl> ppp b / stdlib / core / CompilerProtocols . swift <nl> public protocol StringInterpolationConvertible { <nl> init < T > ( stringInterpolationSegment expr : T ) <nl> } <nl> <nl> + / / / A container is destructor safe if whether it may store to memory on <nl> + / / / destruction only depends on its type parameters . <nl> + / / / For example , whether Array < T > may store to memory on destruction depends <nl> + / / / only on T . <nl> + / / / If T is an Int we know the Array < Int > does not store to memory during <nl> + / / / destruction . If T is an arbitrary class Array < MemoryUnsafeDestructorClass > <nl> + / / / then the compiler will deduce may store to memory on destruction because <nl> + / / / MemoryUnsafeDestructorClass ' destructor may store to memory on destruction . <nl> + public protocol _DestructorSafeContainer { <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . 84eb752dfa67 <nl> mmm / dev / null <nl> ppp b / test / SILAnalysis / DestructorAnalysis . swift <nl> <nl> + / / RUN : % swift - O - emit - sil % s - Xllvm - debug - only = destructor - analysis 2 > & 1 | FileCheck % s <nl> + <nl> + / / This test depends on asserts because we look at debug output . <nl> + / / REQUIRES : asserts <nl> + <nl> + class Foo { } <nl> + <nl> + var a : [ Int ] = [ ] <nl> + var b : [ [ Int ] ] = [ [ ] ] <nl> + var c : [ Foo ] = [ ] <nl> + var d : [ [ Foo ] ] = [ [ ] ] <nl> + <nl> + a . append ( 1 ) <nl> + b . append ( [ 1 ] ) <nl> + c . append ( Foo ( ) ) <nl> + d . append ( [ Foo ( ) ] ) <nl> + <nl> + / / CHECK - DAG : mayStoreToMemoryOnDestruction is false : Array < Int > <nl> + / / CHECK - DAG : mayStoreToMemoryOnDestruction is false : Builtin . Word <nl> + / / CHECK - DAG : mayStoreToMemoryOnDestruction is false : Array < Array < Int > > <nl> + / / CHECK - DAG : mayStoreToMemoryOnDestruction is true : Array < Foo > <nl> + / / CHECK - DAG : mayStoreToMemoryOnDestruction is true : Array < Array < Foo > > <nl> + / / CHECK - DAG : mayStoreToMemoryOnDestruction is true : Array < T > <nl> mmm a / tools / sil - opt / SILOpt . cpp <nl> ppp b / tools / sil - opt / SILOpt . cpp <nl> static void runCommandLineSelectedPasses ( SILModule * Module , <nl> PM . registerAnalysis ( createPostOrderAnalysis ( Module ) ) ; <nl> PM . registerAnalysis ( createClassHierarchyAnalysis ( Module ) ) ; <nl> PM . registerAnalysis ( createRCIdentityAnalysis ( Module , & PM ) ) ; <nl> + PM . registerAnalysis ( createDestructorAnalysis ( Module ) ) ; <nl> <nl> for ( auto Pass : Passes ) { <nl> switch ( Pass ) { <nl> | Add a destructor memory effect analysis | apple/swift | 06a0a235629e5e36167dda4412181278030bb168 | 2014-11-11T19:27:41Z |
mmm a / xbmc / cores / VideoPlayer / DVDCodecs / Video / VAAPI . cpp <nl> ppp b / xbmc / cores / VideoPlayer / DVDCodecs / Video / VAAPI . cpp <nl> void COutput : : InitCycle ( ) <nl> / / and use for direct export , so we run into trouble if we or the user want to switch <nl> / / deinterlacing on / off mid - stream . <nl> / / See also : https : / / bugs . freedesktop . org / show_bug . cgi ? id = 105145 <nl> - const bool alwaysInsertVpp = m_config . driverIsMesa & & ( ( m_config . vidWidth * m_config . vidHeight ) < = ( 1920 * 1080 ) ) ; <nl> + const bool alwaysInsertVpp = m_config . driverIsMesa & & <nl> + ( ( m_config . vidWidth * m_config . vidHeight ) < = ( 1920 * 1080 ) ) & & <nl> + interlaced ; <nl> <nl> m_config . stats - > SetVpp ( false ) ; <nl> if ( ! preferVaapiRender ) <nl> | VideoPlayer : vaapi - fix quirk for mesa | xbmc/xbmc | 4f04d746233eaa9996987a1a63dc648a5d898942 | 2018-06-10T17:25:36Z |
mmm a / src / citra / src / citra . cpp <nl> ppp b / src / citra / src / citra . cpp <nl> int __cdecl main ( int argc , char * * argv ) { <nl> <nl> System : : Init ( emu_window ) ; <nl> <nl> - / / if ( E_OK ! = Core : : Init ( emu_window ) ) { <nl> - / / LOG_ERROR ( TMASTER , " core initialization failed , exiting . . . " ) ; <nl> - / / core : : Kill ( ) ; <nl> - / / exit ( 1 ) ; <nl> - / / } <nl> - <nl> - / / / / Load a game or die . . . <nl> - / / if ( E_OK = = dvd : : LoadBootableFile ( common : : g_config - > default_boot_file ( ) ) ) { <nl> - / / if ( common : : g_config - > enable_auto_boot ( ) ) { <nl> - / / core : : Start ( ) ; <nl> - / / } else { <nl> - / / LOG_ERROR ( TMASTER , " Autoboot required in no - GUI mode . . . Exiting ! \ n " ) ; <nl> - / / } <nl> - / / } else { <nl> - / / LOG_ERROR ( TMASTER , " Failed to load a bootable file . . . Exiting ! \ n " ) ; <nl> - / / exit ( E_ERR ) ; <nl> - / / } <nl> - / / / / run the game <nl> - / / while ( core : : SYS_DIE ! = core : : g_state ) { <nl> - / / if ( core : : SYS_RUNNING = = core : : g_state ) { <nl> - / / if ( ! ( cpu - > is_on ) ) { <nl> - / / cpu - > Start ( ) ; / / Initialize and start CPU . <nl> - / / } else { <nl> - / / for ( tight_loop = 0 ; tight_loop < 10000 ; + + tight_loop ) { <nl> - / / cpu - > execStep ( ) ; <nl> - / / } <nl> - / / } <nl> - / / } else if ( core : : SYS_HALTED = = core : : g_state ) { <nl> - / / core : : Stop ( ) ; <nl> - / / } <nl> - / / } <nl> - / / core : : Kill ( ) ; <nl> - <nl> std : : string boot_filename = " homebrew . elf " ; <nl> std : : string error_str ; <nl> <nl> int __cdecl main ( int argc , char * * argv ) { <nl> if ( ! res ) { <nl> ERROR_LOG ( BOOT , " Failed to load ROM : % s " , error_str . c_str ( ) ) ; <nl> } <nl> - for ( int tight_loop = 0 ; tight_loop < 10000 ; + + tight_loop ) { <nl> + <nl> + for ( ; ; ) { <nl> Core : : SingleStep ( ) ; <nl> } <nl> <nl> | removed unused comments , changed main processing loop to be infinite | yuzu-emu/yuzu | efef514fd8252e1f07cd1b45455dbb5207f2b0c3 | 2014-04-07T04:53:47Z |
mmm a / buildscripts / idl / idl / ast . py <nl> ppp b / buildscripts / idl / idl / ast . py <nl> def __init__ ( self , file_name , line , column ) : <nl> self . redact = False # type : bool <nl> self . test_only = False # type : bool <nl> self . deprecated_name = [ ] # type : List [ unicode ] <nl> - <nl> - # Only valid if cpp_varname or cpp_class is specified . <nl> self . default = None # type : Expression <nl> <nl> # Only valid if cpp_varname is specified . <nl> self . validator = None # type : Validator <nl> self . on_update = None # type : unicode <nl> <nl> - # Required if cpp_varname is NOT specified . <nl> - self . from_bson = None # type : unicode <nl> - self . append_bson = None # type : unicode <nl> - self . from_string = None # type : unicode <nl> - <nl> super ( ServerParameter , self ) . __init__ ( file_name , line , column ) <nl> <nl> <nl> mmm a / buildscripts / idl / idl / binder . py <nl> ppp b / buildscripts / idl / idl / binder . py <nl> def _bind_server_parameter_class ( ctxt , ast_param , param ) : <nl> " " " Bind and validate ServerParameter attributes specific to specialized ServerParameters . " " " <nl> <nl> # Fields specific to bound and unbound standard params . <nl> - for field in [ <nl> - ' cpp_vartype ' , ' cpp_varname ' , ' on_update ' , ' validator ' , ' append_bson ' , ' from_bson ' , <nl> - ' from_string ' <nl> - ] : <nl> + for field in [ ' cpp_vartype ' , ' cpp_varname ' , ' on_update ' , ' validator ' ] : <nl> if getattr ( param , field ) is not None : <nl> ctxt . add_server_parameter_invalid_attr ( param , field , ' specialized ' ) <nl> return None <nl> def _bind_server_parameter_with_storage ( ctxt , ast_param , param ) : <nl> " " " Bind and validate ServerParameter attributes specific to bound ServerParameters . " " " <nl> <nl> # Fields specific to specialized and unbound standard params . <nl> - for field in [ ' cpp_class ' , ' append_bson ' , ' from_bson ' , ' from_string ' ] : <nl> + for field in [ ' cpp_class ' ] : <nl> if getattr ( param , field ) is not None : <nl> ctxt . add_server_parameter_invalid_attr ( param , field , ' bound ' ) <nl> return None <nl> def _bind_server_parameter_with_storage ( ctxt , ast_param , param ) : <nl> return ast_param <nl> <nl> <nl> - def _bind_server_parameter_without_storage ( ctxt , ast_param , param ) : <nl> - # type : ( errors . ParserContext , ast . ServerParameter , syntax . ServerParameter ) - > ast . ServerParameter <nl> - " " " Bind and validate ServerParameter attributes specific to unbound ServerParameters . " " " <nl> - <nl> - # Fields specific to specialized and unbound standard params . <nl> - for field in [ ' cpp_class ' , ' cpp_vartype ' , ' cpp_varname ' , ' default ' , ' on_update ' , ' validator ' ] : <nl> - if getattr ( param , field ) is not None : <nl> - ctxt . add_server_parameter_invalid_attr ( param , field , ' unbound ' ) <nl> - return None <nl> - <nl> - if param . from_string is None : <nl> - ctxt . add_server_parameter_required_attr ( param , ' from_string ' , ' unbound ' ) <nl> - return None <nl> - <nl> - if ( not param . redact ) and ( param . append_bson is None ) : <nl> - ctxt . add_server_parameter_required_attr ( param , ' append_bson ' , ' unbound ' ) <nl> - return None <nl> - <nl> - ast_param . append_bson = param . append_bson <nl> - ast_param . from_bson = param . from_bson <nl> - ast_param . from_string = param . from_string <nl> - <nl> - if param . validator is not None : <nl> - ast_param . validator = _bind_validator ( ctxt , param . validator ) <nl> - if ast_param . validator is None : <nl> - return None <nl> - <nl> - return ast_param <nl> - <nl> - <nl> def _bind_server_parameter_set_at ( ctxt , param ) : <nl> # type : ( errors . ParserContext , syntax . ServerParameter ) - > unicode <nl> " " " Translate set_at options to C + + enum value . " " " <nl> def _bind_server_parameter ( ctxt , param ) : <nl> elif param . cpp_varname : <nl> return _bind_server_parameter_with_storage ( ctxt , ast_param , param ) <nl> else : <nl> - return _bind_server_parameter_without_storage ( ctxt , ast_param , param ) <nl> + ctxt . add_server_parameter_required_attr ( param , ' cpp_varname ' , ' server_parameter ' ) <nl> + return None <nl> <nl> <nl> def _is_invalid_config_short_name ( name ) : <nl> mmm a / buildscripts / idl / idl / generator . py <nl> ppp b / buildscripts / idl / idl / generator . py <nl> def _gen_server_parameter_with_storage ( self , param ) : <nl> <nl> self . _writer . write_line ( ' return ret ; ' ) <nl> <nl> - def _gen_server_parameter_without_storage ( self , param ) : <nl> - # type : ( ast . ServerParameter ) - > None <nl> - " " " Generate a single IDLServerParameter . " " " <nl> - self . _writer . write_line ( <nl> - common . template_args ( ' auto * ret = new IDLServerParameter ( $ { name } , $ { spt } ) ; ' , <nl> - spt = param . set_at , name = _encaps ( param . name ) ) ) <nl> - if param . from_bson : <nl> - self . _writer . write_line ( ' ret - > setFromBSON ( % s ) ; ' % ( param . from_bson ) ) <nl> - <nl> - if param . append_bson : <nl> - self . _writer . write_line ( ' ret - > setAppendBSON ( % s ) ; ' % ( param . append_bson ) ) <nl> - elif param . redact : <nl> - self . _writer . write_line ( ' ret - > setAppendBSON ( IDLServerParameter : : redactedAppendBSON ) ; ' ) <nl> - <nl> - self . _writer . write_line ( ' ret - > setFromString ( % s ) ; ' % ( param . from_string ) ) <nl> - self . _writer . write_line ( ' return ret ; ' ) <nl> - <nl> def _gen_server_parameter ( self , param ) : <nl> # type : ( ast . ServerParameter ) - > None <nl> " " " Generate a single IDLServerParameter ( WithStorage ) . " " " <nl> if param . cpp_class is not None : <nl> self . _gen_server_parameter_specialized ( param ) <nl> - elif param . cpp_varname is not None : <nl> - self . _gen_server_parameter_with_storage ( param ) <nl> else : <nl> - self . _gen_server_parameter_without_storage ( param ) <nl> + self . _gen_server_parameter_with_storage ( param ) <nl> <nl> def _gen_server_parameter_deprecated_aliases ( self , param_no , param ) : <nl> # type : ( int , ast . ServerParameter ) - > None <nl> mmm a / buildscripts / idl / idl / parser . py <nl> ppp b / buildscripts / idl / idl / parser . py <nl> def _parse_server_parameter ( ctxt , spec , name , node ) : <nl> " default " : _RuleDesc ( ' scalar_or_mapping ' , mapping_parser_func = _parse_expression ) , <nl> " test_only " : _RuleDesc ( ' bool_scalar ' ) , <nl> " deprecated_name " : _RuleDesc ( ' scalar_or_sequence ' ) , <nl> - " from_bson " : _RuleDesc ( ' scalar ' ) , <nl> - " append_bson " : _RuleDesc ( ' scalar ' ) , <nl> - " from_string " : _RuleDesc ( ' scalar ' ) , <nl> " validator " : _RuleDesc ( ' mapping ' , mapping_parser_func = _parse_validator ) , <nl> " on_update " : _RuleDesc ( " scalar " ) , <nl> " cpp_class " : _RuleDesc ( ' scalar_or_mapping ' , mapping_parser_func = map_class ) , <nl> mmm a / buildscripts / idl / idl / syntax . py <nl> ppp b / buildscripts / idl / idl / syntax . py <nl> def __init__ ( self , file_name , line , column ) : <nl> self . deprecated_name = [ ] # type : List [ unicode ] <nl> self . redact = False # type : bool <nl> self . test_only = False # type : bool <nl> - <nl> - # Only valid if cpp_varname or cpp_class is specified . <nl> self . default = None # type : Expression <nl> <nl> # Only valid if cpp_varname is specified . <nl> self . validator = None # type : Validator <nl> self . on_update = None # type : unicode <nl> <nl> - # Required if cpp_varname is not specified . <nl> - self . from_bson = None # type : unicode <nl> - self . append_bson = None # type : unicode <nl> - self . from_string = None # type : unicode <nl> - <nl> super ( ServerParameter , self ) . __init__ ( file_name , line , column ) <nl> <nl> <nl> mmm a / buildscripts / idl / tests / test_binder . py <nl> ppp b / buildscripts / idl / tests / test_binder . py <nl> def test_server_parameter_positive ( self ) : <nl> # type : ( ) - > None <nl> " " " Positive server parameter test cases . " " " <nl> <nl> - # server parameter without storage . <nl> - self . assert_bind ( <nl> - textwrap . dedent ( " " " <nl> - server_parameters : <nl> - foo : <nl> - set_at : startup <nl> - description : bar <nl> - append_bson : baz <nl> - from_bson : buzz <nl> - from_string : qux <nl> - " " " ) ) <nl> - <nl> # server parameter with storage . <nl> # Also try valid set_at values . <nl> for set_at in [ " startup " , " runtime " , " [ startup , runtime ] " ] : <nl> def test_server_parameter_positive ( self ) : <nl> callback : qux <nl> " " " ) ) <nl> <nl> - # Custom setting missing from_bson callback , okay because default impl works . <nl> - self . assert_bind ( <nl> - textwrap . dedent ( " " " <nl> - server_parameters : <nl> - foo : <nl> - set_at : startup <nl> - description : bar <nl> - append_bson : baz <nl> - from_string : qux <nl> - " " " ) ) <nl> - <nl> - # Custom setting with only from_string callback , and auto - redaction . <nl> - self . assert_bind ( <nl> - textwrap . dedent ( " " " <nl> - server_parameters : <nl> - foo : <nl> - set_at : startup <nl> - description : bar <nl> - redact : true <nl> - from_string : baz <nl> - " " " ) ) <nl> - <nl> # Bound setting with arbitrary expression default and validators . <nl> self . assert_bind ( <nl> textwrap . dedent ( " " " <nl> def test_server_parameter_negative ( self ) : <nl> # type : ( ) - > None <nl> " " " Negative server parameter test cases . " " " <nl> <nl> - # server parameter without storage requires all get / set callbacks . <nl> - self . assert_bind_fail ( <nl> - textwrap . dedent ( " " " <nl> - server_parameters : <nl> - foo : <nl> - set_at : startup <nl> - description : bar <nl> - append_bson : baz <nl> - from_bson : buzz <nl> - " " " ) , idl . errors . ERROR_ID_SERVER_PARAMETER_REQUIRED_ATTR ) <nl> - <nl> - self . assert_bind_fail ( <nl> - textwrap . dedent ( " " " <nl> - server_parameters : <nl> - foo : <nl> - set_at : startup <nl> - description : bar <nl> - from_bson : buzz <nl> - from_string : qux <nl> - " " " ) , idl . errors . ERROR_ID_SERVER_PARAMETER_REQUIRED_ATTR ) <nl> - <nl> - # server parameter without storage may not have storage fields . <nl> - self . assert_bind_fail ( <nl> - textwrap . dedent ( " " " <nl> - server_parameters : <nl> - foo : <nl> - set_at : startup <nl> - description : bar <nl> - append_bson : baz <nl> - from_bson : buzz <nl> - from_string : qux <nl> - default : 42 <nl> - " " " ) , idl . errors . ERROR_ID_SERVER_PARAMETER_INVALID_ATTR ) <nl> - <nl> - self . assert_bind_fail ( <nl> - textwrap . dedent ( " " " <nl> - server_parameters : <nl> - foo : <nl> - set_at : startup <nl> - description : bar <nl> - append_bson : baz <nl> - from_bson : buzz <nl> - from_string : qux <nl> - on_update : flip <nl> - " " " ) , idl . errors . ERROR_ID_SERVER_PARAMETER_INVALID_ATTR ) <nl> - <nl> - self . assert_bind_fail ( <nl> - textwrap . dedent ( " " " <nl> - server_parameters : <nl> - foo : <nl> - set_at : startup <nl> - description : bar <nl> - append_bson : baz <nl> - from_bson : buzz <nl> - from_string : qux <nl> - validator : { gt : 0 } <nl> - " " " ) , idl . errors . ERROR_ID_SERVER_PARAMETER_INVALID_ATTR ) <nl> - <nl> - # server parameter with storage may not have set / get methodsa <nl> - for callback in [ " append_bson " , " from_bson " , " from_string " ] : <nl> - self . assert_bind_fail ( <nl> - textwrap . dedent ( " " " <nl> - server_parameters : <nl> - foo : <nl> - set_at : startup <nl> - description : bar <nl> - cpp_varname : baz <nl> - % s : buzz <nl> - " " " % ( callback ) ) , idl . errors . ERROR_ID_SERVER_PARAMETER_INVALID_ATTR ) <nl> - <nl> # Invalid set_at values . <nl> self . assert_bind_fail ( <nl> textwrap . dedent ( " " " <nl> def test_server_parameter_negative ( self ) : <nl> cpp_varname : bling <nl> " " " ) , idl . errors . ERROR_ID_SERVER_PARAMETER_INVALID_ATTR ) <nl> <nl> - # Mix of specialized with unbound . <nl> - self . assert_bind_fail ( <nl> - textwrap . dedent ( " " " <nl> - server_parameters : <nl> - foo : <nl> - set_at : startup <nl> - description : bar <nl> - cpp_class : baz <nl> - append_bson : bling <nl> - from_string : blong <nl> - " " " ) , idl . errors . ERROR_ID_SERVER_PARAMETER_INVALID_ATTR ) <nl> - <nl> # Default without data . <nl> self . assert_bind_fail ( <nl> textwrap . dedent ( " " " <nl> mmm a / src / mongo / idl / SConscript <nl> ppp b / src / mongo / idl / SConscript <nl> env . Library ( <nl> env . CppUnitTest ( <nl> target = ' idl_server_parameter_test ' , <nl> source = [ <nl> - ' server_parameter_test . cpp ' , <nl> - env . Idlc ( ' server_parameter_test . idl ' ) [ 0 ] , <nl> ' server_parameter_with_storage_test . cpp ' , <nl> env . Idlc ( ' server_parameter_with_storage_test . idl ' ) [ 0 ] , <nl> ' server_parameter_specialized_test . cpp ' , <nl> mmm a / src / mongo / idl / server_parameter . cpp <nl> ppp b / src / mongo / idl / server_parameter . cpp <nl> MONGO_INITIALIZER_GROUP ( EndServerParameterRegistration , <nl> ( " BeginServerParameterRegistration " ) , <nl> ( " BeginStartupOptionHandling " ) ) <nl> <nl> - IDLServerParameter : : IDLServerParameter ( StringData name , ServerParameterType paramType ) <nl> - : ServerParameter ( ServerParameterSet : : getGlobal ( ) , <nl> - name , <nl> - paramType = = SPT : : kStartupOnly | | paramType = = SPT : : kStartupAndRuntime , <nl> - paramType = = SPT : : kRuntimeOnly | | paramType = = SPT : : kStartupAndRuntime ) { } <nl> - <nl> - void IDLServerParameter : : append ( OperationContext * opCtx , <nl> - BSONObjBuilder & b , <nl> - const std : : string & name ) { <nl> - invariant ( _appendBSON , <nl> - " append ( ) called on IDLServerParamter with no appendBSON implementation " ) ; <nl> - _appendBSON ( opCtx , & b , name ) ; <nl> - } <nl> - <nl> IDLServerParameterDeprecatedAlias : : IDLServerParameterDeprecatedAlias ( StringData name , <nl> ServerParameter * sp ) <nl> : ServerParameter ( ServerParameterSet : : getGlobal ( ) , <nl> IDLServerParameterDeprecatedAlias : : IDLServerParameterDeprecatedAlias ( StringData <nl> } <nl> } <nl> <nl> - Status IDLServerParameter : : set ( const BSONElement & newValueElement ) try { <nl> - if ( _fromBSON ) { <nl> - return _fromBSON ( newValueElement ) ; <nl> - } else { <nl> - / / Default fallback behavior : Cast to string and use ' from_string ' method . <nl> - return setFromString ( newValueElement . String ( ) ) ; <nl> - } <nl> - } catch ( const AssertionException & ex ) { <nl> - return { ErrorCodes : : BadValue , <nl> - str : : stream ( ) < < " Invalid value ' " < < newValueElement < < " ' for setParameter ' " <nl> - < < name ( ) <nl> - < < " ' : " <nl> - < < ex . what ( ) } ; <nl> - } <nl> - <nl> - Status IDLServerParameter : : setFromString ( const std : : string & str ) { <nl> - invariant ( _fromString , <nl> - " setFromString ( ) called on IDLServerParamter with no setFromString implementation " ) ; <nl> - return _fromString ( str ) ; <nl> - } <nl> - <nl> void IDLServerParameterDeprecatedAlias : : append ( OperationContext * opCtx , <nl> BSONObjBuilder & b , <nl> const std : : string & fieldName ) { <nl> mmm a / src / mongo / idl / server_parameter . h <nl> ppp b / src / mongo / idl / server_parameter . h <nl> <nl> <nl> namespace mongo { <nl> <nl> - / * * <nl> - * Specialization of ServerParameter used by IDL generator . <nl> - * / <nl> - class IDLServerParameter : public ServerParameter { <nl> - public : <nl> - IDLServerParameter ( StringData name , ServerParameterType paramType ) ; <nl> - <nl> - / * * <nl> - * Define a callback for populating a BSONObj with the current setting . <nl> - * / <nl> - using appendBSON_t = void ( OperationContext * , BSONObjBuilder * , StringData ) ; <nl> - void setAppendBSON ( std : : function < appendBSON_t > appendBSON ) { <nl> - _appendBSON = std : : move ( appendBSON ) ; <nl> - } <nl> - <nl> - / * * <nl> - * Encode the setting into BSON object . <nl> - * <nl> - * Typically invoked by { getParameter : . . . } to produce a dictionary <nl> - * of SCP settings . <nl> - * / <nl> - void append ( OperationContext * opCtx , BSONObjBuilder & b , const std : : string & name ) final ; <nl> - <nl> - / * * <nl> - * Define a callback for setting the value from a BSONElement . <nl> - * / <nl> - using fromBSON_t = Status ( const BSONElement & ) ; <nl> - void setFromBSON ( std : : function < fromBSON_t > fromBSON ) { <nl> - _fromBSON = std : : move ( fromBSON ) ; <nl> - } <nl> - <nl> - / * * <nl> - * Update the underlying value using a BSONElement . <nl> - * <nl> - * Allows setting non - basic values ( e . g . vector < string > ) <nl> - * via the { setParameter : . . . } call . <nl> - * / <nl> - Status set ( const BSONElement & newValueElement ) final ; <nl> - <nl> - / * * <nl> - * Define a callback for setting the value from a string . <nl> - * / <nl> - using fromString_t = Status ( StringData ) ; <nl> - void setFromString ( std : : function < fromString_t > fromString ) { <nl> - _fromString = std : : move ( fromString ) ; <nl> - } <nl> - <nl> - / * * <nl> - * Update the underlying value from a string . <nl> - * <nl> - * Typically invoked from commandline - - setParameter usage . <nl> - * / <nl> - Status setFromString ( const std : : string & str ) final ; <nl> - <nl> - / * * <nl> - * Helper method usable as setAppendBSON ( ) callback when redaction of value is requested . <nl> - * / <nl> - static void redactedAppendBSON ( OperationContext * , BSONObjBuilder * b , StringData name ) { <nl> - b - > append ( name , " # # # " ) ; <nl> - } <nl> - <nl> - protected : <nl> - std : : function < appendBSON_t > _appendBSON ; <nl> - std : : function < fromBSON_t > _fromBSON ; <nl> - std : : function < fromString_t > _fromString ; <nl> - } ; <nl> - <nl> / * * <nl> * Proxy instance for deprecated aliases of set parameters . <nl> * / <nl> deleted file mode 100644 <nl> index 6a541364b072 . . 000000000000 <nl> mmm a / src / mongo / idl / server_parameter_test . cpp <nl> ppp / dev / null <nl> <nl> - / * * <nl> - * Copyright ( C ) 2018 - present MongoDB , Inc . <nl> - * <nl> - * This program is free software : you can redistribute it and / or modify <nl> - * it under the terms of the Server Side Public License , version 1 , <nl> - * as published by MongoDB , Inc . <nl> - * <nl> - * This program is distributed in the hope that it will be useful , <nl> - * but WITHOUT ANY WARRANTY ; without even the implied warranty of <nl> - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the <nl> - * Server Side Public License for more details . <nl> - * <nl> - * You should have received a copy of the Server Side Public License <nl> - * along with this program . If not , see <nl> - * < http : / / www . mongodb . com / licensing / server - side - public - license > . <nl> - * <nl> - * As a special exception , the copyright holders give permission to link the <nl> - * code of portions of this program with the OpenSSL library under certain <nl> - * conditions as described in each individual source file and distribute <nl> - * linked combinations including the program with the OpenSSL library . You <nl> - * must comply with the Server Side Public License in all respects for <nl> - * all of the code used other than as permitted herein . If you modify file ( s ) <nl> - * with this exception , you may extend this exception to your version of the <nl> - * file ( s ) , but you are not obligated to do so . If you do not wish to do so , <nl> - * delete this exception statement from your version . If you delete this <nl> - * exception statement from all source files in the program , then also delete <nl> - * it in the license file . <nl> - * / <nl> - <nl> - # include " mongo / platform / basic . h " <nl> - <nl> - # include " mongo / idl / server_parameter . h " <nl> - # include " mongo / unittest / unittest . h " <nl> - <nl> - namespace mongo { <nl> - namespace test { <nl> - <nl> - namespace { <nl> - std : : string gCustomSetting ; <nl> - } / / namespace <nl> - <nl> - void customSettingAppendBSON ( OperationContext * , BSONObjBuilder * builder , StringData name ) { <nl> - builder - > append ( name , gCustomSetting ) ; <nl> - } <nl> - <nl> - Status customSettingFromBSON ( const BSONElement & element ) { <nl> - gCustomSetting = element . String ( ) ; <nl> - return Status : : OK ( ) ; <nl> - } <nl> - <nl> - Status customSettingFromString ( StringData str ) { <nl> - gCustomSetting = str . toString ( ) ; <nl> - return Status : : OK ( ) ; <nl> - } <nl> - } / / namespace test <nl> - <nl> - namespace { <nl> - <nl> - TEST ( ServerParameter , setAppendBSON ) { <nl> - IDLServerParameter param ( " setAppendBSON " _sd , ServerParameterType : : kStartupOnly ) ; <nl> - <nl> - param . setAppendBSON ( [ ] ( OperationContext * , BSONObjBuilder * builder , StringData name ) { <nl> - builder - > append ( name , 42 ) ; <nl> - } ) ; <nl> - BSONObjBuilder builder ; <nl> - param . append ( nullptr , builder , param . name ( ) ) ; <nl> - auto obj = builder . obj ( ) ; <nl> - ASSERT_EQ ( obj . nFields ( ) , 1 ) ; <nl> - ASSERT_EQ ( obj [ param . name ( ) ] . Int ( ) , 42 ) ; <nl> - } <nl> - <nl> - TEST ( ServerParameter , setFromString ) { <nl> - IDLServerParameter param ( " setFromString " _sd , ServerParameterType : : kStartupOnly ) ; <nl> - <nl> - param . setFromString ( [ ] ( StringData ) { return Status : : OK ( ) ; } ) ; <nl> - ASSERT_OK ( param . setFromString ( " A value " ) ) ; <nl> - <nl> - param . setFromString ( [ ] ( StringData ) { return Status ( ErrorCodes : : BadValue , " Can ' t set me . " ) ; } ) ; <nl> - ASSERT_NOT_OK ( param . setFromString ( " A value " ) ) ; <nl> - } <nl> - <nl> - TEST ( ServerParameter , setFromBSON ) { <nl> - IDLServerParameter param ( " setFromBSON " _sd , ServerParameterType : : kStartupOnly ) ; <nl> - BSONElement elem ; <nl> - <nl> - param . setFromBSON ( [ ] ( const BSONElement & ) { return Status : : OK ( ) ; } ) ; <nl> - ASSERT_OK ( param . set ( elem ) ) ; <nl> - <nl> - param . setFromBSON ( <nl> - [ ] ( const BSONElement & ) { return Status ( ErrorCodes : : BadValue , " Can ' t set me . " ) ; } ) ; <nl> - ASSERT_NOT_OK ( param . set ( elem ) ) ; <nl> - } <nl> - <nl> - TEST ( ServerParameter , setFromBSONViaString ) { <nl> - IDLServerParameter param ( " setFromBSONViaString " _sd , ServerParameterType : : kStartupOnly ) ; <nl> - auto obj = BSON ( " " <nl> - < < " value " ) ; <nl> - auto elem = obj . firstElement ( ) ; <nl> - <nl> - param . setFromString ( [ ] ( StringData ) { return Status : : OK ( ) ; } ) ; <nl> - ASSERT_OK ( param . set ( elem ) ) ; <nl> - <nl> - param . setFromString ( [ ] ( StringData ) { return Status ( ErrorCodes : : BadValue , " Can ' t set me . " ) ; } ) ; <nl> - ASSERT_NOT_OK ( param . set ( elem ) ) ; <nl> - } <nl> - <nl> - TEST ( ServerParameter , deprecatedAlias ) { <nl> - IDLServerParameter param ( " basename " _sd , ServerParameterType : : kStartupOnly ) ; <nl> - IDLServerParameterDeprecatedAlias alias ( " aliasname " _sd , & param ) ; <nl> - std : : string value ; <nl> - param . setFromString ( [ & value ] ( StringData str ) { <nl> - value = str . toString ( ) ; <nl> - return Status : : OK ( ) ; <nl> - } ) ; <nl> - ASSERT_OK ( param . setFromString ( " alpha " ) ) ; <nl> - ASSERT_EQ ( " alpha " , value ) ; <nl> - <nl> - ASSERT_OK ( alias . setFromString ( " bravo " ) ) ; <nl> - ASSERT_EQ ( " bravo " , value ) ; <nl> - } <nl> - <nl> - ServerParameter * getServerParameter ( const std : : string & name ) { <nl> - const auto & spMap = ServerParameterSet : : getGlobal ( ) - > getMap ( ) ; <nl> - const auto & spIt = spMap . find ( name ) ; <nl> - ASSERT ( spIt ! = spMap . end ( ) ) ; <nl> - <nl> - auto * sp = spIt - > second ; <nl> - ASSERT ( sp ) ; <nl> - return sp ; <nl> - } <nl> - <nl> - TEST ( IDLServerParameter , customSettingTest ) { <nl> - auto * cst = getServerParameter ( " customSettingTest " ) ; <nl> - ASSERT_OK ( cst - > setFromString ( " New Value " ) ) ; <nl> - ASSERT_EQ ( test : : gCustomSetting , " New Value " ) ; <nl> - <nl> - auto * cswobson = getServerParameter ( " customSettingWithoutFromBSON " ) ; <nl> - ASSERT_OK ( cswobson - > set ( BSON ( " " <nl> - < < " no bson " ) <nl> - . firstElement ( ) ) ) ; <nl> - ASSERT_EQ ( test : : gCustomSetting , " no bson " ) ; <nl> - <nl> - auto * depr = getServerParameter ( " customSettingTestDeprecated " ) ; <nl> - ASSERT_OK ( depr - > setFromString ( " Value via depr name " ) ) ; <nl> - ASSERT_EQ ( test : : gCustomSetting , " Value via depr name " ) ; <nl> - } <nl> - <nl> - TEST ( IDLServerParameter , customSettingWithRedaction ) { <nl> - auto * csr = getServerParameter ( " customSettingWithRedaction " ) ; <nl> - ASSERT_OK ( csr - > setFromString ( " Secret " ) ) ; <nl> - ASSERT_EQ ( test : : gCustomSetting , " Secret " ) ; <nl> - <nl> - BSONObjBuilder b ; <nl> - csr - > append ( nullptr , b , csr - > name ( ) ) ; <nl> - auto obj = b . obj ( ) ; <nl> - ASSERT_EQ ( obj . nFields ( ) , 1 ) ; <nl> - ASSERT_EQ ( obj [ csr - > name ( ) ] . String ( ) , " # # # " ) ; <nl> - } <nl> - <nl> - TEST ( IDLServerParameter , customTestOnly ) { <nl> - auto * cto = getServerParameter ( " customTestOnlyParameter " ) ; <nl> - ASSERT_OK ( cto - > setFromString ( " enabled " ) ) ; <nl> - ASSERT_EQ ( test : : gCustomSetting , " enabled " ) ; <nl> - <nl> - { <nl> - BSONObjBuilder b ; <nl> - cto - > append ( nullptr , b , cto - > name ( ) ) ; <nl> - auto obj = b . obj ( ) ; <nl> - ASSERT_EQ ( obj . nFields ( ) , 1 ) ; <nl> - ASSERT_EQ ( obj [ cto - > name ( ) ] . String ( ) , " enabled " ) ; <nl> - } <nl> - <nl> - ServerParameterSet : : getGlobal ( ) - > disableTestParameters ( ) ; <nl> - auto * disabled = getServerParameter ( " customTestOnlyParameter " ) ; <nl> - ASSERT_NE ( cto , disabled ) ; <nl> - ASSERT_EQ ( cto - > name ( ) , disabled - > name ( ) ) ; <nl> - <nl> - { <nl> - BSONObjBuilder b ; <nl> - disabled - > append ( nullptr , b , disabled - > name ( ) ) ; <nl> - auto obj = b . obj ( ) ; <nl> - ASSERT_EQ ( obj . nFields ( ) , 0 ) ; <nl> - } <nl> - <nl> - auto status = disabled - > setFromString ( " disabled " ) ; <nl> - ASSERT_NOT_OK ( status ) ; <nl> - ASSERT_EQ ( status . code ( ) , ErrorCodes : : BadValue ) ; <nl> - ASSERT_EQ ( <nl> - status . reason ( ) , <nl> - " setParameter : ' customTestOnlyParameter ' is only supported with ' enableTestCommands = true ' " ) ; <nl> - <nl> - ASSERT_EQ ( test : : gCustomSetting , " enabled " ) ; <nl> - } <nl> - <nl> - } / / namespace <nl> - } / / namespace mongo <nl> deleted file mode 100644 <nl> index 1791b550472b . . 000000000000 <nl> mmm a / src / mongo / idl / server_parameter_test . h <nl> ppp / dev / null <nl> <nl> - / * * <nl> - * Copyright ( C ) 2018 - present MongoDB , Inc . <nl> - * <nl> - * This program is free software : you can redistribute it and / or modify <nl> - * it under the terms of the Server Side Public License , version 1 , <nl> - * as published by MongoDB , Inc . <nl> - * <nl> - * This program is distributed in the hope that it will be useful , <nl> - * but WITHOUT ANY WARRANTY ; without even the implied warranty of <nl> - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the <nl> - * Server Side Public License for more details . <nl> - * <nl> - * You should have received a copy of the Server Side Public License <nl> - * along with this program . If not , see <nl> - * < http : / / www . mongodb . com / licensing / server - side - public - license > . <nl> - * <nl> - * As a special exception , the copyright holders give permission to link the <nl> - * code of portions of this program with the OpenSSL library under certain <nl> - * conditions as described in each individual source file and distribute <nl> - * linked combinations including the program with the OpenSSL library . You <nl> - * must comply with the Server Side Public License in all respects for <nl> - * all of the code used other than as permitted herein . If you modify file ( s ) <nl> - * with this exception , you may extend this exception to your version of the <nl> - * file ( s ) , but you are not obligated to do so . If you do not wish to do so , <nl> - * delete this exception statement from your version . If you delete this <nl> - * exception statement from all source files in the program , then also delete <nl> - * it in the license file . <nl> - * / <nl> - <nl> - # pragma once <nl> - <nl> - # include " mongo / platform / basic . h " <nl> - <nl> - # include " mongo / idl / server_parameter . h " <nl> - <nl> - namespace mongo { <nl> - namespace test { <nl> - <nl> - / / The callbacks listed in this file are bound to the set parameter <nl> - / / " customSettingsTest " defined in server_parameter_test . idl and <nl> - / / instatiated from server_parater_test . cpp . <nl> - <nl> - / * * <nl> - * Appends a single field named { name } to the { builder } object <nl> - * with a global string value previously set by one of the subsequent <nl> - * two callbacks . <nl> - * / <nl> - void customSettingAppendBSON ( OperationContext * , BSONObjBuilder * builder , StringData name ) ; <nl> - <nl> - / * * <nl> - * Sets a global string value from the { element } which is <nl> - * expected to be of type String . <nl> - * / <nl> - Status customSettingFromBSON ( const BSONElement & element ) ; <nl> - <nl> - / * * <nl> - * Sets a global string value from { str } . <nl> - * / <nl> - Status customSettingFromString ( StringData str ) ; <nl> - <nl> - } / / namespace test <nl> - } / / namespace mongo <nl> deleted file mode 100644 <nl> index 377228303969 . . 000000000000 <nl> mmm a / src / mongo / idl / server_parameter_test . idl <nl> ppp / dev / null <nl> <nl> - # Copyright ( C ) 2018 - present MongoDB , Inc . <nl> - # <nl> - # This program is free software : you can redistribute it and / or modify <nl> - # it under the terms of the Server Side Public License , version 1 , <nl> - # as published by MongoDB , Inc . <nl> - # <nl> - # This program is distributed in the hope that it will be useful , <nl> - # but WITHOUT ANY WARRANTY ; without even the implied warranty of <nl> - # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the <nl> - # Server Side Public License for more details . <nl> - # <nl> - # You should have received a copy of the Server Side Public License <nl> - # along with this program . If not , see <nl> - # < http : / / www . mongodb . com / licensing / server - side - public - license > . <nl> - # <nl> - # As a special exception , the copyright holders give permission to link the <nl> - # code of portions of this program with the OpenSSL library under certain <nl> - # conditions as described in each individual source file and distribute <nl> - # linked combinations including the program with the OpenSSL library . You <nl> - # must comply with the Server Side Public License in all respects for <nl> - # all of the code used other than as permitted herein . If you modify file ( s ) <nl> - # with this exception , you may extend this exception to your version of the <nl> - # file ( s ) , but you are not obligated to do so . If you do not wish to do so , <nl> - # delete this exception statement from your version . If you delete this <nl> - # exception statement from all source files in the program , then also delete <nl> - # it in the license file . <nl> - # <nl> - <nl> - global : <nl> - cpp_namespace : " mongo : : test " <nl> - cpp_includes : <nl> - - " mongo / idl / server_parameter_test . h " <nl> - <nl> - imports : <nl> - - " mongo / idl / basic_types . idl " <nl> - <nl> - server_parameters : <nl> - customSettingTest : <nl> - set_at : startup <nl> - description : " Basic test setting using custom callbacks . " <nl> - append_bson : " customSettingAppendBSON " <nl> - from_bson : " customSettingFromBSON " <nl> - from_string : " customSettingFromString " <nl> - deprecated_name : " customSettingTestDeprecated " <nl> - <nl> - customSettingWithoutFromBSON : <nl> - set_at : startup <nl> - description : " Basic test using default fromBSON callback . " <nl> - append_bson : " customSettingAppendBSON " <nl> - from_string : " customSettingFromString " <nl> - <nl> - customSettingWithPositiveConditions : <nl> - set_at : startup <nl> - description : " Testing that conditions are created . " <nl> - append_bson : " customSettingAppendBSON " <nl> - from_string : " customSettingFromString " <nl> - condition : <nl> - expr : " true " <nl> - preprocessor : " 1 = = 1 " <nl> - <nl> - customSettingWithNegativeConditions : <nl> - set_at : startup <nl> - description : " Testing that conditions are created . " <nl> - append_bson : " customSettingAppendBSON " <nl> - from_string : " customSettingFromString " <nl> - condition : <nl> - expr : " false " <nl> - preprocessor : " 1 = = 0 " <nl> - <nl> - customSettingWithRedaction : <nl> - set_at : startup <nl> - description : " If requested , this setting will reply with # # # as value " <nl> - from_string : " customSettingFromString " <nl> - redact : true <nl> - <nl> - customTestOnlyParameter : <nl> - set_at : startup <nl> - description : " That that ' test_only ' params get disabled . " <nl> - append_bson : " customSettingAppendBSON " <nl> - from_string : " customSettingFromString " <nl> - test_only : true <nl> | SERVER - 38934 Remove IDLServerParameter ( without storage ) | mongodb/mongo | 90c1759dab18a2105abaa31cf963c788c05c0e77 | 2019-01-12T03:12:23Z |
mmm a / Marlin / src / inc / Conditionals_LCD . h <nl> ppp b / Marlin / src / inc / Conditionals_LCD . h <nl> <nl> # define IS_CARTESIAN ! IS_KINEMATIC <nl> <nl> # define HAS_ACTION_COMMANDS ( defined ( ACTION_ON_KILL ) | | defined ( ACTION_ON_PAUSE ) | | defined ( ACTION_ON_PAUSED ) | | defined ( ACTION_ON_RESUME ) | | defined ( ACTION_ON_RESUMED ) | | defined ( ACTION_ON_CANCEL ) | | defined ( G29_ACTION_ON_RECOVER ) | | defined ( G29_ACTION_ON_FAILURE ) | | defined ( ACTION_ON_FILAMENT_RUNOUT ) ) <nl> + <nl> + # ifndef INVERT_X_DIR <nl> + # define INVERT_X_DIR false <nl> + # endif <nl> + # ifndef INVERT_Y_DIR <nl> + # define INVERT_Y_DIR false <nl> + # endif <nl> + # ifndef INVERT_Z_DIR <nl> + # define INVERT_Z_DIR false <nl> + # endif <nl> + # ifndef INVERT_E_DIR <nl> + # define INVERT_E_DIR false <nl> + # endif <nl> mmm a / Marlin / src / module / stepper . cpp <nl> ppp b / Marlin / src / module / stepper . cpp <nl> Stepper stepper ; / / Singleton <nl> <nl> / / private : <nl> <nl> - block_t * Stepper : : current_block = NULL ; / / A pointer to the block currently being traced <nl> + block_t * Stepper : : current_block ; / / ( = NULL ) A pointer to the block currently being traced <nl> <nl> - uint8_t Stepper : : last_direction_bits = 0 , <nl> - Stepper : : axis_did_move ; <nl> + uint8_t Stepper : : last_direction_bits , / / = 0 <nl> + Stepper : : axis_did_move ; / / = 0 <nl> <nl> bool Stepper : : abort_current_block ; <nl> <nl> void Stepper : : init ( ) { <nl> E_AXIS_INIT ( 5 ) ; <nl> # endif <nl> <nl> - set_directions ( ) ; <nl> - <nl> / / Init Stepper ISR to 122 Hz for quick starting <nl> HAL_timer_start ( STEP_TIMER_NUM , 122 ) ; <nl> <nl> ENABLE_STEPPER_DRIVER_INTERRUPT ( ) ; <nl> <nl> sei ( ) ; <nl> + <nl> + / / Init direction bits for first moves <nl> + last_direction_bits = 0 <nl> + | ( INVERT_X_DIR ? _BV ( X_AXIS ) : 0 ) <nl> + | ( INVERT_Y_DIR ? _BV ( Y_AXIS ) : 0 ) <nl> + | ( INVERT_Z_DIR ? _BV ( Z_AXIS ) : 0 ) ; <nl> + <nl> + set_directions ( ) ; <nl> } <nl> <nl> / * * <nl> | Fix init of last_direction_bits ( ) | MarlinFirmware/Marlin | 4d1093b3868a37ee0def13dbe2785f3ce98fcf6d | 2019-02-03T07:29:00Z |
mmm a / jstests / hooks / run_check_repl_dbhash_background . js <nl> ppp b / jstests / hooks / run_check_repl_dbhash_background . js <nl> function checkReplDbhashBackgroundThread ( hosts ) { <nl> hasTransientError = true ; <nl> } <nl> <nl> + / / In debug builds , read - only operations can receive write conflicts when the storage <nl> + / / engine cache is full . Since dbHash holds open a read snapshot for an extended period <nl> + / / of time and pulls all collection data into cache , the storage engine may abort the <nl> + / / operation if it needs to free up space . Try again after space has been freed . <nl> + if ( e . code = = = ErrorCodes . WriteConflict & & buildInfo ( ) . debug ) { <nl> + hasTransientError = true ; <nl> + } <nl> + <nl> return hasTransientError ; <nl> } ; <nl> <nl> | SERVER - 43060 CheckReplDBHashInBackground should retry the dbHash command on WriteConflicts in debug builds | mongodb/mongo | ab4d803f1f2f57cf9dbec89175f8eb52cb4761f2 | 2020-07-09T17:40:17Z |
mmm a / README . md <nl> ppp b / README . md <nl> For information on parity status with Android and iOS , including details on impl <nl> <nl> # # Opening Issues <nl> <nl> - If you encounter a bug with the React Native Windows plugin , we would like to hear about it . Search the [ existing issues ] ( https : / / github . com / ReactWindows / react - native - windows / issues ) and try to make sure your problem doesn ’ t already exist before opening a new issue . It ’ s helpful if you include the version of Windows , React Native , React Native Windows plugin , and device family ( i . e . , mobile , desktop , Xbox , etc . ) you ’ re using . Please include a stack trace and reduced repro case when appropriate , too . <nl> + If you encounter a bug with the React Native Windows plugin , we would like to hear about it . Search the [ existing issues ] ( https : / / github . com / Microsoft / react - native - windows / issues ) and try to make sure your problem doesn ’ t already exist before opening a new issue . It ’ s helpful if you include the version of Windows , React Native , React Native Windows plugin , and device family ( i . e . , mobile , desktop , Xbox , etc . ) you ’ re using . Please include a stack trace and reduced repro case when appropriate , too . <nl> <nl> The GitHub issues are intended for bug reports and feature requests . For help and questions with using the React Native Windows plugin please make use of the resources listed in the [ Getting Help ] ( # getting - help ) section . There are limited resources available for handling issues , and by keeping the list of open issues lean we can respond in a timely manner . <nl> <nl> The GitHub issues are intended for bug reports and feature requests . For help an <nl> - Install the [ system requirements ] ( # system - requirements ) <nl> - Check out the React Native Windows code itself and install npm dependencies <nl> ` ` ` <nl> - git clone - - recursive https : / / github . com / ReactWindows / react - native - windows . git <nl> + git clone - - recursive https : / / github . com / Microsoft / react - native - windows . git <nl> cd react - native - windows <nl> npm install <nl> ` ` ` <nl> npm install <nl> <nl> For more information about contributing PRs and issues , see our [ Contribution Guidelines ] ( CONTRIBUTING . md ) <nl> <nl> - [ Good First Task ] ( https : / / github . com / ReactWindows / react - native - windows / labels / Good % 20First % 20Task ) and [ help wanted ] ( https : / / github . com / ReactWindows / react - native - windows / labels / help % 20wanted ) are great starting points for PRs . <nl> + [ Good First Task ] ( https : / / github . com / Microsoft / react - native - windows / labels / Good % 20First % 20Task ) and [ help wanted ] ( https : / / github . com / Microsoft / react - native - windows / labels / help % 20wanted ) are great starting points for PRs . <nl> <nl> Each pull request has the unit tests , code analysis , and a [ Winium ] ( https : / / github . com / 2gis / Winium ) integration test run in the AppVeyor CI service . To shorten the feedback cycle , please be sure to [ run the unit tests in Visual Studio ] ( CONTRIBUTING . md # running - unit - tests - in - visual - studio ) and verify they are passing before submitting pull requests . For extra credit , [ verify the examples in RNTester ] ( CONTRIBUTING . md # using - rntester ) continue to work properly . <nl> <nl> | README : repository is now in Microsoft org ( ) | microsoft/react-native-windows | 932dc4206f5660c34ae42b1898e33908cd572da6 | 2019-03-22T18:11:34Z |
mmm a / include / table . h <nl> ppp b / include / table . h <nl> swTableRow * swTableRow_get ( swTable * table , const char * key , int keylen , swTableR <nl> void swTable_iterator_rewind ( swTable * table ) ; <nl> swTableRow * swTable_iterator_current ( swTable * table ) ; <nl> void swTable_iterator_forward ( swTable * table ) ; <nl> - int swTableRow_del ( swTable * table , char * key , int keylen ) ; <nl> + int swTableRow_del ( swTable * table , const char * key , int keylen ) ; <nl> <nl> static sw_inline swTableColumn * swTableColumn_get ( swTable * table , const std : : string & key ) <nl> { <nl> mmm a / src / memory / table . cc <nl> ppp b / src / memory / table . cc <nl> static int insert_count = 0 ; <nl> static int conflict_max_level = 0 ; <nl> # endif <nl> <nl> + static inline void swTable_check_key_length ( int & keylen ) <nl> + { <nl> + if ( keylen > = SW_TABLE_KEY_SIZE ) <nl> + { <nl> + keylen = SW_TABLE_KEY_SIZE - 1 ; <nl> + } <nl> + } <nl> + <nl> swTable * swTable_new ( uint32_t rows_size , float conflict_proportion ) <nl> { <nl> if ( rows_size > = 0x80000000 ) <nl> void swTable_iterator_forward ( swTable * table ) <nl> <nl> swTableRow * swTableRow_get ( swTable * table , const char * key , int keylen , swTableRow * * rowlock ) <nl> { <nl> - if ( keylen > SW_TABLE_KEY_SIZE ) <nl> - { <nl> - keylen = SW_TABLE_KEY_SIZE ; <nl> - } <nl> + swTable_check_key_length ( keylen ) ; <nl> <nl> swTableRow * row = swTable_hash ( table , key , keylen ) ; <nl> * rowlock = row ; <nl> swTableRow * swTableRow_get ( swTable * table , const char * key , int keylen , swTableR <nl> return row ; <nl> } <nl> <nl> + static inline void swTableRow_init ( swTable * table , swTableRow * new_row , const char * key , int keylen ) <nl> + { <nl> + bzero ( new_row , sizeof ( swTableRow ) ) ; <nl> + memcpy ( new_row - > key , key , keylen ) ; <nl> + new_row - > key [ keylen ] = ' \ 0 ' ; <nl> + new_row - > key_len = keylen ; <nl> + new_row - > active = 1 ; <nl> + sw_atomic_fetch_add ( & ( table - > row_num ) , 1 ) ; <nl> + } <nl> + <nl> swTableRow * swTableRow_set ( swTable * table , const char * key , int keylen , swTableRow * * rowlock ) <nl> { <nl> - if ( keylen > = SW_TABLE_KEY_SIZE ) <nl> - { <nl> - keylen = SW_TABLE_KEY_SIZE - 1 ; <nl> - } <nl> + swTable_check_key_length ( keylen ) ; <nl> <nl> swTableRow * row = swTable_hash ( table , key , keylen ) ; <nl> * rowlock = row ; <nl> swTableRow * swTableRow_set ( swTable * table , const char * key , int keylen , swTableR <nl> { <nl> break ; <nl> } <nl> - else if ( row - > next = = NULL ) <nl> + else if ( row - > next = = nullptr ) <nl> { <nl> table - > lock . lock ( & table - > lock ) ; <nl> swTableRow * new_row = ( swTableRow * ) table - > pool - > alloc ( table - > pool , 0 ) ; <nl> swTableRow * swTableRow_set ( swTable * table , const char * key , int keylen , swTableR <nl> <nl> # endif <nl> table - > lock . unlock ( & table - > lock ) ; <nl> - <nl> if ( ! new_row ) <nl> { <nl> - return NULL ; <nl> + return nullptr ; <nl> } <nl> - / / add row_num <nl> - bzero ( new_row , sizeof ( swTableRow ) ) ; <nl> - sw_atomic_fetch_add ( & ( table - > row_num ) , 1 ) ; <nl> + swTableRow_init ( table , new_row , key , keylen ) ; <nl> row - > next = new_row ; <nl> row = new_row ; <nl> break ; <nl> swTableRow * swTableRow_set ( swTable * table , const char * key , int keylen , swTableR <nl> # ifdef SW_TABLE_DEBUG <nl> insert_count + + ; <nl> # endif <nl> - sw_atomic_fetch_add ( & ( table - > row_num ) , 1 ) ; <nl> + swTableRow_init ( table , row , key , keylen ) ; <nl> } <nl> <nl> - memcpy ( row - > key , key , keylen ) ; <nl> - row - > key [ keylen ] = ' \ 0 ' ; <nl> - row - > key_len = keylen ; <nl> - row - > active = 1 ; <nl> return row ; <nl> } <nl> <nl> - int swTableRow_del ( swTable * table , char * key , int keylen ) <nl> + int swTableRow_del ( swTable * table , const char * key , int keylen ) <nl> { <nl> - if ( keylen > SW_TABLE_KEY_SIZE ) <nl> - { <nl> - keylen = SW_TABLE_KEY_SIZE ; <nl> - } <nl> + swTable_check_key_length ( keylen ) ; <nl> <nl> swTableRow * row = swTable_hash ( table , key , keylen ) ; <nl> / / no exists <nl> int swTableRow_del ( swTable * table , char * key , int keylen ) <nl> return SW_ERR ; <nl> } <nl> <nl> - swTableRow * tmp = row ; <nl> - swTableRow * prev = NULL ; <nl> + swTableRow * tmp , * prev = nullptr ; <nl> <nl> swTableRow_lock ( row ) ; <nl> - if ( row - > next = = NULL ) <nl> + if ( row - > next = = nullptr ) <nl> { <nl> if ( sw_mem_equal ( row - > key , row - > key_len , key , keylen ) ) <nl> { <nl> - bzero ( row , sizeof ( swTableRow ) + table - > item_size ) ; <nl> + bzero ( row , sizeof ( swTableRow ) ) ; <nl> goto _delete_element ; <nl> } <nl> else <nl> int swTableRow_del ( swTable * table , char * key , int keylen ) <nl> } <nl> else <nl> { <nl> + tmp = row ; <nl> while ( tmp ) <nl> { <nl> - if ( sw_mem_equal ( row - > key , row - > key_len , key , keylen ) ) <nl> + if ( sw_mem_equal ( tmp - > key , tmp - > key_len , key , keylen ) ) <nl> { <nl> break ; <nl> } <nl> int swTableRow_del ( swTable * table , char * key , int keylen ) <nl> tmp = tmp - > next ; <nl> } <nl> <nl> - if ( tmp = = NULL ) <nl> + if ( tmp = = nullptr ) <nl> { <nl> _not_exists : <nl> swTableRow_unlock ( row ) ; <nl> + <nl> return SW_ERR ; <nl> } <nl> <nl> int swTableRow_del ( swTable * table , char * key , int keylen ) <nl> { <nl> tmp = tmp - > next ; <nl> row - > next = tmp - > next ; <nl> - memcpy ( row - > key , tmp - > key , strlen ( tmp - > key ) + 1 ) ; <nl> + memcpy ( row - > key , tmp - > key , tmp - > key_len + 1 ) ; <nl> + row - > key_len = tmp - > key_len ; <nl> memcpy ( row - > data , tmp - > data , table - > item_size ) ; <nl> } <nl> if ( prev ) <nl> mmm a / tests / swoole_table / bug_2263 . phpt <nl> ppp b / tests / swoole_table / bug_2263 . phpt <nl> $ table - > set ( " 44984 " , [ ' data ' = > ' 2 ' ] ) ; <nl> $ table - > del ( " 1234567890 " ) ; <nl> <nl> foreach ( $ table as $ ip = > $ row ) { <nl> - echo $ ip ; <nl> + echo $ ip . " \ n " ; <nl> } <nl> <nl> ? > <nl> | Optimize table ( ) | swoole/swoole-src | d7b87b65dff123eb8b0c7043ec3b1d40805ea79f | 2020-05-08T02:44:28Z |
mmm a / docs / en / interfaces / third - party_gui . md <nl> ppp b / docs / en / interfaces / third - party_gui . md <nl> The following features are planned for development : <nl> - Cluster management . <nl> - Monitoring replicated and Kafka tables . <nl> <nl> + # # DBeaver <nl> + <nl> + [ DBeaver ] ( https : / / dbeaver . io / ) - universal desktop database client with ClickHouse support . <nl> + <nl> + Key features : <nl> + <nl> + - Query development with syntax highlight . <nl> + - Table preview . <nl> + - Autocompletion . <nl> mmm a / docs / ru / interfaces / third - party_client_libraries . md <nl> ppp b / docs / ru / interfaces / third - party_client_libraries . md <nl> <nl> - [ clickhouse_ecto ] ( https : / / github . com / appodeal / clickhouse_ecto ) <nl> - Java <nl> - [ clickhouse - client - java ] ( https : / / github . com / VirtusAI / clickhouse - client - java ) <nl> + - Kotlin <nl> + - [ AORM ] ( https : / / github . com / TanVD / AORM ) <nl> - Nim <nl> - [ nim - clickhouse ] ( https : / / github . com / leonardoce / nim - clickhouse ) <nl> mmm a / docs / ru / interfaces / third - party_gui . md <nl> ppp b / docs / ru / interfaces / third - party_gui . md <nl> <nl> <nl> # # DBeaver <nl> <nl> - [ DBeaver ] ( https : / / dbeaver . io / ) - Универсальный клиент баз данных <nl> + [ DBeaver ] ( https : / / dbeaver . io / ) - универсальный desktop клиент баз данных с поддержкой ClickHouse . <nl> <nl> Основные возможности : <nl> <nl> - - Построение запросов с подсветкой синтаксиса <nl> - - Просмотр таблиц <nl> - - Автодополнение команд <nl> + - Построение запросов с подсветкой синтаксиса . <nl> + - Просмотр таблиц . <nl> + - Автодополнение команд . <nl> | Some sync between 3rd party software lists | ClickHouse/ClickHouse | 415f763910c1d46e2b0e62c3fbc087543aceb98c | 2018-10-12T13:26:57Z |
mmm a / tensorflow / core / grappler / op_types . cc <nl> ppp b / tensorflow / core / grappler / op_types . cc <nl> bool IsValuePreserving ( const NodeDef & node ) { <nl> return value_preserving_ops . count ( node . op ( ) ) > 0 ; <nl> } <nl> <nl> + bool HasOpDef ( const NodeDef & node ) { <nl> + const OpDef * op_def = nullptr ; <nl> + return OpRegistry : : Global ( ) - > LookUpOpDef ( node . op ( ) , & op_def ) . ok ( ) ; <nl> + } <nl> + <nl> } / / namespace grappler <nl> } / / end namespace tensorflow <nl> mmm a / tensorflow / core / grappler / op_types . h <nl> ppp b / tensorflow / core / grappler / op_types . h <nl> bool IsInvolution ( const NodeDef & node ) ; <nl> / / function returns true if the op commutes with all element - wise operations . <nl> bool IsValuePreserving ( const NodeDef & node ) ; <nl> <nl> + / / Returns true if we can find an opdef corresponding to the op of the node . <nl> + bool HasOpDef ( const NodeDef & node ) ; <nl> + <nl> } / / end namespace grappler <nl> } / / end namespace tensorflow <nl> <nl> mmm a / tensorflow / core / grappler / optimizers / dependency_optimizer . cc <nl> ppp b / tensorflow / core / grappler / optimizers / dependency_optimizer . cc <nl> limitations under the License . <nl> <nl> # include " tensorflow / core / grappler / optimizers / dependency_optimizer . h " <nl> <nl> + # include < unordered_map > <nl> # include < unordered_set > <nl> <nl> # include " tensorflow / core / framework / node_def . pb . h " <nl> Status DependencyOptimizer : : TransitiveReduction ( ) { <nl> num_nodes ) ; <nl> for ( int node_idx = 0 ; node_idx < num_nodes ; + + node_idx ) { <nl> const NodeDef & node = optimized_graph_ - > node ( node_idx ) ; <nl> - if ( ModifiesFrameInfo ( node ) ) { <nl> - / / Ignore nodes that modify frame info . <nl> + if ( ModifiesFrameInfo ( node ) | | ! HasOpDef ( node ) ) { <nl> + / / Ignore function nodes and nodes that modify frame info . <nl> continue ; <nl> } <nl> for ( int input_slot = 0 ; input_slot < node . input_size ( ) ; + + input_slot ) { <nl> const string & input = node . input ( input_slot ) ; <nl> const NodeDef * input_node = node_map_ - > GetNode ( input ) ; <nl> - if ( ModifiesFrameInfo ( * input_node ) ) { <nl> - / / Ignore edges from nodes that modify frame info . <nl> + if ( ModifiesFrameInfo ( * input_node ) | | IsMerge ( * input_node ) ) { <nl> + / / Ignore edges from nodes that modify frame info and from Merge nodes , <nl> + / / because we cannot know which of it ' s input paths executes . <nl> continue ; <nl> } <nl> const int input_node_idx = node_to_idx_ [ input_node ] ; <nl> Status DependencyOptimizer : : TransitiveReduction ( ) { <nl> / / of length > 1 , we can drop that control dependency . <nl> int num_controls_removed = 0 ; <nl> std : : vector < int > longest_distance ( num_nodes ) ; <nl> + / / Map from target_index - > set of ( input_slot , source_index ) , representing <nl> + / / the control edges to remove . We sort them in reverse order by input slot , <nl> + / / such that when we swap them out so we don ' t clobber the <nl> + / / node ( target ) . input ( ) repeated field . <nl> + typedef std : : pair < int , int > InputSlotAndSource ; <nl> + std : : unordered_map < <nl> + int , std : : set < InputSlotAndSource , std : : greater < InputSlotAndSource > > > <nl> + control_edges_to_remove ; <nl> for ( int source = 0 ; source < num_nodes ; + + source ) { <nl> int highest_control_target = - 1 ; <nl> for ( const auto & control_output : control_outputs [ source ] ) { <nl> Status DependencyOptimizer : : TransitiveReduction ( ) { <nl> highest_control_target = control_output . first ; <nl> } <nl> } <nl> - if ( highest_control_target < source ) { <nl> + if ( highest_control_target < = source ) { <nl> continue ; <nl> } <nl> std : : fill ( longest_distance . begin ( ) + source , <nl> Status DependencyOptimizer : : TransitiveReduction ( ) { <nl> for ( int input : inputs [ target ] ) { <nl> / / If the input node is before source in the topo order , no path <nl> / / source - > input - > target can exits and we can skip it . <nl> - if ( input > = source ) { <nl> + / / Also only extend a path from the source itself or from nodes that <nl> + / / have a path from source , indicated by longest_distance [ input ] > 0 . <nl> + if ( input = = source | | <nl> + ( input > source & & longest_distance [ input ] > 0 ) ) { <nl> / / If source - > input - > target is longer than the longest <nl> / / path so far from source - > target , update the longest_distance . <nl> int candidate_longest_distance = longest_distance [ input ] + 1 ; <nl> Status DependencyOptimizer : : TransitiveReduction ( ) { <nl> } <nl> } <nl> <nl> - / / If the longest path from the source to the target of a control dependency <nl> - / / is longer than 1 , there exists an alternate path , and we can eliminate <nl> - / / the control dependency since it is redundant . <nl> + / / If the longest path from source to target of a control dependency is <nl> + / / longer than 1 , there exists an alternate path , and we can eliminate the <nl> + / / redundant direct control dependency . <nl> for ( const auto & control_output : control_outputs [ source ] ) { <nl> const int target = control_output . first ; <nl> if ( longest_distance [ target ] > 1 ) { <nl> const int input_slot = control_output . second ; <nl> - / / We modify the node inplace here . This is safe because there can <nl> - / / only be one control edge from a given source to a given target . <nl> - const NodeDef & source_node = optimized_graph_ - > node ( source ) ; <nl> - NodeDef * target_node = optimized_graph_ - > mutable_node ( target ) ; <nl> - target_node - > mutable_input ( ) - > SwapElements ( <nl> - input_slot , target_node - > input_size ( ) - 1 ) ; <nl> - node_map_ - > RemoveOutput ( source_node . name ( ) , target_node - > name ( ) ) ; <nl> - target_node - > mutable_input ( ) - > RemoveLast ( ) ; <nl> - + + num_controls_removed ; <nl> + control_edges_to_remove [ target ] . emplace ( input_slot , source ) ; <nl> + VLOG ( 1 ) < < " Removing edge from : \ n " <nl> + < < optimized_graph_ - > node ( source ) . DebugString ( ) < < " \ n \ nto : \ n \ n " <nl> + < < optimized_graph_ - > node ( target ) . DebugString ( ) ; <nl> } <nl> } <nl> } <nl> + <nl> + for ( const auto & it : control_edges_to_remove ) { <nl> + const int target = it . first ; <nl> + NodeDef * target_node = optimized_graph_ - > mutable_node ( target ) ; <nl> + for ( const InputSlotAndSource & slot_and_source : it . second ) { <nl> + const int input_slot = slot_and_source . first ; <nl> + const int source = slot_and_source . second ; <nl> + const NodeDef & source_node = optimized_graph_ - > node ( source ) ; <nl> + CHECK_LT ( input_slot , target_node - > input_size ( ) ) ; <nl> + target_node - > mutable_input ( ) - > SwapElements ( input_slot , <nl> + target_node - > input_size ( ) - 1 ) ; <nl> + node_map_ - > RemoveOutput ( source_node . name ( ) , target_node - > name ( ) ) ; <nl> + target_node - > mutable_input ( ) - > RemoveLast ( ) ; <nl> + + + num_controls_removed ; <nl> + } <nl> + } <nl> VLOG ( 1 ) < < " Removed " < < num_controls_removed < < " out of " < < num_controls <nl> < < " control dependencies " ; <nl> return Status : : OK ( ) ; <nl> Status DependencyOptimizer : : Optimize ( Cluster * cluster , const GrapplerItem & item , <nl> nodes_to_preserve_ = item . NodesToPreserve ( ) ; <nl> fetch_nodes_known_ = ! item . fetch . empty ( ) ; <nl> <nl> - VLOG ( 1 ) < < " Graph before optimization : \ n " < < optimized_graph_ - > DebugString ( ) ; <nl> CleanControlInputs ( ) ; <nl> - const int num_iterations = opt_level_ = = RewriterConfig : : AGGRESSIVE ? 2 : 1 ; <nl> + const int num_iterations = 2 ; <nl> for ( int iteration = 0 ; iteration < num_iterations ; + + iteration ) { <nl> Status topo_sort_status ; <nl> - if ( opt_level_ = = RewriterConfig : : AGGRESSIVE ) { <nl> - / / Prepare the graph for transitive reduction if enabled . <nl> - topo_sort_status = TopologicalSort ( optimized_graph_ ) ; <nl> - } <nl> + / / Perform topological sort to prepare the graph for transitive reduction . <nl> + topo_sort_status = TopologicalSort ( optimized_graph_ ) ; <nl> <nl> + / / Set up index - based graph datastructures to speed up analysis steps below . <nl> node_map_ . reset ( new NodeMap ( optimized_graph_ ) ) ; <nl> BuildNodeToIdx ( ) ; <nl> <nl> - / / Remove redundant control dependencies , iteration 1 . <nl> - if ( opt_level_ = = RewriterConfig : : AGGRESSIVE ) { <nl> - if ( topo_sort_status . ok ( ) ) { <nl> - TF_RETURN_IF_ERROR ( TransitiveReduction ( ) ) ; <nl> - } else { <nl> - LOG ( ERROR ) < < topo_sort_status . error_message ( ) ; <nl> - } <nl> - VLOG ( 1 ) < < " Graph after transitive reduction : \ n " <nl> - < < optimized_graph_ - > DebugString ( ) ; <nl> + if ( topo_sort_status . ok ( ) ) { <nl> + / / Remove redundant control dependencies . <nl> + TF_RETURN_IF_ERROR ( TransitiveReduction ( ) ) ; <nl> + } else { <nl> + LOG ( ERROR ) < < topo_sort_status . error_message ( ) ; <nl> } <nl> <nl> - / / Turn nodes without non - control outputs into NoOps , prune NoOps . <nl> + / / Turn nodes with only control outputs into NoOps , prune NoOps . <nl> TF_RETURN_IF_ERROR ( OptimizeDependencies ( ) ) ; <nl> - VLOG ( 1 ) < < " Graph after NoOp conversion & pruning : \ n " <nl> - < < optimized_graph_ - > DebugString ( ) ; <nl> } <nl> - VLOG ( 1 ) < < " Graph after optimization : \ n " < < optimized_graph_ - > DebugString ( ) ; <nl> <nl> return Status : : OK ( ) ; <nl> } <nl> mmm a / tensorflow / core / grappler / optimizers / dependency_optimizer_test . cc <nl> ppp b / tensorflow / core / grappler / optimizers / dependency_optimizer_test . cc <nl> TEST_F ( DependencyOptimizerTest , ChangeToNoop_NoFetch ) { <nl> GrapplerItem item ; <nl> TF_CHECK_OK ( s . ToGraphDef ( & item . graph ) ) ; <nl> <nl> - DependencyOptimizer optimizer ( RewriterConfig : : AGGRESSIVE ) ; <nl> + DependencyOptimizer optimizer ; <nl> GraphDef output ; <nl> Status status = optimizer . Optimize ( nullptr , item , & output ) ; <nl> TF_EXPECT_OK ( status ) ; <nl> TEST_F ( DependencyOptimizerTest , RemoveNoOps_DeviceBoundaries ) { <nl> <nl> / / The optimization should be disabled to prevent increasing the number of <nl> / / nodes crossing device boundaries . <nl> + TF_CHECK_OK ( TopologicalSort ( & item . graph ) ) ; <nl> VerifyGraphsEqual ( item . graph , output , __FUNCTION__ ) ; <nl> } <nl> <nl> TEST_F ( DependencyOptimizerTest , Transitive_Reduction_Simple ) { <nl> GrapplerItem item ; <nl> TF_CHECK_OK ( s . ToGraphDef ( & item . graph ) ) ; <nl> item . fetch . push_back ( " id2 " ) ; <nl> - DependencyOptimizer optimizer ( RewriterConfig : : AGGRESSIVE ) ; <nl> + DependencyOptimizer optimizer ; <nl> GraphDef output ; <nl> Status status = optimizer . Optimize ( nullptr , item , & output ) ; <nl> TF_EXPECT_OK ( status ) ; <nl> mmm a / tensorflow / python / debug / cli / analyzer_cli_test . py <nl> ppp b / tensorflow / python / debug / cli / analyzer_cli_test . py <nl> def no_rewrite_session_config ( ) : <nl> rewriter_config = rewriter_config_pb2 . RewriterConfig ( <nl> disable_model_pruning = True , <nl> constant_folding = rewriter_config_pb2 . RewriterConfig . OFF , <nl> - arithmetic_optimization = rewriter_config_pb2 . RewriterConfig . OFF ) <nl> + arithmetic_optimization = rewriter_config_pb2 . RewriterConfig . OFF , <nl> + dependency_optimization = rewriter_config_pb2 . RewriterConfig . OFF ) <nl> <nl> graph_options = config_pb2 . GraphOptions ( rewrite_options = rewriter_config ) <nl> return config_pb2 . ConfigProto ( graph_options = graph_options ) <nl> | Fixed a couple of bugs in transitive reduction : | tensorflow/tensorflow | fcf61d57079c8874cd479d4b0dfdb48033e742d8 | 2017-12-19T21:38:16Z |
mmm a / Code / Sandbox / Plugins / MeshImporter / AssetImporterFBX . cpp <nl> ppp b / Code / Sandbox / Plugins / MeshImporter / AssetImporterFBX . cpp <nl> std : : vector < CAsset * > CAssetImporterFBX : : ImportAssets ( const std : : vector < string > & <nl> <nl> std : : vector < CAsset * > importedAssets ; <nl> importedAssets . reserve ( assetPaths . size ( ) ) ; <nl> - for ( const string & assetPath : assetPaths ) <nl> - { <nl> - MoveAsset ( ctx , assetPath ) ; <nl> - <nl> - CAsset * const pAsset = ctx . LoadAsset ( assetPath ) ; <nl> - if ( pAsset ) <nl> - { <nl> - importedAssets . push_back ( pAsset ) ; <nl> - } <nl> - } <nl> <nl> if ( m_bCreateMaterial ) <nl> { <nl> std : : vector < CAsset * > CAssetImporterFBX : : ImportAssets ( const std : : vector < string > & <nl> } <nl> } <nl> <nl> + for ( const string & assetPath : assetPaths ) <nl> + { <nl> + MoveAsset ( ctx , assetPath ) ; <nl> + <nl> + CAsset * const pAsset = ctx . LoadAsset ( assetPath ) ; <nl> + if ( pAsset ) <nl> + { <nl> + importedAssets . push_back ( pAsset ) ; <nl> + } <nl> + } <nl> + <nl> ImportCharacterDefinition ( ctx , importedAssets ) ; <nl> <nl> return importedAssets ; / / TODO : Return complete list of assets ! <nl> string CAssetImporterFBX : : ImportMaterial ( CAssetImportContext & ctx , const std : : ve <nl> const int mtlFlags = materialCount > 1 ? MTL_FLAG_MULTI_SUBMTL : 0 ; <nl> <nl> const string materialName = ctx . GetOutputFilePath ( " " ) ; <nl> - _smart_ptr < CMaterial > pMaterial = GetIEditor ( ) - > GetMaterialManager ( ) - > CreateMaterial ( materialName , XmlNodeRef ( ) , mtlFlags ) ; <nl> + <nl> + / / Do not overwrite existing . <nl> + IDataBaseItem * pMaterialItem = GetIEditor ( ) - > GetMaterialManager ( ) - > FindItemByName ( materialName ) ; <nl> + if ( pMaterialItem ) <nl> + { <nl> + return { } ; <nl> + } <nl> + <nl> + CMaterial * pMaterial = GetIEditor ( ) - > GetMaterialManager ( ) - > CreateMaterial ( materialName , XmlNodeRef ( ) , mtlFlags ) ; <nl> if ( ! pMaterial ) <nl> { <nl> - return string ( ) ; <nl> + return { } ; <nl> } <nl> const string outDir = ctx . GetOutputDirectoryPath ( ) ; <nl> CreateMaterial ( pMaterial , pFbxScene , [ & relTexs , & outDir ] ( CMaterial * pEditorMaterial , const FbxTool : : SMaterial & fbxMaterial ) <nl> | ! XB ( CE - 20717 ) ( Sandbox ) Importing an FBX - file triggers a crash and pure function call sometimes | CRYTEK/CRYENGINE | fa442736bb90d29bcca7946aaed6b84c0a5aa201 | 2019-05-29T14:50:28Z |
mmm a / src / mongo / db / query / single_solution_runner . h <nl> ppp b / src / mongo / db / query / single_solution_runner . h <nl> namespace mongo { <nl> <nl> virtual void kill ( ) { _exec - > kill ( ) ; } <nl> <nl> + virtual void writeExplainTo ( BSONObjBuilder * bob ) ; <nl> private : <nl> scoped_ptr < CanonicalQuery > _canonicalQuery ; <nl> scoped_ptr < QuerySolution > _solution ; <nl> | SERVER - 10565 implemented writeExplainTo in single solution runner | mongodb/mongo | 8993f914a4e4b68d07d4a81b37a2869d26c45344 | 2013-09-19T16:06:57Z |
mmm a / xbmc / interfaces / json - rpc / VideoLibrary . cpp <nl> ppp b / xbmc / interfaces / json - rpc / VideoLibrary . cpp <nl> JSONRPC_STATUS CVideoLibrary : : GetTVShows ( const std : : string & method , ITransportLa <nl> if ( ! videoUrl . FromString ( " videodb : / / tvshows / titles / " ) ) <nl> return InternalError ; <nl> <nl> - int genreID = - 1 , year = - 1 ; <nl> const CVariant & filter = parameterObject [ " filter " ] ; <nl> if ( filter . isMember ( " genreid " ) ) <nl> - genreID = ( int ) filter [ " genreid " ] . asInteger ( ) ; <nl> + videoUrl . AddOption ( " genreid " , ( int ) filter [ " genreid " ] . asInteger ( ) ) ; <nl> else if ( filter . isMember ( " genre " ) ) <nl> videoUrl . AddOption ( " genre " , filter [ " genre " ] . asString ( ) ) ; <nl> else if ( filter . isMember ( " year " ) ) <nl> - year = ( int ) filter [ " year " ] . asInteger ( ) ; <nl> + videoUrl . AddOption ( " year " , ( int ) filter [ " year " ] . asInteger ( ) ) ; <nl> else if ( filter . isMember ( " actor " ) ) <nl> videoUrl . AddOption ( " actor " , filter [ " actor " ] . asString ( ) ) ; <nl> else if ( filter . isMember ( " studio " ) ) <nl> JSONRPC_STATUS CVideoLibrary : : GetTVShows ( const std : : string & method , ITransportLa <nl> } <nl> <nl> CFileItemList items ; <nl> - if ( ! videodatabase . GetTvShowsNav ( videoUrl . ToString ( ) , items , genreID , year , - 1 , - 1 , - 1 , - 1 , sorting ) ) <nl> + CDatabase : : Filter nofilter ; <nl> + if ( ! videodatabase . GetTvShowsByWhere ( videoUrl . ToString ( ) , nofilter , items , sorting ) ) <nl> return InvalidParams ; <nl> <nl> bool additionalInfo = false ; <nl> mmm a / xbmc / interfaces / json - rpc / schema / version . txt <nl> ppp b / xbmc / interfaces / json - rpc / schema / version . txt <nl> @ @ - 1 + 1 @ @ <nl> - 7 . 0 . 0 <nl> + 7 . 0 . 1 <nl> mmm a / xbmc / video / VideoDatabase . cpp <nl> ppp b / xbmc / video / VideoDatabase . cpp <nl> bool CVideoDatabase : : GetTvShowsNav ( const std : : string & strBaseDir , CFileItemList & <nl> videoUrl . AddOption ( " tagid " , idTag ) ; <nl> <nl> Filter filter ; <nl> + if ( ! CSettings : : GetInstance ( ) . GetBool ( CSettings : : SETTING_VIDEOLIBRARY_SHOWEMPTYTVSHOWS ) ) <nl> + filter . AppendWhere ( " totalCount IS NOT NULL AND totalCount > 0 " ) ; <nl> return GetTvShowsByWhere ( videoUrl . ToString ( ) , filter , items , sortDescription ) ; <nl> } <nl> <nl> bool CVideoDatabase : : GetTvShowsByWhere ( const std : : string & strBaseDir , const Filt <nl> <nl> CFileItemPtr pItem ( new CFileItem ( ) ) ; <nl> CVideoInfoTag movie = GetDetailsForTvShow ( record , false , pItem . get ( ) ) ; <nl> - if ( ( CProfilesManager : : GetInstance ( ) . GetMasterProfile ( ) . getLockMode ( ) = = LOCK_MODE_EVERYONE | | <nl> + if ( CProfilesManager : : GetInstance ( ) . GetMasterProfile ( ) . getLockMode ( ) = = LOCK_MODE_EVERYONE | | <nl> g_passwordManager . bMasterUser | | <nl> - g_passwordManager . IsDatabasePathUnlocked ( movie . m_strPath , * CMediaSourceSettings : : GetInstance ( ) . GetSources ( " video " ) ) ) & & <nl> - ( CSettings : : GetInstance ( ) . GetBool ( CSettings : : SETTING_VIDEOLIBRARY_SHOWEMPTYTVSHOWS ) | | movie . m_iEpisode > 0 ) ) <nl> + g_passwordManager . IsDatabasePathUnlocked ( movie . m_strPath , * CMediaSourceSettings : : GetInstance ( ) . GetSources ( " video " ) ) ) <nl> { <nl> pItem - > SetFromVideoInfoTag ( movie ) ; <nl> <nl> | Merge pull request from anaconda / json - gettvshows - empty | xbmc/xbmc | 1ee82c3ca77a8676760178486ba039c063f3dccf | 2015-12-29T17:43:32Z |
mmm a / caffe2 / operators / generate_proposals_op_util_nms_gpu_test . cc <nl> ppp b / caffe2 / operators / generate_proposals_op_util_nms_gpu_test . cc <nl> TEST ( UtilsNMSTest , TestPerfRotatedNMS ) { <nl> ratio ) ; <nl> } <nl> <nl> - TEST ( UtilsNMSTest , GPUEqualsCPURotatedCorrectnessTest ) { <nl> - if ( ! HasCudaGPU ( ) ) <nl> - return ; <nl> - Workspace ws ; <nl> - DeviceOption option ; <nl> - option . set_device_type ( PROTO_CUDA ) ; <nl> - CUDAContext cuda_context ( option ) ; <nl> - <nl> - const int box_dim = 5 ; <nl> - const std : : vector < int > nboxes_vec = { 10 , 100 , 1000 , 2000 } ; <nl> - for ( int nboxes : nboxes_vec ) { <nl> - Tensor host_boxes { CPU } ; <nl> - Tensor host_scores { CPU } ; <nl> - host_boxes . Resize ( box_dim * nboxes ) ; <nl> - host_scores . Resize ( nboxes ) ; <nl> - <nl> - float * h_boxes = host_boxes . template mutable_data < float > ( ) ; <nl> - float * h_scores = host_scores . template mutable_data < float > ( ) ; <nl> - <nl> - / / Generating random input <nl> - generateRandomRotatedBoxes ( h_boxes , h_scores , nboxes ) ; <nl> - <nl> - const int ntests = 1 ; <nl> - const float thresh = 0 . 7 ; <nl> - / / Not timing the sort for the CPU <nl> - / / in the real - world use case scores already have been sorted earlier in the <nl> - / / generate proposals workflow <nl> - std : : vector < int > indices ( nboxes ) ; <nl> - std : : iota ( indices . begin ( ) , indices . end ( ) , 0 ) ; <nl> - std : : sort ( indices . begin ( ) , indices . end ( ) , [ h_scores ] ( int lhs , int rhs ) { <nl> - return h_scores [ lhs ] > h_scores [ rhs ] ; <nl> - } ) ; <nl> - <nl> - std : : vector < float > sorted_boxes ( nboxes * box_dim ) ; <nl> - std : : vector < float > sorted_scores ( nboxes ) ; <nl> - Eigen : : ArrayXXf eig_proposals ( nboxes , box_dim ) ; <nl> - Eigen : : ArrayXXf eig_scores ( nboxes , 1 ) ; <nl> - for ( int i = 0 ; i < nboxes ; + + i ) { <nl> - for ( int d = 0 ; d < box_dim ; + + d ) { <nl> - sorted_boxes [ i * box_dim + d ] = h_boxes [ indices [ i ] * box_dim + d ] ; <nl> - eig_proposals ( i , d ) = h_boxes [ indices [ i ] * box_dim + d ] ; <nl> - } <nl> - sorted_scores [ i ] = h_scores [ indices [ i ] ] ; <nl> - eig_scores ( i ) = h_scores [ indices [ i ] ] ; <nl> - } <nl> - std : : vector < int > sorted_indices ( nboxes ) ; <nl> - std : : iota ( sorted_indices . begin ( ) , sorted_indices . end ( ) , 0 ) ; <nl> - <nl> - Tensor dev_boxes { CUDA } ; <nl> - Tensor dev_delete_mask { CUDA } ; <nl> - Tensor host_delete_mask { CPU } ; <nl> - Tensor dev_list { CUDA } ; <nl> - <nl> - dev_boxes . Resize ( box_dim * nboxes ) ; <nl> - float * d_sorted_boxes = dev_boxes . template mutable_data < float > ( ) ; <nl> - dev_list . Resize ( nboxes ) ; <nl> - int * d_list = dev_list . template mutable_data < int > ( ) ; <nl> - <nl> - / / No timing the memcpies because data is already on the GPU in the <nl> - / / real - world use case ( generated by the GPU generate_proposals ) <nl> - CUDA_CHECK ( cudaMemcpyAsync ( <nl> - d_sorted_boxes , <nl> - & sorted_boxes [ 0 ] , <nl> - sizeof ( * d_sorted_boxes ) * box_dim * nboxes , <nl> - cudaMemcpyHostToDevice , <nl> - cuda_context . cuda_stream ( ) ) ) ; <nl> - <nl> - / / Running ntests runs of CPU NMS <nl> - for ( int itest = 0 ; itest < ntests ; + + itest ) { <nl> - std : : vector < int > keep = utils : : nms_cpu ( <nl> - eig_proposals , <nl> - eig_scores , <nl> - sorted_indices , <nl> - thresh , <nl> - - 1 , / * topN * / <nl> - true / * legacy_plus_one * / ) ; <nl> - int list_nitems ; <nl> - utils : : nms_gpu ( <nl> - d_sorted_boxes , <nl> - nboxes , <nl> - thresh , <nl> - true , / * legacy_plus_one * / <nl> - d_list , <nl> - & list_nitems , <nl> - dev_delete_mask , <nl> - host_delete_mask , <nl> - & cuda_context , <nl> - box_dim ) ; <nl> - std : : vector < int > gpu_keep ( list_nitems ) ; <nl> - CUDA_CHECK ( cudaMemcpyAsync ( <nl> - & gpu_keep [ 0 ] , <nl> - d_list , <nl> - list_nitems * sizeof ( int ) , <nl> - cudaMemcpyDeviceToHost , <nl> - cuda_context . cuda_stream ( ) ) ) ; <nl> - CUDA_CHECK ( cudaStreamSynchronize ( cuda_context . cuda_stream ( ) ) ) ; <nl> - <nl> - ASSERT_EQ ( keep . size ( ) , gpu_keep . size ( ) ) ; <nl> - std : : sort ( keep . begin ( ) , keep . end ( ) ) ; <nl> - std : : sort ( gpu_keep . begin ( ) , gpu_keep . end ( ) ) ; <nl> - <nl> - for ( int i = 0 ; i < list_nitems ; + + i ) <nl> - EXPECT_EQ ( keep [ i ] , gpu_keep [ i ] ) ; <nl> - } <nl> - } <nl> - } <nl> + / / Skipped . See https : / / github . com / pytorch / pytorch / issues / 26811 <nl> + / / TEST ( UtilsNMSTest , GPUEqualsCPURotatedCorrectnessTest ) { <nl> + / / if ( ! HasCudaGPU ( ) ) <nl> + / / return ; <nl> + / / Workspace ws ; <nl> + / / DeviceOption option ; <nl> + / / option . set_device_type ( PROTO_CUDA ) ; <nl> + / / CUDAContext cuda_context ( option ) ; <nl> + <nl> + / / const int box_dim = 5 ; <nl> + / / const std : : vector < int > nboxes_vec = { 10 , 100 , 1000 , 2000 } ; <nl> + / / for ( int nboxes : nboxes_vec ) { <nl> + / / Tensor host_boxes { CPU } ; <nl> + / / Tensor host_scores { CPU } ; <nl> + / / host_boxes . Resize ( box_dim * nboxes ) ; <nl> + / / host_scores . Resize ( nboxes ) ; <nl> + <nl> + / / float * h_boxes = host_boxes . template mutable_data < float > ( ) ; <nl> + / / float * h_scores = host_scores . template mutable_data < float > ( ) ; <nl> + <nl> + / / / / Generating random input <nl> + / / generateRandomRotatedBoxes ( h_boxes , h_scores , nboxes ) ; <nl> + <nl> + / / const int ntests = 1 ; <nl> + / / const float thresh = 0 . 7 ; <nl> + / / / / Not timing the sort for the CPU <nl> + / / / / in the real - world use case scores already have been sorted earlier in the <nl> + / / / / generate proposals workflow <nl> + / / std : : vector < int > indices ( nboxes ) ; <nl> + / / std : : iota ( indices . begin ( ) , indices . end ( ) , 0 ) ; <nl> + / / std : : sort ( indices . begin ( ) , indices . end ( ) , [ h_scores ] ( int lhs , int rhs ) { <nl> + / / return h_scores [ lhs ] > h_scores [ rhs ] ; <nl> + / / } ) ; <nl> + <nl> + / / std : : vector < float > sorted_boxes ( nboxes * box_dim ) ; <nl> + / / std : : vector < float > sorted_scores ( nboxes ) ; <nl> + / / Eigen : : ArrayXXf eig_proposals ( nboxes , box_dim ) ; <nl> + / / Eigen : : ArrayXXf eig_scores ( nboxes , 1 ) ; <nl> + / / for ( int i = 0 ; i < nboxes ; + + i ) { <nl> + / / for ( int d = 0 ; d < box_dim ; + + d ) { <nl> + / / sorted_boxes [ i * box_dim + d ] = h_boxes [ indices [ i ] * box_dim + d ] ; <nl> + / / eig_proposals ( i , d ) = h_boxes [ indices [ i ] * box_dim + d ] ; <nl> + / / } <nl> + / / sorted_scores [ i ] = h_scores [ indices [ i ] ] ; <nl> + / / eig_scores ( i ) = h_scores [ indices [ i ] ] ; <nl> + / / } <nl> + / / std : : vector < int > sorted_indices ( nboxes ) ; <nl> + / / std : : iota ( sorted_indices . begin ( ) , sorted_indices . end ( ) , 0 ) ; <nl> + <nl> + / / Tensor dev_boxes { CUDA } ; <nl> + / / Tensor dev_delete_mask { CUDA } ; <nl> + / / Tensor host_delete_mask { CPU } ; <nl> + / / Tensor dev_list { CUDA } ; <nl> + <nl> + / / dev_boxes . Resize ( box_dim * nboxes ) ; <nl> + / / float * d_sorted_boxes = dev_boxes . template mutable_data < float > ( ) ; <nl> + / / dev_list . Resize ( nboxes ) ; <nl> + / / int * d_list = dev_list . template mutable_data < int > ( ) ; <nl> + <nl> + / / / / No timing the memcpies because data is already on the GPU in the <nl> + / / / / real - world use case ( generated by the GPU generate_proposals ) <nl> + / / CUDA_CHECK ( cudaMemcpyAsync ( <nl> + / / d_sorted_boxes , <nl> + / / & sorted_boxes [ 0 ] , <nl> + / / sizeof ( * d_sorted_boxes ) * box_dim * nboxes , <nl> + / / cudaMemcpyHostToDevice , <nl> + / / cuda_context . cuda_stream ( ) ) ) ; <nl> + <nl> + / / / / Running ntests runs of CPU NMS <nl> + / / for ( int itest = 0 ; itest < ntests ; + + itest ) { <nl> + / / std : : vector < int > keep = utils : : nms_cpu ( <nl> + / / eig_proposals , <nl> + / / eig_scores , <nl> + / / sorted_indices , <nl> + / / thresh , <nl> + / / - 1 , / * topN * / <nl> + / / true / * legacy_plus_one * / ) ; <nl> + / / int list_nitems ; <nl> + / / utils : : nms_gpu ( <nl> + / / d_sorted_boxes , <nl> + / / nboxes , <nl> + / / thresh , <nl> + / / true , / * legacy_plus_one * / <nl> + / / d_list , <nl> + / / & list_nitems , <nl> + / / dev_delete_mask , <nl> + / / host_delete_mask , <nl> + / / & cuda_context , <nl> + / / box_dim ) ; <nl> + / / std : : vector < int > gpu_keep ( list_nitems ) ; <nl> + / / CUDA_CHECK ( cudaMemcpyAsync ( <nl> + / / & gpu_keep [ 0 ] , <nl> + / / d_list , <nl> + / / list_nitems * sizeof ( int ) , <nl> + / / cudaMemcpyDeviceToHost , <nl> + / / cuda_context . cuda_stream ( ) ) ) ; <nl> + / / CUDA_CHECK ( cudaStreamSynchronize ( cuda_context . cuda_stream ( ) ) ) ; <nl> + <nl> + / / ASSERT_EQ ( keep . size ( ) , gpu_keep . size ( ) ) ; <nl> + / / std : : sort ( keep . begin ( ) , keep . end ( ) ) ; <nl> + / / std : : sort ( gpu_keep . begin ( ) , gpu_keep . end ( ) ) ; <nl> + <nl> + / / for ( int i = 0 ; i < list_nitems ; + + i ) <nl> + / / EXPECT_EQ ( keep [ i ] , gpu_keep [ i ] ) ; <nl> + / / } <nl> + / / } <nl> + / / } <nl> <nl> } / / namespace caffe2 <nl> | Skips flaky UtilsNMSTest . GPUEqualsCPURotatedCorrectnessTest ( ) | pytorch/pytorch | 188d0a9add7e10578dc1d6989bb3b22f59850eb9 | 2019-11-21T21:44:44Z |
mmm a / Code / CryEngine / CryAction / ViewSystem / View . cpp <nl> ppp b / Code / CryEngine / CryAction / ViewSystem / View . cpp <nl> <nl> # include " GameObjects / GameObject . h " <nl> # include " IGameSessionHandler . h " <nl> # include " ViewSystem . h " <nl> - # include < DefaultComponents / Audio / ListenerComponent . h > <nl> + # include < DefaultComponents / Audio / DefaultListenerComponent . h > <nl> <nl> namespace Cry <nl> { <nl> void CView : : Update ( float frameTime , bool isActive ) <nl> { <nl> m_viewParams . SaveLast ( ) ; <nl> <nl> - const CCamera & sysCam = m_pSystem - > GetViewCamera ( ) ; <nl> + const CCamera & sysCam = m_pSystem - > GetViewCamera ( ) ; <nl> <nl> / / process screen shaking <nl> ProcessShaking ( frameTime ) ; <nl> void CView : : Update ( float frameTime , bool isActive ) <nl> const Vec3 cameraLocalPos = m_viewParams . position ; <nl> <nl> / / Set entity ' s camera space position <nl> - const Vec3 cameraSpacePos ( - cameraLocalPos * m_viewParams . rotation ) ; <nl> + const Vec3 cameraSpacePos ( - cameraLocalPos * m_viewParams . rotation ) ; <nl> pLinkedToEntity - > SetSlotCameraSpacePos ( slotIndex , cameraSpacePos ) ; <nl> <nl> / / Add world pos onto camera local pos <nl> void CView : : CreateAudioListener ( ) <nl> gEnv - > pEntitySystem - > AddEntityEventListener ( m_pAudioListenerEntity - > GetId ( ) , ENTITY_EVENT_DONE , this ) ; <nl> m_pAudioListenerEntity - > SetName ( pIEntity - > GetName ( ) ) ; <nl> <nl> - m_pAudioListenerComponent = m_pAudioListenerEntity - > GetOrCreateComponent < Cry : : Audio : : DefaultComponents : : CListenerComponent > ( ) ; <nl> + m_pAudioListenerComponent = m_pAudioListenerEntity - > GetOrCreateComponent < Cry : : Audio : : DefaultComponents : : CDefaultListenerComponent > ( ) ; <nl> CRY_ASSERT ( m_pAudioListenerComponent ! = nullptr ) ; <nl> m_pAudioListenerComponent - > SetComponentFlags ( m_pAudioListenerComponent - > GetComponentFlags ( ) | IEntityComponent : : EFlags : : UserAdded ) ; <nl> } <nl> mmm a / Code / CryEngine / CryAction / ViewSystem / View . h <nl> ppp b / Code / CryEngine / CryAction / ViewSystem / View . h <nl> namespace Audio <nl> { <nl> namespace DefaultComponents <nl> { <nl> - class CListenerComponent ; <nl> + class CDefaultListenerComponent ; <nl> } / / namespace DefaultComponents <nl> } / / namespace Audio <nl> } / / namespace Cry <nl> class CView final : public IView , public IEntityEventListener <nl> <nl> std : : vector < SShake > m_shakes ; <nl> <nl> - Cry : : Audio : : DefaultComponents : : CListenerComponent * m_pAudioListenerComponent ; <nl> + Cry : : Audio : : DefaultComponents : : CDefaultListenerComponent * m_pAudioListenerComponent ; <nl> IEntity * m_pAudioListenerEntity ; <nl> Ang3 m_frameAdditiveAngles ; / / Used mainly for cinematics , where the game can slightly override camera orientation <nl> <nl> mmm a / Code / CryEngine / CryAudioSystem / CMakeLists . txt <nl> ppp b / Code / CryEngine / CryAudioSystem / CMakeLists . txt <nl> add_sources ( " CryAudioSystem_uber_0 . cpp " <nl> " Managers . h " <nl> " Object . h " <nl> " ObjectRequestData . h " <nl> + " OcclusionInfo . h " <nl> " PropagationProcessor . h " <nl> " RayInfo . h " <nl> " Request . h " <nl> mmm a / Code / CryEngine / CryAudioSystem / CVars . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / CVars . cpp <nl> void CCVars : : RegisterVariables ( ) <nl> " 1 : Accumulate pool sizes of the global context and the largest pool size for each control in any other context . \ n " <nl> " This option may be used if maximum one other context besides the global context will be active at any time . \ n " ) ; <nl> <nl> + m_pListeners = REGISTER_STRING ( g_szListenersCVarName , " " , VF_READONLY , <nl> + " Specifies the names of listeners that should get constructed when the audio system gets initialized . \ n " <nl> + " Usage : s_Listeners Listener1 , Listener2 , . . \ n " <nl> + " More than one listener can be specified by using a comma separated list " ) ; <nl> + <nl> # if defined ( CRY_AUDIO_USE_OCCLUSION ) <nl> REGISTER_CVAR2 ( " s_OcclusionMaxDistance " , & m_occlusionMaxDistance , m_occlusionMaxDistance , VF_CHEAT | VF_CHEAT_NOCHECK , <nl> " Occlusion is not calculated for audio objects , whose distance to the listener is greater than this value . Setting this value to 0 disables obstruction / occlusion calculations . \ n " <nl> void CCVars : : UnregisterVariables ( ) <nl> pConsole - > UnregisterVariable ( " s_TriggerInstancePoolSize " ) ; <nl> pConsole - > UnregisterVariable ( " s_IgnoreWindowFocus " ) ; <nl> pConsole - > UnregisterVariable ( " s_PoolAllocationMode " ) ; <nl> + pConsole - > UnregisterVariable ( g_szListenersCVarName ) ; <nl> <nl> # if defined ( CRY_AUDIO_USE_OCCLUSION ) <nl> pConsole - > UnregisterVariable ( " s_OcclusionMaxDistance " ) ; <nl> mmm a / Code / CryEngine / CryAudioSystem / CVars . h <nl> ppp b / Code / CryEngine / CryAudioSystem / CVars . h <nl> class CCVars final <nl> int m_fileCacheManagerSize = 384 < < 10 ; <nl> # endif / / CRY_PLATFORM_DURANGO <nl> <nl> - int m_objectPoolSize = 256 ; <nl> - int m_triggerInstancePoolSize = 512 ; <nl> - int m_ignoreWindowFocus = 0 ; <nl> - int m_poolAllocationMode = 0 ; <nl> + int m_objectPoolSize = 256 ; <nl> + int m_triggerInstancePoolSize = 512 ; <nl> + int m_ignoreWindowFocus = 0 ; <nl> + int m_poolAllocationMode = 0 ; <nl> + ICVar * m_pListeners = nullptr ; <nl> <nl> # if defined ( CRY_AUDIO_USE_OCCLUSION ) <nl> int m_occlusionCollisionTypes = 0 ; <nl> mmm a / Code / CryEngine / CryAudioSystem / Common . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / Common . cpp <nl> <nl> # include " Common . h " <nl> # include " System . h " <nl> # include " Object . h " <nl> + # include " Listener . h " <nl> # include " GlobalObject . h " <nl> # include " LoseFocusTrigger . h " <nl> # include " GetFocusTrigger . h " <nl> TriggerInstanceId g_triggerInstanceIdCounter = 1 ; <nl> SPoolSizes g_poolSizes ; <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + CListener g_defaultListener ( DefaultListenerId , false , g_szDefaultListenerName ) ; <nl> + CListener g_previewListener ( g_previewListenerId , false , g_szPreviewListenerName ) ; <nl> Objects g_constructedObjects ; <nl> CGlobalObject g_object ( " Global Object " ) ; <nl> CGlobalObject g_previewObject ( " Preview Object " ) ; <nl> SPoolSizes g_debugPoolSizes ; <nl> ContextInfo g_contextInfo ; <nl> ContextDebugInfo g_contextDebugInfo ; <nl> # else <nl> + CListener g_defaultListener ( DefaultListenerId , false ) ; <nl> CGlobalObject g_object ; <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> } / / namespace CryAudio <nl> mmm a / Code / CryEngine / CryAudioSystem / Common . h <nl> ppp b / Code / CryEngine / CryAudioSystem / Common . h <nl> struct ISwitchStateConnection ; <nl> struct ITriggerConnection ; <nl> } / / namespace Impl <nl> <nl> + class CListener ; <nl> class CSystem ; <nl> class CObject ; <nl> class CGlobalObject ; <nl> using SwitchStateConnections = std : : vector < Impl : : ISwitchStateConnection * > ; <nl> using EnvironmentConnections = std : : vector < Impl : : IEnvironmentConnection * > ; <nl> using SettingConnections = std : : vector < Impl : : ISettingConnection * > ; <nl> using Objects = std : : vector < CObject * > ; <nl> + using Listeners = std : : vector < CListener * > ; <nl> <nl> extern Impl : : IImpl * g_pIImpl ; <nl> + extern CListener g_defaultListener ; <nl> extern CSystem g_system ; <nl> extern ESystemStates g_systemStates ; <nl> extern TriggerLookup g_triggers ; <nl> static void IncrementTriggerInstanceIdCounter ( ) <nl> } <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + extern CListener g_previewListener ; <nl> extern Objects g_constructedObjects ; <nl> <nl> + constexpr char const * g_szPreviewListenerName = " Preview Listener " ; <nl> + constexpr ListenerId g_previewListenerId = StringToId ( " ThisIsTheHopefullyUniqueIdForThePreviewListener " ) ; <nl> + <nl> constexpr char const * g_szPreviewTriggerName = " preview_trigger " ; <nl> constexpr ControlId g_previewTriggerId = StringToId ( g_szPreviewTriggerName ) ; <nl> <nl> mmm a / Code / CryEngine / CryAudioSystem / Common / IImpl . h <nl> ppp b / Code / CryEngine / CryAudioSystem / Common / IImpl . h <nl> struct ITriggerConnection ; <nl> struct ITriggerInfo ; <nl> struct SFileInfo ; <nl> <nl> + using IListeners = DynArray < IListener * > ; <nl> + <nl> struct IImpl <nl> { <nl> / * * @ cond * / <nl> struct IImpl <nl> / * * <nl> * Create an object implementing IObject that stores all of the data needed by the AudioImplementation <nl> * to identify and use the GlobalAudioObject . <nl> + * @ param listeners - listeners which listen to all sounds emmitted from the object <nl> * @ return IObject pointer to the audio implementation - specific data needed by the audio middleware and the <nl> * @ return AudioImplementation code to use the corresponding GlobalAudioObject ; nullptr if the new IObject instance was not created <nl> * @ see DestructObject <nl> * / <nl> - virtual IObject * ConstructGlobalObject ( ) = 0 ; <nl> + virtual IObject * ConstructGlobalObject ( IListeners const & listeners ) = 0 ; <nl> <nl> / * * <nl> * Create an object implementing IObject that stores all of the data needed by the AudioImplementation <nl> * to identify and use the AudioObject . Return a pointer to that object . <nl> * @ param transformation - transformation of the object to construct <nl> + * @ param listeners - listeners which listen to all sounds emmitted from the object <nl> * @ param szName - optional name of the object to construct ( not used in release builds ) <nl> * @ return IObject pointer to the audio implementation - specific data needed by the audio middleware and the <nl> * @ return AudioImplementation code to use the corresponding GlobalAudioObject ; nullptr if the new IObject instance was not created <nl> * @ see DestructObject <nl> * / <nl> - virtual IObject * ConstructObject ( CTransformation const & transformation , char const * const szName = nullptr ) = 0 ; <nl> + virtual IObject * ConstructObject ( CTransformation const & transformation , IListeners const & listeners , char const * const szName = nullptr ) = 0 ; <nl> <nl> / * * <nl> * Free the memory and potentially other resources used by the supplied IObject instance <nl> struct IImpl <nl> * Construct an object implementing IListener that stores all of the data needed by the AudioImplementation <nl> * to identify and use an AudioListener . Return a pointer to that object . <nl> * @ param transformation - transformation of the listener to construct <nl> - * @ param szName - optional name of the listener to construct ( not used in release builds ) <nl> + * @ param szName - name of the listener to construct ( not used in release builds ) <nl> * @ return CryAudio : : Impl : : IListener pointer to the audio implementation - specific data needed by the audio middleware and the <nl> * @ return AudioImplementation code to use the corresponding AudioListener ; nullptr if the new CryAudio : : Impl : : IListener instance was not created . <nl> * @ see DestructListener <nl> * / <nl> - virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName = nullptr ) = 0 ; <nl> + virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName ) = 0 ; <nl> <nl> / * * <nl> * Destruct the supplied CryAudio : : Impl : : IListener instance . <nl> struct IImpl <nl> * @ param [ out ] auxGeom - a reference to the IRenderAuxGeom that draws the debug info . <nl> * @ param [ out ] posX - x - axis position of the auxGeom . Has to be increased by the width of the list ( s ) to avoid overlapping with other debug info . <nl> * @ param [ in ] posY - y - axis position of the auxGeom . <nl> + * @ param [ in ] camPos - position of the camera . Useful for distance filtering . <nl> * @ param [ in ] debugDistance - distance from the listener to where object debug is drawn . Is < = 0 if filtering is disabled . <nl> * @ param [ in ] szTextFilter - current set text filter . Is nullptr if filtering is disabled . <nl> * @ return void <nl> * / <nl> - virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , float const debugDistance , char const * const szTextFilter ) const = 0 ; <nl> + virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , Vec3 const & camPos , float const debugDistance , char const * const szTextFilter ) const = 0 ; <nl> } ; <nl> } / / namespace Impl <nl> } / / namespace CryAudio <nl> mmm a / Code / CryEngine / CryAudioSystem / Common / IObject . h <nl> ppp b / Code / CryEngine / CryAudioSystem / Common / IObject . h <nl> struct IEvent ; <nl> struct IParameterConnection ; <nl> struct ISwitchStateConnection ; <nl> struct ITriggerConnection ; <nl> + struct IListener ; <nl> <nl> / * * <nl> * An implementation may use this interface to define a class for storing implementation - specific <nl> struct IObject <nl> <nl> / * * <nl> * Set the provided occlusion value . <nl> + * @ param pIListener - listener which listens to the occluded sound . <nl> * @ param occlusion - the occlusion value to be set , it describes how much all sound paths ( direct and indirect ) are obstructed <nl> + * @ param numRemainingListeners - the number of remaining listeners which will get an occlusion update . Is 1 for the last listener . <nl> * @ return void <nl> * / <nl> - virtual void SetOcclusion ( float const occlusion ) = 0 ; <nl> + virtual void SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) = 0 ; <nl> <nl> / * * <nl> * Set the provided occlusion type . <nl> struct IObject <nl> * / <nl> virtual ERequestStatus SetName ( char const * const szName ) = 0 ; <nl> <nl> + / * * <nl> + * Adds a listener to the audio object . <nl> + * @ param pIListener - listener to add . <nl> + * @ return void <nl> + * / <nl> + virtual void AddListener ( IListener * const pIListener ) = 0 ; <nl> + <nl> + / * * <nl> + * Removes a listener from the audio object . <nl> + * @ param pIListener - listener to remove . <nl> + * @ return void <nl> + * / <nl> + virtual void RemoveListener ( IListener * const pIListener ) = 0 ; <nl> + <nl> / * * <nl> * Enables and disables a certain functionality on the object . <nl> * @ param type - defines the type of functionality . <nl> mmm a / Code / CryEngine / CryAudioSystem / CryAudioSystem . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / CryAudioSystem . cpp <nl> CEngineModule_CryAudioSystem : : CEngineModule_CryAudioSystem ( ) <nl> gEnv - > pSystem - > GetISystemEventDispatcher ( ) - > RegisterListener ( & g_system , " CryAudio : : CSystem " ) ; <nl> } <nl> <nl> - m_pImplNameCVar = REGISTER_STRING_CB ( g_implCVarName , " CryAudioImplSDLMixer " , 0 , <nl> + m_pImplNameCVar = REGISTER_STRING_CB ( g_szImplCVarName , " CryAudioImplSDLMixer " , 0 , <nl> " Holds the name of the audio implementation library to be used . \ n " <nl> " Usage : s_ImplName < name of the library without extension > \ n " <nl> " Default : CryAudioImplSDLMixer \ n " , <nl> CEngineModule_CryAudioSystem : : ~ CEngineModule_CryAudioSystem ( ) <nl> { <nl> if ( gEnv - > pConsole ! = nullptr ) <nl> { <nl> - gEnv - > pConsole - > UnregisterVariable ( g_implCVarName ) ; <nl> + gEnv - > pConsole - > UnregisterVariable ( g_szImplCVarName ) ; <nl> } <nl> <nl> if ( gEnv - > pSystem ! = nullptr ) <nl> mmm a / Code / CryEngine / CryAudioSystem / Impl . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / Impl . cpp <nl> struct SObject final : IObject <nl> virtual void Update ( float const deltaTime ) override { } <nl> virtual void SetTransformation ( CTransformation const & transformation ) override { } <nl> virtual CTransformation const & GetTransformation ( ) const override { return CTransformation : : GetEmptyObject ( ) ; } <nl> - virtual void SetOcclusion ( float const occlusion ) override { } <nl> + virtual void SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) override { } <nl> virtual void SetOcclusionType ( EOcclusionType const occlusionType ) override { } <nl> virtual void StopAllTriggers ( ) override { } <nl> virtual ERequestStatus SetName ( char const * const szName ) override { return ERequestStatus : : Success ; } <nl> + virtual void AddListener ( IListener * const pIListener ) override { } <nl> + virtual void RemoveListener ( IListener * const pIListener ) override { } <nl> virtual void ToggleFunctionality ( EObjectFunctionality const type , bool const enable ) override { } <nl> virtual void DrawDebugInfo ( IRenderAuxGeom & auxGeom , float const posX , float posY , char const * const szTextFilter ) override { } <nl> } ; <nl> void CImpl : : GetInfo ( SImplInfo & implInfo ) const <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IObject * CImpl : : ConstructGlobalObject ( ) <nl> + IObject * CImpl : : ConstructGlobalObject ( IListeners const & listeners ) <nl> { <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioSystem , " CryAudio : : Impl : : Null : : SObject " ) ; <nl> return static_cast < IObject * > ( new SObject ( ) ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IObject * CImpl : : ConstructObject ( CTransformation const & transformation , char const * const szName / * = nullptr * / ) <nl> + IObject * CImpl : : ConstructObject ( CTransformation const & transformation , IListeners const & listeners , char const * const szName / * = nullptr * / ) <nl> { <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioSystem , " CryAudio : : Impl : : Null : : SObject " ) ; <nl> return static_cast < IObject * > ( new SObject ( ) ) ; <nl> void CImpl : : DestructListener ( IListener * const pIListener ) <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char const * const szName / * = nullptr * / ) <nl> + IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char const * const szName ) <nl> { <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioSystem , " CryAudio : : Impl : : Null : : SListener " ) ; <nl> return static_cast < IListener * > ( new SListener ( ) ) ; <nl> void CImpl : : DrawDebugMemoryInfo ( IRenderAuxGeom & auxGeom , float posX , float & posY <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , float const debugDistance , char const * const szTextFilter ) const <nl> + void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , Vec3 const & camPos , float const debugDistance , char const * const szTextFilter ) const <nl> { <nl> } <nl> } / / namespace Null <nl> mmm a / Code / CryEngine / CryAudioSystem / Impl . h <nl> ppp b / Code / CryEngine / CryAudioSystem / Impl . h <nl> class CImpl final : public IImpl <nl> virtual void DestructEnvironmentConnection ( IEnvironmentConnection const * const pIEnvironmentConnection ) override ; <nl> virtual ISettingConnection * ConstructSettingConnection ( XmlNodeRef const & rootNode ) override ; <nl> virtual void DestructSettingConnection ( ISettingConnection const * const pISettingConnection ) override ; <nl> - virtual IObject * ConstructGlobalObject ( ) override ; <nl> - virtual IObject * ConstructObject ( CTransformation const & transformation , char const * const szName = nullptr ) override ; <nl> + virtual IObject * ConstructGlobalObject ( IListeners const & listeners ) override ; <nl> + virtual IObject * ConstructObject ( CTransformation const & transformation , IListeners const & listeners , char const * const szName = nullptr ) override ; <nl> virtual void DestructObject ( IObject const * const pIObject ) override ; <nl> - virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName = nullptr ) override ; <nl> + virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName ) override ; <nl> virtual void DestructListener ( IListener * const pIListener ) override ; <nl> virtual void GamepadConnected ( DeviceId const deviceUniqueID ) override ; <nl> virtual void GamepadDisconnected ( DeviceId const deviceUniqueID ) override ; <nl> class CImpl final : public IImpl <nl> <nl> / / Below data is only used when CRY_AUDIO_USE_DEBUG_CODE is defined ! <nl> virtual void DrawDebugMemoryInfo ( IRenderAuxGeom & auxGeom , float const posX , float & posY , bool const drawDetailedInfo ) override ; <nl> - virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , float const debugDistance , char const * const szTextFilter ) const override ; <nl> + virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , Vec3 const & camPos , float const debugDistance , char const * const szTextFilter ) const override ; <nl> / / ~ CryAudio : : Impl : : IImpl <nl> } ; <nl> } / / namespace Null <nl> mmm a / Code / CryEngine / CryAudioSystem / Listener . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / Listener . cpp <nl> <nl> # include " Common . h " <nl> # include " System . h " <nl> # include " ListenerRequestData . h " <nl> + # include " Managers . h " <nl> + # include " ListenerManager . h " <nl> # include " Common / IListener . h " <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> - # include " GlobalObject . h " <nl> + # include " Common / Logger . h " <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> <nl> namespace CryAudio <nl> void CListener : : HandleSetTransformation ( CTransformation const & transformation ) <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> m_transformation = transformation ; <nl> - g_previewObject . HandleSetTransformation ( transformation ) ; <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> } <nl> <nl> CTransformation const & CListener : : GetTransformation ( ) const <nl> void CListener : : SetName ( char const * const szName , SRequestUserData const & userData / * = SRequestUserData : : GetEmptyObject ( ) * / ) <nl> { <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> - SListenerRequestData < EListenerRequestType : : SetName > requestData ( szName , this ) ; <nl> - CRequest const request ( & requestData , userData ) ; <nl> - g_system . PushRequest ( request ) ; <nl> + if ( m_isUserCreated & & ( _stricmp ( szName , m_name . c_str ( ) ) ! = 0 ) ) <nl> + { <nl> + SListenerRequestData < EListenerRequestType : : SetName > requestData ( szName , this ) ; <nl> + CRequest const request ( & requestData , userData ) ; <nl> + g_system . PushRequest ( request ) ; <nl> + } <nl> + else <nl> + { <nl> + Cry : : Audio : : Log ( ELogType : : Error , " Cannot change name of listener \ " % s \ " during % s " , m_name . c_str ( ) , __FUNCTION__ ) ; <nl> + } <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> } <nl> <nl> void CListener : : SetName ( char const * const szName , SRequestUserData const & userDa <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CListener : : HandleSetName ( char const * const szName ) <nl> { <nl> - m_name = szName ; <nl> - m_pImplData - > SetName ( m_name ) ; <nl> + g_listenerManager . GetUniqueListenerName ( szName , m_name ) ; <nl> + m_id = StringToId ( m_name . c_str ( ) ) ; <nl> + m_pImplData - > SetName ( m_name . c_str ( ) ) ; <nl> } <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> } / / namespace CryAudio <nl> mmm a / Code / CryEngine / CryAudioSystem / Listener . h <nl> ppp b / Code / CryEngine / CryAudioSystem / Listener . h <nl> class CListener final : public CryAudio : : IListener <nl> CListener & operator = ( CListener const & ) = delete ; <nl> CListener & operator = ( CListener & & ) = delete ; <nl> <nl> - explicit CListener ( Impl : : IListener * const pImplData ) <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + explicit CListener ( Impl : : IListener * const pImplData , ListenerId const id , bool const isUserCreated , char const * const szName ) <nl> : m_pImplData ( pImplData ) <nl> + , m_id ( id ) <nl> + , m_isUserCreated ( isUserCreated ) <nl> + , m_name ( szName ) <nl> { } <nl> <nl> + explicit CListener ( ListenerId const id , bool const isUserCreated , char const * const szName ) <nl> + : m_pImplData ( nullptr ) <nl> + , m_id ( id ) <nl> + , m_isUserCreated ( isUserCreated ) <nl> + , m_name ( szName ) <nl> + { } <nl> + # else <nl> + explicit CListener ( Impl : : IListener * const pImplData , ListenerId const id , bool const isUserCreated ) <nl> + : m_pImplData ( pImplData ) <nl> + , m_id ( id ) <nl> + , m_isUserCreated ( isUserCreated ) <nl> + { } <nl> + <nl> + explicit CListener ( ListenerId const id , bool const isUserCreated ) <nl> + : m_pImplData ( nullptr ) <nl> + , m_id ( id ) <nl> + , m_isUserCreated ( isUserCreated ) <nl> + { } <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + <nl> / / CryAudio : : IListener <nl> - virtual void SetTransformation ( CTransformation const & transformation , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> - virtual void SetName ( char const * const szName , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> + virtual ListenerId GetId ( ) const override { return m_id ; } <nl> + virtual void SetTransformation ( CTransformation const & transformation , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> + virtual void SetName ( char const * const szName , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> / / ~ CryAudio : : IListener <nl> <nl> + Impl : : IListener * GetImplData ( ) const { return m_pImplData ; } <nl> + void SetImplData ( Impl : : IListener * const pIListener ) { m_pImplData = pIListener ; } <nl> + <nl> + bool IsUserCreated ( ) const { return m_isUserCreated ; } <nl> void Update ( float const deltaTime ) ; <nl> void HandleSetTransformation ( CTransformation const & transformation ) ; <nl> CTransformation const & GetTransformation ( ) const ; <nl> <nl> + private : <nl> + <nl> Impl : : IListener * m_pImplData ; <nl> + ListenerId m_id ; <nl> + bool m_isUserCreated ; <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + public : <nl> + <nl> void HandleSetName ( char const * const szName ) ; <nl> char const * GetName ( ) const { return m_name . c_str ( ) ; } <nl> CTransformation const & GetDebugTransformation ( ) const { return m_transformation ; } <nl> mmm a / Code / CryEngine / CryAudioSystem / ListenerManager . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / ListenerManager . cpp <nl> <nl> # include " Listener . h " <nl> # include < IImpl . h > <nl> <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + # include " Common / Logger . h " <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + <nl> namespace CryAudio <nl> { <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> CListenerManager : : ~ CListenerManager ( ) <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CListenerManager : : Terminate ( ) <nl> + void CListenerManager : : Initialize ( ) <nl> { <nl> - for ( auto const pListener : m_constructedListeners ) <nl> - { <nl> - CRY_ASSERT_MESSAGE ( pListener - > m_pImplData = = nullptr , " A listener cannot have valid impl data during % s " , __FUNCTION__ ) ; <nl> - delete pListener ; <nl> - } <nl> + m_constructedListeners . push_back ( & g_defaultListener ) ; <nl> <nl> - m_constructedListeners . clear ( ) ; <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + m_constructedListeners . push_back ( & g_previewListener ) ; <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CListenerManager : : OnAfterImplChanged ( ) <nl> + void CListenerManager : : Terminate ( ) <nl> { <nl> - # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> - if ( ! m_constructedListeners . empty ( ) ) <nl> + for ( auto const pListener : m_constructedListeners ) <nl> { <nl> - for ( auto const pListener : m_constructedListeners ) <nl> + CRY_ASSERT_MESSAGE ( pListener - > GetImplData ( ) = = nullptr , " A listener cannot have valid impl data during % s " , __FUNCTION__ ) ; <nl> + <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + ListenerId const id = pListener - > GetId ( ) ; <nl> + <nl> + if ( ( id ! = DefaultListenerId ) & & ( id ! = g_previewListenerId ) ) <nl> + # else <nl> + if ( pListener - > GetId ( ) ! = DefaultListenerId ) <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> { <nl> - pListener - > m_pImplData = g_pIImpl - > ConstructListener ( pListener - > GetDebugTransformation ( ) , pListener - > GetName ( ) ) ; <nl> + delete pListener ; <nl> } <nl> } <nl> - else <nl> - { <nl> - CreateListener ( CTransformation : : GetEmptyObject ( ) , " DefaultListener " ) ; <nl> - } <nl> - # else <nl> - CreateListener ( CTransformation : : GetEmptyObject ( ) , " DefaultListener " ) ; <nl> - # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + <nl> + m_constructedListeners . clear ( ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CListenerManager : : ReleaseImplData ( ) <nl> { <nl> for ( auto const pListener : m_constructedListeners ) <nl> { <nl> - g_pIImpl - > DestructListener ( pListener - > m_pImplData ) ; <nl> - pListener - > m_pImplData = nullptr ; <nl> + g_pIImpl - > DestructListener ( pListener - > GetImplData ( ) ) ; <nl> + pListener - > SetImplData ( nullptr ) ; <nl> } <nl> } <nl> <nl> void CListenerManager : : Update ( float const deltaTime ) <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - CListener * CListenerManager : : CreateListener ( CTransformation const & transformation , char const * const szName ) <nl> + CListener * CListenerManager : : CreateListener ( CTransformation const & transformation , char const * const szName , bool const isUserCreated ) <nl> { <nl> - if ( ! m_constructedListeners . empty ( ) ) <nl> - { <nl> - / / Currently only one listener supported ! <nl> - CListener * const pListener = m_constructedListeners . front ( ) ; <nl> - <nl> - # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> - pListener - > SetName ( szName ) ; <nl> - # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> - <nl> - return pListener ; <nl> - } <nl> + CryFixedStringT < MaxObjectNameLength > name = szName ; <nl> + GetUniqueListenerName ( szName , name ) ; <nl> <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioSystem , " CryAudio : : CListener " ) ; <nl> - auto const pListener = new CListener ( g_pIImpl - > ConstructListener ( transformation , szName ) ) ; <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> - pListener - > SetName ( szName ) ; <nl> + auto const pListener = new CListener ( g_pIImpl - > ConstructListener ( transformation , name . c_str ( ) ) , StringToId ( name . c_str ( ) ) , isUserCreated , name . c_str ( ) ) ; <nl> + # else <nl> + auto const pListener = new CListener ( g_pIImpl - > ConstructListener ( transformation , name . c_str ( ) ) , StringToId ( name . c_str ( ) ) , isUserCreated ) ; <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> <nl> m_constructedListeners . push_back ( pListener ) ; <nl> CListener * CListenerManager : : CreateListener ( CTransformation const & transformatio <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CListenerManager : : ReleaseListener ( CListener * const pListener ) <nl> { <nl> - / / As we currently support only one listener we will destroy that instance only on engine shutdown ! <nl> - / * m_constructedListeners . erase <nl> - ( <nl> - std : : find_if ( m_constructedListeners . begin ( ) , m_constructedListeners . end ( ) , [ = ] ( CListener const * pRegisteredListener ) <nl> - { <nl> - if ( pRegisteredListener = = pListener ) <nl> - { <nl> - g_pIImpl - > DestructListener ( pListener - > m_pImplData ) ; <nl> - delete pListener ; <nl> - return true ; <nl> - } <nl> - <nl> - return false ; <nl> - } ) <nl> - ) ; * / <nl> + m_constructedListeners . erase ( <nl> + std : : find_if ( m_constructedListeners . begin ( ) , m_constructedListeners . end ( ) , [ = ] ( CListener const * pRegisteredListener ) <nl> + { <nl> + if ( pRegisteredListener = = pListener ) <nl> + { <nl> + g_pIImpl - > DestructListener ( pListener - > GetImplData ( ) ) ; <nl> + <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + CRY_ASSERT_MESSAGE ( ( pListener - > GetId ( ) ! = DefaultListenerId ) & & ( pListener - > GetId ( ) ! = g_previewListenerId ) , <nl> + " Listener \ " % s \ " passed wrongly in % s " , pListener - > GetName ( ) , __FUNCTION__ ) ; <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + <nl> + delete pListener ; <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + return false ; <nl> + } ) <nl> + ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - CTransformation const & CListenerManager : : GetActiveListenerTransformation ( ) const <nl> + CListener * CListenerManager : : GetListener ( ListenerId const id ) const <nl> { <nl> - for ( auto const pListener : m_constructedListeners ) <nl> + CListener * pListenerToFind = & g_defaultListener ; <nl> + <nl> + if ( id ! = DefaultListenerId ) <nl> + { <nl> + for ( auto const pListener : m_constructedListeners ) <nl> + { <nl> + if ( pListener - > GetId ( ) = = id ) <nl> + { <nl> + pListenerToFind = pListener ; <nl> + break ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + return pListenerToFind ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CListenerManager : : GetUniqueListenerName ( char const * const szName , CryFixedStringT < MaxObjectNameLength > & newName ) <nl> + { <nl> + GenerateUniqueListenerName ( newName ) ; <nl> + <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + ListenerId const id = StringToId ( newName . c_str ( ) ) ; <nl> + <nl> + if ( StringToId ( szName ) ! = id ) <nl> + { <nl> + Cry : : Audio : : Log ( ELogType : : Error , R " ( A listener with the name " % s " already exists . Setting new name to " % s " ( Id : % u ) ) " , szName , newName . c_str ( ) , id ) ; <nl> + } <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CListenerManager : : GenerateUniqueListenerName ( CryFixedStringT < MaxObjectNameLength > & name ) <nl> + { <nl> + bool nameChanged = false ; <nl> + ListenerId const id = StringToId ( name . c_str ( ) ) ; <nl> + <nl> + for ( auto const pListenerSearched : m_constructedListeners ) <nl> { <nl> - / / Only one listener supported currently ! <nl> - return pListener - > GetTransformation ( ) ; <nl> + if ( pListenerSearched - > GetId ( ) = = id ) <nl> + { <nl> + name + = " _1 " ; <nl> + nameChanged = true ; <nl> + break ; <nl> + } <nl> } <nl> <nl> - return CTransformation : : GetEmptyObject ( ) ; <nl> + if ( nameChanged ) <nl> + { <nl> + GenerateUniqueListenerName ( name ) ; <nl> + } <nl> } <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - size_t CListenerManager : : GetNumActiveListeners ( ) const <nl> + void CListenerManager : : ReconstructImplData ( ) <nl> { <nl> - return m_constructedListeners . size ( ) ; <nl> + for ( auto const pListener : m_constructedListeners ) <nl> + { <nl> + ListenerId const id = pListener - > GetId ( ) ; <nl> + <nl> + if ( ( id ! = DefaultListenerId ) & & ( id ! = g_previewListenerId ) ) <nl> + { <nl> + if ( pListener - > GetImplData ( ) ! = nullptr ) <nl> + { <nl> + g_pIImpl - > DestructListener ( pListener - > GetImplData ( ) ) ; <nl> + } <nl> + <nl> + pListener - > SetImplData ( g_pIImpl - > ConstructListener ( pListener - > GetDebugTransformation ( ) , pListener - > GetName ( ) ) ) ; <nl> + } <nl> + } <nl> } <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> } / / namespace CryAudio <nl> mmm a / Code / CryEngine / CryAudioSystem / ListenerManager . h <nl> ppp b / Code / CryEngine / CryAudioSystem / ListenerManager . h <nl> <nl> <nl> # pragma once <nl> <nl> + # include < CryAudio / IAudioInterfacesCommonData . h > <nl> # include < CryMath / Cry_Math . h > <nl> <nl> namespace CryAudio <nl> class CListenerManager final <nl> <nl> CListenerManager ( CListenerManager const & ) = delete ; <nl> CListenerManager ( CListenerManager & & ) = delete ; <nl> - CListenerManager & operator = ( CListenerManager const & ) = delete ; <nl> - CListenerManager & operator = ( CListenerManager & & ) = delete ; <nl> - <nl> - void Terminate ( ) ; <nl> - void OnAfterImplChanged ( ) ; <nl> - void ReleaseImplData ( ) ; <nl> - void Update ( float const deltaTime ) ; <nl> - CListener * CreateListener ( CTransformation const & transformation , char const * const szName ) ; <nl> - void ReleaseListener ( CListener * const pListener ) ; <nl> - CTransformation const & GetActiveListenerTransformation ( ) const ; <nl> + CListenerManager & operator = ( CListenerManager const & ) = delete ; <nl> + CListenerManager & operator = ( CListenerManager & & ) = delete ; <nl> + <nl> + void Initialize ( ) ; <nl> + void Terminate ( ) ; <nl> + void ReleaseImplData ( ) ; <nl> + void Update ( float const deltaTime ) ; <nl> + CListener * CreateListener ( CTransformation const & transformation , char const * const szName , bool const isUserCreated ) ; <nl> + void ReleaseListener ( CListener * const pListener ) ; <nl> + CListener * GetListener ( ListenerId const id ) const ; <nl> + void GetUniqueListenerName ( char const * const szName , CryFixedStringT < MaxObjectNameLength > & newName ) ; <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> - size_t GetNumActiveListeners ( ) const ; <nl> + size_t GetNumListeners ( ) const { return m_constructedListeners . size ( ) ; } <nl> + void ReconstructImplData ( ) ; <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> <nl> private : <nl> <nl> + void GenerateUniqueListenerName ( CryFixedStringT < MaxObjectNameLength > & name ) ; <nl> + <nl> std : : vector < CListener * > m_constructedListeners ; <nl> } ; <nl> } / / namespace CryAudio <nl> mmm a / Code / CryEngine / CryAudioSystem / Object . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / Object . cpp <nl> <nl> # include " Managers . h " <nl> # include " System . h " <nl> # include " ListenerManager . h " <nl> + # include " Listener . h " <nl> # include " Request . h " <nl> # include " Environment . h " <nl> # include " Parameter . h " <nl> void CObject : : Update ( float const deltaTime ) <nl> <nl> if ( m_propagationProcessor . HasNewOcclusionValues ( ) ) <nl> { <nl> - m_pIObject - > SetOcclusion ( m_propagationProcessor . GetOcclusion ( ) ) ; <nl> + auto numRemainingListeners = static_cast < uint8 > ( m_listeners . size ( ) ) ; <nl> + <nl> + for ( auto const pListener : m_listeners ) <nl> + { <nl> + m_pIObject - > SetOcclusion ( pListener - > GetImplData ( ) , m_propagationProcessor . GetOcclusion ( pListener ) , numRemainingListeners ) ; <nl> + - - numRemainingListeners ; <nl> + } <nl> } <nl> # endif / / CRY_AUDIO_USE_OCCLUSION <nl> <nl> void CObject : : HandleSetTransformation ( CTransformation const & transformation ) <nl> m_pIObject - > SetTransformation ( transformation ) ; <nl> } <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CObject : : HandleAddListener ( ListenerId const id ) <nl> + { <nl> + bool hasListener = false ; <nl> + <nl> + for ( auto const pListener : m_listeners ) <nl> + { <nl> + if ( pListener - > GetId ( ) = = id ) <nl> + { <nl> + hasListener = true ; <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + if ( ! hasListener ) <nl> + { <nl> + CListener * const pListener = g_listenerManager . GetListener ( id ) ; <nl> + m_listeners . push_back ( pListener ) ; <nl> + m_pIObject - > AddListener ( pListener - > GetImplData ( ) ) ; <nl> + <nl> + # if defined ( CRY_AUDIO_USE_OCCLUSION ) <nl> + m_propagationProcessor . AddListener ( pListener ) ; <nl> + # endif / / CRY_AUDIO_USE_OCCLUSION <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CObject : : HandleRemoveListener ( ListenerId const id ) <nl> + { <nl> + auto iter ( m_listeners . begin ( ) ) ; <nl> + auto const iterEnd ( m_listeners . cend ( ) ) ; <nl> + <nl> + for ( ; iter ! = iterEnd ; + + iter ) <nl> + { <nl> + CListener * const pListener = * iter ; <nl> + <nl> + if ( pListener - > GetId ( ) = = id ) <nl> + { <nl> + m_pIObject - > RemoveListener ( pListener - > GetImplData ( ) ) ; <nl> + <nl> + # if defined ( CRY_AUDIO_USE_OCCLUSION ) <nl> + m_propagationProcessor . RemoveListener ( pListener ) ; <nl> + # endif / / CRY_AUDIO_USE_OCCLUSION <nl> + <nl> + if ( iter ! = ( iterEnd - 1 ) ) <nl> + { <nl> + ( * iter ) = m_listeners . back ( ) ; <nl> + } <nl> + <nl> + m_listeners . pop_back ( ) ; <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + if ( m_listeners . empty ( ) ) <nl> + { <nl> + Cry : : Audio : : Log ( ELogType : : Warning , R " ( Object " % s " has no listener ! ) " , m_name . c_str ( ) ) ; <nl> + } <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + } <nl> + <nl> # if defined ( CRY_AUDIO_USE_OCCLUSION ) <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CObject : : SetOcclusion ( float const occlusion ) <nl> { <nl> - m_pIObject - > SetOcclusion ( occlusion ) ; <nl> + auto numRemainingListeners = static_cast < uint8 > ( m_listeners . size ( ) ) ; <nl> + <nl> + for ( auto const pListener : m_listeners ) <nl> + { <nl> + m_pIObject - > SetOcclusion ( pListener - > GetImplData ( ) , occlusion , numRemainingListeners ) ; <nl> + - - numRemainingListeners ; <nl> + } <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CObject : : ReleasePendingRays ( ) <nl> # endif / / CRY_AUDIO_USE_OCCLUSION <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CObject : : Init ( Impl : : IObject * const pIObject ) <nl> + void CObject : : Init ( Impl : : IObject * const pIObject , Listeners const & listeners ) <nl> { <nl> m_pIObject = pIObject ; <nl> + m_listeners = listeners ; <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> CRY_ASSERT_MESSAGE ( m_pIObject ! = nullptr , " m_pIObject is nullptr on object \ " % s \ " during % s " , m_name . c_str ( ) , __FUNCTION__ ) ; <nl> void CObject : : DrawDebugInfo ( <nl> { <nl> Vec3 const & position = m_transformation . GetPosition ( ) ; <nl> Vec3 screenPos ( ZERO ) ; <nl> + float distance = 0 . 0f ; <nl> <nl> if ( IRenderer * const pRenderer = gEnv - > pRenderer ) <nl> { <nl> void CObject : : DrawDebugInfo ( <nl> <nl> screenPos . x = screenPos . x * 0 . 01f * camera . GetViewSurfaceX ( ) ; <nl> screenPos . y = screenPos . y * 0 . 01f * camera . GetViewSurfaceZ ( ) ; <nl> + <nl> + distance = position . GetDistance ( camera . GetPosition ( ) ) ; <nl> } <nl> else <nl> { <nl> screenPos . z = - 1 . 0f ; <nl> } <nl> <nl> - if ( ( screenPos . z > = 0 . 0f ) & & ( screenPos . z < = 1 . 0f ) ) <nl> + if ( ( screenPos . z > = 0 . 0f ) & & ( screenPos . z < = 1 . 0f ) & & ( ( g_cvars . m_debugDistance < = 0 . 0f ) | | ( ( g_cvars . m_debugDistance > 0 . 0f ) & & ( distance < = g_cvars . m_debugDistance ) ) ) ) <nl> { <nl> - float const distance = position . GetDistance ( g_listenerManager . GetActiveListenerTransformation ( ) . GetPosition ( ) ) ; <nl> - <nl> - if ( ( g_cvars . m_debugDistance < = 0 . 0f ) | | ( ( g_cvars . m_debugDistance > 0 . 0f ) & & ( distance < = g_cvars . m_debugDistance ) ) ) <nl> - { <nl> - bool const drawSphere = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : Spheres ) ! = 0 ; <nl> - bool const drawLabel = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectLabel ) ! = 0 ; <nl> - bool const drawTriggers = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectTriggers ) ! = 0 ; <nl> - bool const drawStates = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectStates ) ! = 0 ; <nl> - bool const drawParameters = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectParameters ) ! = 0 ; <nl> - bool const drawEnvironments = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectEnvironments ) ! = 0 ; <nl> - bool const drawDistance = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectDistance ) ! = 0 ; <nl> + bool const drawSphere = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : Spheres ) ! = 0 ; <nl> + bool const drawLabel = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectLabel ) ! = 0 ; <nl> + bool const drawTriggers = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectTriggers ) ! = 0 ; <nl> + bool const drawStates = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectStates ) ! = 0 ; <nl> + bool const drawParameters = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectParameters ) ! = 0 ; <nl> + bool const drawEnvironments = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectEnvironments ) ! = 0 ; <nl> + bool const drawDistance = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectDistance ) ! = 0 ; <nl> # if defined ( CRY_AUDIO_USE_OCCLUSION ) <nl> - bool const drawOcclusionRayLabel = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionRayLabels ) ! = 0 ; <nl> - bool const drawOcclusionRayOffset = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionRayOffset ) ! = 0 ; <nl> - bool const drawOcclusionRaysOrSpheres = ( ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionRays ) ! = 0 ) | | <nl> - ( ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionCollisionSpheres ) ! = 0 ) ; <nl> - bool const drawOcclusionListenerPlane = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionListenerPlane ) ! = 0 ; <nl> + bool const drawOcclusionRayLabel = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionRayLabels ) ! = 0 ; <nl> + bool const drawOcclusionRayOffset = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionRayOffset ) ! = 0 ; <nl> + bool const drawOcclusionRaysOrSpheres = ( ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionRays ) ! = 0 ) | | <nl> + ( ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionCollisionSpheres ) ! = 0 ) ; <nl> + bool const drawOcclusionListenerPlane = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionListenerPlane ) ! = 0 ; <nl> # endif / / CRY_AUDIO_USE_OCCLUSION <nl> - bool const filterAllObjectInfo = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : FilterAllObjectInfo ) ! = 0 ; <nl> + bool const filterAllObjectInfo = ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : FilterAllObjectInfo ) ! = 0 ; <nl> + <nl> + / / Check if any trigger matches text filter . <nl> + bool doesTriggerMatchFilter = false ; <nl> + std : : vector < CryFixedStringT < MaxMiscStringLength > > triggerInfo ; <nl> <nl> - / / Check if any trigger matches text filter . <nl> - bool doesTriggerMatchFilter = false ; <nl> - std : : vector < CryFixedStringT < MaxMiscStringLength > > triggerInfo ; <nl> + if ( ( drawTriggers & & ! m_triggerInstances . empty ( ) ) | | filterAllObjectInfo ) <nl> + { <nl> + Debug : : TriggerCounts triggerCounts ; <nl> <nl> - if ( ( drawTriggers & & ! m_triggerInstances . empty ( ) ) | | filterAllObjectInfo ) <nl> + for ( auto const & triggerInstancePair : m_triggerInstances ) <nl> { <nl> - Debug : : TriggerCounts triggerCounts ; <nl> + + + ( triggerCounts [ triggerInstancePair . second - > GetTriggerId ( ) ] ) ; <nl> + } <nl> <nl> - for ( auto const & triggerInstancePair : m_triggerInstances ) <nl> - { <nl> - + + ( triggerCounts [ triggerInstancePair . second - > GetTriggerId ( ) ] ) ; <nl> - } <nl> + for ( auto const & triggerCountsPair : triggerCounts ) <nl> + { <nl> + CTrigger const * const pTrigger = stl : : find_in_map ( g_triggers , triggerCountsPair . first , nullptr ) ; <nl> <nl> - for ( auto const & triggerCountsPair : triggerCounts ) <nl> + if ( pTrigger ! = nullptr ) <nl> { <nl> - CTrigger const * const pTrigger = stl : : find_in_map ( g_triggers , triggerCountsPair . first , nullptr ) ; <nl> + char const * const szTriggerName = pTrigger - > GetName ( ) ; <nl> <nl> - if ( pTrigger ! = nullptr ) <nl> + if ( ! isTextFilterDisabled ) <nl> { <nl> - char const * const szTriggerName = pTrigger - > GetName ( ) ; <nl> + CryFixedStringT < MaxControlNameLength > lowerCaseTriggerName ( szTriggerName ) ; <nl> + lowerCaseTriggerName . MakeLower ( ) ; <nl> <nl> - if ( ! isTextFilterDisabled ) <nl> + if ( lowerCaseTriggerName . find ( lowerCaseSearchString ) ! = CryFixedStringT < MaxControlNameLength > : : npos ) <nl> { <nl> - CryFixedStringT < MaxControlNameLength > lowerCaseTriggerName ( szTriggerName ) ; <nl> - lowerCaseTriggerName . MakeLower ( ) ; <nl> - <nl> - if ( lowerCaseTriggerName . find ( lowerCaseSearchString ) ! = CryFixedStringT < MaxControlNameLength > : : npos ) <nl> - { <nl> - doesTriggerMatchFilter = true ; <nl> - } <nl> + doesTriggerMatchFilter = true ; <nl> } <nl> + } <nl> <nl> - CryFixedStringT < MaxMiscStringLength > debugText ; <nl> - uint8 const numInstances = triggerCountsPair . second ; <nl> - <nl> - if ( numInstances = = 1 ) <nl> - { <nl> - debugText . Format ( " % s \ n " , szTriggerName ) ; <nl> - } <nl> - else <nl> - { <nl> - debugText . Format ( " % s : % u \ n " , szTriggerName , numInstances ) ; <nl> - } <nl> + CryFixedStringT < MaxMiscStringLength > debugText ; <nl> + uint8 const numInstances = triggerCountsPair . second ; <nl> <nl> - triggerInfo . emplace_back ( debugText ) ; <nl> + if ( numInstances = = 1 ) <nl> + { <nl> + debugText . Format ( " % s \ n " , szTriggerName ) ; <nl> } <nl> + else <nl> + { <nl> + debugText . Format ( " % s : % u \ n " , szTriggerName , numInstances ) ; <nl> + } <nl> + <nl> + triggerInfo . emplace_back ( debugText ) ; <nl> } <nl> } <nl> + } <nl> <nl> - / / Check if any state or switch matches text filter . <nl> - bool doesStateSwitchMatchFilter = false ; <nl> - std : : map < CSwitch const * const , CSwitchState const * const > switchStateInfo ; <nl> + / / Check if any state or switch matches text filter . <nl> + bool doesStateSwitchMatchFilter = false ; <nl> + std : : map < CSwitch const * const , CSwitchState const * const > switchStateInfo ; <nl> <nl> - if ( ( drawStates & & ! m_switchStates . empty ( ) ) | | filterAllObjectInfo ) <nl> + if ( ( drawStates & & ! m_switchStates . empty ( ) ) | | filterAllObjectInfo ) <nl> + { <nl> + for ( auto const & switchStatePair : m_switchStates ) <nl> { <nl> - for ( auto const & switchStatePair : m_switchStates ) <nl> + CSwitch const * const pSwitch = stl : : find_in_map ( g_switches , switchStatePair . first , nullptr ) ; <nl> + <nl> + if ( pSwitch ! = nullptr ) <nl> { <nl> - CSwitch const * const pSwitch = stl : : find_in_map ( g_switches , switchStatePair . first , nullptr ) ; <nl> + CSwitchState const * const pSwitchState = stl : : find_in_map ( pSwitch - > GetStates ( ) , switchStatePair . second , nullptr ) ; <nl> <nl> - if ( pSwitch ! = nullptr ) <nl> + if ( pSwitchState ! = nullptr ) <nl> { <nl> - CSwitchState const * const pSwitchState = stl : : find_in_map ( pSwitch - > GetStates ( ) , switchStatePair . second , nullptr ) ; <nl> - <nl> - if ( pSwitchState ! = nullptr ) <nl> + if ( ! isTextFilterDisabled ) <nl> { <nl> - if ( ! isTextFilterDisabled ) <nl> + char const * const szSwitchName = pSwitch - > GetName ( ) ; <nl> + CryFixedStringT < MaxControlNameLength > lowerCaseSwitchName ( szSwitchName ) ; <nl> + lowerCaseSwitchName . MakeLower ( ) ; <nl> + char const * const szStateName = pSwitchState - > GetName ( ) ; <nl> + CryFixedStringT < MaxControlNameLength > lowerCaseStateName ( szStateName ) ; <nl> + lowerCaseStateName . MakeLower ( ) ; <nl> + <nl> + if ( ( lowerCaseSwitchName . find ( lowerCaseSearchString ) ! = CryFixedStringT < MaxControlNameLength > : : npos ) | | <nl> + ( lowerCaseStateName . find ( lowerCaseSearchString ) ! = CryFixedStringT < MaxControlNameLength > : : npos ) ) <nl> { <nl> - char const * const szSwitchName = pSwitch - > GetName ( ) ; <nl> - CryFixedStringT < MaxControlNameLength > lowerCaseSwitchName ( szSwitchName ) ; <nl> - lowerCaseSwitchName . MakeLower ( ) ; <nl> - char const * const szStateName = pSwitchState - > GetName ( ) ; <nl> - CryFixedStringT < MaxControlNameLength > lowerCaseStateName ( szStateName ) ; <nl> - lowerCaseStateName . MakeLower ( ) ; <nl> - <nl> - if ( ( lowerCaseSwitchName . find ( lowerCaseSearchString ) ! = CryFixedStringT < MaxControlNameLength > : : npos ) | | <nl> - ( lowerCaseStateName . find ( lowerCaseSearchString ) ! = CryFixedStringT < MaxControlNameLength > : : npos ) ) <nl> - { <nl> - doesStateSwitchMatchFilter = true ; <nl> - } <nl> + doesStateSwitchMatchFilter = true ; <nl> } <nl> - <nl> - switchStateInfo . emplace ( pSwitch , pSwitchState ) ; <nl> } <nl> + <nl> + switchStateInfo . emplace ( pSwitch , pSwitchState ) ; <nl> } <nl> } <nl> } <nl> + } <nl> <nl> - / / Check if any parameter matches text filter . <nl> - bool doesParameterMatchFilter = false ; <nl> - std : : map < char const * const , float const > parameterInfo ; <nl> + / / Check if any parameter matches text filter . <nl> + bool doesParameterMatchFilter = false ; <nl> + std : : map < char const * const , float const > parameterInfo ; <nl> <nl> - if ( ( drawParameters & & ! m_parameters . empty ( ) ) | | filterAllObjectInfo ) <nl> + if ( ( drawParameters & & ! m_parameters . empty ( ) ) | | filterAllObjectInfo ) <nl> + { <nl> + for ( auto const & parameterPair : m_parameters ) <nl> { <nl> - for ( auto const & parameterPair : m_parameters ) <nl> + CParameter const * const pParameter = stl : : find_in_map ( g_parameters , parameterPair . first , nullptr ) ; <nl> + <nl> + if ( pParameter ! = nullptr ) <nl> { <nl> - CParameter const * const pParameter = stl : : find_in_map ( g_parameters , parameterPair . first , nullptr ) ; <nl> + char const * const szParameterName = pParameter - > GetName ( ) ; <nl> <nl> - if ( pParameter ! = nullptr ) <nl> + if ( ! isTextFilterDisabled ) <nl> { <nl> - char const * const szParameterName = pParameter - > GetName ( ) ; <nl> + CryFixedStringT < MaxControlNameLength > lowerCaseParameterName ( szParameterName ) ; <nl> + lowerCaseParameterName . MakeLower ( ) ; <nl> <nl> - if ( ! isTextFilterDisabled ) <nl> + if ( lowerCaseParameterName . find ( lowerCaseSearchString ) ! = CryFixedStringT < MaxControlNameLength > : : npos ) <nl> { <nl> - CryFixedStringT < MaxControlNameLength > lowerCaseParameterName ( szParameterName ) ; <nl> - lowerCaseParameterName . MakeLower ( ) ; <nl> - <nl> - if ( lowerCaseParameterName . find ( lowerCaseSearchString ) ! = CryFixedStringT < MaxControlNameLength > : : npos ) <nl> - { <nl> - doesParameterMatchFilter = true ; <nl> - } <nl> + doesParameterMatchFilter = true ; <nl> } <nl> - <nl> - parameterInfo . emplace ( szParameterName , parameterPair . second ) ; <nl> } <nl> + <nl> + parameterInfo . emplace ( szParameterName , parameterPair . second ) ; <nl> } <nl> } <nl> + } <nl> <nl> - / / Check if any environment matches text filter . <nl> - bool doesEnvironmentMatchFilter = false ; <nl> - std : : map < char const * const , float const > environmentInfo ; <nl> + / / Check if any environment matches text filter . <nl> + bool doesEnvironmentMatchFilter = false ; <nl> + std : : map < char const * const , float const > environmentInfo ; <nl> <nl> - if ( ( drawEnvironments & & ! m_environments . empty ( ) ) | | filterAllObjectInfo ) <nl> + if ( ( drawEnvironments & & ! m_environments . empty ( ) ) | | filterAllObjectInfo ) <nl> + { <nl> + for ( auto const & environmentPair : m_environments ) <nl> { <nl> - for ( auto const & environmentPair : m_environments ) <nl> + if ( environmentPair . second > 0 . 0f ) <nl> { <nl> - if ( environmentPair . second > 0 . 0f ) <nl> + CEnvironment const * const pEnvironment = stl : : find_in_map ( g_environments , environmentPair . first , nullptr ) ; <nl> + <nl> + if ( pEnvironment ! = nullptr ) <nl> { <nl> - CEnvironment const * const pEnvironment = stl : : find_in_map ( g_environments , environmentPair . first , nullptr ) ; <nl> + char const * const szEnvironmentName = pEnvironment - > GetName ( ) ; <nl> <nl> - if ( pEnvironment ! = nullptr ) <nl> + if ( ! isTextFilterDisabled ) <nl> { <nl> - char const * const szEnvironmentName = pEnvironment - > GetName ( ) ; <nl> + CryFixedStringT < MaxControlNameLength > lowerCaseEnvironmentName ( szEnvironmentName ) ; <nl> + lowerCaseEnvironmentName . MakeLower ( ) ; <nl> <nl> - if ( ! isTextFilterDisabled ) <nl> + if ( lowerCaseEnvironmentName . find ( lowerCaseSearchString ) ! = CryFixedStringT < MaxControlNameLength > : : npos ) <nl> { <nl> - CryFixedStringT < MaxControlNameLength > lowerCaseEnvironmentName ( szEnvironmentName ) ; <nl> - lowerCaseEnvironmentName . MakeLower ( ) ; <nl> - <nl> - if ( lowerCaseEnvironmentName . find ( lowerCaseSearchString ) ! = CryFixedStringT < MaxControlNameLength > : : npos ) <nl> - { <nl> - doesEnvironmentMatchFilter = true ; <nl> - } <nl> + doesEnvironmentMatchFilter = true ; <nl> } <nl> - <nl> - environmentInfo . emplace ( szEnvironmentName , environmentPair . second ) ; <nl> } <nl> + <nl> + environmentInfo . emplace ( szEnvironmentName , environmentPair . second ) ; <nl> } <nl> } <nl> } <nl> + } <nl> <nl> - / / Check if object name matches text filter . <nl> - bool doesObjectNameMatchFilter = false ; <nl> + / / Check if object name matches text filter . <nl> + bool doesObjectNameMatchFilter = false ; <nl> <nl> # if defined ( CRY_AUDIO_USE_OCCLUSION ) <nl> - if ( ! isTextFilterDisabled & & <nl> - ( drawSphere | | <nl> - drawLabel | | <nl> - drawDistance | | <nl> - drawOcclusionRayLabel | | <nl> - drawOcclusionRayOffset | | <nl> - drawOcclusionRaysOrSpheres | | <nl> - drawOcclusionListenerPlane | | <nl> - filterAllObjectInfo ) ) <nl> + if ( ! isTextFilterDisabled & & <nl> + ( drawSphere | | <nl> + drawLabel | | <nl> + drawDistance | | <nl> + drawOcclusionRayLabel | | <nl> + drawOcclusionRayOffset | | <nl> + drawOcclusionRaysOrSpheres | | <nl> + drawOcclusionListenerPlane | | <nl> + filterAllObjectInfo ) ) <nl> # else <nl> - if ( ! isTextFilterDisabled & & ( drawSphere | | drawLabel | | drawDistance | | filterAllObjectInfo ) ) <nl> + if ( ! isTextFilterDisabled & & ( drawSphere | | drawLabel | | drawDistance | | filterAllObjectInfo ) ) <nl> # endif / / CRY_AUDIO_USE_OCCLUSION <nl> + { <nl> + CryFixedStringT < MaxControlNameLength > lowerCaseObjectName ( m_name . c_str ( ) ) ; <nl> + lowerCaseObjectName . MakeLower ( ) ; <nl> + doesObjectNameMatchFilter = ( lowerCaseObjectName . find ( lowerCaseSearchString ) ! = CryFixedStringT < MaxControlNameLength > : : npos ) ; <nl> + } <nl> + <nl> + bool const hasActiveData = ( m_flags & EObjectFlags : : Active ) ! = 0 ; <nl> + bool const isVirtual = ( m_flags & EObjectFlags : : Virtual ) ! = 0 ; <nl> + bool const canDraw = ( g_cvars . m_hideInactiveObjects = = 0 ) | | ( ( g_cvars . m_hideInactiveObjects ! = 0 ) & & hasActiveData & & ! isVirtual ) ; <nl> + <nl> + if ( canDraw ) <nl> + { <nl> + if ( drawSphere & & ( isTextFilterDisabled | | doesObjectNameMatchFilter ) ) <nl> { <nl> - CryFixedStringT < MaxControlNameLength > lowerCaseObjectName ( m_name . c_str ( ) ) ; <nl> - lowerCaseObjectName . MakeLower ( ) ; <nl> - doesObjectNameMatchFilter = ( lowerCaseObjectName . find ( lowerCaseSearchString ) ! = CryFixedStringT < MaxControlNameLength > : : npos ) ; <nl> + auxGeom . DrawSphere ( <nl> + position , <nl> + Debug : : g_objectRadiusPositionSphere , <nl> + isVirtual ? Debug : : s_globalColorVirtual : Debug : : s_objectColorPositionSphere ) ; <nl> } <nl> <nl> - bool const hasActiveData = ( m_flags & EObjectFlags : : Active ) ! = 0 ; <nl> - bool const isVirtual = ( m_flags & EObjectFlags : : Virtual ) ! = 0 ; <nl> - bool const canDraw = ( g_cvars . m_hideInactiveObjects = = 0 ) | | ( ( g_cvars . m_hideInactiveObjects ! = 0 ) & & hasActiveData & & ! isVirtual ) ; <nl> - <nl> - if ( canDraw ) <nl> + if ( drawLabel & & ( isTextFilterDisabled | | doesObjectNameMatchFilter ) ) <nl> { <nl> - if ( drawSphere & & ( isTextFilterDisabled | | doesObjectNameMatchFilter ) ) <nl> - { <nl> - auxGeom . DrawSphere ( <nl> - position , <nl> - Debug : : g_objectRadiusPositionSphere , <nl> - isVirtual ? Debug : : s_globalColorVirtual : Debug : : s_objectColorPositionSphere ) ; <nl> - } <nl> + auxGeom . Draw2dLabel ( <nl> + screenPos . x , <nl> + screenPos . y , <nl> + Debug : : g_objectFontSize , <nl> + isVirtual ? Debug : : s_globalColorVirtual : ( hasActiveData ? Debug : : s_objectColorActive : Debug : : s_globalColorInactive ) , <nl> + false , <nl> + " % s " , m_name . c_str ( ) ) ; <nl> + <nl> + screenPos . y + = Debug : : g_objectLineHeight ; <nl> + } <nl> <nl> - if ( drawLabel & & ( isTextFilterDisabled | | doesObjectNameMatchFilter ) ) <nl> + if ( drawTriggers & & ( isTextFilterDisabled | | doesTriggerMatchFilter ) ) <nl> + { <nl> + for ( auto const & debugText : triggerInfo ) <nl> { <nl> auxGeom . Draw2dLabel ( <nl> screenPos . x , <nl> screenPos . y , <nl> Debug : : g_objectFontSize , <nl> - isVirtual ? Debug : : s_globalColorVirtual : ( hasActiveData ? Debug : : s_objectColorActive : Debug : : s_globalColorInactive ) , <nl> + isVirtual ? Debug : : s_globalColorVirtual : Debug : : s_objectColorTrigger , <nl> false , <nl> - " % s " , m_name . c_str ( ) ) ; <nl> + " % s " , debugText . c_str ( ) ) ; <nl> <nl> screenPos . y + = Debug : : g_objectLineHeight ; <nl> } <nl> + } <nl> <nl> - if ( drawTriggers & & ( isTextFilterDisabled | | doesTriggerMatchFilter ) ) <nl> - { <nl> - for ( auto const & debugText : triggerInfo ) <nl> - { <nl> - auxGeom . Draw2dLabel ( <nl> - screenPos . x , <nl> - screenPos . y , <nl> - Debug : : g_objectFontSize , <nl> - isVirtual ? Debug : : s_globalColorVirtual : Debug : : s_objectColorTrigger , <nl> - false , <nl> - " % s " , debugText . c_str ( ) ) ; <nl> - <nl> - screenPos . y + = Debug : : g_objectLineHeight ; <nl> - } <nl> - } <nl> - <nl> - if ( drawStates & & ( isTextFilterDisabled | | doesStateSwitchMatchFilter ) ) <nl> + if ( drawStates & & ( isTextFilterDisabled | | doesStateSwitchMatchFilter ) ) <nl> + { <nl> + for ( auto const & switchStatePair : switchStateInfo ) <nl> { <nl> - for ( auto const & switchStatePair : switchStateInfo ) <nl> - { <nl> - auto const pSwitch = switchStatePair . first ; <nl> - auto const pSwitchState = switchStatePair . second ; <nl> + auto const pSwitch = switchStatePair . first ; <nl> + auto const pSwitchState = switchStatePair . second ; <nl> <nl> - Debug : : CStateDrawData & drawData = m_stateDrawInfo . emplace ( std : : piecewise_construct , std : : forward_as_tuple ( pSwitch - > GetId ( ) ) , std : : forward_as_tuple ( pSwitchState - > GetId ( ) ) ) . first - > second ; <nl> - drawData . Update ( pSwitchState - > GetId ( ) ) ; <nl> - ColorF const switchTextColor = { 0 . 8f , drawData . m_currentSwitchColor , 0 . 6f } ; <nl> + Debug : : CStateDrawData & drawData = m_stateDrawInfo . emplace ( std : : piecewise_construct , std : : forward_as_tuple ( pSwitch - > GetId ( ) ) , std : : forward_as_tuple ( pSwitchState - > GetId ( ) ) ) . first - > second ; <nl> + drawData . Update ( pSwitchState - > GetId ( ) ) ; <nl> + ColorF const switchTextColor = { 0 . 8f , drawData . m_currentSwitchColor , 0 . 6f } ; <nl> <nl> - auxGeom . Draw2dLabel ( <nl> - screenPos . x , <nl> - screenPos . y , <nl> - Debug : : g_objectFontSize , <nl> - isVirtual ? Debug : : s_globalColorVirtual : switchTextColor , <nl> - false , <nl> - " % s : % s \ n " , <nl> - pSwitch - > GetName ( ) , <nl> - pSwitchState - > GetName ( ) ) ; <nl> - <nl> - screenPos . y + = Debug : : g_objectLineHeight ; <nl> - } <nl> - } <nl> - <nl> - if ( drawParameters & & ( isTextFilterDisabled | | doesParameterMatchFilter ) ) <nl> - { <nl> - for ( auto const & parameterPair : parameterInfo ) <nl> - { <nl> - auxGeom . Draw2dLabel ( <nl> - screenPos . x , <nl> - screenPos . y , <nl> - Debug : : g_objectFontSize , <nl> - isVirtual ? Debug : : s_globalColorVirtual : Debug : : s_objectColorParameter , <nl> - false , <nl> - " % s : % 2 . 2f \ n " , <nl> - parameterPair . first , <nl> - parameterPair . second ) ; <nl> + auxGeom . Draw2dLabel ( <nl> + screenPos . x , <nl> + screenPos . y , <nl> + Debug : : g_objectFontSize , <nl> + isVirtual ? Debug : : s_globalColorVirtual : switchTextColor , <nl> + false , <nl> + " % s : % s \ n " , <nl> + pSwitch - > GetName ( ) , <nl> + pSwitchState - > GetName ( ) ) ; <nl> <nl> - screenPos . y + = Debug : : g_objectLineHeight ; <nl> - } <nl> + screenPos . y + = Debug : : g_objectLineHeight ; <nl> } <nl> + } <nl> <nl> - if ( drawEnvironments & & ( isTextFilterDisabled | | doesEnvironmentMatchFilter ) ) <nl> + if ( drawParameters & & ( isTextFilterDisabled | | doesParameterMatchFilter ) ) <nl> + { <nl> + for ( auto const & parameterPair : parameterInfo ) <nl> { <nl> - for ( auto const & environmentPair : environmentInfo ) <nl> - { <nl> - auxGeom . Draw2dLabel ( <nl> - screenPos . x , <nl> - screenPos . y , <nl> - Debug : : g_objectFontSize , <nl> - isVirtual ? Debug : : s_globalColorVirtual : Debug : : s_objectColorEnvironment , <nl> - false , <nl> - " % s : % . 2f \ n " , <nl> - environmentPair . first , <nl> - environmentPair . second ) ; <nl> + auxGeom . Draw2dLabel ( <nl> + screenPos . x , <nl> + screenPos . y , <nl> + Debug : : g_objectFontSize , <nl> + isVirtual ? Debug : : s_globalColorVirtual : Debug : : s_objectColorParameter , <nl> + false , <nl> + " % s : % 2 . 2f \ n " , <nl> + parameterPair . first , <nl> + parameterPair . second ) ; <nl> <nl> - screenPos . y + = Debug : : g_objectLineHeight ; <nl> - } <nl> + screenPos . y + = Debug : : g_objectLineHeight ; <nl> } <nl> + } <nl> <nl> - if ( drawDistance & & ( isTextFilterDisabled | | doesObjectNameMatchFilter ) ) <nl> + if ( drawEnvironments & & ( isTextFilterDisabled | | doesEnvironmentMatchFilter ) ) <nl> + { <nl> + for ( auto const & environmentPair : environmentInfo ) <nl> { <nl> - CryFixedStringT < MaxMiscStringLength > debugText ; <nl> - <nl> - if ( m_maxRadius > 0 . 0f ) <nl> - { <nl> - debugText . Format ( " Dist : % 4 . 1fm / Max : % . 1fm " , distance , m_maxRadius ) ; <nl> - } <nl> - else <nl> - { <nl> - debugText . Format ( " Dist : % 4 . 1fm " , distance ) ; <nl> - } <nl> - <nl> auxGeom . Draw2dLabel ( <nl> screenPos . x , <nl> screenPos . y , <nl> Debug : : g_objectFontSize , <nl> - isVirtual ? Debug : : s_globalColorVirtual : Debug : : s_objectColorActive , <nl> + isVirtual ? Debug : : s_globalColorVirtual : Debug : : s_objectColorEnvironment , <nl> false , <nl> - " % s " , debugText . c_str ( ) ) ; <nl> + " % s : % . 2f \ n " , <nl> + environmentPair . first , <nl> + environmentPair . second ) ; <nl> <nl> screenPos . y + = Debug : : g_objectLineHeight ; <nl> } <nl> + } <nl> + <nl> + if ( drawDistance & & ( isTextFilterDisabled | | doesObjectNameMatchFilter ) ) <nl> + { <nl> + CryFixedStringT < MaxMiscStringLength > debugText ; <nl> + <nl> + if ( m_maxRadius > 0 . 0f ) <nl> + { <nl> + debugText . Format ( " Dist : % 4 . 1fm / Max : % . 1fm " , distance , m_maxRadius ) ; <nl> + } <nl> + else <nl> + { <nl> + debugText . Format ( " Dist : % 4 . 1fm " , distance ) ; <nl> + } <nl> + <nl> + auxGeom . Draw2dLabel ( <nl> + screenPos . x , <nl> + screenPos . y , <nl> + Debug : : g_objectFontSize , <nl> + isVirtual ? Debug : : s_globalColorVirtual : Debug : : s_objectColorActive , <nl> + false , <nl> + " % s " , debugText . c_str ( ) ) ; <nl> + <nl> + screenPos . y + = Debug : : g_objectLineHeight ; <nl> + } <nl> <nl> # if defined ( CRY_AUDIO_USE_OCCLUSION ) <nl> - if ( ( ( m_flags & EObjectFlags : : CanRunOcclusion ) ! = 0 ) & & ( isTextFilterDisabled | | doesObjectNameMatchFilter ) ) <nl> + if ( ( ( m_flags & EObjectFlags : : CanRunOcclusion ) ! = 0 ) & & ( isTextFilterDisabled | | doesObjectNameMatchFilter ) ) <nl> + { <nl> + if ( drawOcclusionRayLabel ) <nl> { <nl> - if ( drawOcclusionRayLabel ) <nl> + EOcclusionType const occlusionType = m_propagationProcessor . GetOcclusionType ( ) ; <nl> + OcclusionInfos const & occlusionInfos = m_propagationProcessor . GetOcclusionInfos ( ) ; <nl> + <nl> + for ( auto const & info : occlusionInfos ) <nl> { <nl> - EOcclusionType const occlusionType = m_propagationProcessor . GetOcclusionType ( ) ; <nl> - float const occlusion = m_propagationProcessor . GetOcclusion ( ) ; <nl> + float const occlusion = info . occlusion ; <nl> <nl> CryFixedStringT < MaxMiscStringLength > debugText ; <nl> <nl> void CObject : : DrawDebugInfo ( <nl> debugText . Format ( <nl> " % s ( % s ) " , <nl> Debug : : g_szOcclusionTypes [ static_cast < std : : underlying_type < EOcclusionType > : : type > ( occlusionType ) ] , <nl> - Debug : : g_szOcclusionTypes [ static_cast < std : : underlying_type < EOcclusionType > : : type > ( m_propagationProcessor . GetOcclusionTypeWhenAdaptive ( ) ) ] ) ; <nl> + Debug : : g_szOcclusionTypes [ static_cast < std : : underlying_type < EOcclusionType > : : type > ( info . occlusionTypeWhenAdaptive ) ] ) ; <nl> } <nl> else <nl> { <nl> void CObject : : DrawDebugInfo ( <nl> Debug : : g_objectFontSize , <nl> isVirtual ? Debug : : s_globalColorVirtual : ( ( ( occlusionType ! = EOcclusionType : : None ) & & ( occlusionType ! = EOcclusionType : : Ignore ) ) ? activeRayLabelColor : Debug : : s_globalColorInactive ) , <nl> false , <nl> - " Occl : % 3 . 2f | Type : % s " , <nl> + " Occl : % 3 . 2f | Type : % s | % s " , <nl> occlusion , <nl> - debugText . c_str ( ) ) ; <nl> + debugText . c_str ( ) , <nl> + info . pListener - > GetName ( ) ) ; <nl> <nl> screenPos . y + = Debug : : g_objectLineHeight ; <nl> } <nl> + } <nl> <nl> - if ( drawOcclusionRayOffset & & ! isVirtual ) <nl> - { <nl> - float const occlusionRayOffset = m_propagationProcessor . GetOcclusionRayOffset ( ) ; <nl> - <nl> - if ( occlusionRayOffset > 0 . 0f ) <nl> - { <nl> - SAuxGeomRenderFlags const previousRenderFlags = auxGeom . GetRenderFlags ( ) ; <nl> - SAuxGeomRenderFlags newRenderFlags ( e_Def3DPublicRenderflags | e_AlphaBlended ) ; <nl> - auxGeom . SetRenderFlags ( newRenderFlags ) ; <nl> + if ( drawOcclusionRayOffset & & ! isVirtual ) <nl> + { <nl> + float const occlusionRayOffset = m_propagationProcessor . GetOcclusionRayOffset ( ) ; <nl> <nl> - auxGeom . DrawSphere ( <nl> - position , <nl> - occlusionRayOffset , <nl> - Debug : : s_objectColorOcclusionOffsetSphere ) ; <nl> + if ( occlusionRayOffset > 0 . 0f ) <nl> + { <nl> + SAuxGeomRenderFlags const previousRenderFlags = auxGeom . GetRenderFlags ( ) ; <nl> + SAuxGeomRenderFlags newRenderFlags ( e_Def3DPublicRenderflags | e_AlphaBlended ) ; <nl> + auxGeom . SetRenderFlags ( newRenderFlags ) ; <nl> <nl> - auxGeom . SetRenderFlags ( previousRenderFlags ) ; <nl> - } <nl> - } <nl> + auxGeom . DrawSphere ( <nl> + position , <nl> + occlusionRayOffset , <nl> + Debug : : s_objectColorOcclusionOffsetSphere ) ; <nl> <nl> - if ( drawOcclusionRaysOrSpheres ) <nl> - { <nl> - m_propagationProcessor . DrawDebugInfo ( auxGeom ) ; <nl> + auxGeom . SetRenderFlags ( previousRenderFlags ) ; <nl> } <nl> + } <nl> <nl> - if ( drawOcclusionListenerPlane ) <nl> - { <nl> - m_propagationProcessor . DrawListenerPlane ( auxGeom ) ; <nl> - } <nl> + if ( drawOcclusionRaysOrSpheres ) <nl> + { <nl> + m_propagationProcessor . DrawDebugInfo ( auxGeom ) ; <nl> } <nl> - # endif / / CRY_AUDIO_USE_OCCLUSION <nl> <nl> - if ( ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectImplInfo ) ! = 0 ) <nl> + if ( drawOcclusionListenerPlane ) <nl> { <nl> - m_pIObject - > DrawDebugInfo ( auxGeom , screenPos . x , screenPos . y , ( isTextFilterDisabled ? nullptr : lowerCaseSearchString . c_str ( ) ) ) ; <nl> + m_propagationProcessor . DrawListenerPlane ( auxGeom ) ; <nl> } <nl> } <nl> + # endif / / CRY_AUDIO_USE_OCCLUSION <nl> + <nl> + if ( ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : ObjectImplInfo ) ! = 0 ) <nl> + { <nl> + m_pIObject - > DrawDebugInfo ( auxGeom , screenPos . x , screenPos . y , ( isTextFilterDisabled ? nullptr : lowerCaseSearchString . c_str ( ) ) ) ; <nl> + } <nl> } <nl> } <nl> } <nl> void CObject : : SetName ( char const * const szName , SRequestUserData const & userData <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> } <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CObject : : AddListener ( ListenerId const id , SRequestUserData const & userData / * = SRequestUserData : : GetEmptyObject ( ) * / ) <nl> + { <nl> + SObjectRequestData < EObjectRequestType : : AddListener > requestData ( this , id ) ; <nl> + PushRequest ( requestData , userData ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CObject : : RemoveListener ( ListenerId const id , SRequestUserData const & userData / * = SRequestUserData : : GetEmptyObject ( ) * / ) <nl> + { <nl> + SObjectRequestData < EObjectRequestType : : RemoveListener > requestData ( this , id ) ; <nl> + PushRequest ( requestData , userData ) ; <nl> + } <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CObject : : ToggleAbsoluteVelocityTracking ( bool const enable , SRequestUserData const & userData / * = SAudioRequestUserData : : GetEmptyObject ( ) * / ) <nl> { <nl> mmm a / Code / CryEngine / CryAudioSystem / Object . h <nl> ppp b / Code / CryEngine / CryAudioSystem / Object . h <nl> class CObject final : public IObject , public CPoolObject < CObject , stl : : PSyncNone <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> <nl> void HandleSetTransformation ( CTransformation const & transformation ) ; <nl> + void HandleAddListener ( ListenerId const id ) ; <nl> + void HandleRemoveListener ( ListenerId const id ) ; <nl> <nl> - void Init ( Impl : : IObject * const pIObject ) ; <nl> + void Init ( Impl : : IObject * const pIObject , Listeners const & listeners ) ; <nl> void Destruct ( ) ; <nl> <nl> void StopAllTriggers ( ) ; <nl> class CObject final : public IObject , public CPoolObject < CObject , stl : : PSyncNone <nl> # endif / / CRY_AUDIO_USE_OCCLUSION <nl> <nl> Impl : : IObject * GetImplDataPtr ( ) const { return m_pIObject ; } <nl> + Listeners const & GetListeners ( ) const { return m_listeners ; } <nl> CTransformation const & GetTransformation ( ) const { return m_transformation ; } <nl> <nl> bool IsPlaying ( ) const ; <nl> class CObject final : public IObject , public CPoolObject < CObject , stl : : PSyncNone <nl> virtual void SetOcclusionType ( EOcclusionType const occlusionType , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> virtual void SetOcclusionRayOffset ( float const offset , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> virtual void SetName ( char const * const szName , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> - void ToggleAbsoluteVelocityTracking ( bool const enable , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> - void ToggleRelativeVelocityTracking ( bool const enable , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> + virtual void AddListener ( ListenerId const id , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> + virtual void RemoveListener ( ListenerId const id , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> + virtual void ToggleAbsoluteVelocityTracking ( bool const enable , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> + virtual void ToggleRelativeVelocityTracking ( bool const enable , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> / / ~ CryAudio : : IObject <nl> <nl> void SetActive ( ) ; <nl> class CObject final : public IObject , public CPoolObject < CObject , stl : : PSyncNone <nl> CPropagationProcessor m_propagationProcessor ; <nl> # endif / / CRY_AUDIO_USE_OCCLUSION <nl> <nl> + Listeners m_listeners ; <nl> + <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> public : <nl> <nl> mmm a / Code / CryEngine / CryAudioSystem / ObjectRequestData . h <nl> ppp b / Code / CryEngine / CryAudioSystem / ObjectRequestData . h <nl> enum class EObjectRequestType : EnumFlagsType <nl> SetCurrentEnvironments , <nl> SetEnvironment , <nl> ProcessPhysicsRay , <nl> + AddListener , <nl> + RemoveListener , <nl> ToggleAbsoluteVelocityTracking , <nl> ToggleRelativeVelocityTracking , <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> struct SObjectRequestData < EObjectRequestType : : ProcessPhysicsRay > final : public <nl> CRayInfo & rayInfo ; <nl> } ; <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + template < > <nl> + struct SObjectRequestData < EObjectRequestType : : AddListener > final : public SObjectRequestDataBase <nl> + { <nl> + explicit SObjectRequestData ( CObject * const pObject_ , ListenerId const listenerId_ ) <nl> + : SObjectRequestDataBase ( EObjectRequestType : : AddListener , pObject_ ) <nl> + , listenerId ( listenerId_ ) <nl> + { } <nl> + <nl> + explicit SObjectRequestData ( SObjectRequestData < EObjectRequestType : : AddListener > const * const pORData ) <nl> + : SObjectRequestDataBase ( EObjectRequestType : : AddListener , pORData - > pObject ) <nl> + , listenerId ( pORData - > listenerId ) <nl> + { } <nl> + <nl> + virtual ~ SObjectRequestData ( ) override = default ; <nl> + <nl> + ListenerId const listenerId ; <nl> + } ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + template < > <nl> + struct SObjectRequestData < EObjectRequestType : : RemoveListener > final : public SObjectRequestDataBase <nl> + { <nl> + explicit SObjectRequestData ( CObject * const pObject_ , ListenerId const listenerId_ ) <nl> + : SObjectRequestDataBase ( EObjectRequestType : : RemoveListener , pObject_ ) <nl> + , listenerId ( listenerId_ ) <nl> + { } <nl> + <nl> + explicit SObjectRequestData ( SObjectRequestData < EObjectRequestType : : RemoveListener > const * const pORData ) <nl> + : SObjectRequestDataBase ( EObjectRequestType : : RemoveListener , pORData - > pObject ) <nl> + , listenerId ( pORData - > listenerId ) <nl> + { } <nl> + <nl> + virtual ~ SObjectRequestData ( ) override = default ; <nl> + <nl> + ListenerId const listenerId ; <nl> + } ; <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> template < > <nl> struct SObjectRequestData < EObjectRequestType : : ToggleAbsoluteVelocityTracking > final : public SObjectRequestDataBase <nl> new file mode 100644 <nl> index 0000000000 . . fd03917000 <nl> mmm / dev / null <nl> ppp b / Code / CryEngine / CryAudioSystem / OcclusionInfo . h <nl> <nl> + / / Copyright 2001 - 2018 Crytek GmbH / Crytek Group . All rights reserved . <nl> + <nl> + # pragma once <nl> + <nl> + # if defined ( CRY_AUDIO_USE_OCCLUSION ) <nl> + # include " RayInfo . h " <nl> + # include < CryAudio / IAudioInterfacesCommonData . h > <nl> + <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + # include < CryMath / Cry_Color . h > <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + <nl> + namespace CryAudio <nl> + { <nl> + class CListener ; <nl> + <nl> + constexpr uint8 g_numberLow = 7 ; <nl> + constexpr uint8 g_numberMedium = 9 ; <nl> + constexpr uint8 g_numberHigh = 11 ; <nl> + constexpr uint8 g_numRaySamplePositionsLow = g_numberLow * g_numberLow ; <nl> + constexpr uint8 g_numRaySamplePositionsMedium = g_numberMedium * g_numberMedium ; <nl> + constexpr uint8 g_numRaySamplePositionsHigh = g_numberHigh * g_numberHigh ; <nl> + constexpr uint8 g_numConcurrentRaysLow = 1 ; <nl> + constexpr uint8 g_numConcurrentRaysMedium = 2 ; <nl> + constexpr uint8 g_numConcurrentRaysHigh = 4 ; <nl> + constexpr uint8 g_numInitialSamplePositions = 5 ; <nl> + <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + struct SRayDebugInfo final <nl> + { <nl> + SRayDebugInfo ( ) = default ; <nl> + <nl> + Vec3 begin = ZERO ; <nl> + Vec3 end = ZERO ; <nl> + float occlusionValue = 0 . 0f ; <nl> + float distanceToNearestObstacle = FLT_MAX ; <nl> + uint8 numHits = 0 ; <nl> + uint8 samplePosIndex = 0 ; <nl> + } ; <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + <nl> + struct SOcclusionInfo final <nl> + { <nl> + SOcclusionInfo ( SOcclusionInfo const & rhs ) <nl> + : pListener ( rhs . pListener ) <nl> + , lastQuerriedOcclusion ( rhs . lastQuerriedOcclusion ) <nl> + , occlusion ( rhs . occlusion ) <nl> + , currentListenerDistance ( rhs . currentListenerDistance ) <nl> + , rayIndex ( rhs . rayIndex ) <nl> + , raysOcclusion ( rhs . raysOcclusion ) <nl> + , raysInfo ( rhs . raysInfo ) <nl> + , occlusionTypeWhenAdaptive ( rhs . occlusionTypeWhenAdaptive ) <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + , rayDebugInfos ( rhs . rayDebugInfos ) <nl> + , listenerOcclusionPlaneColor ( rhs . listenerOcclusionPlaneColor ) <nl> + , collisionSpherePositions ( rhs . collisionSpherePositions ) <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + { } <nl> + <nl> + SOcclusionInfo ( SOcclusionInfo & & rhs ) <nl> + : pListener ( rhs . pListener ) <nl> + , lastQuerriedOcclusion ( rhs . lastQuerriedOcclusion ) <nl> + , occlusion ( rhs . occlusion ) <nl> + , currentListenerDistance ( rhs . currentListenerDistance ) <nl> + , rayIndex ( rhs . rayIndex ) <nl> + , raysOcclusion ( rhs . raysOcclusion ) <nl> + , raysInfo ( rhs . raysInfo ) <nl> + , occlusionTypeWhenAdaptive ( rhs . occlusionTypeWhenAdaptive ) <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + , rayDebugInfos ( rhs . rayDebugInfos ) <nl> + , listenerOcclusionPlaneColor ( rhs . listenerOcclusionPlaneColor ) <nl> + , collisionSpherePositions ( rhs . collisionSpherePositions ) <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + { } <nl> + <nl> + SOcclusionInfo & operator = ( SOcclusionInfo const & rhs ) <nl> + { <nl> + pListener = rhs . pListener ; <nl> + lastQuerriedOcclusion = rhs . lastQuerriedOcclusion ; <nl> + occlusion = rhs . occlusion ; <nl> + currentListenerDistance = rhs . currentListenerDistance ; <nl> + rayIndex = rhs . rayIndex ; <nl> + raysOcclusion = rhs . raysOcclusion ; <nl> + raysInfo = rhs . raysInfo ; <nl> + occlusionTypeWhenAdaptive = rhs . occlusionTypeWhenAdaptive ; <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + rayDebugInfos = rhs . rayDebugInfos ; <nl> + listenerOcclusionPlaneColor = rhs . listenerOcclusionPlaneColor ; <nl> + collisionSpherePositions = rhs . collisionSpherePositions ; <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + return * this ; <nl> + } <nl> + <nl> + SOcclusionInfo & operator = ( SOcclusionInfo & & rhs ) <nl> + { <nl> + pListener = rhs . pListener ; <nl> + lastQuerriedOcclusion = rhs . lastQuerriedOcclusion ; <nl> + occlusion = rhs . occlusion ; <nl> + currentListenerDistance = rhs . currentListenerDistance ; <nl> + rayIndex = rhs . rayIndex ; <nl> + raysOcclusion = std : : move ( rhs . raysOcclusion ) ; <nl> + raysInfo = std : : move ( rhs . raysInfo ) ; <nl> + occlusionTypeWhenAdaptive = rhs . occlusionTypeWhenAdaptive ; <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + rayDebugInfos = std : : move ( rhs . rayDebugInfos ) ; <nl> + listenerOcclusionPlaneColor = std : : move ( rhs . listenerOcclusionPlaneColor ) ; <nl> + collisionSpherePositions = std : : move ( rhs . collisionSpherePositions ) ; <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + return * this ; <nl> + } <nl> + <nl> + explicit SOcclusionInfo ( CListener * const pListener_ ) <nl> + : pListener ( pListener_ ) <nl> + , lastQuerriedOcclusion ( 0 . 0f ) <nl> + , occlusion ( 0 . 0f ) <nl> + , currentListenerDistance ( 0 . 0f ) <nl> + , rayIndex ( 0 ) <nl> + , raysOcclusion { { 0 . 0f } } <nl> + , occlusionTypeWhenAdaptive ( EOcclusionType : : Low ) <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + , collisionSpherePositions { { ZERO } } <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + { } <nl> + <nl> + CListener * pListener ; <nl> + float lastQuerriedOcclusion ; <nl> + float occlusion ; <nl> + float currentListenerDistance ; <nl> + uint8 rayIndex ; <nl> + std : : array < float , g_numRaySamplePositionsHigh > raysOcclusion ; <nl> + std : : array < CRayInfo , g_numConcurrentRaysHigh > raysInfo ; <nl> + EOcclusionType occlusionTypeWhenAdaptive ; <nl> + <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + std : : array < SRayDebugInfo , g_numConcurrentRaysHigh > rayDebugInfos ; <nl> + ColorB listenerOcclusionPlaneColor ; <nl> + std : : array < Vec3 , g_numRaySamplePositionsHigh > collisionSpherePositions ; <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + } ; <nl> + <nl> + using OcclusionInfos = std : : vector < SOcclusionInfo > ; <nl> + } / / namespace CryAudio <nl> + # endif / / CRY_AUDIO_USE_OCCLUSION <nl> \ No newline at end of file <nl> mmm a / Code / CryEngine / CryAudioSystem / PropagationProcessor . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / PropagationProcessor . cpp <nl> <nl> # include " CVars . h " <nl> # include " Object . h " <nl> # include " System . h " <nl> + # include " Listener . h " <nl> # include " ObjectRequestData . h " <nl> # include < Cry3DEngine / I3DEngine . h > <nl> # include < Cry3DEngine / ISurfaceType . h > <nl> int CPropagationProcessor : : OnObstructionTest ( EventPhys const * pEvent ) <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> CPropagationProcessor : : CPropagationProcessor ( CObject & object ) <nl> - : m_lastQuerriedOcclusion ( 0 . 0f ) <nl> - , m_occlusion ( 0 . 0f ) <nl> - , m_currentListenerDistance ( 0 . 0f ) <nl> - , m_occlusionRayOffset ( 0 . 1f ) <nl> + : m_occlusionRayOffset ( 0 . 1f ) <nl> , m_remainingRays ( 0 ) <nl> - , m_rayIndex ( 0 ) <nl> , m_object ( object ) <nl> , m_occlusionType ( EOcclusionType : : None ) <nl> , m_originalOcclusionType ( EOcclusionType : : None ) <nl> - , m_occlusionTypeWhenAdaptive ( EOcclusionType : : Low ) / / will be updated in the first Update <nl> { <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CPropagationProcessor : : Init ( ) <nl> { <nl> - for ( auto & rayInfo : m_raysInfo ) <nl> + auto const & listeners = m_object . GetListeners ( ) ; <nl> + m_occlusionInfos . reserve ( listeners . size ( ) ) ; <nl> + <nl> + for ( auto const pListener : listeners ) <nl> { <nl> - rayInfo . pObject = & m_object ; <nl> + AddListener ( pListener ) ; <nl> } <nl> - <nl> - m_currentListenerDistance = g_listenerManager . GetActiveListenerTransformation ( ) . GetPosition ( ) . GetDistance ( m_object . GetTransformation ( ) . GetPosition ( ) ) ; <nl> - <nl> - # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> - m_listenerOcclusionPlaneColor . set ( cry_random < uint8 > ( 0 , 255 ) , cry_random < uint8 > ( 0 , 255 ) , cry_random < uint8 > ( 0 , 255 ) , uint8 ( 128 ) ) ; <nl> - # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CPropagationProcessor : : Update ( ) <nl> <nl> if ( CanRunOcclusion ( ) ) <nl> { <nl> - if ( m_occlusionType = = EOcclusionType : : Adaptive ) <nl> + for ( auto & info : m_occlusionInfos ) <nl> { <nl> - if ( m_currentListenerDistance < g_cvars . m_occlusionHighDistance ) <nl> - { <nl> - m_occlusionTypeWhenAdaptive = EOcclusionType : : High ; <nl> - } <nl> - else if ( m_currentListenerDistance < g_cvars . m_occlusionMediumDistance ) <nl> - { <nl> - m_occlusionTypeWhenAdaptive = EOcclusionType : : Medium ; <nl> - } <nl> - else <nl> + if ( m_occlusionType = = EOcclusionType : : Adaptive ) <nl> { <nl> - m_occlusionTypeWhenAdaptive = EOcclusionType : : Low ; <nl> + if ( info . currentListenerDistance < g_cvars . m_occlusionHighDistance ) <nl> + { <nl> + info . occlusionTypeWhenAdaptive = EOcclusionType : : High ; <nl> + } <nl> + else if ( info . currentListenerDistance < g_cvars . m_occlusionMediumDistance ) <nl> + { <nl> + info . occlusionTypeWhenAdaptive = EOcclusionType : : Medium ; <nl> + } <nl> + else <nl> + { <nl> + info . occlusionTypeWhenAdaptive = EOcclusionType : : Low ; <nl> + } <nl> } <nl> } <nl> <nl> void CPropagationProcessor : : Update ( ) <nl> } <nl> else <nl> { <nl> - m_occlusion = 0 . 0f ; <nl> + for ( auto & info : m_occlusionInfos ) <nl> + { <nl> + info . occlusion = 0 . 0f ; <nl> + } <nl> } <nl> } <nl> <nl> void CPropagationProcessor : : UpdateOcclusion ( ) <nl> { <nl> if ( g_cvars . m_occlusionInitialRayCastMode = = 1 ) <nl> { <nl> - Vec3 const & listenerPosition = g_listenerManager . GetActiveListenerTransformation ( ) . GetPosition ( ) ; <nl> - Vec3 const & objectPosition = m_object . GetTransformation ( ) . GetPosition ( ) ; <nl> + for ( auto & info : m_occlusionInfos ) <nl> + { <nl> + Vec3 const & listenerPosition = info . pListener - > GetTransformation ( ) . GetPosition ( ) ; <nl> + Vec3 const & objectPosition = m_object . GetTransformation ( ) . GetPosition ( ) ; <nl> <nl> - m_occlusion = CastInitialRay ( listenerPosition , objectPosition , ( g_cvars . m_occlusionAccumulate > 0 ) ) ; <nl> + info . occlusion = CastInitialRay ( listenerPosition , objectPosition , ( g_cvars . m_occlusionAccumulate > 0 ) ) ; <nl> <nl> - for ( auto & rayOcclusion : m_raysOcclusion ) <nl> - { <nl> - rayOcclusion = m_occlusion ; <nl> + for ( auto & rayOcclusion : info . raysOcclusion ) <nl> + { <nl> + rayOcclusion = info . occlusion ; <nl> + } <nl> } <nl> } <nl> else if ( g_cvars . m_occlusionInitialRayCastMode > 1 ) <nl> { <nl> - float occlusionValues [ g_numInitialSamplePositions ] ; <nl> - Vec3 const & listenerPosition = g_listenerManager . GetActiveListenerTransformation ( ) . GetPosition ( ) ; <nl> - Vec3 const & objectPosition = m_object . GetTransformation ( ) . GetPosition ( ) ; <nl> + for ( auto & info : m_occlusionInfos ) <nl> + { <nl> + float occlusionValues [ g_numInitialSamplePositions ] ; <nl> + Vec3 const & listenerPosition = info . pListener - > GetTransformation ( ) . GetPosition ( ) ; <nl> + Vec3 const & objectPosition = m_object . GetTransformation ( ) . GetPosition ( ) ; <nl> <nl> - / / TODO : this breaks if listener and object x and y coordinates are exactly the same . <nl> - Vec3 const side ( ( listenerPosition - objectPosition ) . Cross ( Vec3Constants < float > : : fVec3_OneZ ) . normalize ( ) ) ; <nl> - Vec3 const up ( ( listenerPosition - objectPosition ) . Cross ( side ) . normalize ( ) ) ; <nl> - bool const accumulate = g_cvars . m_occlusionAccumulate > 0 ; <nl> + / / TODO : this breaks if listener and object x and y coordinates are exactly the same . <nl> + Vec3 const side ( ( listenerPosition - objectPosition ) . Cross ( Vec3Constants < float > : : fVec3_OneZ ) . normalize ( ) ) ; <nl> + Vec3 const up ( ( listenerPosition - objectPosition ) . Cross ( side ) . normalize ( ) ) ; <nl> + bool const accumulate = g_cvars . m_occlusionAccumulate > 0 ; <nl> <nl> - for ( uint8 i = 0 ; i < g_numInitialSamplePositions ; + + i ) <nl> - { <nl> - switch ( m_occlusionType ) <nl> + for ( uint8 i = 0 ; i < g_numInitialSamplePositions ; + + i ) <nl> { <nl> - case EOcclusionType : : Adaptive : <nl> + switch ( m_occlusionType ) <nl> { <nl> - switch ( m_occlusionTypeWhenAdaptive ) <nl> + case EOcclusionType : : Adaptive : <nl> { <nl> - case EOcclusionType : : Low : <nl> + switch ( info . occlusionTypeWhenAdaptive ) <nl> { <nl> - SRayOffset const & rayOffset = g_initialRaySamplePositionsLow [ i ] ; <nl> - Vec3 const origin ( listenerPosition + up * rayOffset . z + side * rayOffset . x ) ; <nl> - occlusionValues [ i ] = CastInitialRay ( origin , objectPosition , accumulate ) ; <nl> - <nl> - break ; <nl> + case EOcclusionType : : Low : <nl> + { <nl> + SRayOffset const & rayOffset = g_initialRaySamplePositionsLow [ i ] ; <nl> + Vec3 const origin ( listenerPosition + up * rayOffset . z + side * rayOffset . x ) ; <nl> + occlusionValues [ i ] = CastInitialRay ( origin , objectPosition , accumulate ) ; <nl> + <nl> + break ; <nl> + } <nl> + case EOcclusionType : : Medium : <nl> + { <nl> + SRayOffset const & rayOffset = g_initialRaySamplePositionsMedium [ i ] ; <nl> + Vec3 const origin ( listenerPosition + up * rayOffset . z + side * rayOffset . x ) ; <nl> + occlusionValues [ i ] = CastInitialRay ( origin , objectPosition , accumulate ) ; <nl> + <nl> + break ; <nl> + } <nl> + case EOcclusionType : : High : <nl> + { <nl> + SRayOffset const & rayOffset = g_initialRaySamplePositionsHigh [ i ] ; <nl> + Vec3 const origin ( listenerPosition + up * rayOffset . z + side * rayOffset . x ) ; <nl> + occlusionValues [ i ] = CastInitialRay ( origin , objectPosition , accumulate ) ; <nl> + <nl> + break ; <nl> + } <nl> + default : <nl> + { <nl> + break ; <nl> + } <nl> } <nl> - case EOcclusionType : : Medium : <nl> - { <nl> - SRayOffset const & rayOffset = g_initialRaySamplePositionsMedium [ i ] ; <nl> - Vec3 const origin ( listenerPosition + up * rayOffset . z + side * rayOffset . x ) ; <nl> - occlusionValues [ i ] = CastInitialRay ( origin , objectPosition , accumulate ) ; <nl> <nl> - break ; <nl> - } <nl> - case EOcclusionType : : High : <nl> - { <nl> - SRayOffset const & rayOffset = g_initialRaySamplePositionsHigh [ i ] ; <nl> - Vec3 const origin ( listenerPosition + up * rayOffset . z + side * rayOffset . x ) ; <nl> - occlusionValues [ i ] = CastInitialRay ( origin , objectPosition , accumulate ) ; <nl> - <nl> - break ; <nl> - } <nl> - default : <nl> - { <nl> - break ; <nl> - } <nl> + break ; <nl> } <nl> + case EOcclusionType : : Low : <nl> + { <nl> + SRayOffset const & rayOffset = g_initialRaySamplePositionsLow [ i ] ; <nl> + Vec3 const origin ( listenerPosition + up * rayOffset . z + side * rayOffset . x ) ; <nl> + occlusionValues [ i ] = CastInitialRay ( origin , objectPosition , accumulate ) ; <nl> <nl> - break ; <nl> - } <nl> - case EOcclusionType : : Low : <nl> - { <nl> - SRayOffset const & rayOffset = g_initialRaySamplePositionsLow [ i ] ; <nl> - Vec3 const origin ( listenerPosition + up * rayOffset . z + side * rayOffset . x ) ; <nl> - occlusionValues [ i ] = CastInitialRay ( origin , objectPosition , accumulate ) ; <nl> - <nl> - break ; <nl> - } <nl> - case EOcclusionType : : Medium : <nl> - { <nl> - SRayOffset const & rayOffset = g_initialRaySamplePositionsMedium [ i ] ; <nl> - Vec3 const origin ( listenerPosition + up * rayOffset . z + side * rayOffset . x ) ; <nl> - occlusionValues [ i ] = CastInitialRay ( origin , objectPosition , accumulate ) ; <nl> + break ; <nl> + } <nl> + case EOcclusionType : : Medium : <nl> + { <nl> + SRayOffset const & rayOffset = g_initialRaySamplePositionsMedium [ i ] ; <nl> + Vec3 const origin ( listenerPosition + up * rayOffset . z + side * rayOffset . x ) ; <nl> + occlusionValues [ i ] = CastInitialRay ( origin , objectPosition , accumulate ) ; <nl> <nl> - break ; <nl> - } <nl> - case EOcclusionType : : High : <nl> - { <nl> - SRayOffset const & rayOffset = g_initialRaySamplePositionsHigh [ i ] ; <nl> - Vec3 const origin ( listenerPosition + up * rayOffset . z + side * rayOffset . x ) ; <nl> - occlusionValues [ i ] = CastInitialRay ( origin , objectPosition , accumulate ) ; <nl> + break ; <nl> + } <nl> + case EOcclusionType : : High : <nl> + { <nl> + SRayOffset const & rayOffset = g_initialRaySamplePositionsHigh [ i ] ; <nl> + Vec3 const origin ( listenerPosition + up * rayOffset . z + side * rayOffset . x ) ; <nl> + occlusionValues [ i ] = CastInitialRay ( origin , objectPosition , accumulate ) ; <nl> <nl> - break ; <nl> - } <nl> - default : <nl> - { <nl> - break ; <nl> + break ; <nl> + } <nl> + default : <nl> + { <nl> + break ; <nl> + } <nl> } <nl> } <nl> - } <nl> <nl> - m_occlusion = 0 . 0f ; <nl> + info . occlusion = 0 . 0f ; <nl> <nl> - for ( auto const value : occlusionValues ) <nl> - { <nl> - m_occlusion + = value ; <nl> - } <nl> + for ( auto const value : occlusionValues ) <nl> + { <nl> + info . occlusion + = value ; <nl> + } <nl> <nl> - m_occlusion / = static_cast < float > ( g_numInitialSamplePositions ) ; <nl> + info . occlusion / = static_cast < float > ( g_numInitialSamplePositions ) ; <nl> <nl> - for ( auto & rayOcclusion : m_raysOcclusion ) <nl> - { <nl> - rayOcclusion = m_occlusion ; <nl> + for ( auto & rayOcclusion : info . raysOcclusion ) <nl> + { <nl> + rayOcclusion = info . occlusion ; <nl> + } <nl> } <nl> } <nl> else <nl> { <nl> - m_occlusion = 0 . 0f ; <nl> - m_lastQuerriedOcclusion = 0 . 0f ; <nl> + for ( auto & info : m_occlusionInfos ) <nl> + { <nl> + info . occlusion = 0 . 0f ; <nl> + info . lastQuerriedOcclusion = 0 . 0f ; <nl> + } <nl> } <nl> } <nl> else <nl> { <nl> - m_occlusion = 0 . 0f ; <nl> - m_lastQuerriedOcclusion = 0 . 0f ; <nl> + for ( auto & info : m_occlusionInfos ) <nl> + { <nl> + info . occlusion = 0 . 0f ; <nl> + info . lastQuerriedOcclusion = 0 . 0f ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CPropagationProcessor : : AddListener ( CListener * const pListener ) <nl> + { <nl> + SOcclusionInfo info ( pListener ) ; <nl> + info . currentListenerDistance = pListener - > GetTransformation ( ) . GetPosition ( ) . GetDistance ( m_object . GetTransformation ( ) . GetPosition ( ) ) ; <nl> + <nl> + for ( auto & rayInfo : info . raysInfo ) <nl> + { <nl> + rayInfo . pObject = & m_object ; <nl> + } <nl> + <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + info . listenerOcclusionPlaneColor . set ( cry_random < uint8 > ( 0 , 255 ) , cry_random < uint8 > ( 0 , 255 ) , cry_random < uint8 > ( 0 , 255 ) , uint8 ( 128 ) ) ; <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + <nl> + m_occlusionInfos . emplace_back ( info ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CPropagationProcessor : : RemoveListener ( CListener * const pListener ) <nl> + { <nl> + auto iter ( m_occlusionInfos . begin ( ) ) ; <nl> + auto const iterEnd ( m_occlusionInfos . cend ( ) ) ; <nl> + <nl> + for ( ; iter ! = iterEnd ; + + iter ) <nl> + { <nl> + SOcclusionInfo const & info = * iter ; <nl> + <nl> + if ( info . pListener = = pListener ) <nl> + { <nl> + if ( iter ! = ( iterEnd - 1 ) ) <nl> + { <nl> + ( * iter ) = m_occlusionInfos . back ( ) ; <nl> + } <nl> + <nl> + m_occlusionInfos . pop_back ( ) ; <nl> + break ; <nl> + } <nl> } <nl> } <nl> <nl> bool CPropagationProcessor : : CanRunOcclusion ( ) <nl> ( ( m_object . GetFlags ( ) & EObjectFlags : : Virtual ) = = 0 ) & & <nl> s_bCanIssueRWIs ) <nl> { <nl> - m_currentListenerDistance = m_object . GetTransformation ( ) . GetPosition ( ) . GetDistance ( g_listenerManager . GetActiveListenerTransformation ( ) . GetPosition ( ) ) ; <nl> - <nl> - if ( ( m_currentListenerDistance > g_cvars . m_occlusionMinDistance ) & & ( m_currentListenerDistance < g_cvars . m_occlusionMaxDistance ) ) <nl> + for ( auto & info : m_occlusionInfos ) <nl> { <nl> - canRun = true ; <nl> + info . currentListenerDistance = m_object . GetTransformation ( ) . GetPosition ( ) . GetDistance ( info . pListener - > GetTransformation ( ) . GetPosition ( ) ) ; <nl> + <nl> + if ( ( info . currentListenerDistance > g_cvars . m_occlusionMinDistance ) & & ( info . currentListenerDistance < g_cvars . m_occlusionMaxDistance ) ) <nl> + { <nl> + canRun = true ; <nl> + } <nl> } <nl> } <nl> <nl> bool CPropagationProcessor : : CanRunOcclusion ( ) <nl> return canRun ; <nl> } <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + float CPropagationProcessor : : GetOcclusion ( CListener * const pListener ) const <nl> + { <nl> + float occlusion = 0 . 0f ; <nl> + <nl> + for ( auto const & info : m_occlusionInfos ) <nl> + { <nl> + if ( pListener = = info . pListener ) <nl> + { <nl> + occlusion = info . occlusion ; <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + return occlusion ; <nl> + } <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CPropagationProcessor : : ProcessPhysicsRay ( CRayInfo & rayInfo ) <nl> { <nl> bool CPropagationProcessor : : HasNewOcclusionValues ( ) <nl> { <nl> bool hasNewValues = false ; <nl> <nl> - if ( fabs_tpl ( m_lastQuerriedOcclusion - m_occlusion ) > FloatEpsilon ) <nl> + for ( auto & info : m_occlusionInfos ) <nl> { <nl> - m_lastQuerriedOcclusion = m_occlusion ; <nl> - hasNewValues = true ; <nl> + if ( fabs_tpl ( info . lastQuerriedOcclusion - info . occlusion ) > FloatEpsilon ) <nl> + { <nl> + info . lastQuerriedOcclusion = info . occlusion ; <nl> + hasNewValues = true ; <nl> + } <nl> } <nl> <nl> return hasNewValues ; <nl> bool CPropagationProcessor : : HasNewOcclusionValues ( ) <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CPropagationProcessor : : ProcessObstructionOcclusion ( ) <nl> { <nl> - m_occlusion = 0 . 0f ; <nl> - CRY_ASSERT_MESSAGE ( m_currentListenerDistance > 0 . 0f , " Distance to Listener is 0 during % s " , __FUNCTION__ ) ; <nl> + for ( auto & info : m_occlusionInfos ) <nl> + { <nl> + info . occlusion = 0 . 0f ; <nl> + CRY_ASSERT_MESSAGE ( info . currentListenerDistance > 0 . 0f , " Distance to Listener is 0 during % s " , __FUNCTION__ ) ; <nl> <nl> - uint8 const numSamplePositions = GetNumSamplePositions ( ) ; <nl> - uint8 const numConcurrentRays = GetNumConcurrentRays ( ) ; <nl> + uint8 const numSamplePositions = GetNumSamplePositions ( info . occlusionTypeWhenAdaptive ) ; <nl> + uint8 const numConcurrentRays = GetNumConcurrentRays ( info . occlusionTypeWhenAdaptive ) ; <nl> <nl> - if ( numSamplePositions > 0 & & numConcurrentRays > 0 ) <nl> - { <nl> - for ( uint8 i = 0 ; i < numConcurrentRays ; + + i ) <nl> + if ( numSamplePositions > 0 & & numConcurrentRays > 0 ) <nl> { <nl> - CRayInfo const & rayInfo = m_raysInfo [ i ] ; <nl> - m_raysOcclusion [ rayInfo . samplePosIndex ] = rayInfo . totalSoundOcclusion ; <nl> - } <nl> + for ( uint8 i = 0 ; i < numConcurrentRays ; + + i ) <nl> + { <nl> + CRayInfo const & rayInfo = info . raysInfo [ i ] ; <nl> + info . raysOcclusion [ rayInfo . samplePosIndex ] = rayInfo . totalSoundOcclusion ; <nl> + } <nl> <nl> - / / Calculate the new occlusion average . <nl> - / / TODO : Optimize this ! <nl> - for ( uint8 i = 0 ; i < numSamplePositions ; + + i ) <nl> - { <nl> - m_occlusion + = m_raysOcclusion [ i ] ; <nl> - } <nl> + / / Calculate the new occlusion average . <nl> + / / TODO : Optimize this ! <nl> + for ( uint8 i = 0 ; i < numSamplePositions ; + + i ) <nl> + { <nl> + info . occlusion + = info . raysOcclusion [ i ] ; <nl> + } <nl> <nl> - m_occlusion = ( m_occlusion / numSamplePositions ) ; <nl> - } <nl> + info . occlusion = ( info . occlusion / numSamplePositions ) ; <nl> + } <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> - if ( ( m_object . GetFlags ( ) & EObjectFlags : : CanRunOcclusion ) ! = 0 ) <nl> - { <nl> - for ( uint8 i = 0 ; i < numConcurrentRays ; + + i ) <nl> + if ( ( m_object . GetFlags ( ) & EObjectFlags : : CanRunOcclusion ) ! = 0 ) <nl> { <nl> - CRayInfo const & rayInfo = m_raysInfo [ i ] ; <nl> - SRayDebugInfo & rayDebugInfo = m_rayDebugInfos [ i ] ; <nl> - rayDebugInfo . samplePosIndex = rayInfo . samplePosIndex ; <nl> - rayDebugInfo . begin = rayInfo . startPosition ; <nl> - rayDebugInfo . end = rayInfo . startPosition + rayInfo . direction ; <nl> - rayDebugInfo . distanceToNearestObstacle = rayInfo . distanceToFirstObstacle ; <nl> - rayDebugInfo . numHits = rayInfo . numHits ; <nl> - rayDebugInfo . occlusionValue = rayInfo . totalSoundOcclusion ; <nl> + for ( uint8 i = 0 ; i < numConcurrentRays ; + + i ) <nl> + { <nl> + CRayInfo const & rayInfo = info . raysInfo [ i ] ; <nl> + SRayDebugInfo & rayDebugInfo = info . rayDebugInfos [ i ] ; <nl> + rayDebugInfo . samplePosIndex = rayInfo . samplePosIndex ; <nl> + rayDebugInfo . begin = rayInfo . startPosition ; <nl> + rayDebugInfo . end = rayInfo . startPosition + rayInfo . direction ; <nl> + rayDebugInfo . distanceToNearestObstacle = rayInfo . distanceToFirstObstacle ; <nl> + rayDebugInfo . numHits = rayInfo . numHits ; <nl> + rayDebugInfo . occlusionValue = rayInfo . totalSoundOcclusion ; <nl> + } <nl> } <nl> - } <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + } <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CPropagationProcessor : : CastObstructionRay ( <nl> Vec3 const & origin , <nl> uint8 const rayIndex , <nl> uint8 const samplePosIndex , <nl> - bool const bSynch ) <nl> + bool const bSynch , <nl> + SOcclusionInfo & info ) <nl> { <nl> Vec3 const direction ( m_object . GetTransformation ( ) . GetPosition ( ) - origin ) ; <nl> Vec3 directionNormalized ( direction ) ; <nl> void CPropagationProcessor : : CastObstructionRay ( <nl> <nl> / / We use " rwi_max_piercing " to allow audio rays to always pierce surfaces regardless of the " pierceability " attribute . <nl> / / Note : The very first entry of rayInfo . hits ( solid slot ) is always empty . <nl> - CRayInfo & rayInfo = m_raysInfo [ rayIndex ] ; <nl> + CRayInfo & rayInfo = info . raysInfo [ rayIndex ] ; <nl> rayInfo . samplePosIndex = samplePosIndex ; <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> void CPropagationProcessor : : RunObstructionQuery ( ) <nl> { <nl> if ( m_remainingRays = = 0 ) <nl> { <nl> - / / Make the physics ray cast call synchronous or asynchronous depending on the distance to the listener . <nl> - bool const bSynch = ( m_currentListenerDistance < = g_cvars . m_occlusionMaxSyncDistance ) ; <nl> + for ( auto & info : m_occlusionInfos ) <nl> + { <nl> + / / Make the physics ray cast call synchronous or asynchronous depending on the distance to the listener . <nl> + bool const bSynch = ( info . currentListenerDistance < = g_cvars . m_occlusionMaxSyncDistance ) ; <nl> <nl> - Vec3 const & listenerPosition = g_listenerManager . GetActiveListenerTransformation ( ) . GetPosition ( ) ; <nl> + Vec3 const & listenerPosition = info . pListener - > GetTransformation ( ) . GetPosition ( ) ; <nl> <nl> - / / TODO : this breaks if listener and object x and y coordinates are exactly the same . <nl> - Vec3 const side ( ( listenerPosition - m_object . GetTransformation ( ) . GetPosition ( ) ) . Cross ( Vec3Constants < float > : : fVec3_OneZ ) . normalize ( ) ) ; <nl> - Vec3 const up ( ( listenerPosition - m_object . GetTransformation ( ) . GetPosition ( ) ) . Cross ( side ) . normalize ( ) ) ; <nl> + / / TODO : this breaks if listener and object x and y coordinates are exactly the same . <nl> + Vec3 const side ( ( listenerPosition - m_object . GetTransformation ( ) . GetPosition ( ) ) . Cross ( Vec3Constants < float > : : fVec3_OneZ ) . normalize ( ) ) ; <nl> + Vec3 const up ( ( listenerPosition - m_object . GetTransformation ( ) . GetPosition ( ) ) . Cross ( side ) . normalize ( ) ) ; <nl> <nl> - switch ( m_occlusionType ) <nl> - { <nl> - case EOcclusionType : : Adaptive : <nl> + switch ( m_occlusionType ) <nl> { <nl> - switch ( m_occlusionTypeWhenAdaptive ) <nl> + case EOcclusionType : : Adaptive : <nl> { <nl> - case EOcclusionType : : Low : <nl> - { <nl> - ProcessLow ( up , side , bSynch ) ; <nl> - break ; <nl> - } <nl> - case EOcclusionType : : Medium : <nl> - { <nl> - ProcessMedium ( up , side , bSynch ) ; <nl> - break ; <nl> - } <nl> - case EOcclusionType : : High : <nl> + switch ( info . occlusionTypeWhenAdaptive ) <nl> { <nl> - ProcessHigh ( up , side , bSynch ) ; <nl> - break ; <nl> - } <nl> - default : <nl> - { <nl> - CRY_ASSERT_MESSAGE ( false , " Calculated Adaptive Occlusion Type invalid during % s " , __FUNCTION__ ) ; <nl> - break ; <nl> + case EOcclusionType : : Low : <nl> + { <nl> + ProcessLow ( up , side , bSynch , info ) ; <nl> + break ; <nl> + } <nl> + case EOcclusionType : : Medium : <nl> + { <nl> + ProcessMedium ( up , side , bSynch , info ) ; <nl> + break ; <nl> + } <nl> + case EOcclusionType : : High : <nl> + { <nl> + ProcessHigh ( up , side , bSynch , info ) ; <nl> + break ; <nl> + } <nl> + default : <nl> + { <nl> + CRY_ASSERT_MESSAGE ( false , " Calculated Adaptive Occlusion Type invalid during % s " , __FUNCTION__ ) ; <nl> + break ; <nl> + } <nl> } <nl> - } <nl> <nl> - break ; <nl> - } <nl> - case EOcclusionType : : Low : <nl> - { <nl> - ProcessLow ( up , side , bSynch ) ; <nl> - break ; <nl> - } <nl> - case EOcclusionType : : Medium : <nl> - { <nl> - ProcessMedium ( up , side , bSynch ) ; <nl> - break ; <nl> - } <nl> - case EOcclusionType : : High : <nl> - { <nl> - ProcessHigh ( up , side , bSynch ) ; <nl> - break ; <nl> - } <nl> - default : <nl> - { <nl> - break ; <nl> + break ; <nl> + } <nl> + case EOcclusionType : : Low : <nl> + { <nl> + ProcessLow ( up , side , bSynch , info ) ; <nl> + break ; <nl> + } <nl> + case EOcclusionType : : Medium : <nl> + { <nl> + ProcessMedium ( up , side , bSynch , info ) ; <nl> + break ; <nl> + } <nl> + case EOcclusionType : : High : <nl> + { <nl> + ProcessHigh ( up , side , bSynch , info ) ; <nl> + break ; <nl> + } <nl> + default : <nl> + { <nl> + break ; <nl> + } <nl> } <nl> } <nl> } <nl> void CPropagationProcessor : : RunObstructionQuery ( ) <nl> void CPropagationProcessor : : ProcessLow ( <nl> Vec3 const & up , <nl> Vec3 const & side , <nl> - bool const bSynch ) <nl> + bool const bSynch , <nl> + SOcclusionInfo & info ) <nl> { <nl> for ( uint8 i = 0 ; i < g_numConcurrentRaysLow ; + + i ) <nl> { <nl> - if ( m_rayIndex > = g_numRaySamplePositionsLow ) <nl> + if ( info . rayIndex > = g_numRaySamplePositionsLow ) <nl> { <nl> - m_rayIndex = 0 ; <nl> + info . rayIndex = 0 ; <nl> } <nl> <nl> - Vec3 const origin ( g_listenerManager . GetActiveListenerTransformation ( ) . GetPosition ( ) + up * g_raySamplePositionsLow [ m_rayIndex ] . z + side * g_raySamplePositionsLow [ m_rayIndex ] . x ) ; <nl> - CastObstructionRay ( origin , i , m_rayIndex , bSynch ) ; <nl> - + + m_rayIndex ; <nl> + Vec3 const origin ( info . pListener - > GetTransformation ( ) . GetPosition ( ) + up * g_raySamplePositionsLow [ info . rayIndex ] . z + side * g_raySamplePositionsLow [ info . rayIndex ] . x ) ; <nl> + CastObstructionRay ( origin , i , info . rayIndex , bSynch , info ) ; <nl> + + + info . rayIndex ; <nl> } <nl> } <nl> <nl> void CPropagationProcessor : : ProcessLow ( <nl> void CPropagationProcessor : : ProcessMedium ( <nl> Vec3 const & up , <nl> Vec3 const & side , <nl> - bool const bSynch ) <nl> + bool const bSynch , <nl> + SOcclusionInfo & info ) <nl> { <nl> for ( uint8 i = 0 ; i < g_numConcurrentRaysMedium ; + + i ) <nl> { <nl> - if ( m_rayIndex > = g_numRaySamplePositionsMedium ) <nl> + if ( info . rayIndex > = g_numRaySamplePositionsMedium ) <nl> { <nl> - m_rayIndex = 0 ; <nl> + info . rayIndex = 0 ; <nl> } <nl> <nl> - Vec3 const origin ( g_listenerManager . GetActiveListenerTransformation ( ) . GetPosition ( ) + up * g_raySamplePositionsMedium [ m_rayIndex ] . z + side * g_raySamplePositionsMedium [ m_rayIndex ] . x ) ; <nl> - CastObstructionRay ( origin , i , m_rayIndex , bSynch ) ; <nl> - + + m_rayIndex ; <nl> + Vec3 const origin ( info . pListener - > GetTransformation ( ) . GetPosition ( ) + up * g_raySamplePositionsMedium [ info . rayIndex ] . z + side * g_raySamplePositionsMedium [ info . rayIndex ] . x ) ; <nl> + CastObstructionRay ( origin , i , info . rayIndex , bSynch , info ) ; <nl> + + + info . rayIndex ; <nl> } <nl> } <nl> <nl> void CPropagationProcessor : : ProcessMedium ( <nl> void CPropagationProcessor : : ProcessHigh ( <nl> Vec3 const & up , <nl> Vec3 const & side , <nl> - bool const bSynch ) <nl> + bool const bSynch , <nl> + SOcclusionInfo & info ) <nl> { <nl> for ( uint8 i = 0 ; i < g_numConcurrentRaysHigh ; + + i ) <nl> { <nl> - if ( m_rayIndex > = g_numRaySamplePositionsHigh ) <nl> + if ( info . rayIndex > = g_numRaySamplePositionsHigh ) <nl> { <nl> - m_rayIndex = 0 ; <nl> + info . rayIndex = 0 ; <nl> } <nl> <nl> - Vec3 const origin ( g_listenerManager . GetActiveListenerTransformation ( ) . GetPosition ( ) + up * g_raySamplePositionsHigh [ m_rayIndex ] . z + side * g_raySamplePositionsHigh [ m_rayIndex ] . x ) ; <nl> - CastObstructionRay ( origin , i , m_rayIndex , bSynch ) ; <nl> - + + m_rayIndex ; <nl> + Vec3 const origin ( info . pListener - > GetTransformation ( ) . GetPosition ( ) + up * g_raySamplePositionsHigh [ info . rayIndex ] . z + side * g_raySamplePositionsHigh [ info . rayIndex ] . x ) ; <nl> + CastObstructionRay ( origin , i , info . rayIndex , bSynch , info ) ; <nl> + + + info . rayIndex ; <nl> } <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - uint8 CPropagationProcessor : : GetNumConcurrentRays ( ) const <nl> + uint8 CPropagationProcessor : : GetNumConcurrentRays ( EOcclusionType const occlusionTypeWhenAdaptive ) const <nl> { <nl> uint8 numConcurrentRays = 0 ; <nl> <nl> uint8 CPropagationProcessor : : GetNumConcurrentRays ( ) const <nl> { <nl> case EOcclusionType : : Adaptive : <nl> { <nl> - switch ( m_occlusionTypeWhenAdaptive ) <nl> + switch ( occlusionTypeWhenAdaptive ) <nl> { <nl> case EOcclusionType : : Low : <nl> { <nl> uint8 CPropagationProcessor : : GetNumConcurrentRays ( ) const <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - uint8 CPropagationProcessor : : GetNumSamplePositions ( ) const <nl> + uint8 CPropagationProcessor : : GetNumSamplePositions ( EOcclusionType const occlusionTypeWhenAdaptive ) const <nl> { <nl> uint8 numSamplePositions = 0 ; <nl> <nl> uint8 CPropagationProcessor : : GetNumSamplePositions ( ) const <nl> { <nl> case EOcclusionType : : Adaptive : <nl> { <nl> - switch ( m_occlusionTypeWhenAdaptive ) <nl> + switch ( occlusionTypeWhenAdaptive ) <nl> { <nl> case EOcclusionType : : Low : <nl> { <nl> void CPropagationProcessor : : UpdateOcclusionPlanes ( ) <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CPropagationProcessor : : DrawDebugInfo ( IRenderAuxGeom & auxGeom ) <nl> { <nl> - uint8 const numConcurrentRays = GetNumConcurrentRays ( ) ; <nl> - <nl> - for ( uint8 i = 0 ; i < numConcurrentRays ; + + i ) <nl> + for ( auto & info : m_occlusionInfos ) <nl> { <nl> - SRayDebugInfo const & rayDebugInfo = m_rayDebugInfos [ i ] ; <nl> - bool const isRayObstructed = ( rayDebugInfo . numHits > 0 ) ; <nl> - Vec3 const rayEnd = isRayObstructed ? <nl> - rayDebugInfo . begin + ( rayDebugInfo . end - rayDebugInfo . begin ) . GetNormalized ( ) * rayDebugInfo . distanceToNearestObstacle : <nl> - rayDebugInfo . end ; / / Only draw the ray to the first collision point . <nl> + uint8 const numConcurrentRays = GetNumConcurrentRays ( info . occlusionTypeWhenAdaptive ) ; <nl> <nl> - if ( ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionRays ) ! = 0 ) <nl> + for ( uint8 i = 0 ; i < numConcurrentRays ; + + i ) <nl> { <nl> - SAuxGeomRenderFlags const previousRenderFlags = auxGeom . GetRenderFlags ( ) ; <nl> - SAuxGeomRenderFlags newRenderFlags ( e_Def3DPublicRenderflags ) ; <nl> - newRenderFlags . SetCullMode ( e_CullModeNone ) ; <nl> - ColorF const & rayColor = isRayObstructed ? Debug : : s_rayColorObstructed : Debug : : s_rayColorFree ; <nl> - auxGeom . SetRenderFlags ( newRenderFlags ) ; <nl> - auxGeom . DrawLine ( rayDebugInfo . begin , rayColor , rayEnd , rayColor , 1 . 0f ) ; <nl> - auxGeom . SetRenderFlags ( previousRenderFlags ) ; <nl> - } <nl> + SRayDebugInfo const & rayDebugInfo = info . rayDebugInfos [ i ] ; <nl> + bool const isRayObstructed = ( rayDebugInfo . numHits > 0 ) ; <nl> + Vec3 const rayEnd = isRayObstructed ? <nl> + rayDebugInfo . begin + ( rayDebugInfo . end - rayDebugInfo . begin ) . GetNormalized ( ) * rayDebugInfo . distanceToNearestObstacle : <nl> + rayDebugInfo . end ; / / Only draw the ray to the first collision point . <nl> <nl> - if ( ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionCollisionSpheres ) ! = 0 ) <nl> - { <nl> - if ( isRayObstructed ) <nl> + if ( ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionRays ) ! = 0 ) <nl> { <nl> - m_collisionSpherePositions [ rayDebugInfo . samplePosIndex ] = rayEnd ; <nl> + SAuxGeomRenderFlags const previousRenderFlags = auxGeom . GetRenderFlags ( ) ; <nl> + SAuxGeomRenderFlags newRenderFlags ( e_Def3DPublicRenderflags ) ; <nl> + newRenderFlags . SetCullMode ( e_CullModeNone ) ; <nl> + ColorF const & rayColor = isRayObstructed ? Debug : : s_rayColorObstructed : Debug : : s_rayColorFree ; <nl> + auxGeom . SetRenderFlags ( newRenderFlags ) ; <nl> + auxGeom . DrawLine ( rayDebugInfo . begin , rayColor , rayEnd , rayColor , 1 . 0f ) ; <nl> + auxGeom . SetRenderFlags ( previousRenderFlags ) ; <nl> } <nl> - else <nl> + <nl> + if ( ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionCollisionSpheres ) ! = 0 ) <nl> { <nl> - m_collisionSpherePositions [ rayDebugInfo . samplePosIndex ] = ZERO ; <nl> + if ( isRayObstructed ) <nl> + { <nl> + info . collisionSpherePositions [ rayDebugInfo . samplePosIndex ] = rayEnd ; <nl> + } <nl> + else <nl> + { <nl> + info . collisionSpherePositions [ rayDebugInfo . samplePosIndex ] = ZERO ; <nl> + } <nl> } <nl> } <nl> - } <nl> - <nl> - if ( ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionCollisionSpheres ) ! = 0 ) <nl> - { <nl> - uint8 const numSamplePositions = GetNumSamplePositions ( ) ; <nl> <nl> - for ( uint8 i = 0 ; i < g_numRaySamplePositionsHigh ; + + i ) <nl> + if ( ( g_cvars . m_drawDebug & Debug : : EDrawFilter : : OcclusionCollisionSpheres ) ! = 0 ) <nl> { <nl> - auto & spherePos = m_collisionSpherePositions [ i ] ; <nl> + uint8 const numSamplePositions = GetNumSamplePositions ( info . occlusionTypeWhenAdaptive ) ; <nl> <nl> - if ( i < numSamplePositions ) <nl> + for ( uint8 i = 0 ; i < g_numRaySamplePositionsHigh ; + + i ) <nl> { <nl> - if ( ! spherePos . IsZero ( ) ) <nl> + auto & spherePos = info . collisionSpherePositions [ i ] ; <nl> + <nl> + if ( i < numSamplePositions ) <nl> { <nl> - auxGeom . DrawSphere ( spherePos , Debug : : g_rayRadiusCollisionSphere , m_listenerOcclusionPlaneColor ) ; <nl> + if ( ! spherePos . IsZero ( ) ) <nl> + { <nl> + auxGeom . DrawSphere ( spherePos , Debug : : g_rayRadiusCollisionSphere , info . listenerOcclusionPlaneColor ) ; <nl> + } <nl> + } <nl> + else <nl> + { <nl> + spherePos = ZERO ; <nl> } <nl> - } <nl> - else <nl> - { <nl> - spherePos = ZERO ; <nl> } <nl> } <nl> } <nl> void CPropagationProcessor : : DrawListenerPlane ( IRenderAuxGeom & auxGeom ) <nl> newRenderFlags . SetCullMode ( e_CullModeNone ) ; <nl> auxGeom . SetRenderFlags ( newRenderFlags ) ; <nl> <nl> - Vec3 const & listenerPosition = g_listenerManager . GetActiveListenerTransformation ( ) . GetPosition ( ) ; <nl> + for ( auto const & info : m_occlusionInfos ) <nl> + { <nl> + Vec3 const & listenerPosition = info . pListener - > GetTransformation ( ) . GetPosition ( ) ; <nl> <nl> - / / TODO : this breaks if listener and object x and y coordinates are exactly the same . <nl> - Vec3 const side ( ( listenerPosition - m_object . GetTransformation ( ) . GetPosition ( ) ) . Cross ( Vec3Constants < float > : : fVec3_OneZ ) . normalize ( ) ) ; <nl> - Vec3 const up ( ( listenerPosition - m_object . GetTransformation ( ) . GetPosition ( ) ) . Cross ( side ) . normalize ( ) ) ; <nl> + / / TODO : this breaks if listener and object x and y coordinates are exactly the same . <nl> + Vec3 const side ( ( listenerPosition - m_object . GetTransformation ( ) . GetPosition ( ) ) . Cross ( Vec3Constants < float > : : fVec3_OneZ ) . normalize ( ) ) ; <nl> + Vec3 const up ( ( listenerPosition - m_object . GetTransformation ( ) . GetPosition ( ) ) . Cross ( side ) . normalize ( ) ) ; <nl> <nl> - Vec3 const quadVertices [ g_numPoints ] = <nl> - { <nl> - Vec3 ( listenerPosition + up * g_listenerHeadSizeHalf + side * g_listenerHeadSizeHalf ) , <nl> - Vec3 ( listenerPosition + up * - g_listenerHeadSizeHalf + side * g_listenerHeadSizeHalf ) , <nl> - Vec3 ( listenerPosition + up * g_listenerHeadSizeHalf + side * - g_listenerHeadSizeHalf ) , <nl> - Vec3 ( listenerPosition + up * - g_listenerHeadSizeHalf + side * - g_listenerHeadSizeHalf ) } ; <nl> + Vec3 const quadVertices [ g_numPoints ] = <nl> + { <nl> + Vec3 ( listenerPosition + up * g_listenerHeadSizeHalf + side * g_listenerHeadSizeHalf ) , <nl> + Vec3 ( listenerPosition + up * - g_listenerHeadSizeHalf + side * g_listenerHeadSizeHalf ) , <nl> + Vec3 ( listenerPosition + up * g_listenerHeadSizeHalf + side * - g_listenerHeadSizeHalf ) , <nl> + Vec3 ( listenerPosition + up * - g_listenerHeadSizeHalf + side * - g_listenerHeadSizeHalf ) } ; <nl> + <nl> + auxGeom . DrawTriangles ( quadVertices , g_numPoints , g_auxIndices , g_numIndices , info . listenerOcclusionPlaneColor ) ; <nl> + <nl> + } <nl> <nl> - auxGeom . DrawTriangles ( quadVertices , g_numPoints , g_auxIndices , g_numIndices , m_listenerOcclusionPlaneColor ) ; <nl> auxGeom . SetRenderFlags ( previousRenderFlags ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CPropagationProcessor : : ResetRayData ( ) <nl> { <nl> - if ( m_occlusionType ! = EOcclusionType : : None & & m_occlusionType ! = EOcclusionType : : Ignore ) <nl> + if ( ( m_occlusionType ! = EOcclusionType : : None ) & & ( m_occlusionType ! = EOcclusionType : : Ignore ) ) <nl> { <nl> - for ( uint8 i = 0 ; i < g_numConcurrentRaysHigh ; + + i ) <nl> + for ( auto & info : m_occlusionInfos ) <nl> { <nl> - m_raysInfo [ i ] . Reset ( ) ; <nl> - m_rayDebugInfos [ i ] = SRayDebugInfo ( ) ; <nl> + for ( uint8 i = 0 ; i < g_numConcurrentRaysHigh ; + + i ) <nl> + { <nl> + info . raysInfo [ i ] . Reset ( ) ; <nl> + info . rayDebugInfos [ i ] = SRayDebugInfo ( ) ; <nl> + } <nl> } <nl> } <nl> } <nl> mmm a / Code / CryEngine / CryAudioSystem / PropagationProcessor . h <nl> ppp b / Code / CryEngine / CryAudioSystem / PropagationProcessor . h <nl> <nl> # pragma once <nl> <nl> # if defined ( CRY_AUDIO_USE_OCCLUSION ) <nl> - # include " RayInfo . h " <nl> + # include " OcclusionInfo . h " <nl> # include < CryAudio / IAudioInterfacesCommonData . h > <nl> # include < CryPhysics / IPhysics . h > <nl> <nl> namespace CryAudio <nl> { <nl> - constexpr uint8 g_numberLow = 7 ; <nl> - constexpr uint8 g_numberMedium = 9 ; <nl> - constexpr uint8 g_numberHigh = 11 ; <nl> - constexpr uint8 g_numRaySamplePositionsLow = g_numberLow * g_numberLow ; <nl> - constexpr uint8 g_numRaySamplePositionsMedium = g_numberMedium * g_numberMedium ; <nl> - constexpr uint8 g_numRaySamplePositionsHigh = g_numberHigh * g_numberHigh ; <nl> - constexpr uint8 g_numConcurrentRaysLow = 1 ; <nl> - constexpr uint8 g_numConcurrentRaysMedium = 2 ; <nl> - constexpr uint8 g_numConcurrentRaysHigh = 4 ; <nl> - constexpr uint8 g_numInitialSamplePositions = 5 ; <nl> - <nl> class CPropagationProcessor final <nl> { <nl> public : <nl> class CPropagationProcessor final <nl> <nl> void Update ( ) ; <nl> void SetOcclusionType ( EOcclusionType const occlusionType ) ; <nl> - float GetOcclusion ( ) const { return m_occlusion ; } <nl> + float GetOcclusion ( CListener * const pListener ) const ; <nl> void ProcessPhysicsRay ( CRayInfo & rayInfo ) ; <nl> void ReleasePendingRays ( ) ; <nl> bool HasPendingRays ( ) const { return m_remainingRays > 0 ; } <nl> bool HasNewOcclusionValues ( ) ; <nl> void UpdateOcclusion ( ) ; <nl> void SetOcclusionRayOffset ( float const offset ) { m_occlusionRayOffset = std : : max ( 0 . 0f , offset ) ; } <nl> + void AddListener ( CListener * const pListener ) ; <nl> + void RemoveListener ( CListener * const pListener ) ; <nl> <nl> private : <nl> <nl> class CPropagationProcessor final <nl> Vec3 const & origin , <nl> uint8 const rayIndex , <nl> uint8 const samplePosIndex , <nl> - bool const bSynch ) ; <nl> + bool const bSynch , <nl> + SOcclusionInfo & info ) ; <nl> void RunObstructionQuery ( ) ; <nl> - void ProcessLow ( Vec3 const & up , Vec3 const & side , bool const bSynch ) ; <nl> - void ProcessMedium ( Vec3 const & up , Vec3 const & side , bool const bSynch ) ; <nl> - void ProcessHigh ( Vec3 const & up , Vec3 const & side , bool const bSynch ) ; <nl> - uint8 GetNumConcurrentRays ( ) const ; <nl> - uint8 GetNumSamplePositions ( ) const ; <nl> + void ProcessLow ( Vec3 const & up , Vec3 const & side , bool const bSynch , SOcclusionInfo & info ) ; <nl> + void ProcessMedium ( Vec3 const & up , Vec3 const & side , bool const bSynch , SOcclusionInfo & info ) ; <nl> + void ProcessHigh ( Vec3 const & up , Vec3 const & side , bool const bSynch , SOcclusionInfo & info ) ; <nl> + uint8 GetNumConcurrentRays ( EOcclusionType const occlusionTypeWhenAdaptive ) const ; <nl> + uint8 GetNumSamplePositions ( EOcclusionType const occlusionTypeWhenAdaptive ) const ; <nl> bool CanRunOcclusion ( ) ; <nl> float CastInitialRay ( Vec3 const & origin , Vec3 const & target , bool const accumulate ) ; <nl> <nl> - float m_lastQuerriedOcclusion ; <nl> - float m_occlusion ; <nl> - float m_currentListenerDistance ; <nl> float m_occlusionRayOffset ; <nl> - float m_raysOcclusion [ g_numRaySamplePositionsHigh ] = { 0 . 0f } ; <nl> <nl> uint8 m_remainingRays ; <nl> - uint8 m_rayIndex ; <nl> <nl> CObject & m_object ; <nl> <nl> - CRayInfo m_raysInfo [ g_numConcurrentRaysHigh ] ; <nl> EOcclusionType m_occlusionType ; <nl> EOcclusionType m_originalOcclusionType ; <nl> - EOcclusionType m_occlusionTypeWhenAdaptive ; <nl> + <nl> + OcclusionInfos m_occlusionInfos ; <nl> <nl> static int s_occlusionRayFlags ; <nl> <nl> class CPropagationProcessor final <nl> static uint16 s_totalSyncPhysRays ; <nl> static uint16 s_totalAsyncPhysRays ; <nl> <nl> - void DrawDebugInfo ( IRenderAuxGeom & auxGeom ) ; <nl> - void DrawListenerPlane ( IRenderAuxGeom & auxGeom ) ; <nl> - EOcclusionType GetOcclusionType ( ) const { return m_occlusionType ; } <nl> - EOcclusionType GetOcclusionTypeWhenAdaptive ( ) const { return m_occlusionTypeWhenAdaptive ; } <nl> - float GetOcclusionRayOffset ( ) const { return m_occlusionRayOffset ; } <nl> - void ResetRayData ( ) ; <nl> - <nl> - private : <nl> - <nl> - struct SRayDebugInfo final <nl> - { <nl> - SRayDebugInfo ( ) = default ; <nl> - <nl> - Vec3 begin = ZERO ; <nl> - Vec3 end = ZERO ; <nl> - float occlusionValue = 0 . 0f ; <nl> - float distanceToNearestObstacle = FLT_MAX ; <nl> - uint8 numHits = 0 ; <nl> - uint8 samplePosIndex = 0 ; <nl> - } ; <nl> - <nl> - SRayDebugInfo m_rayDebugInfos [ g_numConcurrentRaysHigh ] ; <nl> - ColorB m_listenerOcclusionPlaneColor ; <nl> - Vec3 m_collisionSpherePositions [ g_numRaySamplePositionsHigh ] = { ZERO } ; <nl> + void DrawDebugInfo ( IRenderAuxGeom & auxGeom ) ; <nl> + void DrawListenerPlane ( IRenderAuxGeom & auxGeom ) ; <nl> + EOcclusionType GetOcclusionType ( ) const { return m_occlusionType ; } <nl> + OcclusionInfos const & GetOcclusionInfos ( ) const { return m_occlusionInfos ; } <nl> + float GetOcclusionRayOffset ( ) const { return m_occlusionRayOffset ; } <nl> + void ResetRayData ( ) ; <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> } ; <nl> } / / namespace CryAudio <nl> mmm a / Code / CryEngine / CryAudioSystem / RequestData . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / RequestData . cpp <nl> std : : shared_ptr < SRequestData > AllocateRequestData ( SRequestData const * const pReq <nl> CRY_AUDIO_SYSTEM_REQUEST_BLOCK ( ESystemRequestType : : GetImplInfo ) <nl> CRY_AUDIO_SYSTEM_REQUEST_BLOCK ( ESystemRequestType : : RegisterListener ) <nl> CRY_AUDIO_SYSTEM_REQUEST_BLOCK ( ESystemRequestType : : ReleaseListener ) <nl> + CRY_AUDIO_SYSTEM_REQUEST_BLOCK ( ESystemRequestType : : GetListener ) <nl> CRY_AUDIO_SYSTEM_REQUEST_BLOCK ( ESystemRequestType : : RegisterObject ) <nl> CRY_AUDIO_SYSTEM_REQUEST_BLOCK ( ESystemRequestType : : ReleaseObject ) <nl> CRY_AUDIO_SYSTEM_REQUEST_BLOCK ( ESystemRequestType : : ExecuteTrigger ) <nl> std : : shared_ptr < SRequestData > AllocateRequestData ( SRequestData const * const pReq <nl> CRY_AUDIO_OBJECT_REQUEST_BLOCK ( EObjectRequestType : : SetCurrentEnvironments ) <nl> CRY_AUDIO_OBJECT_REQUEST_BLOCK ( EObjectRequestType : : SetEnvironment ) <nl> CRY_AUDIO_OBJECT_REQUEST_BLOCK ( EObjectRequestType : : ProcessPhysicsRay ) <nl> + CRY_AUDIO_OBJECT_REQUEST_BLOCK ( EObjectRequestType : : AddListener ) <nl> + CRY_AUDIO_OBJECT_REQUEST_BLOCK ( EObjectRequestType : : RemoveListener ) <nl> CRY_AUDIO_OBJECT_REQUEST_BLOCK ( EObjectRequestType : : ToggleAbsoluteVelocityTracking ) <nl> CRY_AUDIO_OBJECT_REQUEST_BLOCK ( EObjectRequestType : : ToggleRelativeVelocityTracking ) <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> mmm a / Code / CryEngine / CryAudioSystem / System . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / System . cpp <nl> <nl> # include < CrySystem / ITimer . h > <nl> # include < CryString / CryPath . h > <nl> # include < CryEntitySystem / IEntitySystem . h > <nl> + # include < CryMath / Cry_Camera . h > <nl> <nl> # if defined ( CRY_AUDIO_USE_OCCLUSION ) <nl> # include " PropagationProcessor . h " <nl> bool CSystem : : Initialize ( ) <nl> std : : forward_as_tuple ( SContextInfo ( GlobalContextId , true , true ) ) ) ; <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> <nl> + g_listenerManager . Initialize ( ) ; <nl> g_fileCacheManager . Initialize ( ) ; <nl> <nl> CRY_ASSERT_MESSAGE ( ! m_mainThread . IsActive ( ) , " AudioSystem thread active before initialization during % s " , __FUNCTION__ ) ; <nl> char const * CSystem : : GetConfigPath ( ) const <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - CryAudio : : IListener * CSystem : : CreateListener ( CTransformation const & transformation , char const * const szName / * = nullptr * / ) <nl> + CryAudio : : IListener * CSystem : : CreateListener ( CTransformation const & transformation , char const * const szName ) <nl> { <nl> CListener * pListener = nullptr ; <nl> SSystemRequestData < ESystemRequestType : : RegisterListener > const requestData ( & pListener , transformation , szName ) ; <nl> CryAudio : : IListener * CSystem : : CreateListener ( CTransformation const & transformati <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CSystem : : ReleaseListener ( CryAudio : : IListener * const pIListener ) <nl> { <nl> - SSystemRequestData < ESystemRequestType : : ReleaseListener > const requestData ( static_cast < CListener * > ( pIListener ) ) ; <nl> - CRequest const request ( & requestData ) ; <nl> - PushRequest ( request ) ; <nl> + if ( static_cast < CListener * > ( pIListener ) - > IsUserCreated ( ) ) <nl> + { <nl> + SSystemRequestData < ESystemRequestType : : ReleaseListener > const requestData ( static_cast < CListener * > ( pIListener ) ) ; <nl> + CRequest const request ( & requestData ) ; <nl> + PushRequest ( request ) ; <nl> + } <nl> + # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + else <nl> + { <nl> + Cry : : Audio : : Log ( ELogType : : Error , " Non - user - created listener cannot get released during % s " , __FUNCTION__ ) ; <nl> + } <nl> + # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + IListener * CSystem : : GetListener ( ListenerId const id / * = DefaultListenerId * / ) <nl> + { <nl> + CListener * pListener = & g_defaultListener ; <nl> + <nl> + if ( ( id ! = DefaultListenerId ) & & ( id ! = InvalidListenerId ) ) <nl> + { <nl> + SSystemRequestData < ESystemRequestType : : GetListener > const requestData ( & pListener , id ) ; <nl> + CRequest const request ( & requestData , ERequestFlags : : ExecuteBlocking ) ; <nl> + PushRequest ( request ) ; <nl> + } <nl> + <nl> + return static_cast < CryAudio : : IListener * > ( pListener ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> ERequestStatus CSystem : : ProcessSystemRequest ( CRequest const & request ) <nl> <nl> if ( pTrigger ! = nullptr ) <nl> { <nl> + Listeners listeners ; <nl> + <nl> + for ( auto const id : pRequestData - > listenerIds ) <nl> + { <nl> + listeners . push_back ( g_listenerManager . GetListener ( id ) ) ; <nl> + } <nl> + <nl> + Impl : : IListeners implListeners ; <nl> + <nl> + for ( auto const pListener : listeners ) <nl> + { <nl> + implListeners . push_back ( pListener - > GetImplData ( ) ) ; <nl> + } <nl> + <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioSystem , " CryAudio : : CObject " ) ; <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> auto const pNewObject = new CObject ( pRequestData - > transformation , pRequestData - > name . c_str ( ) ) ; <nl> - pNewObject - > Init ( g_pIImpl - > ConstructObject ( pRequestData - > transformation , pNewObject - > GetName ( ) ) ) ; <nl> + pNewObject - > Init ( g_pIImpl - > ConstructObject ( pRequestData - > transformation , implListeners , pNewObject - > GetName ( ) ) , listeners ) ; <nl> g_constructedObjects . push_back ( pNewObject ) ; <nl> # else <nl> auto const pNewObject = new CObject ( pRequestData - > transformation ) ; <nl> - pNewObject - > Init ( g_pIImpl - > ConstructObject ( pRequestData - > transformation ) ) ; <nl> + pNewObject - > Init ( g_pIImpl - > ConstructObject ( pRequestData - > transformation , implListeners ) , listeners ) ; <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> <nl> if ( pRequestData - > setCurrentEnvironments ) <nl> ERequestStatus CSystem : : ProcessSystemRequest ( CRequest const & request ) <nl> case ESystemRequestType : : RegisterListener : <nl> { <nl> auto const pRequestData = static_cast < SSystemRequestData < ESystemRequestType : : RegisterListener > const * > ( request . GetData ( ) ) ; <nl> - * pRequestData - > ppListener = g_listenerManager . CreateListener ( pRequestData - > transformation , pRequestData - > name . c_str ( ) ) ; <nl> + * pRequestData - > ppListener = g_listenerManager . CreateListener ( pRequestData - > transformation , pRequestData - > name . c_str ( ) , true ) ; <nl> break ; <nl> } <nl> case ESystemRequestType : : ReleaseListener : <nl> ERequestStatus CSystem : : ProcessSystemRequest ( CRequest const & request ) <nl> result = ERequestStatus : : Success ; <nl> } <nl> <nl> + break ; <nl> + } <nl> + case ESystemRequestType : : GetListener : <nl> + { <nl> + auto const pRequestData = static_cast < SSystemRequestData < ESystemRequestType : : GetListener > const * > ( request . GetData ( ) ) ; <nl> + * pRequestData - > ppListener = g_listenerManager . GetListener ( pRequestData - > id ) ; <nl> break ; <nl> } <nl> case ESystemRequestType : : RegisterObject : <nl> { <nl> auto const pRequestData = static_cast < SSystemRequestData < ESystemRequestType : : RegisterObject > const * > ( request . GetData ( ) ) ; <nl> <nl> + Listeners listeners ; <nl> + <nl> + for ( auto const id : pRequestData - > listenerIds ) <nl> + { <nl> + listeners . push_back ( g_listenerManager . GetListener ( id ) ) ; <nl> + } <nl> + <nl> + Impl : : IListeners implListeners ; <nl> + implListeners . reserve ( listeners . size ( ) ) ; <nl> + <nl> + for ( auto const pListener : listeners ) <nl> + { <nl> + implListeners . push_back ( pListener - > GetImplData ( ) ) ; <nl> + } <nl> + <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioSystem , " CryAudio : : CObject " ) ; <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> auto const pNewObject = new CObject ( pRequestData - > transformation , pRequestData - > name . c_str ( ) ) ; <nl> - pNewObject - > Init ( g_pIImpl - > ConstructObject ( pRequestData - > transformation , pNewObject - > GetName ( ) ) ) ; <nl> + pNewObject - > Init ( g_pIImpl - > ConstructObject ( pRequestData - > transformation , implListeners , pNewObject - > GetName ( ) ) , listeners ) ; <nl> g_constructedObjects . push_back ( pNewObject ) ; <nl> # else <nl> auto const pNewObject = new CObject ( pRequestData - > transformation ) ; <nl> - pNewObject - > Init ( g_pIImpl - > ConstructObject ( pRequestData - > transformation ) ) ; <nl> + pNewObject - > Init ( g_pIImpl - > ConstructObject ( pRequestData - > transformation , implListeners ) , listeners ) ; <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> <nl> if ( pRequestData - > setCurrentEnvironments ) <nl> ERequestStatus CSystem : : ProcessObjectRequest ( CRequest const & request ) <nl> break ; <nl> } <nl> # endif / / CRY_AUDIO_USE_OCCLUSION <nl> + case EObjectRequestType : : AddListener : <nl> + { <nl> + auto const pRequestData = static_cast < SObjectRequestData < EObjectRequestType : : AddListener > const * > ( request . GetData ( ) ) ; <nl> + <nl> + pObject - > HandleAddListener ( pRequestData - > listenerId ) ; <nl> + result = ERequestStatus : : Success ; <nl> + <nl> + break ; <nl> + } <nl> + case EObjectRequestType : : RemoveListener : <nl> + { <nl> + auto const pRequestData = static_cast < SObjectRequestData < EObjectRequestType : : RemoveListener > const * > ( request . GetData ( ) ) ; <nl> + <nl> + pObject - > HandleRemoveListener ( pRequestData - > listenerId ) ; <nl> + result = ERequestStatus : : Success ; <nl> + <nl> + break ; <nl> + } <nl> case EObjectRequestType : : ToggleAbsoluteVelocityTracking : <nl> { <nl> auto const pRequestData = static_cast < SObjectRequestData < EObjectRequestType : : ToggleAbsoluteVelocityTracking > const * > ( request . GetData ( ) ) ; <nl> ERequestStatus CSystem : : HandleSetImpl ( Impl : : IImpl * const pIImpl ) <nl> g_pIImpl = static_cast < Impl : : IImpl * > ( pImpl ) ; <nl> } <nl> <nl> + CRY_ASSERT_MESSAGE ( g_defaultListener . GetImplData ( ) = = nullptr , " < Audio > The default listeners ' s impl - data must be nullptr during % s " , __FUNCTION__ ) ; <nl> + g_defaultListener . SetImplData ( g_pIImpl - > ConstructListener ( CTransformation : : GetEmptyObject ( ) , g_szDefaultListenerName ) ) ; <nl> + <nl> CRY_ASSERT_MESSAGE ( g_object . GetImplDataPtr ( ) = = nullptr , " < Audio > The global object ' s impl - data must be nullptr during % s " , __FUNCTION__ ) ; <nl> - g_object . SetImplDataPtr ( g_pIImpl - > ConstructGlobalObject ( ) ) ; <nl> + Impl : : IListeners const defaultImplListener { g_defaultListener . GetImplData ( ) } ; <nl> + g_object . SetImplDataPtr ( g_pIImpl - > ConstructGlobalObject ( defaultImplListener ) ) ; <nl> + <nl> + string const listenerNames = g_cvars . m_pListeners - > GetString ( ) ; <nl> + <nl> + if ( ! listenerNames . empty ( ) ) <nl> + { <nl> + int curPos = 0 ; <nl> + string listenerName = listenerNames . Tokenize ( " , " , curPos ) ; <nl> + <nl> + while ( ! listenerName . empty ( ) ) <nl> + { <nl> + listenerName . Trim ( ) ; <nl> + <nl> + if ( g_listenerManager . GetListener ( StringToId ( listenerName . c_str ( ) ) ) = = & g_defaultListener ) <nl> + { <nl> + g_listenerManager . CreateListener ( CTransformation : : GetEmptyObject ( ) , listenerName . c_str ( ) , false ) ; <nl> + } <nl> + <nl> + listenerName = listenerNames . Tokenize ( " , " , curPos ) ; <nl> + } <nl> + } <nl> <nl> # if defined ( CRY_AUDIO_USE_DEBUG_CODE ) <nl> + CRY_ASSERT_MESSAGE ( g_previewListener . GetImplData ( ) = = nullptr , " < Audio > The preview listeners ' s impl - data must be nullptr during % s " , __FUNCTION__ ) ; <nl> + g_previewListener . SetImplData ( g_pIImpl - > ConstructListener ( CTransformation : : GetEmptyObject ( ) , g_szPreviewListenerName ) ) ; <nl> + <nl> CRY_ASSERT_MESSAGE ( g_previewObject . GetImplDataPtr ( ) = = nullptr , " < Audio > The preview object ' s impl - data must be nullptr during % s " , __FUNCTION__ ) ; <nl> - g_previewObject . SetImplDataPtr ( g_pIImpl - > ConstructObject ( g_previewObject . GetTransformation ( ) , g_previewObject . GetName ( ) ) ) ; <nl> + Impl : : IListeners const previewImplListener { g_previewListener . GetImplData ( ) } ; <nl> + g_previewObject . SetImplDataPtr ( g_pIImpl - > ConstructObject ( g_previewObject . GetTransformation ( ) , previewImplListener , g_previewObject . GetName ( ) ) ) ; <nl> + <nl> + g_listenerManager . ReconstructImplData ( ) ; <nl> <nl> for ( auto const pObject : g_constructedObjects ) <nl> { <nl> CRY_ASSERT_MESSAGE ( pObject - > GetImplDataPtr ( ) = = nullptr , " < Audio > The object ' s impl - data must be nullptr during % s " , __FUNCTION__ ) ; <nl> <nl> - pObject - > SetImplDataPtr ( g_pIImpl - > ConstructObject ( pObject - > GetTransformation ( ) , pObject - > GetName ( ) ) ) ; <nl> + Listeners const & listeners = pObject - > GetListeners ( ) ; <nl> + Impl : : IListeners implListeners ; <nl> + <nl> + for ( auto const pListener : listeners ) <nl> + { <nl> + implListeners . push_back ( pListener - > GetImplData ( ) ) ; <nl> + } <nl> + <nl> + pObject - > SetImplDataPtr ( g_pIImpl - > ConstructObject ( pObject - > GetTransformation ( ) , implListeners , pObject - > GetName ( ) ) ) ; <nl> } <nl> <nl> for ( auto const & contextPair : g_contextInfo ) <nl> ERequestStatus CSystem : : HandleSetImpl ( Impl : : IImpl * const pIImpl ) <nl> } <nl> <nl> HandleUpdateDebugInfo ( ) ; <nl> - <nl> # endif / / CRY_AUDIO_USE_DEBUG_CODE <nl> - g_listenerManager . OnAfterImplChanged ( ) ; <nl> <nl> SetImplLanguage ( ) ; <nl> <nl> void DrawObjectInfo ( <nl> IRenderAuxGeom & auxGeom , <nl> float const posX , <nl> float & posY , <nl> + Vec3 const & camPos , <nl> CObject const & object , <nl> CryFixedStringT < MaxControlNameLength > const & lowerCaseSearchString , <nl> size_t & numObjects ) <nl> { <nl> Vec3 const & position = object . GetTransformation ( ) . GetPosition ( ) ; <nl> - float const distance = position . GetDistance ( g_listenerManager . GetActiveListenerTransformation ( ) . GetPosition ( ) ) ; <nl> + float const distance = position . GetDistance ( camPos ) ; <nl> <nl> if ( ( g_cvars . m_debugDistance < = 0 . 0f ) | | ( ( g_cvars . m_debugDistance > 0 . 0f ) & & ( distance < g_cvars . m_debugDistance ) ) ) <nl> { <nl> void DrawObjectDebugInfo ( IRenderAuxGeom & auxGeom , float const posX , float posY ) <nl> DrawGlobalObjectInfo ( auxGeom , posX , posY , g_object , lowerCaseSearchString , numObjects ) ; <nl> DrawGlobalObjectInfo ( auxGeom , posX , posY , g_previewObject , lowerCaseSearchString , numObjects ) ; <nl> <nl> + Vec3 const & camPos = GetISystem ( ) - > GetViewCamera ( ) . GetPosition ( ) ; <nl> + <nl> for ( auto const pObject : g_constructedObjects ) <nl> { <nl> - DrawObjectInfo ( auxGeom , posX , posY , * pObject , lowerCaseSearchString , numObjects ) ; <nl> + float const distance = pObject - > GetTransformation ( ) . GetPosition ( ) . GetDistance ( camPos ) ; <nl> + <nl> + if ( ( g_cvars . m_debugDistance < = 0 . 0f ) | | ( ( g_cvars . m_debugDistance > 0 . 0f ) & & ( distance < = g_cvars . m_debugDistance ) ) ) <nl> + { <nl> + DrawObjectInfo ( auxGeom , posX , posY , camPos , * pObject , lowerCaseSearchString , numObjects ) ; <nl> + } <nl> } <nl> <nl> auxGeom . Draw2dLabel ( posX , headerPosY , Debug : : g_listHeaderFontSize , Debug : : s_globalColorHeader , false , " Audio Objects [ % " PRISIZE_T " ] " , numObjects ) ; <nl> void CSystem : : HandleDrawDebug ( ) <nl> <nl> size_t const numObjects = g_constructedObjects . size ( ) ; <nl> size_t const numActiveObjects = g_activeObjects . size ( ) ; <nl> - size_t const numListeners = g_listenerManager . GetNumActiveListeners ( ) ; <nl> + size_t const numListeners = g_listenerManager . GetNumListeners ( ) ; <nl> size_t const numEventListeners = g_eventListenerManager . GetNumEventListeners ( ) ; <nl> <nl> # if defined ( CRY_AUDIO_USE_OCCLUSION ) <nl> void CSystem : : HandleDrawDebug ( ) <nl> { <nl> if ( g_pIImpl ! = nullptr ) <nl> { <nl> - g_pIImpl - > DrawDebugInfoList ( * pAuxGeom , posX , posY , g_cvars . m_debugDistance , g_cvars . m_pDebugFilter - > GetString ( ) ) ; <nl> + Vec3 const & camPos = GetISystem ( ) - > GetViewCamera ( ) . GetPosition ( ) ; <nl> + <nl> + g_pIImpl - > DrawDebugInfoList ( * pAuxGeom , posX , posY , camPos , g_cvars . m_debugDistance , g_cvars . m_pDebugFilter - > GetString ( ) ) ; <nl> / / The impl is responsible for increasing posX . <nl> } <nl> } <nl> mmm a / Code / CryEngine / CryAudioSystem / System . h <nl> ppp b / Code / CryEngine / CryAudioSystem / System . h <nl> class CSystem final : public IAudioSystem , public : : ISystemEventListener , public <nl> virtual void RemoveRequestListener ( void ( * func ) ( SRequestInfo const * const ) , void * const pObjectToListenTo ) override ; <nl> virtual void ExternalUpdate ( ) override ; <nl> virtual char const * GetConfigPath ( ) const override ; <nl> - virtual IListener * CreateListener ( CTransformation const & transformation , char const * const szName = nullptr ) override ; <nl> + virtual IListener * CreateListener ( CTransformation const & transformation , char const * const szName ) override ; <nl> virtual void ReleaseListener ( IListener * const pIListener ) override ; <nl> + virtual IListener * GetListener ( ListenerId const id = DefaultListenerId ) override ; <nl> virtual IObject * CreateObject ( SCreateObjectData const & objectData = SCreateObjectData : : GetEmptyObject ( ) ) override ; <nl> virtual void ReleaseObject ( IObject * const pIObject ) override ; <nl> virtual void GetTriggerData ( ControlId const triggerId , STriggerData & triggerData ) override ; <nl> mmm a / Code / CryEngine / CryAudioSystem / SystemRequestData . h <nl> ppp b / Code / CryEngine / CryAudioSystem / SystemRequestData . h <nl> enum class ESystemRequestType : EnumFlagsType <nl> ReleasePendingRays , <nl> GetImplInfo , <nl> RegisterListener , <nl> + GetListener , <nl> ReleaseListener , <nl> RegisterObject , <nl> ReleaseObject , <nl> struct SSystemRequestData < ESystemRequestType : : RegisterListener > final : public S <nl> CryFixedStringT < MaxObjectNameLength > const name ; <nl> } ; <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + template < > <nl> + struct SSystemRequestData < ESystemRequestType : : GetListener > final : public SSystemRequestDataBase <nl> + { <nl> + explicit SSystemRequestData ( CListener * * const ppListener_ , ListenerId const id_ ) <nl> + : SSystemRequestDataBase ( ESystemRequestType : : GetListener ) <nl> + , ppListener ( ppListener_ ) <nl> + , id ( id_ ) <nl> + { } <nl> + <nl> + explicit SSystemRequestData ( SSystemRequestData < ESystemRequestType : : GetListener > const * const pALRData ) <nl> + : SSystemRequestDataBase ( ESystemRequestType : : GetListener ) <nl> + , ppListener ( pALRData - > ppListener ) <nl> + , id ( pALRData - > id ) <nl> + { } <nl> + <nl> + virtual ~ SSystemRequestData ( ) override = default ; <nl> + <nl> + CListener * * const ppListener ; <nl> + ListenerId const id ; <nl> + } ; <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> template < > <nl> struct SSystemRequestData < ESystemRequestType : : ReleaseListener > final : public SSystemRequestDataBase <nl> struct SSystemRequestData < ESystemRequestType : : RegisterObject > final : public SSy <nl> , occlusionType ( data . occlusionType ) <nl> , transformation ( data . transformation ) <nl> , setCurrentEnvironments ( data . setCurrentEnvironments ) <nl> + , listenerIds ( data . listenerIds ) <nl> { } <nl> <nl> explicit SSystemRequestData ( SSystemRequestData < ESystemRequestType : : RegisterObject > const * const pSRData ) <nl> struct SSystemRequestData < ESystemRequestType : : RegisterObject > final : public SSy <nl> , occlusionType ( pSRData - > occlusionType ) <nl> , transformation ( pSRData - > transformation ) <nl> , setCurrentEnvironments ( pSRData - > setCurrentEnvironments ) <nl> + , listenerIds ( pSRData - > listenerIds ) <nl> { } <nl> <nl> virtual ~ SSystemRequestData ( ) override = default ; <nl> struct SSystemRequestData < ESystemRequestType : : RegisterObject > final : public SSy <nl> EOcclusionType const occlusionType ; <nl> CTransformation const transformation ; <nl> bool const setCurrentEnvironments ; <nl> + ListenerIds const listenerIds ; <nl> } ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> struct SSystemRequestData < ESystemRequestType : : ExecuteTriggerEx > final : public S <nl> , entityId ( data . entityId ) <nl> , setCurrentEnvironments ( data . setCurrentEnvironments ) <nl> , triggerId ( data . triggerId ) <nl> + , listenerIds ( data . listenerIds ) <nl> { } <nl> <nl> explicit SSystemRequestData ( SSystemRequestData < ESystemRequestType : : ExecuteTriggerEx > const * const pSRData ) <nl> struct SSystemRequestData < ESystemRequestType : : ExecuteTriggerEx > final : public S <nl> , entityId ( pSRData - > entityId ) <nl> , setCurrentEnvironments ( pSRData - > setCurrentEnvironments ) <nl> , triggerId ( pSRData - > triggerId ) <nl> + , listenerIds ( pSRData - > listenerIds ) <nl> { } <nl> <nl> virtual ~ SSystemRequestData ( ) override = default ; <nl> struct SSystemRequestData < ESystemRequestType : : ExecuteTriggerEx > final : public S <nl> EntityId const entityId ; <nl> bool const setCurrentEnvironments ; <nl> ControlId const triggerId ; <nl> + ListenerIds const listenerIds ; <nl> } ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / BaseObject . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / BaseObject . cpp <nl> static void PlaybackEventCallback ( void * pObject , CriAtomExPlaybackEvent playback <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - CBaseObject : : CBaseObject ( ) <nl> - : m_flags ( EObjectFlags : : IsVirtual ) / / Set to virtual because voices always start in virtual state . <nl> + CBaseObject : : CBaseObject ( CListener * const pListener ) <nl> + : m_pListener ( pListener ) <nl> + , m_flags ( EObjectFlags : : IsVirtual ) / / Set to virtual because voices always start in virtual state . <nl> { <nl> ZeroStruct ( m_3dAttributes ) ; <nl> m_p3dSource = criAtomEx3dSource_Create ( & g_3dSourceConfig , nullptr , 0 ) ; <nl> m_pPlayer = criAtomExPlayer_Create ( & g_playerConfig , nullptr , 0 ) ; <nl> - criAtomExPlayer_SetPlaybackEventCallback ( m_pPlayer , PlaybackEventCallback , this ) ; <nl> CRY_ASSERT_MESSAGE ( m_pPlayer ! = nullptr , " m_pPlayer is null pointer during % s " , __FUNCTION__ ) ; <nl> + criAtomExPlayer_SetPlaybackEventCallback ( m_pPlayer , PlaybackEventCallback , this ) ; <nl> + criAtomExPlayer_Set3dListenerHn ( m_pPlayer , m_pListener - > GetHandle ( ) ) ; <nl> + criAtomExPlayer_Set3dSourceHn ( m_pPlayer , m_p3dSource ) ; <nl> m_cueInstances . reserve ( 2 ) ; <nl> } <nl> <nl> ERequestStatus CBaseObject : : SetName ( char const * const szName ) <nl> return ERequestStatus : : Success ; <nl> } <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CBaseObject : : AddListener ( IListener * const pIListener ) <nl> + { <nl> + m_pListener = static_cast < CListener * > ( pIListener ) ; <nl> + <nl> + criAtomExPlayer_Stop ( m_pPlayer ) ; <nl> + criAtomExPlayer_Set3dListenerHn ( m_pPlayer , m_pListener - > GetHandle ( ) ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CBaseObject : : RemoveListener ( IListener * const pIListener ) <nl> + { <nl> + if ( m_pListener = = static_cast < CListener * > ( pIListener ) ) <nl> + { <nl> + m_pListener = nullptr ; <nl> + criAtomExPlayer_Stop ( m_pPlayer ) ; <nl> + criAtomExPlayer_Set3dListenerHn ( m_pPlayer , nullptr ) ; <nl> + } <nl> + } <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CBaseObject : : AddCueInstance ( CCueInstance * const pCueInstance ) <nl> { <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / BaseObject . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / BaseObject . h <nl> namespace Adx2 <nl> { <nl> class CCue ; <nl> class CCueInstance ; <nl> + class CListener ; <nl> <nl> enum class EObjectFlags : EnumFlagsType <nl> { <nl> class CBaseObject : public IObject <nl> virtual CTransformation const & GetTransformation ( ) const override { return CTransformation : : GetEmptyObject ( ) ; } <nl> virtual void StopAllTriggers ( ) override ; <nl> virtual ERequestStatus SetName ( char const * const szName ) override ; <nl> + virtual void AddListener ( IListener * const pIListener ) override ; <nl> + virtual void RemoveListener ( IListener * const pIListener ) override ; <nl> virtual void ToggleFunctionality ( EObjectFunctionality const type , bool const enable ) override { } <nl> <nl> / / Below data is only used when CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE is defined ! <nl> class CBaseObject : public IObject <nl> void PausePlayer ( CriBool const shouldPause ) ; <nl> <nl> CriAtomExPlayerHn GetPlayer ( ) const { return m_pPlayer ; } <nl> - CriAtomEx3dSourceHn Get3dSource ( ) const { return m_p3dSource ; } <nl> - <nl> CueInstances const & GetCueInstances ( ) const { return m_cueInstances ; } <nl> <nl> # if defined ( CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE ) <nl> - char const * GetName ( ) const { return m_name . c_str ( ) ; } <nl> + CListener * GetListener ( ) const { return m_pListener ; } <nl> + char const * GetName ( ) const { return m_name . c_str ( ) ; } <nl> # endif / / CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE <nl> <nl> protected : <nl> <nl> - CBaseObject ( ) ; <nl> + CBaseObject ( CListener * const pListener ) ; <nl> <nl> void UpdateVirtualState ( CCueInstance * const pCueInstance ) ; <nl> <nl> + CListener * m_pListener ; <nl> EObjectFlags m_flags ; <nl> S3DAttributes m_3dAttributes ; <nl> CriAtomEx3dSourceHn m_p3dSource ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Common . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Common . cpp <nl> namespace Impl <nl> namespace Adx2 <nl> { <nl> CImpl * g_pImpl = nullptr ; <nl> - CGlobalObject * g_pObject = nullptr ; <nl> - CListener * g_pListener = nullptr ; <nl> <nl> Objects g_constructedObjects ; <nl> AcbHandles g_acbHandles ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Common . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Common . h <nl> namespace Adx2 <nl> { <nl> class CImpl ; <nl> class CBaseObject ; <nl> - class CGlobalObject ; <nl> - class CListener ; <nl> class CCueInstance ; <nl> <nl> extern CImpl * g_pImpl ; <nl> - extern CGlobalObject * g_pObject ; <nl> - extern CListener * g_pListener ; <nl> <nl> using Objects = std : : vector < CBaseObject * > ; <nl> extern Objects g_constructedObjects ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Cue . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Cue . cpp <nl> ETriggerResult CCue : : Execute ( IObject * const pIObject , TriggerInstanceId const tr <nl> case EActionType : : Start : <nl> { <nl> CriAtomExPlayerHn const pPlayer = pBaseObject - > GetPlayer ( ) ; <nl> - <nl> - criAtomExPlayer_Set3dListenerHn ( pPlayer , g_pListener - > GetHandle ( ) ) ; <nl> - criAtomExPlayer_Set3dSourceHn ( pPlayer , pBaseObject - > Get3dSource ( ) ) ; <nl> - <nl> auto const iter = g_acbHandles . find ( m_cueSheetId ) ; <nl> <nl> if ( iter ! = g_acbHandles . end ( ) ) <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / GlobalObject . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / GlobalObject . cpp <nl> namespace Impl <nl> namespace Adx2 <nl> { <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - CGlobalObject : : CGlobalObject ( ) <nl> + CGlobalObject : : CGlobalObject ( CListener * const pListener ) <nl> + : CBaseObject ( pListener ) <nl> { <nl> - CRY_ASSERT_MESSAGE ( g_pObject = = nullptr , " g_pObject is not nullptr during % s " , __FUNCTION__ ) ; <nl> - g_pObject = this ; <nl> - <nl> # if defined ( CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE ) <nl> m_name = " Global Object " ; <nl> # endif / / CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE <nl> } <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - CGlobalObject : : ~ CGlobalObject ( ) <nl> - { <nl> - g_pObject = nullptr ; <nl> - } <nl> - <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CGlobalObject : : SetTransformation ( CTransformation const & transformation ) <nl> { <nl> void CGlobalObject : : SetTransformation ( CTransformation const & transformation ) <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CGlobalObject : : SetOcclusion ( float const occlusion ) <nl> + void CGlobalObject : : SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) <nl> { <nl> # if defined ( CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE ) <nl> Cry : : Audio : : Log ( ELogType : : Error , " Trying to set occlusion and obstruction values on the global object ! " ) ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / GlobalObject . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / GlobalObject . h <nl> class CGlobalObject final : public CBaseObject <nl> CGlobalObject & operator = ( CGlobalObject const & ) = delete ; <nl> CGlobalObject & operator = ( CGlobalObject & & ) = delete ; <nl> <nl> - CGlobalObject ( ) ; <nl> - virtual ~ CGlobalObject ( ) override ; <nl> + CGlobalObject ( CListener * const pListener ) ; <nl> + virtual ~ CGlobalObject ( ) override = default ; <nl> <nl> / / CryAudio : : Impl : : IObject <nl> virtual void SetTransformation ( CTransformation const & transformation ) override ; <nl> - virtual void SetOcclusion ( float const occlusion ) override ; <nl> + virtual void SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) override ; <nl> virtual void SetOcclusionType ( EOcclusionType const occlusionType ) override ; <nl> / / ~ CryAudio : : Impl : : IObject <nl> } ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Impl . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Impl . cpp <nl> SPoolSizes g_debugPoolSizes ; <nl> CueInstances g_constructedCueInstances ; <nl> uint16 g_objectPoolSize = 0 ; <nl> uint16 g_cueInstancePoolSize = 0 ; <nl> + std : : vector < CListener * > g_constructedListeners ; <nl> # endif / / CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : GetInfo ( SImplInfo & implInfo ) const <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IObject * CImpl : : ConstructGlobalObject ( ) <nl> + IObject * CImpl : : ConstructGlobalObject ( IListeners const & listeners ) <nl> { <nl> + auto const pListener = static_cast < CListener * > ( listeners [ 0 ] ) ; / / ADX2 supports only one listener per player . <nl> + <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : Adx2 : : CGlobalObject " ) ; <nl> - new CGlobalObject ; <nl> + auto const pObject = new CGlobalObject ( pListener ) ; <nl> <nl> - if ( ! stl : : push_back_unique ( g_constructedObjects , static_cast < CBaseObject * > ( g_pObject ) ) ) <nl> - { <nl> # if defined ( CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE ) <nl> + if ( ! stl : : push_back_unique ( g_constructedObjects , static_cast < CBaseObject * > ( pObject ) ) ) <nl> + { <nl> Cry : : Audio : : Log ( ELogType : : Warning , " Trying to construct an already registered object . " ) ; <nl> - # endif / / CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE <nl> } <nl> <nl> - return static_cast < IObject * > ( g_pObject ) ; <nl> + if ( listeners . size ( ) > 1 ) <nl> + { <nl> + Cry : : Audio : : Log ( ELogType : : Warning , R " ( More than one listener is passed in % s . Adx2 supports only one listener per object . Listener " % s " will be used for object " % s " . ) " , <nl> + __FUNCTION__ , pListener - > GetName ( ) , pObject - > GetName ( ) ) ; <nl> + } <nl> + # else <nl> + stl : : push_back_unique ( g_constructedObjects , static_cast < CBaseObject * > ( pObject ) ) ; <nl> + # endif / / CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE <nl> + <nl> + return static_cast < IObject * > ( pObject ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IObject * CImpl : : ConstructObject ( CTransformation const & transformation , char const * const szName / * = nullptr * / ) <nl> + IObject * CImpl : : ConstructObject ( CTransformation const & transformation , IListeners const & listeners , char const * const szName / * = nullptr * / ) <nl> { <nl> + auto const pListener = static_cast < CListener * > ( listeners [ 0 ] ) ; / / ADX2 supports only one listener per player . <nl> + <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : Adx2 : : CObject " ) ; <nl> - auto const pObject = new CObject ( transformation ) ; <nl> + auto const pObject = new CObject ( transformation , pListener ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE ) <nl> pObject - > SetName ( szName ) ; <nl> IObject * CImpl : : ConstructObject ( CTransformation const & transformation , char cons <nl> { <nl> Cry : : Audio : : Log ( ELogType : : Warning , " Trying to construct an already registered object . " ) ; <nl> } <nl> + <nl> + if ( listeners . size ( ) > 1 ) <nl> + { <nl> + Cry : : Audio : : Log ( ELogType : : Warning , R " ( More than one listener is passed in % s . Adx2 supports only one listener per object . Listener " % s " will be used for object " % s " . ) " , <nl> + __FUNCTION__ , pListener - > GetName ( ) , pObject - > GetName ( ) ) ; <nl> + } <nl> # else <nl> stl : : push_back_unique ( g_constructedObjects , pObject ) ; <nl> # endif / / CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE <nl> void CImpl : : DestructObject ( IObject const * const pIObject ) <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char const * const szName / * = nullptr * / ) <nl> + IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char const * const szName ) <nl> { <nl> IListener * pIListener = nullptr ; <nl> <nl> - static uint16 id = 0 ; <nl> CriAtomEx3dListenerHn const pHandle = criAtomEx3dListener_Create ( & m_listenerConfig , nullptr , 0 ) ; <nl> <nl> if ( pHandle ! = nullptr ) <nl> { <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : Adx2 : : CListener " ) ; <nl> - g_pListener = new CListener ( transformation , id + + , pHandle ) ; <nl> + auto const pListener = new CListener ( transformation , pHandle ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE ) <nl> - g_pListener - > SetName ( szName ) ; <nl> + pListener - > SetName ( szName ) ; <nl> + g_constructedListeners . push_back ( pListener ) ; <nl> # endif / / CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE <nl> <nl> - pIListener = static_cast < IListener * > ( g_pListener ) ; <nl> + pIListener = static_cast < IListener * > ( pListener ) ; <nl> } <nl> <nl> return pIListener ; <nl> IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : DestructListener ( IListener * const pIListener ) <nl> { <nl> - CRY_ASSERT_MESSAGE ( pIListener = = g_pListener , " pIListener is not g_pListener during % s " , __FUNCTION__ ) ; <nl> - criAtomEx3dListener_Destroy ( g_pListener - > GetHandle ( ) ) ; <nl> - delete g_pListener ; <nl> - g_pListener = nullptr ; <nl> + auto const pListener = static_cast < CListener * > ( pIListener ) ; <nl> + criAtomEx3dListener_Destroy ( pListener - > GetHandle ( ) ) ; <nl> + <nl> + # if defined ( CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE ) <nl> + auto iter ( g_constructedListeners . begin ( ) ) ; <nl> + auto const iterEnd ( g_constructedListeners . cend ( ) ) ; <nl> + <nl> + for ( ; iter ! = iterEnd ; + + iter ) <nl> + { <nl> + if ( ( * iter ) = = pListener ) <nl> + { <nl> + if ( iter ! = ( iterEnd - 1 ) ) <nl> + { <nl> + ( * iter ) = g_constructedListeners . back ( ) ; <nl> + } <nl> + <nl> + g_constructedListeners . pop_back ( ) ; <nl> + break ; <nl> + } <nl> + } <nl> + # endif / / CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE <nl> + <nl> + delete pListener ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : DrawDebugMemoryInfo ( IRenderAuxGeom & auxGeom , float const posX , float <nl> m_name . c_str ( ) , memAllocSizeString . c_str ( ) , totalPoolSizeString . c_str ( ) , acfSizeString . c_str ( ) , totalMemSizeString . c_str ( ) ) ; <nl> <nl> size_t const numCueInstances = g_constructedCueInstances . size ( ) ; <nl> + size_t const numListeners = g_constructedListeners . size ( ) ; <nl> <nl> posY + = Debug : : g_systemLineHeight ; <nl> auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorTextSecondary , false , <nl> - " Active Cues : % 3 " PRISIZE_T " | Objects with Doppler : % u | DSP Bus Setting : % s | Active Snapshot : % s " , <nl> - numCueInstances , g_numObjectsWithDoppler , g_debugCurrentDspBusSettingName . c_str ( ) , g_debugActiveSnapShotName . c_str ( ) ) ; <nl> + " Active Cues : % 3 " PRISIZE_T " | Listeners : % " PRISIZE_T " | Objects with Doppler : % u | DSP Bus Setting : % s | Active Snapshot : % s " , <nl> + numCueInstances , numListeners , g_numObjectsWithDoppler , g_debugCurrentDspBusSettingName . c_str ( ) , g_debugActiveSnapShotName . c_str ( ) ) ; <nl> <nl> - Vec3 const & listenerPosition = g_pListener - > GetPosition ( ) ; <nl> - Vec3 const & listenerDirection = g_pListener - > GetTransformation ( ) . GetForward ( ) ; <nl> - float const listenerVelocity = g_pListener - > GetVelocity ( ) . GetLength ( ) ; <nl> - char const * const szName = g_pListener - > GetName ( ) ; <nl> + for ( auto const pListener : g_constructedListeners ) <nl> + { <nl> + Vec3 const & listenerPosition = pListener - > GetPosition ( ) ; <nl> + Vec3 const & listenerDirection = pListener - > GetTransformation ( ) . GetForward ( ) ; <nl> + float const listenerVelocity = pListener - > GetVelocity ( ) . GetLength ( ) ; <nl> + char const * const szName = pListener - > GetName ( ) ; <nl> <nl> - posY + = Debug : : g_systemLineHeight ; <nl> - auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorListenerActive , false , " Listener : % s | PosXYZ : % . 2f % . 2f % . 2f | FwdXYZ : % . 2f % . 2f % . 2f | Velocity : % . 2f m / s " , <nl> - szName , listenerPosition . x , listenerPosition . y , listenerPosition . z , listenerDirection . x , listenerDirection . y , listenerDirection . z , listenerVelocity ) ; <nl> + posY + = Debug : : g_systemLineHeight ; <nl> + auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorListenerActive , false , " Listener : % s | PosXYZ : % . 2f % . 2f % . 2f | FwdXYZ : % . 2f % . 2f % . 2f | Velocity : % . 2f m / s " , <nl> + szName , listenerPosition . x , listenerPosition . y , listenerPosition . z , listenerDirection . x , listenerDirection . y , listenerDirection . z , listenerVelocity ) ; <nl> + } <nl> # endif / / CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , float const debugDistance , char const * const szTextFilter ) const <nl> + void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , Vec3 const & camPos , float const debugDistance , char const * const szTextFilter ) const <nl> { <nl> # if defined ( CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE ) <nl> if ( ( g_cvars . m_debugListFilter & g_debugListMask ) ! = 0 ) <nl> void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , <nl> for ( auto const pCueInstance : g_constructedCueInstances ) <nl> { <nl> Vec3 const & position = pCueInstance - > GetObject ( ) . GetTransformation ( ) . GetPosition ( ) ; <nl> - float const distance = position . GetDistance ( g_pListener - > GetPosition ( ) ) ; <nl> + float const distance = position . GetDistance ( camPos ) ; <nl> <nl> if ( ( debugDistance < = 0 . 0f ) | | ( ( debugDistance > 0 . 0f ) & & ( distance < debugDistance ) ) ) <nl> { <nl> void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , <nl> { <nl> ECueInstanceFlags const flags = pCueInstance - > GetFlags ( ) ; <nl> ColorF color = Debug : : s_listColorItemActive ; <nl> + char const * const szListenerName = ( pCueInstance - > GetObject ( ) . GetListener ( ) ! = nullptr ) ? pCueInstance - > GetObject ( ) . GetListener ( ) - > GetName ( ) : " No Listener ! " ; <nl> <nl> CryFixedStringT < MaxMiscStringLength > debugText ; <nl> - debugText . Format ( " % s on % s " , szCueName , pCueInstance - > GetObject ( ) . GetName ( ) ) ; <nl> + debugText . Format ( " % s on % s ( % s ) " , szCueName , pCueInstance - > GetObject ( ) . GetName ( ) , szListenerName ) ; <nl> <nl> if ( ( flags & ECueInstanceFlags : : IsPending ) ! = 0 ) <nl> { <nl> void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , <nl> float const fadeOutTime = pCueInstance - > GetCue ( ) . GetFadeOutTime ( ) ; <nl> float const remainingTime = std : : max ( 0 . 0f , fadeOutTime - ( gEnv - > pTimer - > GetAsyncTime ( ) . GetSeconds ( ) - pCueInstance - > GetTimeFadeOutStarted ( ) ) ) ; <nl> <nl> - debugText . Format ( " % s on % s ( % . 2f sec ) " , szCueName , pCueInstance - > GetObject ( ) . GetName ( ) , remainingTime ) ; <nl> + debugText . Format ( " % s on % s ( % s ) ( % . 2f sec ) " , szCueName , pCueInstance - > GetObject ( ) . GetName ( ) , szListenerName , remainingTime ) ; <nl> color = Debug : : s_listColorItemStopping ; <nl> } <nl> <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Impl . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Impl . h <nl> class CImpl final : public IImpl <nl> virtual void DestructEnvironmentConnection ( IEnvironmentConnection const * const pIEnvironmentConnection ) override ; <nl> virtual ISettingConnection * ConstructSettingConnection ( XmlNodeRef const & rootNode ) override ; <nl> virtual void DestructSettingConnection ( ISettingConnection const * const pISettingConnection ) override ; <nl> - virtual IObject * ConstructGlobalObject ( ) override ; <nl> - virtual IObject * ConstructObject ( CTransformation const & transformation , char const * const szName = nullptr ) override ; <nl> + virtual IObject * ConstructGlobalObject ( IListeners const & listeners ) override ; <nl> + virtual IObject * ConstructObject ( CTransformation const & transformation , IListeners const & listeners , char const * const szName = nullptr ) override ; <nl> virtual void DestructObject ( IObject const * const pIObject ) override ; <nl> - virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName = nullptr ) override ; <nl> + virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName ) override ; <nl> virtual void DestructListener ( IListener * const pIListener ) override ; <nl> virtual void GamepadConnected ( DeviceId const deviceUniqueID ) override ; <nl> virtual void GamepadDisconnected ( DeviceId const deviceUniqueID ) override ; <nl> class CImpl final : public IImpl <nl> <nl> / / Below data is only used when CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE is defined ! <nl> virtual void DrawDebugMemoryInfo ( IRenderAuxGeom & auxGeom , float const posX , float & posY , bool const drawDetailedInfo ) override ; <nl> - virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , float const debugDistance , char const * const szTextFilter ) const override ; <nl> + virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , Vec3 const & camPos , float const debugDistance , char const * const szTextFilter ) const override ; <nl> / / ~ CryAudio : : Impl : : IImpl <nl> <nl> # if defined ( CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE ) <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Listener . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Listener . cpp <nl> namespace Impl <nl> namespace Adx2 <nl> { <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - CListener : : CListener ( CTransformation const & transformation , uint16 const id , CriAtomEx3dListenerHn const pHandle ) <nl> - : m_id ( id ) <nl> - , m_pHandle ( pHandle ) <nl> + CListener : : CListener ( CTransformation const & transformation , CriAtomEx3dListenerHn const pHandle ) <nl> + : m_pHandle ( pHandle ) <nl> , m_isMovingOrDecaying ( false ) <nl> , m_velocity ( ZERO ) <nl> , m_position ( transformation . GetPosition ( ) ) <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Listener . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Listener . h <nl> class CListener final : public IListener <nl> CListener & operator = ( CListener const & ) = delete ; <nl> CListener & operator = ( CListener & & ) = delete ; <nl> <nl> - explicit CListener ( CTransformation const & transformation , uint16 const id , CriAtomEx3dListenerHn const pHandle ) ; <nl> + explicit CListener ( CTransformation const & transformation , CriAtomEx3dListenerHn const pHandle ) ; <nl> virtual ~ CListener ( ) override = default ; <nl> <nl> / / CryAudio : : Impl : : IListener <nl> class CListener final : public IListener <nl> virtual CTransformation const & GetTransformation ( ) const override { return m_transformation ; } <nl> / / ~ CryAudio : : Impl : : IListener <nl> <nl> - uint16 GetId ( ) const { return m_id ; } <nl> CriAtomEx3dListenerHn GetHandle ( ) const { return m_pHandle ; } <nl> Vec3 const & GetPosition ( ) const { return m_position ; } <nl> Vec3 const & GetVelocity ( ) const { return m_velocity ; } <nl> class CListener final : public IListener <nl> <nl> void SetVelocity ( ) ; <nl> <nl> - uint16 const m_id ; <nl> CriAtomEx3dListenerHn const m_pHandle ; <nl> bool m_isMovingOrDecaying ; <nl> Vec3 m_velocity ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Object . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Object . cpp <nl> namespace Adx2 <nl> constexpr CriChar8 const * g_szOcclusionAisacName = " occlusion " ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - CObject : : CObject ( CTransformation const & transformation ) <nl> - : m_transformation ( transformation ) <nl> + CObject : : CObject ( CTransformation const & transformation , CListener * const pListener ) <nl> + : CBaseObject ( pListener ) <nl> + , m_transformation ( transformation ) <nl> , m_occlusion ( 0 . 0f ) <nl> , m_previousAbsoluteVelocity ( 0 . 0f ) <nl> , m_position ( transformation . GetPosition ( ) ) <nl> void CObject : : SetTransformation ( CTransformation const & transformation ) <nl> m_previousPosition = m_position ; <nl> } <nl> <nl> - float const threshold = m_position . GetDistance ( g_pListener - > GetPosition ( ) ) * g_cvars . m_positionUpdateThresholdMultiplier ; <nl> + float const threshold = ( m_pListener ! = nullptr ) ? ( m_position . GetDistance ( m_pListener - > GetPosition ( ) ) * g_cvars . m_positionUpdateThresholdMultiplier ) : 0 . 0f ; <nl> <nl> if ( ! m_transformation . IsEquivalent ( transformation , threshold ) ) <nl> { <nl> void CObject : : SetTransformation ( CTransformation const & transformation ) <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CObject : : SetOcclusion ( float const occlusion ) <nl> + void CObject : : SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) <nl> { <nl> criAtomExPlayer_SetAisacControlByName ( m_pPlayer , g_szOcclusionAisacName , static_cast < CriFloat32 > ( occlusion ) ) ; <nl> criAtomExPlayer_UpdateAll ( m_pPlayer ) ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Object . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplAdx2 / Object . h <nl> class CObject final : public CBaseObject , public CPoolObject < CObject , stl : : PSync <nl> CObject & operator = ( CObject const & ) = delete ; <nl> CObject & operator = ( CObject & & ) = delete ; <nl> <nl> - explicit CObject ( CTransformation const & transformation ) ; <nl> + explicit CObject ( CTransformation const & transformation , CListener * const pListener ) ; <nl> virtual ~ CObject ( ) override ; <nl> <nl> / / CryAudio : : Impl : : IObject <nl> virtual void Update ( float const deltaTime ) override ; <nl> virtual void SetTransformation ( CTransformation const & transformation ) override ; <nl> virtual CTransformation const & GetTransformation ( ) const override { return m_transformation ; } <nl> - virtual void SetOcclusion ( float const occlusion ) override ; <nl> + virtual void SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) override ; <nl> virtual void SetOcclusionType ( EOcclusionType const occlusionType ) override { } <nl> <nl> / / Below data is only used when CRY_AUDIO_IMPL_ADX2_USE_DEBUG_CODE is defined ! <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / BaseObject . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / BaseObject . cpp <nl> <nl> # include " ParameterState . h " <nl> # include " ParameterEnvironment . h " <nl> # include " Return . h " <nl> + # include " Listener . h " <nl> <nl> # include < CryAudio / IAudioSystem . h > <nl> <nl> - # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> - # include < Logger . h > <nl> - # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> - <nl> namespace CryAudio <nl> { <nl> namespace Impl <nl> namespace Impl <nl> namespace Fmod <nl> { <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - CBaseObject : : CBaseObject ( ) <nl> - : m_flags ( EObjectFlags : : None ) <nl> + CBaseObject : : CBaseObject ( int const listenerMask , Listeners const & listeners ) <nl> + : m_listenerMask ( listenerMask ) <nl> + , m_flags ( EObjectFlags : : None ) <nl> , m_occlusion ( 0 . 0f ) <nl> , m_absoluteVelocity ( 0 . 0f ) <nl> + , m_listeners ( listeners ) <nl> { <nl> ZeroStruct ( m_attributes ) ; <nl> m_attributes . forward . z = 1 . 0f ; <nl> m_attributes . up . y = 1 . 0f ; <nl> <nl> m_eventInstances . reserve ( 2 ) ; <nl> + <nl> + # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> + UpdateListenerNames ( ) ; <nl> + # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> ERequestStatus CBaseObject : : SetName ( char const * const szName ) <nl> return ERequestStatus : : Success ; <nl> } <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CBaseObject : : AddListener ( IListener * const pIListener ) <nl> + { <nl> + auto const pNewListener = static_cast < CListener * > ( pIListener ) ; <nl> + int const newListenerId = pNewListener - > GetId ( ) ; <nl> + bool hasListener = false ; <nl> + <nl> + for ( auto const pListener : m_listeners ) <nl> + { <nl> + if ( pListener - > GetId ( ) = = newListenerId ) <nl> + { <nl> + hasListener = true ; <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + if ( ! hasListener ) <nl> + { <nl> + m_listenerMask | = BIT ( newListenerId ) ; <nl> + m_listeners . push_back ( pNewListener ) ; <nl> + <nl> + for ( auto const pEventInstance : m_eventInstances ) <nl> + { <nl> + pEventInstance - > SetListenermask ( m_listenerMask ) ; <nl> + } <nl> + <nl> + # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> + UpdateListenerNames ( ) ; <nl> + # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CBaseObject : : RemoveListener ( IListener * const pIListener ) <nl> + { <nl> + auto const pListenerToRemove = static_cast < CListener * > ( pIListener ) ; <nl> + bool wasRemoved = false ; <nl> + <nl> + auto iter ( m_listeners . begin ( ) ) ; <nl> + auto const iterEnd ( m_listeners . cend ( ) ) ; <nl> + <nl> + for ( ; iter ! = iterEnd ; + + iter ) <nl> + { <nl> + CListener * const pListener = * iter ; <nl> + <nl> + if ( pListener = = pListenerToRemove ) <nl> + { <nl> + m_listenerMask & = ~ BIT ( pListenerToRemove - > GetId ( ) ) ; <nl> + <nl> + if ( iter ! = ( iterEnd - 1 ) ) <nl> + { <nl> + ( * iter ) = m_listeners . back ( ) ; <nl> + } <nl> + <nl> + m_listeners . pop_back ( ) ; <nl> + wasRemoved = true ; <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + if ( wasRemoved ) <nl> + { <nl> + for ( auto const pEventInstance : m_eventInstances ) <nl> + { <nl> + pEventInstance - > SetListenermask ( m_listenerMask ) ; <nl> + } <nl> + <nl> + # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> + UpdateListenerNames ( ) ; <nl> + # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> + } <nl> + } <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CBaseObject : : AddEventInstance ( CEventInstance * const pEventInstance ) <nl> { <nl> void CBaseObject : : UpdateVelocityTracking ( ) <nl> <nl> trackVelocity ? ( m_flags | = EObjectFlags : : TrackAbsoluteVelocity ) : ( m_flags & = ~ EObjectFlags : : TrackAbsoluteVelocity ) ; <nl> } <nl> - } / / namespace Fmod <nl> - } / / namespace Impl <nl> - } / / namespace CryAudio <nl> + <nl> + # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CBaseObject : : UpdateListenerNames ( ) <nl> + { <nl> + m_listenerNames . clear ( ) ; <nl> + size_t const numListeners = m_listeners . size ( ) ; <nl> + <nl> + if ( numListeners ! = 0 ) <nl> + { <nl> + for ( size_t i = 0 ; i < numListeners ; + + i ) <nl> + { <nl> + m_listenerNames + = m_listeners [ i ] - > GetName ( ) ; <nl> + <nl> + if ( i ! = ( numListeners - 1 ) ) <nl> + { <nl> + m_listenerNames + = " , " ; <nl> + } <nl> + } <nl> + } <nl> + else <nl> + { <nl> + m_listenerNames = " No Listener ! " ; <nl> + } <nl> + } <nl> + # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> + } / / namespace Fmod <nl> + } / / namespace Impl <nl> + } / / namespace CryAudio <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / BaseObject . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / BaseObject . h <nl> class CBaseObject : public IObject <nl> virtual CTransformation const & GetTransformation ( ) const override { return CTransformation : : GetEmptyObject ( ) ; } <nl> virtual void StopAllTriggers ( ) override ; <nl> virtual ERequestStatus SetName ( char const * const szName ) override ; <nl> + virtual void AddListener ( IListener * const pIListener ) override ; <nl> + virtual void RemoveListener ( IListener * const pIListener ) override ; <nl> <nl> / / Below data is only used when CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE is defined ! <nl> virtual void DrawDebugInfo ( IRenderAuxGeom & auxGeom , float const posX , float posY , char const * const szTextFilter ) override { } <nl> / / ~ CryAudio : : Impl : : IObject <nl> <nl> + int GetListenerMask ( ) const { return m_listenerMask ; } <nl> + <nl> EventInstances const & GetEventInstances ( ) const { return m_eventInstances ; } <nl> FMOD_3D_ATTRIBUTES & GetAttributes ( ) { return m_attributes ; } <nl> <nl> class CBaseObject : public IObject <nl> void RemoveReturn ( CReturn const * const pReturn ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> - char const * GetName ( ) const { return m_name . c_str ( ) ; } <nl> + char const * GetName ( ) const { return m_name . c_str ( ) ; } <nl> + char const * GetListenerNames ( ) const { return m_listenerNames . c_str ( ) ; } <nl> # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> <nl> protected : <nl> <nl> - CBaseObject ( ) ; <nl> + CBaseObject ( int const listenerMask , Listeners const & listeners ) ; <nl> <nl> void UpdateVirtualFlag ( CEventInstance * const pEventInstance ) ; <nl> void UpdateVelocityTracking ( ) ; <nl> <nl> + # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> + void UpdateListenerNames ( ) ; <nl> + # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> + <nl> + int m_listenerMask ; <nl> EObjectFlags m_flags ; <nl> <nl> EventInstances m_eventInstances ; <nl> class CBaseObject : public IObject <nl> float m_occlusion ; <nl> float m_absoluteVelocity ; <nl> <nl> + Listeners m_listeners ; <nl> + <nl> # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> CryFixedStringT < MaxObjectNameLength > m_name ; <nl> + CryFixedStringT < MaxMiscStringLength > m_listenerNames ; <nl> # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> } ; <nl> } / / namespace Fmod <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Common . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Common . cpp <nl> FMOD : : System * g_pCoreSystem = nullptr ; <nl> FMOD : : Studio : : System * g_pStudioSystem = nullptr ; <nl> <nl> CImpl * g_pImpl = nullptr ; <nl> - CGlobalObject * g_pObject = nullptr ; <nl> - CListener * g_pListener = nullptr ; <nl> uint32 g_numObjectsWithDoppler = 0 ; <nl> bool g_masterBusPaused = false ; <nl> Objects g_constructedObjects ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Common . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Common . h <nl> class CEventInstance ; <nl> class CReturn ; <nl> class CListener ; <nl> class CEvent ; <nl> - class CGlobalObject ; <nl> class CParameterInfo ; <nl> <nl> extern FMOD : : System * g_pCoreSystem ; <nl> extern FMOD : : Studio : : System * g_pStudioSystem ; <nl> <nl> extern CImpl * g_pImpl ; <nl> - extern CGlobalObject * g_pObject ; <nl> - extern CListener * g_pListener ; <nl> extern uint32 g_numObjectsWithDoppler ; <nl> <nl> extern bool g_masterBusPaused ; <nl> extern CParameterInfo g_absoluteVelocityParameterInfo ; <nl> <nl> using Objects = std : : vector < CBaseObject * > ; <nl> using EventInstances = std : : vector < CEventInstance * > ; <nl> + using Listeners = std : : vector < CListener * > ; <nl> <nl> using Returns = std : : map < CReturn const * , float > ; <nl> using SnapshotEventInstances = std : : map < uint32 , FMOD : : Studio : : EventInstance * > ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Event . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Event . cpp <nl> ETriggerResult CEvent : : Execute ( IObject * const pIObject , TriggerInstanceId const <nl> FMOD : : Studio : : EventInstance * pFmodEventInstance = nullptr ; <nl> fmodResult = m_pEventDescription - > createInstance ( & pFmodEventInstance ) ; <nl> CRY_AUDIO_IMPL_FMOD_ASSERT_OK ; <nl> + pFmodEventInstance - > setListenerMask ( pBaseObject - > GetListenerMask ( ) ) ; <nl> pEventInstance - > SetFmodEventInstance ( pFmodEventInstance ) ; <nl> <nl> if ( ( m_flags & EEventFlags : : CheckedParameters ) = = 0 ) <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / EventInstance . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / EventInstance . h <nl> class CEventInstance final : public CPoolObject < CEventInstance , stl : : PSyncNone > <nl> FMOD : : Studio : : EventInstance * GetFmodEventInstance ( ) const { return m_pInstance ; } <nl> void SetFmodEventInstance ( FMOD : : Studio : : EventInstance * const pInstance ) { m_pInstance = pInstance ; } <nl> <nl> + void SetListenermask ( int const mask ) { m_pInstance - > setListenerMask ( mask ) ; } <nl> + <nl> bool PrepareForOcclusion ( ) ; <nl> void SetOcclusion ( float const occlusion ) ; <nl> void SetReturnSend ( CReturn const * const pReturn , float const value ) ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / GlobalObject . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / GlobalObject . cpp <nl> namespace Impl <nl> namespace Fmod <nl> { <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - CGlobalObject : : CGlobalObject ( ) <nl> + CGlobalObject : : CGlobalObject ( int const listenerMask , Listeners const & listeners ) <nl> + : CBaseObject ( listenerMask , listeners ) <nl> { <nl> - CRY_ASSERT_MESSAGE ( g_pObject = = nullptr , " g_pObject is not nullptr during % s " , __FUNCTION__ ) ; <nl> - g_pObject = this ; <nl> - <nl> # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> m_name = " Global Object " ; <nl> # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - CGlobalObject : : ~ CGlobalObject ( ) <nl> - { <nl> - g_pObject = nullptr ; <nl> - } <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CGlobalObject : : SetOcclusion ( float const occlusion ) <nl> + void CGlobalObject : : SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) <nl> { <nl> # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> Cry : : Audio : : Log ( ELogType : : Error , " Trying to set occlusion and obstruction values on the global object ! " ) ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / GlobalObject . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / GlobalObject . h <nl> class CGlobalObject final : public CBaseObject <nl> CGlobalObject & operator = ( CGlobalObject const & ) = delete ; <nl> CGlobalObject & operator = ( CGlobalObject & & ) = delete ; <nl> <nl> - CGlobalObject ( ) ; <nl> - virtual ~ CGlobalObject ( ) override ; <nl> + CGlobalObject ( int const listenerMask , Listeners const & listeners ) ; <nl> + virtual ~ CGlobalObject ( ) override = default ; <nl> <nl> / / CryAudio : : Impl : : IObject <nl> - virtual void SetOcclusion ( float const occlusion ) override ; <nl> + virtual void SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) override ; <nl> virtual void SetOcclusionType ( EOcclusionType const occlusionType ) override ; <nl> virtual void ToggleFunctionality ( EObjectFunctionality const type , bool const enable ) override ; <nl> / / ~ CryAudio : : Impl : : IObject <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Impl . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Impl . cpp <nl> SPoolSizes g_poolSizes ; <nl> std : : map < ContextId , SPoolSizes > g_contextPoolSizes ; <nl> std : : vector < SMasterBank > g_masterBanks ; <nl> <nl> + std : : map < int , bool > g_listenerIds ; <nl> + <nl> # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> SPoolSizes g_debugPoolSizes ; <nl> EventInstances g_constructedEventInstances ; <nl> uint16 g_objectPoolSize = 0 ; <nl> uint16 g_eventInstancePoolSize = 0 ; <nl> size_t g_masterBankSize = 0 ; <nl> + std : : vector < CListener * > g_constructedListeners ; <nl> # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> <nl> constexpr char const * g_szEventPrefix = " event : / " ; <nl> ERequestStatus CImpl : : Init ( uint16 const objectPoolSize ) <nl> m_regularSoundBankFolder + = g_szAssetsFolderName ; <nl> m_localizedSoundBankFolder = m_regularSoundBankFolder ; <nl> <nl> + for ( int i = 0 ; i < FMOD_MAX_LISTENERS ; + + i ) <nl> + { <nl> + g_listenerIds . emplace ( i , false ) ; <nl> + } <nl> + <nl> FMOD_RESULT fmodResult = FMOD : : Studio : : System : : create ( & g_pStudioSystem ) ; <nl> CRY_AUDIO_IMPL_FMOD_ASSERT_OK ; <nl> fmodResult = g_pStudioSystem - > getCoreSystem ( & g_pCoreSystem ) ; <nl> ERequestStatus CImpl : : Init ( uint16 const objectPoolSize ) <nl> fmodResult = g_pStudioSystem - > initialize ( g_cvars . m_maxChannels , studioInitFlags , initFlags , pExtraDriverData ) ; <nl> CRY_AUDIO_IMPL_FMOD_ASSERT_OK ; <nl> <nl> - LoadMasterBanks ( ) ; <nl> - <nl> - FMOD_3D_ATTRIBUTES attributes = { <nl> - { 0 } } ; <nl> - attributes . forward . z = 1 . 0f ; <nl> - attributes . up . y = 1 . 0f ; <nl> - fmodResult = g_pStudioSystem - > setListenerAttributes ( 0 , & attributes ) ; <nl> + fmodResult = g_pStudioSystem - > setNumListeners ( FMOD_MAX_LISTENERS ) ; <nl> CRY_AUDIO_IMPL_FMOD_ASSERT_OK ; <nl> <nl> + LoadMasterBanks ( ) ; <nl> + <nl> return ( fmodResult = = FMOD_OK ) ? ERequestStatus : : Success : ERequestStatus : : Failure ; <nl> } <nl> <nl> void CImpl : : GetInfo ( SImplInfo & implInfo ) const <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IObject * CImpl : : ConstructGlobalObject ( ) <nl> + IObject * CImpl : : ConstructGlobalObject ( IListeners const & listeners ) <nl> { <nl> + int const numListeners = listeners . size ( ) ; <nl> + CRY_ASSERT_MESSAGE ( numListeners < = FMOD_MAX_LISTENERS , " Number of listeners ( % d ) exceeded FMOD_MAX_LISTENERS ( % d ) during % s " , numListeners , FMOD_MAX_LISTENERS , __FUNCTION__ ) ; <nl> + <nl> + int listenerMask = 0 ; <nl> + Listeners objectListeners ; <nl> + <nl> + for ( int i = 0 ; ( i < numListeners ) & & ( i < FMOD_MAX_LISTENERS ) ; + + i ) <nl> + { <nl> + auto const pListener = static_cast < CListener * > ( listeners [ i ] ) ; <nl> + listenerMask | = BIT ( pListener - > GetId ( ) ) ; <nl> + objectListeners . emplace_back ( pListener ) ; <nl> + } <nl> + <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : Fmod : : CGlobalObject " ) ; <nl> - new CGlobalObject ; <nl> + auto const pObject = new CGlobalObject ( listenerMask , objectListeners ) ; <nl> <nl> - if ( ! stl : : push_back_unique ( g_constructedObjects , static_cast < CBaseObject * > ( g_pObject ) ) ) <nl> + if ( ! stl : : push_back_unique ( g_constructedObjects , static_cast < CBaseObject * > ( pObject ) ) ) <nl> { <nl> # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> Cry : : Audio : : Log ( ELogType : : Warning , " Trying to construct an already registered object . " ) ; <nl> # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> } <nl> <nl> - return static_cast < IObject * > ( g_pObject ) ; <nl> + return static_cast < IObject * > ( pObject ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IObject * CImpl : : ConstructObject ( CTransformation const & transformation , char const * const szName / * = nullptr * / ) <nl> + IObject * CImpl : : ConstructObject ( CTransformation const & transformation , IListeners const & listeners , char const * const szName / * = nullptr * / ) <nl> { <nl> + int const numListeners = listeners . size ( ) ; <nl> + CRY_ASSERT_MESSAGE ( numListeners < = FMOD_MAX_LISTENERS , " Number of listeners ( % d ) exceeded FMOD_MAX_LISTENERS ( % d ) during % s " , numListeners , FMOD_MAX_LISTENERS , __FUNCTION__ ) ; <nl> + <nl> + int listenerMask = 0 ; <nl> + Listeners objectListeners ; <nl> + <nl> + for ( int i = 0 ; ( i < numListeners ) & & ( i < FMOD_MAX_LISTENERS ) ; + + i ) <nl> + { <nl> + auto const pListener = static_cast < CListener * > ( listeners [ i ] ) ; <nl> + listenerMask | = BIT ( pListener - > GetId ( ) ) ; <nl> + objectListeners . emplace_back ( pListener ) ; <nl> + } <nl> + <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : Fmod : : CObject " ) ; <nl> - CBaseObject * const pObject = new CObject ( transformation ) ; <nl> + CBaseObject * const pObject = new CObject ( transformation , listenerMask , objectListeners ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> if ( szName ! = nullptr ) <nl> void CImpl : : DestructObject ( IObject const * const pIObject ) <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char const * const szName / * = nullptr * / ) <nl> + IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char const * const szName ) <nl> { <nl> - static int id = 0 ; <nl> + int id = FMOD_MAX_LISTENERS ; <nl> + <nl> + for ( auto & listenerIdPair : g_listenerIds ) <nl> + { <nl> + if ( ! listenerIdPair . second ) <nl> + { <nl> + id = listenerIdPair . first ; <nl> + listenerIdPair . second = true ; <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + CRY_ASSERT_MESSAGE ( id < FMOD_MAX_LISTENERS , " Number of listeners ( % d ) exceeded FMOD_MAX_LISTENERS ( % d ) during % s " , id , FMOD_MAX_LISTENERS , __FUNCTION__ ) ; <nl> <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : Fmod : : CListener " ) ; <nl> - g_pListener = new CListener ( transformation , id + + ) ; <nl> + auto const pListener = new CListener ( transformation , id ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> - if ( szName ! = nullptr ) <nl> + pListener - > SetName ( szName ) ; <nl> + <nl> + if ( ! stl : : push_back_unique ( g_constructedListeners , pListener ) ) <nl> { <nl> - g_pListener - > SetName ( szName ) ; <nl> + Cry : : Audio : : Log ( ELogType : : Warning , " Trying to construct an already registered listener . " ) ; <nl> } <nl> # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> <nl> - return static_cast < IListener * > ( g_pListener ) ; <nl> + return static_cast < IListener * > ( pListener ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : DestructListener ( IListener * const pIListener ) <nl> { <nl> - CRY_ASSERT_MESSAGE ( pIListener = = g_pListener , " pIListener is not g_pListener during % s " , __FUNCTION__ ) ; <nl> - delete g_pListener ; <nl> - g_pListener = nullptr ; <nl> + auto const pListener = static_cast < CListener * > ( pIListener ) ; <nl> + g_listenerIds [ pListener - > GetId ( ) ] = false ; <nl> + <nl> + # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> + if ( ! stl : : find_and_erase ( g_constructedListeners , pListener ) ) <nl> + { <nl> + Cry : : Audio : : Log ( ELogType : : Warning , " Trying to delete a non - existing listener . " ) ; <nl> + } <nl> + # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> + <nl> + delete pListener ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : DrawDebugMemoryInfo ( IRenderAuxGeom & auxGeom , float const posX , float <nl> m_name . c_str ( ) , memAllocSizeString . c_str ( ) , totalPoolSizeString . c_str ( ) , totalMasterBankSizeString . c_str ( ) , totalMemSizeString . c_str ( ) ) ; <nl> <nl> size_t const numEvents = g_constructedEventInstances . size ( ) ; <nl> + size_t const numListeners = g_constructedListeners . size ( ) ; <nl> <nl> posY + = Debug : : g_systemLineHeight ; <nl> - auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorTextSecondary , false , " Active Events : % 3 " PRISIZE_T " | Objects with Doppler : % u " , <nl> - numEvents , g_numObjectsWithDoppler ) ; <nl> + auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorTextSecondary , false , " Active Events : % 3 " PRISIZE_T " | Listeners : % " PRISIZE_T " | Objects with Doppler : % u " , <nl> + numEvents , numListeners , g_numObjectsWithDoppler ) ; <nl> <nl> - Vec3 const & listenerPosition = g_pListener - > GetPosition ( ) ; <nl> - Vec3 const & listenerDirection = g_pListener - > GetTransformation ( ) . GetForward ( ) ; <nl> - float const listenerVelocity = g_pListener - > GetVelocity ( ) . GetLength ( ) ; <nl> - char const * const szName = g_pListener - > GetName ( ) ; <nl> + for ( auto const pListener : g_constructedListeners ) <nl> + { <nl> + Vec3 const & listenerPosition = pListener - > GetPosition ( ) ; <nl> + Vec3 const & listenerDirection = pListener - > GetTransformation ( ) . GetForward ( ) ; <nl> + float const listenerVelocity = pListener - > GetVelocity ( ) . GetLength ( ) ; <nl> + char const * const szName = pListener - > GetName ( ) ; <nl> <nl> - posY + = Debug : : g_systemLineHeight ; <nl> - auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorListenerActive , false , " Listener : % s | PosXYZ : % . 2f % . 2f % . 2f | FwdXYZ : % . 2f % . 2f % . 2f | Velocity : % . 2f m / s " , <nl> - szName , listenerPosition . x , listenerPosition . y , listenerPosition . z , listenerDirection . x , listenerDirection . y , listenerDirection . z , listenerVelocity ) ; <nl> + posY + = Debug : : g_systemLineHeight ; <nl> + auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorListenerActive , false , " Listener : % s | PosXYZ : % . 2f % . 2f % . 2f | FwdXYZ : % . 2f % . 2f % . 2f | Velocity : % . 2f m / s " , <nl> + szName , listenerPosition . x , listenerPosition . y , listenerPosition . z , listenerDirection . x , listenerDirection . y , listenerDirection . z , listenerVelocity ) ; <nl> + } <nl> # endif / / CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , float const debugDistance , char const * const szTextFilter ) const <nl> + void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , Vec3 const & camPos , float const debugDistance , char const * const szTextFilter ) const <nl> { <nl> # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> if ( ( g_cvars . m_debugListFilter & g_debugListMask ) ! = 0 ) <nl> void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , <nl> for ( auto const pEventInstance : g_constructedEventInstances ) <nl> { <nl> Vec3 const & position = pEventInstance - > GetObject ( ) . GetTransformation ( ) . GetPosition ( ) ; <nl> - float const distance = position . GetDistance ( g_pListener - > GetPosition ( ) ) ; <nl> + float const distance = position . GetDistance ( camPos ) ; <nl> <nl> if ( ( debugDistance < = 0 . 0f ) | | ( ( debugDistance > 0 . 0f ) & & ( distance < debugDistance ) ) ) <nl> { <nl> void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , <nl> color = Debug : : s_listColorItemStopping ; <nl> } <nl> <nl> - auxGeom . Draw2dLabel ( posX , posY , Debug : : g_listFontSize , color , false , " % s on % s " , szEventName , pEventInstance - > GetObject ( ) . GetName ( ) ) ; <nl> + auxGeom . Draw2dLabel ( posX , posY , Debug : : g_listFontSize , color , false , " % s on % s ( % s ) " , <nl> + szEventName , pEventInstance - > GetObject ( ) . GetName ( ) , pEventInstance - > GetObject ( ) . GetListenerNames ( ) ) ; <nl> <nl> posY + = Debug : : g_listLineHeight ; <nl> } <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Impl . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Impl . h <nl> class CImpl final : public IImpl <nl> virtual void DestructEnvironmentConnection ( IEnvironmentConnection const * const pIEnvironmentConnection ) override ; <nl> virtual ISettingConnection * ConstructSettingConnection ( XmlNodeRef const & rootNode ) override ; <nl> virtual void DestructSettingConnection ( ISettingConnection const * const pISettingConnection ) override ; <nl> - virtual IObject * ConstructGlobalObject ( ) override ; <nl> - virtual IObject * ConstructObject ( CTransformation const & transformation , char const * const szName = nullptr ) override ; <nl> + virtual IObject * ConstructGlobalObject ( IListeners const & listeners ) override ; <nl> + virtual IObject * ConstructObject ( CTransformation const & transformation , IListeners const & listeners , char const * const szName = nullptr ) override ; <nl> virtual void DestructObject ( IObject const * const pIObject ) override ; <nl> - virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName = nullptr ) override ; <nl> + virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName ) override ; <nl> virtual void DestructListener ( IListener * const pIListener ) override ; <nl> virtual void GamepadConnected ( DeviceId const deviceUniqueID ) override ; <nl> virtual void GamepadDisconnected ( DeviceId const deviceUniqueID ) override ; <nl> class CImpl final : public IImpl <nl> <nl> / / Below data is only used when CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE is defined ! <nl> virtual void DrawDebugMemoryInfo ( IRenderAuxGeom & auxGeom , float const posX , float & posY , bool const drawDetailedInfo ) override ; <nl> - virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , float const debugDistance , char const * const szTextFilter ) const override ; <nl> + virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , Vec3 const & camPos , float const debugDistance , char const * const szTextFilter ) const override ; <nl> / / ~ CryAudio : : Impl : : IImpl <nl> <nl> # if defined ( CRY_AUDIO_IMPL_FMOD_USE_DEBUG_CODE ) <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Object . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Object . cpp <nl> namespace Impl <nl> namespace Fmod <nl> { <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - CObject : : CObject ( CTransformation const & transformation ) <nl> - : m_transformation ( transformation ) <nl> + CObject : : CObject ( CTransformation const & transformation , int const listenerMask , Listeners const & listeners ) <nl> + : CBaseObject ( listenerMask , listeners ) <nl> + , m_transformation ( transformation ) <nl> , m_previousAbsoluteVelocity ( 0 . 0f ) <nl> + , m_lowestOcclusionPerListener ( 1 . 0f ) <nl> , m_position ( transformation . GetPosition ( ) ) <nl> , m_previousPosition ( transformation . GetPosition ( ) ) <nl> , m_velocity ( ZERO ) <nl> void CObject : : SetTransformation ( CTransformation const & transformation ) <nl> m_previousPosition = m_position ; <nl> } <nl> <nl> - float const threshold = m_position . GetDistance ( g_pListener - > GetPosition ( ) ) * g_cvars . m_positionUpdateThresholdMultiplier ; <nl> + float const threshold = GetDistanceToListener ( ) * g_cvars . m_positionUpdateThresholdMultiplier ; <nl> <nl> if ( ! m_transformation . IsEquivalent ( transformation , threshold ) ) <nl> { <nl> void CObject : : SetTransformation ( CTransformation const & transformation ) <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CObject : : SetOcclusion ( float const occlusion ) <nl> + void CObject : : SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) <nl> { <nl> - SetParameter ( g_occlusionParameterInfo , occlusion ) ; <nl> + / / Lowest occlusion value of all listeners is used . <nl> + m_lowestOcclusionPerListener = std : : min ( m_lowestOcclusionPerListener , occlusion ) ; <nl> <nl> - for ( auto const pEventInstance : m_eventInstances ) <nl> + if ( numRemainingListeners = = 1 ) <nl> { <nl> - pEventInstance - > SetOcclusion ( occlusion ) ; <nl> - } <nl> + SetParameter ( g_occlusionParameterInfo , m_lowestOcclusionPerListener ) ; <nl> + <nl> + for ( auto const pEventInstance : m_eventInstances ) <nl> + { <nl> + pEventInstance - > SetOcclusion ( m_lowestOcclusionPerListener ) ; <nl> + } <nl> <nl> - m_occlusion = occlusion ; <nl> + m_occlusion = m_lowestOcclusionPerListener ; <nl> + m_lowestOcclusionPerListener = 1 . 0f ; <nl> + } <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CObject : : UpdateVelocities ( float const deltaTime ) <nl> } <nl> } <nl> } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + float CObject : : GetDistanceToListener ( ) <nl> + { <nl> + float shortestDistanceToListener = std : : numeric_limits < float > : : max ( ) ; <nl> + <nl> + for ( auto const pListener : m_listeners ) <nl> + { <nl> + float const distance = m_position . GetDistance ( pListener - > GetPosition ( ) ) ; <nl> + shortestDistanceToListener = std : : min ( shortestDistanceToListener , distance ) ; <nl> + } <nl> + <nl> + return shortestDistanceToListener ; <nl> + } <nl> } / / namespace Fmod <nl> } / / namespace Impl <nl> } / / namespace CryAudio <nl> \ No newline at end of file <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Object . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplFmod / Object . h <nl> class CObject final : public CBaseObject , public CPoolObject < CObject , stl : : PSync <nl> CObject & operator = ( CObject const & ) = delete ; <nl> CObject & operator = ( CObject & & ) = delete ; <nl> <nl> - explicit CObject ( CTransformation const & transformation ) ; <nl> + explicit CObject ( CTransformation const & transformation , int const listenerMask , Listeners const & listeners ) ; <nl> virtual ~ CObject ( ) override ; <nl> <nl> / / CryAudio : : Impl : : IObject <nl> virtual void Update ( float const deltaTime ) override ; <nl> virtual void SetTransformation ( CTransformation const & transformation ) override ; <nl> virtual CTransformation const & GetTransformation ( ) const override { return m_transformation ; } <nl> - virtual void SetOcclusion ( float const occlusion ) override ; <nl> + virtual void SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) override ; <nl> virtual void SetOcclusionType ( EOcclusionType const occlusionType ) override ; <nl> virtual void ToggleFunctionality ( EObjectFunctionality const type , bool const enable ) override ; <nl> <nl> class CObject final : public CBaseObject , public CPoolObject < CObject , stl : : PSync <nl> <nl> private : <nl> <nl> - void Set3DAttributes ( ) ; <nl> - void UpdateVelocities ( float const deltaTime ) ; <nl> + void Set3DAttributes ( ) ; <nl> + void UpdateVelocities ( float const deltaTime ) ; <nl> + float GetDistanceToListener ( ) ; <nl> <nl> CTransformation m_transformation ; <nl> float m_previousAbsoluteVelocity ; <nl> + float m_lowestOcclusionPerListener ; <nl> Vec3 m_position ; <nl> Vec3 m_previousPosition ; <nl> Vec3 m_velocity ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplPortAudio / Common . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplPortAudio / Common . cpp <nl> namespace Impl <nl> namespace PortAudio <nl> { <nl> CImpl * g_pImpl = nullptr ; <nl> - CListener * g_pListener = nullptr ; <nl> } / / namespace PortAudio <nl> } / / namespace Impl <nl> } / / namespace CryAudio <nl> \ No newline at end of file <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplPortAudio / Common . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplPortAudio / Common . h <nl> namespace Impl <nl> namespace PortAudio <nl> { <nl> class CImpl ; <nl> - class CListener ; <nl> class CEventInstance ; <nl> <nl> extern CImpl * g_pImpl ; <nl> - extern CListener * g_pListener ; <nl> <nl> using EventInstances = std : : vector < CEventInstance * > ; <nl> } / / namespace PortAudio <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplPortAudio / Impl . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplPortAudio / Impl . cpp <nl> uint16 g_debugEventrPoolSize = 0 ; <nl> uint16 g_objectPoolSize = 0 ; <nl> uint16 g_eventInstancePoolSize = 0 ; <nl> EventInstances g_constructedEventInstances ; <nl> + std : : vector < CListener * > g_constructedListeners ; <nl> # endif / / CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : GetInfo ( SImplInfo & implInfo ) const <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IObject * CImpl : : ConstructGlobalObject ( ) <nl> + IObject * CImpl : : ConstructGlobalObject ( IListeners const & listeners ) <nl> { <nl> - MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : PortAudio : : CObject " ) ; <nl> - auto pObject = new CObject ( ) ; <nl> - <nl> - # if defined ( CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE ) <nl> - pObject - > SetName ( " Global Object " ) ; <nl> - # endif / / CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE <nl> - <nl> - stl : : push_back_unique ( g_constructedObjects , pObject ) ; <nl> - <nl> - return static_cast < IObject * > ( pObject ) ; <nl> + return ConstructObject ( CTransformation : : GetEmptyObject ( ) , listeners , " Global Object " ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IObject * CImpl : : ConstructObject ( CTransformation const & transformation , char const * const szName / * = nullptr * / ) <nl> + IObject * CImpl : : ConstructObject ( CTransformation const & transformation , IListeners const & listeners , char const * const szName / * = nullptr * / ) <nl> { <nl> + auto const pListener = static_cast < CListener * > ( listeners [ 0 ] ) ; <nl> + <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : PortAudio : : CObject " ) ; <nl> - auto const pObject = new CObject ( ) ; <nl> + auto const pObject = new CObject ( pListener ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE ) <nl> pObject - > SetName ( szName ) ; <nl> + <nl> + if ( listeners . size ( ) > 1 ) <nl> + { <nl> + Cry : : Audio : : Log ( ELogType : : Warning , R " ( More than one listener is passed in % s . Port Audio supports only one listener per object . Listener " % s " will be used for object " % s " . ) " , <nl> + __FUNCTION__ , pListener - > GetName ( ) , pObject - > GetName ( ) ) ; <nl> + } <nl> # endif / / CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE <nl> <nl> stl : : push_back_unique ( g_constructedObjects , pObject ) ; <nl> void CImpl : : DestructObject ( IObject const * const pIObject ) <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char const * const szName / * = nullptr * / ) <nl> + IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char const * const szName ) <nl> { <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : PortAudio : : CListener " ) ; <nl> - g_pListener = new CListener ( transformation ) ; <nl> + auto const pListener = new CListener ( transformation ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE ) <nl> - g_pListener - > SetName ( szName ) ; <nl> + pListener - > SetName ( szName ) ; <nl> + g_constructedListeners . push_back ( pListener ) ; <nl> # endif / / CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE <nl> <nl> - return static_cast < IListener * > ( g_pListener ) ; <nl> + return static_cast < IListener * > ( pListener ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : DestructListener ( IListener * const pIListener ) <nl> { <nl> - CRY_ASSERT_MESSAGE ( pIListener = = g_pListener , " pIListener is not g_pListener during % s " , __FUNCTION__ ) ; <nl> - delete g_pListener ; <nl> - g_pListener = nullptr ; <nl> + auto const pListener = static_cast < CListener * > ( pIListener ) ; <nl> + <nl> + # if defined ( CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE ) <nl> + auto iter ( g_constructedListeners . begin ( ) ) ; <nl> + auto const iterEnd ( g_constructedListeners . cend ( ) ) ; <nl> + <nl> + for ( ; iter ! = iterEnd ; + + iter ) <nl> + { <nl> + if ( ( * iter ) = = pListener ) <nl> + { <nl> + if ( iter ! = ( iterEnd - 1 ) ) <nl> + { <nl> + ( * iter ) = g_constructedListeners . back ( ) ; <nl> + } <nl> + <nl> + g_constructedListeners . pop_back ( ) ; <nl> + break ; <nl> + } <nl> + } <nl> + # endif / / CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE <nl> + <nl> + delete pListener ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : DrawDebugMemoryInfo ( IRenderAuxGeom & auxGeom , float const posX , float <nl> m_name . c_str ( ) , memAllocSizeString . c_str ( ) , totalPoolSizeString . c_str ( ) , totalMemSizeString . c_str ( ) ) ; <nl> <nl> size_t const numEvents = g_constructedEventInstances . size ( ) ; <nl> + size_t const numListeners = g_constructedListeners . size ( ) ; <nl> <nl> posY + = Debug : : g_systemLineHeight ; <nl> - auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorTextSecondary , false , " Active Events : % " PRISIZE_T , numEvents ) ; <nl> + auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorTextSecondary , false , " Active Events : % 3 " PRISIZE_T " | Listeners : % " PRISIZE_T , numEvents , numListeners ) ; <nl> <nl> - Vec3 const & listenerPosition = g_pListener - > GetTransformation ( ) . GetPosition ( ) ; <nl> - Vec3 const & listenerDirection = g_pListener - > GetTransformation ( ) . GetForward ( ) ; <nl> - char const * const szName = g_pListener - > GetName ( ) ; <nl> + for ( auto const pListener : g_constructedListeners ) <nl> + { <nl> + Vec3 const & listenerPosition = pListener - > GetTransformation ( ) . GetPosition ( ) ; <nl> + Vec3 const & listenerDirection = pListener - > GetTransformation ( ) . GetForward ( ) ; <nl> + char const * const szName = pListener - > GetName ( ) ; <nl> <nl> - posY + = Debug : : g_systemLineHeight ; <nl> - auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorListenerActive , false , " Listener : % s | PosXYZ : % . 2f % . 2f % . 2f | FwdXYZ : % . 2f % . 2f % . 2f " , szName , listenerPosition . x , listenerPosition . y , listenerPosition . z , listenerDirection . x , listenerDirection . y , listenerDirection . z ) ; <nl> + posY + = Debug : : g_systemLineHeight ; <nl> + auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorListenerActive , false , " Listener : % s | PosXYZ : % . 2f % . 2f % . 2f | FwdXYZ : % . 2f % . 2f % . 2f " , <nl> + szName , listenerPosition . x , listenerPosition . y , listenerPosition . z , listenerDirection . x , listenerDirection . y , listenerDirection . z ) ; <nl> + } <nl> # endif / / CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , float const debugDistance , char const * const szTextFilter ) const <nl> + void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , Vec3 const & camPos , float const debugDistance , char const * const szTextFilter ) const <nl> { <nl> # if defined ( CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE ) <nl> CryFixedStringT < MaxControlNameLength > lowerCaseSearchString ( szTextFilter ) ; <nl> void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , <nl> for ( auto const pEventInstance : g_constructedEventInstances ) <nl> { <nl> Vec3 const & position = pEventInstance - > GetObject ( ) . GetTransformation ( ) . GetPosition ( ) ; <nl> - float const distance = position . GetDistance ( g_pListener - > GetTransformation ( ) . GetPosition ( ) ) ; <nl> + float const distance = position . GetDistance ( camPos ) ; <nl> <nl> if ( ( debugDistance < = 0 . 0f ) | | ( ( debugDistance > 0 . 0f ) & & ( distance < debugDistance ) ) ) <nl> { <nl> void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , <nl> <nl> if ( draw ) <nl> { <nl> - auxGeom . Draw2dLabel ( posX , posY , Debug : : g_listFontSize , Debug : : s_listColorItemActive , false , " % s on % s " , szEventName , pEventInstance - > GetObject ( ) . GetName ( ) ) ; <nl> + char const * const szListenerName = ( pEventInstance - > GetObject ( ) . GetListener ( ) ! = nullptr ) ? pEventInstance - > GetObject ( ) . GetListener ( ) - > GetName ( ) : " No Listener ! " ; <nl> + <nl> + auxGeom . Draw2dLabel ( posX , posY , Debug : : g_listFontSize , Debug : : s_listColorItemActive , false , " % s on % s ( % s ) " , <nl> + szEventName , pEventInstance - > GetObject ( ) . GetName ( ) , szListenerName ) ; <nl> <nl> posY + = Debug : : g_listLineHeight ; <nl> } <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplPortAudio / Impl . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplPortAudio / Impl . h <nl> class CImpl final : public IImpl <nl> virtual void DestructEnvironmentConnection ( IEnvironmentConnection const * const pIEnvironmentConnection ) override ; <nl> virtual ISettingConnection * ConstructSettingConnection ( XmlNodeRef const & rootNode ) override ; <nl> virtual void DestructSettingConnection ( ISettingConnection const * const pISettingConnection ) override ; <nl> - virtual IObject * ConstructGlobalObject ( ) override ; <nl> - virtual IObject * ConstructObject ( CTransformation const & transformation , char const * const szName = nullptr ) override ; <nl> + virtual IObject * ConstructGlobalObject ( IListeners const & listeners ) override ; <nl> + virtual IObject * ConstructObject ( CTransformation const & transformation , IListeners const & listeners , char const * const szName = nullptr ) override ; <nl> virtual void DestructObject ( IObject const * const pIObject ) override ; <nl> - virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName = nullptr ) override ; <nl> + virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName ) override ; <nl> virtual void DestructListener ( IListener * const pIListener ) override ; <nl> virtual void GamepadConnected ( DeviceId const deviceUniqueID ) override ; <nl> virtual void GamepadDisconnected ( DeviceId const deviceUniqueID ) override ; <nl> class CImpl final : public IImpl <nl> <nl> / / Below data is only used when CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE is defined ! <nl> virtual void DrawDebugMemoryInfo ( IRenderAuxGeom & auxGeom , float const posX , float & posY , bool const drawDetailedInfo ) override ; <nl> - virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , float const debugDistance , char const * const szTextFilter ) const override ; <nl> + virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , Vec3 const & camPos , float const debugDistance , char const * const szTextFilter ) const override ; <nl> / / ~ CryAudio : : Impl : : IImpl <nl> <nl> # if defined ( CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE ) <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplPortAudio / Object . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplPortAudio / Object . cpp <nl> <nl> # include " Object . h " <nl> # include " Event . h " <nl> # include " EventInstance . h " <nl> + # include " Listener . h " <nl> # include " Impl . h " <nl> # include < CryAudio / IAudioSystem . h > <nl> <nl> void CObject : : SetTransformation ( CTransformation const & transformation ) <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CObject : : SetOcclusion ( float const occlusion ) <nl> + void CObject : : SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) <nl> { <nl> } <nl> <nl> ERequestStatus CObject : : SetName ( char const * const szName ) <nl> return ERequestStatus : : Success ; <nl> } <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CObject : : AddListener ( IListener * const pIListener ) <nl> + { <nl> + m_pListener = static_cast < CListener * > ( pIListener ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CObject : : RemoveListener ( IListener * const pIListener ) <nl> + { <nl> + if ( m_pListener = = static_cast < CListener * > ( pIListener ) ) <nl> + { <nl> + m_pListener = nullptr ; <nl> + } <nl> + } <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CObject : : ToggleFunctionality ( EObjectFunctionality const type , bool const enable ) <nl> { <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplPortAudio / Object . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplPortAudio / Object . h <nl> namespace Impl <nl> namespace PortAudio <nl> { <nl> class CEventInstance ; <nl> + class CListener ; <nl> <nl> class CObject final : public IObject , public CPoolObject < CObject , stl : : PSyncNone > <nl> { <nl> class CObject final : public IObject , public CPoolObject < CObject , stl : : PSyncNone <nl> CObject & operator = ( CObject const & ) = delete ; <nl> CObject & operator = ( CObject & & ) = delete ; <nl> <nl> - CObject ( ) = default ; <nl> + CObject ( CListener * const pListener ) <nl> + : m_pListener ( pListener ) <nl> + { } <nl> + <nl> virtual ~ CObject ( ) override = default ; <nl> <nl> / / CryAudio : : Impl : : IObject <nl> virtual void Update ( float const deltaTime ) override ; <nl> virtual void SetTransformation ( CTransformation const & transformation ) override ; <nl> virtual CTransformation const & GetTransformation ( ) const override { return CTransformation : : GetEmptyObject ( ) ; } <nl> - virtual void SetOcclusion ( float const occlusion ) override ; <nl> + virtual void SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) override ; <nl> virtual void SetOcclusionType ( EOcclusionType const occlusionType ) override ; <nl> virtual void StopAllTriggers ( ) override ; <nl> virtual ERequestStatus SetName ( char const * const szName ) override ; <nl> + virtual void AddListener ( IListener * const pIListener ) override ; <nl> + virtual void RemoveListener ( IListener * const pIListener ) override ; <nl> virtual void ToggleFunctionality ( EObjectFunctionality const type , bool const enable ) override ; <nl> <nl> / / Below data is only used when CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE is defined ! <nl> virtual void DrawDebugInfo ( IRenderAuxGeom & auxGeom , float const posX , float posY , char const * const szTextFilter ) override ; <nl> / / ~ CryAudio : : Impl : : IObject <nl> <nl> - void StopEvent ( uint32 const pathId ) ; <nl> - void RegisterEventInstance ( CEventInstance * const pEventInstance ) ; <nl> + CListener * GetListener ( ) const { return m_pListener ; } <nl> + <nl> + void StopEvent ( uint32 const pathId ) ; <nl> + void RegisterEventInstance ( CEventInstance * const pEventInstance ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE ) <nl> char const * GetName ( ) const { return m_name . c_str ( ) ; } <nl> class CObject final : public IObject , public CPoolObject < CObject , stl : : PSyncNone <nl> <nl> private : <nl> <nl> + CListener * m_pListener ; <nl> EventInstances m_eventInstances ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_PORTAUDIO_USE_DEBUG_CODE ) <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Common . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Common . cpp <nl> namespace SDL_mixer <nl> { <nl> bool g_bMuted = false ; <nl> CImpl * g_pImpl = nullptr ; <nl> - CListener * g_pListener = nullptr ; <nl> - CObject * g_pObject = nullptr ; <nl> Objects g_objects ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Common . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Common . h <nl> namespace SDL_mixer <nl> { <nl> class CEventInstance ; <nl> class CImpl ; <nl> - class CListener ; <nl> class CObject ; <nl> class CEvent ; <nl> <nl> extern bool g_bMuted ; <nl> extern CImpl * g_pImpl ; <nl> - extern CListener * g_pListener ; <nl> - extern CObject * g_pObject ; <nl> <nl> using SampleId = uint ; <nl> using ChannelList = std : : vector < int > ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Impl . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Impl . cpp <nl> uint16 g_objectPoolSize = 0 ; <nl> uint16 g_eventInstancePoolSize = 0 ; <nl> <nl> EventInstances g_constructedEventInstances ; <nl> + std : : vector < CListener * > g_constructedListeners ; <nl> # endif / / CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : DestructSettingConnection ( ISettingConnection const * const pISettingC <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IObject * CImpl : : ConstructGlobalObject ( ) <nl> + IObject * CImpl : : ConstructGlobalObject ( IListeners const & listeners ) <nl> { <nl> - MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : SDL_mixer : : CObject " ) ; <nl> - g_pObject = new CObject ( CTransformation : : GetEmptyObject ( ) , 0 ) ; <nl> - <nl> - # if defined ( CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE ) <nl> - g_pObject - > SetName ( " Global Object " ) ; <nl> - # endif / / CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE <nl> - <nl> - g_objects . push_back ( g_pObject ) ; <nl> - return static_cast < IObject * > ( g_pObject ) ; <nl> + return ConstructObject ( CTransformation : : GetEmptyObject ( ) , listeners , " Global Object " ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IObject * CImpl : : ConstructObject ( CTransformation const & transformation , char const * const szName / * = nullptr * / ) <nl> + IObject * CImpl : : ConstructObject ( CTransformation const & transformation , IListeners const & listeners , char const * const szName / * = nullptr * / ) <nl> { <nl> - static uint32 id = 1 ; <nl> + auto const pListener = static_cast < CListener * > ( listeners [ 0 ] ) ; <nl> <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : SDL_mixer : : CObject " ) ; <nl> - auto const pObject = new CObject ( transformation , id + + ) ; <nl> + auto const pObject = new CObject ( transformation , pListener ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE ) <nl> if ( szName ! = nullptr ) <nl> { <nl> pObject - > SetName ( szName ) ; <nl> } <nl> + <nl> + if ( listeners . size ( ) > 1 ) <nl> + { <nl> + Cry : : Audio : : Log ( ELogType : : Warning , R " ( More than one listener is passed in % s . SDL Mixer supports only one listener per object . Listener " % s " will be used for object " % s " . ) " , <nl> + __FUNCTION__ , pListener - > GetName ( ) , pObject - > GetName ( ) ) ; <nl> + } <nl> # endif / / CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE <nl> <nl> g_objects . push_back ( pObject ) ; <nl> void CImpl : : DestructObject ( IObject const * const pIObject ) <nl> { <nl> auto const pObject = static_cast < CObject const * > ( pIObject ) ; <nl> stl : : find_and_erase ( g_objects , pObject ) ; <nl> - <nl> - if ( pObject = = g_pObject ) <nl> - { <nl> - delete pObject ; <nl> - g_pObject = nullptr ; <nl> - } <nl> - else <nl> - { <nl> - delete pObject ; <nl> - } <nl> + delete pObject ; <nl> } <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char const * const szName / * = nullptr * / ) <nl> + IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char const * const szName ) <nl> { <nl> - static ListenerId id = 0 ; <nl> - <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : SDL_mixer : : CListener " ) ; <nl> - g_pListener = new CListener ( transformation , id + + ) ; <nl> + auto const pListener = new CListener ( transformation ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE ) <nl> - g_pListener - > SetName ( szName ) ; <nl> + pListener - > SetName ( szName ) ; <nl> + g_constructedListeners . push_back ( pListener ) ; <nl> # endif / / CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE <nl> <nl> - return static_cast < IListener * > ( g_pListener ) ; <nl> + return static_cast < IListener * > ( pListener ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : DestructListener ( IListener * const pIListener ) <nl> { <nl> - CRY_ASSERT_MESSAGE ( pIListener = = g_pListener , " pIListener is not g_pListener during % s " , __FUNCTION__ ) ; <nl> - delete g_pListener ; <nl> - g_pListener = nullptr ; <nl> + auto const pListener = static_cast < CListener * > ( pIListener ) ; <nl> + <nl> + # if defined ( CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE ) <nl> + auto iter ( g_constructedListeners . begin ( ) ) ; <nl> + auto const iterEnd ( g_constructedListeners . cend ( ) ) ; <nl> + <nl> + for ( ; iter ! = iterEnd ; + + iter ) <nl> + { <nl> + if ( ( * iter ) = = pListener ) <nl> + { <nl> + if ( iter ! = ( iterEnd - 1 ) ) <nl> + { <nl> + ( * iter ) = g_constructedListeners . back ( ) ; <nl> + } <nl> + <nl> + g_constructedListeners . pop_back ( ) ; <nl> + break ; <nl> + } <nl> + } <nl> + # endif / / CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE <nl> + <nl> + delete pListener ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : DrawDebugMemoryInfo ( IRenderAuxGeom & auxGeom , float const posX , float <nl> m_name . c_str ( ) , memAllocSizeString . c_str ( ) , totalPoolSizeString . c_str ( ) , totalSamplesString . c_str ( ) , totalMemSizeString . c_str ( ) ) ; <nl> <nl> size_t const numEvents = g_constructedEventInstances . size ( ) ; <nl> + size_t const numListeners = g_constructedListeners . size ( ) ; <nl> <nl> posY + = Debug : : g_systemLineHeight ; <nl> - auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorTextSecondary , false , " Active Events : % " PRISIZE_T , numEvents ) ; <nl> + auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorTextSecondary , false , " Active Events : % 3 " PRISIZE_T " | Listeners : % " PRISIZE_T , numEvents , numListeners ) ; <nl> <nl> - Vec3 const & listenerPosition = g_pListener - > GetTransformation ( ) . GetPosition ( ) ; <nl> - Vec3 const & listenerDirection = g_pListener - > GetTransformation ( ) . GetForward ( ) ; <nl> - char const * const szName = g_pListener - > GetName ( ) ; <nl> + for ( auto const pListener : g_constructedListeners ) <nl> + { <nl> + Vec3 const & listenerPosition = pListener - > GetTransformation ( ) . GetPosition ( ) ; <nl> + Vec3 const & listenerDirection = pListener - > GetTransformation ( ) . GetForward ( ) ; <nl> + char const * const szName = pListener - > GetName ( ) ; <nl> <nl> - posY + = Debug : : g_systemLineHeight ; <nl> - auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorListenerActive , false , " Listener : % s | PosXYZ : % . 2f % . 2f % . 2f | FwdXYZ : % . 2f % . 2f % . 2f " , szName , listenerPosition . x , listenerPosition . y , listenerPosition . z , listenerDirection . x , listenerDirection . y , listenerDirection . z ) ; <nl> + posY + = Debug : : g_systemLineHeight ; <nl> + auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorListenerActive , false , " Listener : % s | PosXYZ : % . 2f % . 2f % . 2f | FwdXYZ : % . 2f % . 2f % . 2f " , <nl> + szName , listenerPosition . x , listenerPosition . y , listenerPosition . z , listenerDirection . x , listenerDirection . y , listenerDirection . z ) ; <nl> + } <nl> # endif / / CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , float const debugDistance , char const * const szTextFilter ) const <nl> + void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , Vec3 const & camPos , float const debugDistance , char const * const szTextFilter ) const <nl> { <nl> # if defined ( CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE ) <nl> CryFixedStringT < MaxControlNameLength > lowerCaseSearchString ( szTextFilter ) ; <nl> void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , <nl> for ( auto const pEventInstance : g_constructedEventInstances ) <nl> { <nl> Vec3 const & position = pEventInstance - > GetObject ( ) . GetTransformation ( ) . GetPosition ( ) ; <nl> - float const distance = position . GetDistance ( g_pListener - > GetTransformation ( ) . GetPosition ( ) ) ; <nl> + float const distance = position . GetDistance ( camPos ) ; <nl> <nl> if ( ( debugDistance < = 0 . 0f ) | | ( ( debugDistance > 0 . 0f ) & & ( distance < debugDistance ) ) ) <nl> { <nl> void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , <nl> if ( draw ) <nl> { <nl> ColorF color = Debug : : s_listColorItemActive ; <nl> + char const * const szListenerName = ( pEventInstance - > GetObject ( ) . GetListener ( ) ! = nullptr ) ? pEventInstance - > GetObject ( ) . GetListener ( ) - > GetName ( ) : " No Listener ! " ; <nl> <nl> CryFixedStringT < MaxMiscStringLength > debugText ; <nl> - debugText . Format ( " % s on % s " , szEventName , pEventInstance - > GetObject ( ) . GetName ( ) ) ; <nl> + debugText . Format ( " % s on % s ( % s ) " , szEventName , pEventInstance - > GetObject ( ) . GetName ( ) , szListenerName ) ; <nl> <nl> if ( pEventInstance - > IsFadingOut ( ) ) <nl> { <nl> float const fadeOutTime = static_cast < float > ( pEventInstance - > GetEvent ( ) . GetFadeOutTime ( ) ) / 1000 . 0f ; <nl> float const remainingTime = std : : max ( 0 . 0f , fadeOutTime - ( gEnv - > pTimer - > GetAsyncTime ( ) . GetSeconds ( ) - pEventInstance - > GetTimeFadeOutStarted ( ) ) ) ; <nl> <nl> - debugText . Format ( " % s on % s ( % . 2f sec ) " , szEventName , pEventInstance - > GetObject ( ) . GetName ( ) , remainingTime ) ; <nl> + debugText . Format ( " % s on % s ( % s ) ( % . 2f sec ) " , szEventName , pEventInstance - > GetObject ( ) . GetName ( ) , szListenerName , remainingTime ) ; <nl> color = Debug : : s_listColorItemStopping ; <nl> } <nl> <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Impl . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Impl . h <nl> class CImpl final : public IImpl <nl> virtual void DestructEnvironmentConnection ( IEnvironmentConnection const * const pIEnvironmentConnection ) override ; <nl> virtual ISettingConnection * ConstructSettingConnection ( XmlNodeRef const & rootNode ) override ; <nl> virtual void DestructSettingConnection ( ISettingConnection const * const pISettingConnection ) override ; <nl> - virtual IObject * ConstructGlobalObject ( ) override ; <nl> - virtual IObject * ConstructObject ( CTransformation const & transformation , char const * const szName = nullptr ) override ; <nl> + virtual IObject * ConstructGlobalObject ( IListeners const & listeners ) override ; <nl> + virtual IObject * ConstructObject ( CTransformation const & transformation , IListeners const & listeners , char const * const szName = nullptr ) override ; <nl> virtual void DestructObject ( IObject const * const pIObject ) override ; <nl> - virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName = nullptr ) override ; <nl> + virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName ) override ; <nl> virtual void DestructListener ( IListener * const pIListener ) override ; <nl> virtual void GamepadConnected ( DeviceId const deviceUniqueID ) override ; <nl> virtual void GamepadDisconnected ( DeviceId const deviceUniqueID ) override ; <nl> class CImpl final : public IImpl <nl> <nl> / / Below data is only used when INCLUDE_AUDIO_PRODUCTION_CODE is defined ! <nl> virtual void DrawDebugMemoryInfo ( IRenderAuxGeom & auxGeom , float const posX , float & posY , bool const drawDetailedInfo ) override ; <nl> - virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , float const debugDistance , char const * const szTextFilter ) const override ; <nl> + virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , Vec3 const & camPos , float const debugDistance , char const * const szTextFilter ) const override ; <nl> / / ~ CryAudio : : Impl : : IImpl <nl> <nl> # if defined ( CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE ) <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Listener . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Listener . h <nl> namespace Impl <nl> { <nl> namespace SDL_mixer <nl> { <nl> - using ListenerId = uint ; <nl> - <nl> class CListener final : public IListener <nl> { <nl> public : <nl> class CListener final : public IListener <nl> CListener & operator = ( CListener const & ) = delete ; <nl> CListener & operator = ( CListener & & ) = delete ; <nl> <nl> - explicit CListener ( CTransformation const & transformation , ListenerId const id ) <nl> + explicit CListener ( CTransformation const & transformation ) <nl> : m_transformation ( transformation ) <nl> - , m_id ( id ) <nl> { } <nl> <nl> virtual ~ CListener ( ) override = default ; <nl> class CListener final : public IListener <nl> <nl> private : <nl> <nl> - CTransformation m_transformation ; <nl> - ListenerId const m_id ; <nl> + CTransformation m_transformation ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE ) <nl> CryFixedStringT < MaxObjectNameLength > m_name ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Object . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Object . cpp <nl> void CObject : : Update ( float const deltaTime ) <nl> { <nl> float distance = 0 . 0f ; <nl> float angle = 0 . 0f ; <nl> - GetDistanceAngleToObject ( g_pListener - > GetTransformation ( ) , m_transformation , distance , angle ) ; <nl> + <nl> + if ( m_pListener ! = nullptr ) <nl> + { <nl> + GetDistanceAngleToObject ( m_pListener - > GetTransformation ( ) , m_transformation , distance , angle ) ; <nl> + } <nl> <nl> auto iter ( m_eventInstances . begin ( ) ) ; <nl> auto iterEnd ( m_eventInstances . end ( ) ) ; <nl> ERequestStatus CObject : : SetName ( char const * const szName ) <nl> return ERequestStatus : : Success ; <nl> } <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CObject : : AddListener ( IListener * const pIListener ) <nl> + { <nl> + m_pListener = static_cast < CListener * > ( pIListener ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CObject : : RemoveListener ( IListener * const pIListener ) <nl> + { <nl> + if ( m_pListener = = static_cast < CListener * > ( pIListener ) ) <nl> + { <nl> + m_pListener = nullptr ; <nl> + } <nl> + } <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CObject : : StopEvent ( uint32 const id ) <nl> { <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Object . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / Object . h <nl> namespace Impl <nl> { <nl> namespace SDL_mixer <nl> { <nl> + class CListener ; <nl> + <nl> using VolumeMultipliers = std : : map < SampleId , float > ; <nl> <nl> class CObject final : public IObject , public CPoolObject < CObject , stl : : PSyncNone > <nl> class CObject final : public IObject , public CPoolObject < CObject , stl : : PSyncNone <nl> CObject & operator = ( CObject const & ) = delete ; <nl> CObject & operator = ( CObject & & ) = delete ; <nl> <nl> - explicit CObject ( CTransformation const & transformation , uint32 const id ) <nl> - : m_id ( id ) <nl> + explicit CObject ( CTransformation const & transformation , CListener * const pListener ) <nl> + : m_pListener ( pListener ) <nl> , m_transformation ( transformation ) <nl> { } <nl> <nl> class CObject final : public IObject , public CPoolObject < CObject , stl : : PSyncNone <nl> <nl> / / CryAudio : : Impl : : IObject <nl> virtual void Update ( float const deltaTime ) override ; <nl> - virtual void SetTransformation ( CTransformation const & transformation ) override { m_transformation = transformation ; } <nl> - virtual CTransformation const & GetTransformation ( ) const override { return m_transformation ; } <nl> - virtual void SetOcclusion ( float const occlusion ) override { } <nl> - virtual void SetOcclusionType ( EOcclusionType const occlusionType ) override { } <nl> + virtual void SetTransformation ( CTransformation const & transformation ) override { m_transformation = transformation ; } <nl> + virtual CTransformation const & GetTransformation ( ) const override { return m_transformation ; } <nl> + virtual void SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) override { } <nl> + virtual void SetOcclusionType ( EOcclusionType const occlusionType ) override { } <nl> virtual void StopAllTriggers ( ) override ; <nl> virtual ERequestStatus SetName ( char const * const szName ) override ; <nl> + virtual void AddListener ( IListener * const pIListener ) override ; <nl> + virtual void RemoveListener ( IListener * const pIListener ) override ; <nl> virtual void ToggleFunctionality ( EObjectFunctionality const type , bool const enable ) override { } <nl> <nl> / / Below data is only used when CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE is defined ! <nl> virtual void DrawDebugInfo ( IRenderAuxGeom & auxGeom , float const posX , float posY , char const * const szTextFilter ) override { } <nl> / / ~ CryAudio : : Impl : : IObject <nl> <nl> - void StopEvent ( uint32 const id ) ; <nl> - void SetVolume ( SampleId const sampleId , float const value ) ; <nl> + CListener * GetListener ( ) const { return m_pListener ; } <nl> + <nl> + void StopEvent ( uint32 const id ) ; <nl> + void SetVolume ( SampleId const sampleId , float const value ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE ) <nl> char const * GetName ( ) const { return m_name . c_str ( ) ; } <nl> class CObject final : public IObject , public CPoolObject < CObject , stl : : PSyncNone <nl> <nl> private : <nl> <nl> - uint32 const m_id ; <nl> + CListener * m_pListener ; <nl> CTransformation m_transformation ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_SDLMIXER_USE_DEBUG_CODE ) <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / SoundEngine . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplSDLMixer / SoundEngine . cpp <nl> ETriggerResult SoundEngine : : ExecuteEvent ( CObject * const pObject , CEvent * const p <nl> / / Get distance and angle from the listener to the object <nl> float distance = 0 . 0f ; <nl> float angle = 0 . 0f ; <nl> - GetDistanceAngleToObject ( g_pListener - > GetTransformation ( ) , pObject - > GetTransformation ( ) , distance , angle ) ; <nl> + <nl> + if ( pObject - > GetListener ( ) ! = nullptr ) <nl> + { <nl> + GetDistanceAngleToObject ( pObject - > GetListener ( ) - > GetTransformation ( ) , pObject - > GetTransformation ( ) , distance , angle ) ; <nl> + } <nl> + <nl> SetChannelPosition ( pEventInstance - > GetEvent ( ) , channelID , distance , angle ) ; <nl> <nl> g_channels [ channelID ] . pObject = pObject ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / BaseObject . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / BaseObject . cpp <nl> namespace Wwise <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> CBaseObject : : CBaseObject ( <nl> AkGameObjectID const id , <nl> + ListenerInfos const & listenerInfos , <nl> char const * const szName / * = nullptr * / , <nl> Vec3 const & position / * = { 0 . 0f , 0 . 0f , 0 . 0f } * / ) <nl> : m_id ( id ) <nl> , m_flags ( EObjectFlags : : None ) <nl> , m_position ( position ) <nl> - , m_distanceToListener ( 0 . 0f ) <nl> + , m_shortestDistanceToListener ( 0 . 0f ) <nl> + , m_listenerInfos ( listenerInfos ) <nl> # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> , m_name ( szName ) <nl> # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> { <nl> m_eventInstances . reserve ( 2 ) ; <nl> + SetListeners ( ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CBaseObject : : Update ( float const deltaTime ) <nl> { <nl> # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> / / Always update in production code for debug draw . <nl> - pEventInstance - > UpdateVirtualState ( m_distanceToListener ) ; <nl> + pEventInstance - > UpdateVirtualState ( m_shortestDistanceToListener ) ; <nl> <nl> if ( pEventInstance - > GetState ( ) ! = EEventInstanceState : : Virtual ) <nl> { <nl> void CBaseObject : : Update ( float const deltaTime ) <nl> # else <nl> if ( ( ( m_flags & EObjectFlags : : IsVirtual ) ! = 0 ) & & ( ( m_flags & EObjectFlags : : UpdateVirtualStates ) ! = 0 ) ) <nl> { <nl> - pEventInstance - > UpdateVirtualState ( m_distanceToListener ) ; <nl> + pEventInstance - > UpdateVirtualState ( m_shortestDistanceToListener ) ; <nl> <nl> if ( pEventInstance - > GetState ( ) ! = EEventInstanceState : : Virtual ) <nl> { <nl> void CBaseObject : : AddEventInstance ( CEventInstance * const pEventInstance ) <nl> { <nl> SetDistanceToListener ( ) ; <nl> <nl> - pEventInstance - > UpdateVirtualState ( m_distanceToListener ) ; <nl> + pEventInstance - > UpdateVirtualState ( m_shortestDistanceToListener ) ; <nl> <nl> if ( ( m_flags & EObjectFlags : : IsVirtual ) ! = 0 ) <nl> { <nl> ERequestStatus CBaseObject : : SetName ( char const * const szName ) <nl> # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> } <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CBaseObject : : AddListener ( IListener * const pIListener ) <nl> + { <nl> + auto const pListener = static_cast < CListener * > ( pIListener ) ; <nl> + float const distance = m_position . GetDistance ( pListener - > GetPosition ( ) ) ; <nl> + <nl> + m_listenerInfos . emplace_back ( pListener , distance ) ; <nl> + <nl> + SetListeners ( ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CBaseObject : : RemoveListener ( IListener * const pIListener ) <nl> + { <nl> + auto const pListener = static_cast < CListener * > ( pIListener ) ; <nl> + bool wasRemoved = false ; <nl> + <nl> + auto iter ( m_listenerInfos . begin ( ) ) ; <nl> + auto const iterEnd ( m_listenerInfos . cend ( ) ) ; <nl> + <nl> + for ( ; iter ! = iterEnd ; + + iter ) <nl> + { <nl> + SListenerInfo const & info = * iter ; <nl> + <nl> + if ( info . pListener = = pListener ) <nl> + { <nl> + if ( iter ! = ( iterEnd - 1 ) ) <nl> + { <nl> + ( * iter ) = m_listenerInfos . back ( ) ; <nl> + } <nl> + <nl> + m_listenerInfos . pop_back ( ) ; <nl> + wasRemoved = true ; <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + if ( wasRemoved ) <nl> + { <nl> + SetListeners ( ) ; <nl> + } <nl> + } <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CBaseObject : : StopEvent ( AkUniqueID const eventId ) <nl> { <nl> void CBaseObject : : StopEvent ( AkUniqueID const eventId ) <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CBaseObject : : SetDistanceToListener ( ) <nl> { <nl> - m_distanceToListener = m_position . GetDistance ( g_pListener - > GetPosition ( ) ) ; <nl> + m_shortestDistanceToListener = std : : numeric_limits < float > : : max ( ) ; <nl> + <nl> + for ( auto & listenerInfo : m_listenerInfos ) <nl> + { <nl> + listenerInfo . distance = m_position . GetDistance ( listenerInfo . pListener - > GetPosition ( ) ) ; <nl> + m_shortestDistanceToListener = std : : min ( m_shortestDistanceToListener , listenerInfo . distance ) ; <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CBaseObject : : SetListeners ( ) <nl> + { <nl> + size_t const numListeners = m_listenerInfos . size ( ) ; <nl> + AkGameObjectID * const listenerIds = new AkGameObjectID [ numListeners ] ; <nl> + <nl> + for ( size_t i = 0 ; i < numListeners ; + + i ) <nl> + { <nl> + AkGameObjectID const id = m_listenerInfos [ i ] . pListener - > GetId ( ) ; <nl> + listenerIds [ i ] = id ; <nl> + } <nl> + <nl> + AK : : SoundEngine : : SetListeners ( m_id , listenerIds , static_cast < AkUInt32 > ( numListeners ) ) ; <nl> + delete [ ] listenerIds ; <nl> + <nl> + # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> + UpdateListenerNames ( ) ; <nl> + # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> + } <nl> + <nl> + # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CBaseObject : : UpdateListenerNames ( ) <nl> + { <nl> + m_listenerNames . clear ( ) ; <nl> + size_t const numListeners = m_listenerInfos . size ( ) ; <nl> + <nl> + if ( numListeners ! = 0 ) <nl> + { <nl> + for ( size_t i = 0 ; i < numListeners ; + + i ) <nl> + { <nl> + m_listenerNames + = m_listenerInfos [ i ] . pListener - > GetName ( ) ; <nl> + <nl> + if ( i ! = ( numListeners - 1 ) ) <nl> + { <nl> + m_listenerNames + = " , " ; <nl> + } <nl> + } <nl> + } <nl> + else <nl> + { <nl> + m_listenerNames = " No Listener ! " ; <nl> + } <nl> } <nl> - } / / namespace Wwise <nl> - } / / namespace Impl <nl> - } / / namespace CryAudio <nl> + # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> + } / / namespace Wwise <nl> + } / / namespace Impl <nl> + } / / namespace CryAudio <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / BaseObject . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / BaseObject . h <nl> <nl> # pragma once <nl> <nl> # include " Common . h " <nl> + # include " ListenerInfo . h " <nl> # include < IObject . h > <nl> - # include < AK / SoundEngine / Common / AkTypes . h > <nl> <nl> namespace CryAudio <nl> { <nl> class CBaseObject : public IObject <nl> <nl> / / CryAudio : : Impl : : IObject <nl> virtual void Update ( float const deltaTime ) override ; <nl> - virtual void SetTransformation ( CTransformation const & transformation ) override { } <nl> - virtual CTransformation const & GetTransformation ( ) const override { return CTransformation : : GetEmptyObject ( ) ; } <nl> - virtual void SetOcclusion ( float const occlusion ) override { } <nl> - virtual void SetOcclusionType ( EOcclusionType const occlusionType ) override { } <nl> + virtual void SetTransformation ( CTransformation const & transformation ) override { } <nl> + virtual CTransformation const & GetTransformation ( ) const override { return CTransformation : : GetEmptyObject ( ) ; } <nl> + virtual void SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) override { } <nl> + virtual void SetOcclusionType ( EOcclusionType const occlusionType ) override { } <nl> virtual void StopAllTriggers ( ) override ; <nl> virtual ERequestStatus SetName ( char const * const szName ) override ; <nl> + virtual void AddListener ( IListener * const pIListener ) override ; <nl> + virtual void RemoveListener ( IListener * const pIListener ) override ; <nl> virtual void ToggleFunctionality ( EObjectFunctionality const type , bool const enable ) override { } <nl> <nl> / / Below data is only used when CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE is defined ! <nl> class CBaseObject : public IObject <nl> void StopEvent ( AkUniqueID const eventId ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> - char const * GetName ( ) const { return m_name . c_str ( ) ; } <nl> + char const * GetName ( ) const { return m_name . c_str ( ) ; } <nl> + char const * GetListenerNames ( ) const { return m_listenerNames . c_str ( ) ; } <nl> # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> <nl> protected : <nl> <nl> explicit CBaseObject ( <nl> AkGameObjectID const id , <nl> + ListenerInfos const & listenerInfos , <nl> char const * const szName = nullptr , <nl> Vec3 const & position = { 0 . 0f , 0 . 0f , 0 . 0f } ) ; <nl> <nl> void SetDistanceToListener ( ) ; <nl> + void SetListeners ( ) ; <nl> + <nl> + # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> + void UpdateListenerNames ( ) ; <nl> + # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> <nl> AkGameObjectID const m_id ; <nl> EObjectFlags m_flags ; <nl> Vec3 m_position ; <nl> - float m_distanceToListener ; <nl> + float m_shortestDistanceToListener ; <nl> + ListenerInfos m_listenerInfos ; <nl> EventInstances m_eventInstances ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> CryFixedStringT < MaxObjectNameLength > m_name ; <nl> + CryFixedStringT < MaxMiscStringLength > m_listenerNames ; <nl> # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> } ; <nl> } / / namespace Wwise <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / CMakeLists . txt <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / CMakeLists . txt <nl> add_sources ( " CryAudioImpl_uber_0 . cpp " <nl> " GlobalObject . h " <nl> " Impl . h " <nl> " Listener . h " <nl> + " ListenerInfo . h " <nl> " Object . h " <nl> " Parameter . h " <nl> " ParameterEnvironment . h " <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / Common . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / Common . cpp <nl> namespace Impl <nl> namespace Wwise <nl> { <nl> CImpl * g_pImpl = nullptr ; <nl> - CListener * g_pListener = nullptr ; <nl> - CGlobalObject * g_pObject = nullptr ; <nl> <nl> AkGameObjectID g_listenerId = AK_INVALID_GAME_OBJECT ; / / To be removed once multi - listener support is implemented . <nl> AkGameObjectID g_globalObjectId = AK_INVALID_GAME_OBJECT ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / Common . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / Common . h <nl> namespace Wwise <nl> class CImpl ; <nl> class CListener ; <nl> class CBaseObject ; <nl> - class CGlobalObject ; <nl> class CEventInstance ; <nl> <nl> extern CImpl * g_pImpl ; <nl> - extern CListener * g_pListener ; <nl> - extern CGlobalObject * g_pObject ; <nl> <nl> extern uint32 g_numObjectsWithRelativeVelocity ; <nl> <nl> using EventInstances = std : : vector < CEventInstance * > ; <nl> + using Listeners = std : : vector < CListener * > ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> inline void FillAKVector ( Vec3 const & vCryVector , AkVector & vAKVector ) <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / GlobalObject . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / GlobalObject . cpp <nl> void CGlobalObject : : SetTransformation ( CTransformation const & transformation ) <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CGlobalObject : : SetOcclusion ( float const occlusion ) <nl> + void CGlobalObject : : SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) <nl> { <nl> # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> Cry : : Audio : : Log ( ELogType : : Error , " Trying to set occlusion and obstruction values on the global object ! " ) ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / GlobalObject . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / GlobalObject . h <nl> class CGlobalObject final : public CBaseObject <nl> CGlobalObject & operator = ( CGlobalObject & & ) = delete ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> - CGlobalObject ( AkGameObjectID const id , char const * const szName ) <nl> - : CBaseObject ( id , szName ) <nl> + CGlobalObject ( AkGameObjectID const id , ListenerInfos const & listenerInfos , char const * const szName ) <nl> + : CBaseObject ( id , listenerInfos , szName ) <nl> { } <nl> # else <nl> - CGlobalObject ( AkGameObjectID const id ) <nl> - : CBaseObject ( id ) <nl> + CGlobalObject ( AkGameObjectID const id , ListenerInfos const & listenerInfos ) <nl> + : CBaseObject ( id , listenerInfos ) <nl> { } <nl> # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> <nl> class CGlobalObject final : public CBaseObject <nl> <nl> / / CryAudio : : Impl : : IObject <nl> virtual void SetTransformation ( CTransformation const & transformation ) override ; <nl> - virtual void SetOcclusion ( float const occlusion ) override ; <nl> + virtual void SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) override ; <nl> virtual void SetOcclusionType ( EOcclusionType const occlusionType ) override ; <nl> / / ~ CryAudio : : Impl : : IObject <nl> } ; <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / Impl . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / Impl . cpp <nl> <nl> # include " ParameterEnvironment . h " <nl> # include " ParameterState . h " <nl> # include " Listener . h " <nl> + # include " ListenerInfo . h " <nl> # include " Object . h " <nl> # include " GlobalObject . h " <nl> # include " SoundBank . h " <nl> SPoolSizes g_debugPoolSizes ; <nl> EventInstances g_constructedEventInstances ; <nl> uint16 g_objectPoolSize = 0 ; <nl> uint16 g_eventInstancePoolSize = 0 ; <nl> + std : : vector < CListener * > g_constructedListeners ; <nl> # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : GetInfo ( SImplInfo & implInfo ) const <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IObject * CImpl : : ConstructGlobalObject ( ) <nl> + IObject * CImpl : : ConstructGlobalObject ( IListeners const & listeners ) <nl> { <nl> g_globalObjectId = m_gameObjectId + + ; <nl> <nl> + ListenerInfos listenerInfos ; <nl> + int const numListeners = listeners . size ( ) ; <nl> + <nl> + for ( int i = 0 ; i < numListeners ; + + i ) <nl> + { <nl> + listenerInfos . emplace_back ( static_cast < CListener * > ( listeners [ i ] ) , 0 . 0f ) ; <nl> + } <nl> + <nl> # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> char const * const szName = " GlobalObject " ; <nl> AK : : SoundEngine : : RegisterGameObj ( g_globalObjectId , szName ) ; <nl> <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : Wwise : : CGlobalObject " ) ; <nl> - g_pObject = new CGlobalObject ( g_globalObjectId , szName ) ; <nl> + auto const pObject = new CGlobalObject ( g_globalObjectId , listenerInfos , szName ) ; <nl> <nl> { <nl> CryAutoLock < CryCriticalSection > const lock ( CryAudio : : Impl : : Wwise : : g_cs ) ; <nl> - g_gameObjectIds [ g_globalObjectId ] = g_pObject ; <nl> + g_gameObjectIds [ g_globalObjectId ] = pObject ; <nl> } <nl> # else <nl> AK : : SoundEngine : : RegisterGameObj ( g_globalObjectId ) ; <nl> <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : Wwise : : CGlobalObject " ) ; <nl> - g_pObject = new CGlobalObject ( g_globalObjectId ) ; <nl> + auto const pObject = new CGlobalObject ( g_globalObjectId , listenerInfos ) ; <nl> # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> <nl> - return static_cast < IObject * > ( g_pObject ) ; <nl> + return static_cast < IObject * > ( pObject ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IObject * CImpl : : ConstructObject ( CTransformation const & transformation , char const * const szName / * = nullptr * / ) <nl> + IObject * CImpl : : ConstructObject ( CTransformation const & transformation , IListeners const & listeners , char const * const szName / * = nullptr * / ) <nl> { <nl> # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> AK : : SoundEngine : : RegisterGameObj ( m_gameObjectId , szName ) ; <nl> IObject * CImpl : : ConstructObject ( CTransformation const & transformation , char cons <nl> AK : : SoundEngine : : RegisterGameObj ( m_gameObjectId ) ; <nl> # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> <nl> + ListenerInfos listenerInfos ; <nl> + int const numListeners = listeners . size ( ) ; <nl> + <nl> + for ( int i = 0 ; i < numListeners ; + + i ) <nl> + { <nl> + listenerInfos . emplace_back ( static_cast < CListener * > ( listeners [ i ] ) , 0 . 0f ) ; <nl> + } <nl> + <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : Wwise : : CObject " ) ; <nl> - auto const pObject = new CObject ( m_gameObjectId + + , transformation , szName ) ; <nl> + auto const pObject = new CObject ( m_gameObjectId + + , transformation , listenerInfos , szName ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> { <nl> void CImpl : : DestructObject ( IObject const * const pIObject ) <nl> # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> <nl> delete pBaseObject ; <nl> - <nl> - if ( objectID = = g_globalObjectId ) <nl> - { <nl> - g_pObject = nullptr ; <nl> - } <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char const * const szName / * = nullptr * / ) <nl> + IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char const * const szName ) <nl> { <nl> IListener * pIListener = nullptr ; <nl> <nl> IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char <nl> AK : : SoundEngine : : SetDefaultListeners ( & m_gameObjectId , 1 ) ; <nl> <nl> MEMSTAT_CONTEXT ( EMemStatContextType : : AudioImpl , " CryAudio : : Impl : : Wwise : : CListener " ) ; <nl> - g_pListener = new CListener ( transformation , m_gameObjectId ) ; <nl> + auto const pListener = new CListener ( transformation , m_gameObjectId + + ) ; <nl> <nl> # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> - g_pListener - > SetName ( szName ) ; <nl> + pListener - > SetName ( szName ) ; <nl> + g_constructedListeners . push_back ( pListener ) ; <nl> # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> <nl> - pIListener = static_cast < IListener * > ( g_pListener ) ; <nl> - g_listenerId = m_gameObjectId + + ; <nl> + pIListener = static_cast < IListener * > ( pListener ) ; <nl> <nl> return pIListener ; <nl> } <nl> IListener * CImpl : : ConstructListener ( CTransformation const & transformation , char <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : DestructListener ( IListener * const pIListener ) <nl> { <nl> - CRY_ASSERT_MESSAGE ( pIListener = = g_pListener , " pIListener is not g_pListener during % s " , __FUNCTION__ ) ; <nl> + auto const pListener = static_cast < CListener * > ( pIListener ) ; <nl> + AK : : SoundEngine : : UnregisterGameObj ( pListener - > GetId ( ) ) ; <nl> + <nl> + # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> + auto iter ( g_constructedListeners . begin ( ) ) ; <nl> + auto const iterEnd ( g_constructedListeners . cend ( ) ) ; <nl> <nl> - AK : : SoundEngine : : UnregisterGameObj ( g_pListener - > GetId ( ) ) ; <nl> + for ( ; iter ! = iterEnd ; + + iter ) <nl> + { <nl> + if ( ( * iter ) = = pListener ) <nl> + { <nl> + if ( iter ! = ( iterEnd - 1 ) ) <nl> + { <nl> + ( * iter ) = g_constructedListeners . back ( ) ; <nl> + } <nl> + <nl> + g_constructedListeners . pop_back ( ) ; <nl> + break ; <nl> + } <nl> + } <nl> + # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> <nl> - delete g_pListener ; <nl> - g_pListener = nullptr ; <nl> + delete pListener ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CImpl : : DrawDebugMemoryInfo ( IRenderAuxGeom & auxGeom , float const posX , float <nl> m_name . c_str ( ) , memAllocSizeString . c_str ( ) , totalPoolSizeString . c_str ( ) , initBankSizeString . c_str ( ) , totalMemSizeString . c_str ( ) ) ; <nl> <nl> size_t const numEvents = g_constructedEventInstances . size ( ) ; <nl> + size_t const numListeners = g_constructedListeners . size ( ) ; <nl> <nl> posY + = Debug : : g_systemLineHeight ; <nl> - auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorTextSecondary , false , " Active Events : % 3 " PRISIZE_T " | Objects with relative velocity calculation : % u " , <nl> - numEvents , g_numObjectsWithRelativeVelocity ) ; <nl> + auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorTextSecondary , false , " Active Events : % 3 " PRISIZE_T " | Listeners : % 3 " PRISIZE_T " | Objects with relative velocity calculation : % u " , <nl> + numEvents , numListeners , g_numObjectsWithRelativeVelocity ) ; <nl> <nl> - Vec3 const & listenerPosition = g_pListener - > GetPosition ( ) ; <nl> - Vec3 const & listenerDirection = g_pListener - > GetTransformation ( ) . GetForward ( ) ; <nl> - float const listenerVelocity = g_pListener - > GetVelocity ( ) . GetLength ( ) ; <nl> - char const * const szName = g_pListener - > GetName ( ) ; <nl> + for ( auto const pListener : g_constructedListeners ) <nl> + { <nl> + Vec3 const & listenerPosition = pListener - > GetPosition ( ) ; <nl> + Vec3 const & listenerDirection = pListener - > GetTransformation ( ) . GetForward ( ) ; <nl> + float const listenerVelocity = pListener - > GetVelocity ( ) . GetLength ( ) ; <nl> + char const * const szName = pListener - > GetName ( ) ; <nl> <nl> - posY + = Debug : : g_systemLineHeight ; <nl> - auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorListenerActive , false , " Listener : % s | PosXYZ : % . 2f % . 2f % . 2f | FwdXYZ : % . 2f % . 2f % . 2f | Velocity : % . 2f m / s " , <nl> - szName , listenerPosition . x , listenerPosition . y , listenerPosition . z , listenerDirection . x , listenerDirection . y , listenerDirection . z , listenerVelocity ) ; <nl> + posY + = Debug : : g_systemLineHeight ; <nl> + auxGeom . Draw2dLabel ( posX , posY , Debug : : g_systemFontSize , Debug : : s_systemColorListenerActive , false , " Listener : % s | PosXYZ : % . 2f % . 2f % . 2f | FwdXYZ : % . 2f % . 2f % . 2f | Velocity : % . 2f m / s " , <nl> + szName , listenerPosition . x , listenerPosition . y , listenerPosition . z , listenerDirection . x , listenerDirection . y , listenerDirection . z , listenerVelocity ) ; <nl> + } <nl> <nl> # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , float const debugDistance , char const * const szTextFilter ) const <nl> + void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , Vec3 const & camPos , float const debugDistance , char const * const szTextFilter ) const <nl> { <nl> # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> if ( ( g_cvars . m_debugListFilter & g_debugListMask ) ! = 0 ) <nl> void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , <nl> for ( auto const pEventInstance : g_constructedEventInstances ) <nl> { <nl> Vec3 const & position = pEventInstance - > GetObject ( ) . GetTransformation ( ) . GetPosition ( ) ; <nl> - float const distance = position . GetDistance ( g_pListener - > GetPosition ( ) ) ; <nl> + float const distance = position . GetDistance ( camPos ) ; <nl> <nl> if ( ( debugDistance < = 0 . 0f ) | | ( ( debugDistance > 0 . 0f ) & & ( distance < debugDistance ) ) ) <nl> { <nl> void CImpl : : DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , <nl> if ( draw ) <nl> { <nl> ColorF const & color = ( pEventInstance - > GetState ( ) = = EEventInstanceState : : Virtual ) ? Debug : : s_globalColorVirtual : Debug : : s_listColorItemActive ; <nl> - auxGeom . Draw2dLabel ( posX , posY , Debug : : g_listFontSize , color , false , " % s on % s " , szEventName , pEventInstance - > GetObject ( ) . GetName ( ) ) ; <nl> + auxGeom . Draw2dLabel ( posX , posY , Debug : : g_listFontSize , color , false , " % s on % s ( % s ) " , <nl> + szEventName , pEventInstance - > GetObject ( ) . GetName ( ) , pEventInstance - > GetObject ( ) . GetListenerNames ( ) ) ; <nl> <nl> posY + = Debug : : g_listLineHeight ; <nl> } <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / Impl . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / Impl . h <nl> class CImpl final : public IImpl <nl> virtual void DestructEnvironmentConnection ( IEnvironmentConnection const * const pIEnvironmentConnection ) override ; <nl> virtual ISettingConnection * ConstructSettingConnection ( XmlNodeRef const & rootNode ) override ; <nl> virtual void DestructSettingConnection ( ISettingConnection const * const pISettingConnection ) override ; <nl> - virtual IObject * ConstructGlobalObject ( ) override ; <nl> - virtual IObject * ConstructObject ( CTransformation const & transformation , char const * const szName = nullptr ) override ; <nl> + virtual IObject * ConstructGlobalObject ( IListeners const & listeners ) override ; <nl> + virtual IObject * ConstructObject ( CTransformation const & transformation , IListeners const & listeners , char const * const szName = nullptr ) override ; <nl> virtual void DestructObject ( IObject const * const pIObject ) override ; <nl> - virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName = nullptr ) override ; <nl> + virtual IListener * ConstructListener ( CTransformation const & transformation , char const * const szName ) override ; <nl> virtual void DestructListener ( IListener * const pIListener ) override ; <nl> <nl> / / Below data is only used when CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE is defined ! <nl> virtual void DrawDebugMemoryInfo ( IRenderAuxGeom & auxGeom , float const posX , float & posY , bool const drawDetailedInfo ) override ; <nl> - virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , float const debugDistance , char const * const szTextFilter ) const override ; <nl> + virtual void DrawDebugInfoList ( IRenderAuxGeom & auxGeom , float & posX , float posY , Vec3 const & camPos , float const debugDistance , char const * const szTextFilter ) const override ; <nl> / / ~ CryAudio : : Impl : : IImpl <nl> <nl> # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> new file mode 100644 <nl> index 0000000000 . . 4b63c7f108 <nl> mmm / dev / null <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / ListenerInfo . h <nl> <nl> + / / Copyright 2001 - 2018 Crytek GmbH / Crytek Group . All rights reserved . <nl> + <nl> + # pragma once <nl> + <nl> + # include < AK / SoundEngine / Common / AkTypes . h > <nl> + <nl> + namespace CryAudio <nl> + { <nl> + namespace Impl <nl> + { <nl> + namespace Wwise <nl> + { <nl> + class CListener ; <nl> + <nl> + struct SListenerInfo final <nl> + { <nl> + explicit SListenerInfo ( CListener * const pListener_ , float const distance_ ) <nl> + : pListener ( pListener_ ) <nl> + , distance ( distance_ ) <nl> + { } <nl> + <nl> + CListener * pListener ; <nl> + float distance ; <nl> + } ; <nl> + <nl> + using ListenerInfos = std : : vector < SListenerInfo > ; <nl> + } / / namespace Wwise <nl> + } / / namespace Impl <nl> + } / / namespace CryAudio <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / Object . cpp <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / Object . cpp <nl> constexpr char const * g_szRelativeVelocityParameterName = " relative_velocity " ; <nl> static AkRtpcID const s_relativeVelocityParameterId = AK : : SoundEngine : : GetIDFromString ( g_szRelativeVelocityParameterName ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - CObject : : CObject ( AkGameObjectID const id , CTransformation const & transformation , char const * const szName ) <nl> - : CBaseObject ( id , szName , transformation . GetPosition ( ) ) <nl> + CObject : : CObject ( <nl> + AkGameObjectID const id , <nl> + CTransformation const & transformation , <nl> + ListenerInfos const & listenerInfos , <nl> + char const * const szName ) <nl> + : CBaseObject ( id , listenerInfos , szName , transformation . GetPosition ( ) ) <nl> , m_needsToUpdateAuxSends ( false ) <nl> , m_previousRelativeVelocity ( 0 . 0f ) <nl> , m_previousAbsoluteVelocity ( 0 . 0f ) <nl> void CObject : : SetTransformation ( CTransformation const & transformation ) <nl> m_previousPosition = m_position ; <nl> } <nl> <nl> - float const threshold = m_distanceToListener * g_cvars . m_positionUpdateThresholdMultiplier ; <nl> + float const threshold = m_shortestDistanceToListener * g_cvars . m_positionUpdateThresholdMultiplier ; <nl> <nl> if ( ! m_transformation . IsEquivalent ( transformation , threshold ) ) <nl> { <nl> void CObject : : SetTransformation ( CTransformation const & transformation ) <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - void CObject : : SetOcclusion ( float const occlusion ) <nl> + void CObject : : SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) <nl> { <nl> - if ( g_listenerId ! = AK_INVALID_GAME_OBJECT ) <nl> - { <nl> - AK : : SoundEngine : : SetObjectObstructionAndOcclusion ( <nl> - m_id , <nl> - g_listenerId , / / Set occlusion for only the default listener for now . <nl> - static_cast < AkReal32 > ( occlusion ) , / / The occlusion value is currently used on obstruction as well until a correct obstruction value is calculated . <nl> - static_cast < AkReal32 > ( occlusion ) ) ; <nl> - } <nl> - # if defined ( CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE ) <nl> - else <nl> - { <nl> - Cry : : Audio : : Log ( ELogType : : Warning , " Wwise - invalid listener Id during % s ! " , __FUNCTION__ ) ; <nl> - } <nl> - # endif / / CRY_AUDIO_IMPL_WWISE_USE_DEBUG_CODE <nl> + auto const pListener = static_cast < CListener * > ( pIListener ) ; <nl> + <nl> + AK : : SoundEngine : : SetObjectObstructionAndOcclusion ( <nl> + m_id , <nl> + pListener - > GetId ( ) , / / Set occlusion for only the default listener for now . <nl> + static_cast < AkReal32 > ( occlusion ) , / / The occlusion value is currently used on obstruction as well until a correct obstruction value is calculated . <nl> + static_cast < AkReal32 > ( occlusion ) ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void CObject : : UpdateVelocities ( float const deltaTime ) <nl> <nl> if ( ( m_flags & EObjectFlags : : TrackRelativeVelocity ) ! = 0 ) <nl> { <nl> - / / Approaching positive , departing negative value . <nl> + / / Approaching positive , departing negative value . Highest value of all listeners is used . <nl> float relativeVelocity = 0 . 0f ; <nl> <nl> - if ( ( ( m_flags & EObjectFlags : : MovingOrDecaying ) ! = 0 ) & & ! g_pListener - > HasMoved ( ) ) <nl> + for ( auto const & info : m_listenerInfos ) <nl> { <nl> - relativeVelocity = - m_velocity . Dot ( ( m_position - g_pListener - > GetPosition ( ) ) . GetNormalized ( ) ) ; <nl> - } <nl> - else if ( ( ( m_flags & EObjectFlags : : MovingOrDecaying ) ! = 0 ) & & g_pListener - > HasMoved ( ) ) <nl> - { <nl> - Vec3 const relativeVelocityVec ( m_velocity - g_pListener - > GetVelocity ( ) ) ; <nl> - relativeVelocity = - relativeVelocityVec . Dot ( ( m_position - g_pListener - > GetPosition ( ) ) . GetNormalized ( ) ) ; <nl> + if ( ( ( m_flags & EObjectFlags : : MovingOrDecaying ) ! = 0 ) & & ! info . pListener - > HasMoved ( ) ) <nl> + { <nl> + float const tempRelativeVelocity = - m_velocity . Dot ( ( m_position - info . pListener - > GetPosition ( ) ) . GetNormalized ( ) ) ; <nl> + <nl> + if ( fabs ( tempRelativeVelocity ) > fabs ( relativeVelocity ) ) <nl> + { <nl> + relativeVelocity = tempRelativeVelocity ; <nl> + } <nl> + } <nl> + else if ( ( ( m_flags & EObjectFlags : : MovingOrDecaying ) ! = 0 ) & & info . pListener - > HasMoved ( ) ) <nl> + { <nl> + Vec3 const relativeVelocityVec ( m_velocity - info . pListener - > GetVelocity ( ) ) ; <nl> + <nl> + float const tempRelativeVelocity = - relativeVelocityVec . Dot ( ( m_position - info . pListener - > GetPosition ( ) ) . GetNormalized ( ) ) ; <nl> + <nl> + if ( fabs ( tempRelativeVelocity ) > fabs ( relativeVelocity ) ) <nl> + { <nl> + relativeVelocity = tempRelativeVelocity ; <nl> + } <nl> + } <nl> } <nl> <nl> TryToSetRelativeVelocity ( relativeVelocity ) ; <nl> void CObject : : UpdateVelocities ( float const deltaTime ) <nl> } <nl> else if ( ( m_flags & EObjectFlags : : TrackRelativeVelocity ) ! = 0 ) <nl> { <nl> - / / Approaching positive , departing negative value . <nl> - if ( g_pListener - > HasMoved ( ) ) <nl> - { <nl> - float const relativeVelocity = g_pListener - > GetVelocity ( ) . Dot ( ( m_position - g_pListener - > GetPosition ( ) ) . GetNormalized ( ) ) ; <nl> - TryToSetRelativeVelocity ( relativeVelocity ) ; <nl> - } <nl> - else if ( m_previousRelativeVelocity ! = 0 . 0f ) <nl> + for ( auto const & info : m_listenerInfos ) <nl> { <nl> - TryToSetRelativeVelocity ( 0 . 0f ) ; <nl> + / / Approaching positive , departing negative value . Highest value of all listeners is used . <nl> + float relativeVelocity = 0 . 0f ; <nl> + <nl> + if ( info . pListener - > HasMoved ( ) ) <nl> + { <nl> + float const tempRelativeVelocity = info . pListener - > GetVelocity ( ) . Dot ( ( m_position - info . pListener - > GetPosition ( ) ) . GetNormalized ( ) ) ; <nl> + <nl> + if ( fabs ( tempRelativeVelocity ) > fabs ( relativeVelocity ) ) <nl> + { <nl> + relativeVelocity = tempRelativeVelocity ; <nl> + } <nl> + <nl> + TryToSetRelativeVelocity ( relativeVelocity ) ; <nl> + } <nl> + else if ( m_previousRelativeVelocity ! = 0 . 0f ) <nl> + { <nl> + TryToSetRelativeVelocity ( 0 . 0f ) ; <nl> + } <nl> } <nl> } <nl> } <nl> mmm a / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / Object . h <nl> ppp b / Code / CryEngine / CryAudioSystem / implementations / CryAudioImplWwise / Object . h <nl> class CObject final : public CBaseObject , public CPoolObject < CObject , stl : : PSync <nl> CObject & operator = ( CObject const & ) = delete ; <nl> CObject & operator = ( CObject & & ) = delete ; <nl> <nl> - explicit CObject ( AkGameObjectID const id , CTransformation const & transformation , char const * const szName ) ; <nl> + explicit CObject ( <nl> + AkGameObjectID const id , <nl> + CTransformation const & transformation , <nl> + ListenerInfos const & listenerInfos , <nl> + char const * const szName ) ; <nl> virtual ~ CObject ( ) override ; <nl> <nl> / / CryAudio : : Impl : : IObject <nl> virtual void Update ( float const deltaTime ) override ; <nl> virtual void SetTransformation ( CTransformation const & transformation ) override ; <nl> virtual CTransformation const & GetTransformation ( ) const override { return m_transformation ; } <nl> - virtual void SetOcclusion ( float const occlusion ) override ; <nl> + virtual void SetOcclusion ( IListener * const pIListener , float const occlusion , uint8 const numRemainingListeners ) override ; <nl> virtual void SetOcclusionType ( EOcclusionType const occlusionType ) override ; <nl> virtual void ToggleFunctionality ( EObjectFunctionality const type , bool const enable ) override ; <nl> <nl> mmm a / Code / CryEngine / CryCommon / CryAudio / IAudioInterfacesCommonData . h <nl> ppp b / Code / CryEngine / CryCommon / CryAudio / IAudioInterfacesCommonData . h <nl> <nl> # include " . . / CryCore / Platform / platform . h " <nl> # include " . . / CryCore / CryEnumMacro . h " <nl> # include " . . / CryCore / CryCrc32 . h " <nl> + # include " . . / CryCore / Containers / CryArray . h " <nl> <nl> # define CRY_AUDIO_DATA_ROOT " audio " <nl> <nl> using EnumFlagsType = IdType ; <nl> using AuxObjectId = IdType ; <nl> using LibraryId = IdType ; <nl> using ContextId = IdType ; <nl> + using ListenerId = IdType ; <nl> + <nl> + using ListenerIds = DynArray < ListenerId > ; <nl> <nl> constexpr ControlId InvalidControlId = 0 ; <nl> constexpr SwitchStateId InvalidSwitchStateId = 0 ; <nl> constexpr TriggerInstanceId InvalidTriggerInstanceId = 0 ; <nl> constexpr AuxObjectId InvalidAuxObjectId = 0 ; <nl> constexpr AuxObjectId DefaultAuxObjectId = 1 ; <nl> constexpr ContextId InvalidContextId = 0 ; <nl> + constexpr ListenerId InvalidListenerId = 0 ; <nl> constexpr uint8 MaxInfoStringLength = 128 ; <nl> constexpr uint8 MaxControlNameLength = 128 ; <nl> constexpr uint8 MaxFileNameLength = 128 ; <nl> constexpr uint16 MaxMiscStringLength = 512 ; <nl> constexpr uint32 InvalidCRC32 = 0xFFFFffff ; <nl> constexpr float FloatEpsilon = 1 . 0e - 3f ; <nl> <nl> - constexpr char const * g_implCVarName = " s_ImplName " ; <nl> + constexpr char const * g_szImplCVarName = " s_ImplName " ; <nl> + constexpr char const * g_szListenersCVarName = " s_Listeners " ; <nl> + constexpr char const * g_szDefaultListenerName = " Default Listener " ; <nl> <nl> constexpr char const * g_szLoseFocusTriggerName = " lose_focus " ; <nl> constexpr char const * g_szGetFocusTriggerName = " get_focus " ; <nl> constexpr IdType StringToId ( char const * const szSource ) <nl> constexpr PreloadRequestId GlobalPreloadRequestId = StringToId ( g_szGlobalPreloadRequestName ) ; <nl> constexpr LibraryId DefaultLibraryId = StringToId ( g_szDefaultLibraryName ) ; <nl> constexpr ContextId GlobalContextId = StringToId ( g_szGlobalContextName ) ; <nl> + constexpr ListenerId DefaultListenerId = StringToId ( " ThisIsTheHopefullyUniqueIdForTheDefaultListener " ) ; <nl> + <nl> + static ListenerIds const g_defaultListenerIds { DefaultListenerId } ; <nl> <nl> / * * <nl> * @ enum CryAudio : : ERequestFlags <nl> mmm a / Code / CryEngine / CryCommon / CryAudio / IAudioSystem . h <nl> ppp b / Code / CryEngine / CryCommon / CryAudio / IAudioSystem . h <nl> struct SCreateObjectData <nl> char const * const szName_ = nullptr , <nl> EOcclusionType const occlusionType_ = EOcclusionType : : Ignore , <nl> CTransformation const & transformation_ = CTransformation : : GetEmptyObject ( ) , <nl> - bool const setCurrentEnvironments_ = false ) <nl> + bool const setCurrentEnvironments_ = false , <nl> + ListenerIds const & listenerIds_ = g_defaultListenerIds ) <nl> : szName ( szName_ ) <nl> , occlusionType ( occlusionType_ ) <nl> , transformation ( transformation_ ) <nl> , setCurrentEnvironments ( setCurrentEnvironments_ ) <nl> + , listenerIds ( listenerIds_ ) <nl> { } <nl> <nl> static SCreateObjectData const & GetEmptyObject ( ) { static SCreateObjectData const emptyInstance ; return emptyInstance ; } <nl> struct SCreateObjectData <nl> CTransformation const transformation ; <nl> <nl> bool const setCurrentEnvironments ; <nl> + ListenerIds const listenerIds ; <nl> } ; <nl> <nl> struct SExecuteTriggerData : public SCreateObjectData <nl> struct IAudioSystem <nl> * Constructs an instance of an audio listener . <nl> * Note : Retrieving a listener this way requires the instance to be freed via ReleaseListener once not needed anymore ! <nl> * @ param transformation - transformation of the listener to be created . <nl> - * @ param szName - optional name of the listener to be created . <nl> + * @ param szName - name of the listener to be created . <nl> * @ return Pointer to a freshly constructed CryAudio : : IListener instance . <nl> * @ see ReleaseListener <nl> * / <nl> - virtual IListener * CreateListener ( CTransformation const & transformation , char const * const szName = nullptr ) = 0 ; <nl> + virtual IListener * CreateListener ( CTransformation const & transformation , char const * const szName ) = 0 ; <nl> <nl> / * * <nl> * Destructs the passed audio listener instance . <nl> struct IAudioSystem <nl> * / <nl> virtual void ReleaseListener ( IListener * const pIListener ) = 0 ; <nl> <nl> + / * * <nl> + * Returns a pointer to the requested listener . <nl> + * @ param id - id of the requested listener . If none is provided , a pointer to the default listener is returned . <nl> + * @ return Pointer to the requested listener . <nl> + * / <nl> + virtual IListener * GetListener ( ListenerId const id = DefaultListenerId ) = 0 ; <nl> + <nl> / * * <nl> * Constructs an instance of an audio object . <nl> * Note : Retrieving an object this way requires the object to be freed via ReleaseObject once not needed anymore ! <nl> mmm a / Code / CryEngine / CryCommon / CryAudio / IListener . h <nl> ppp b / Code / CryEngine / CryCommon / CryAudio / IListener . h <nl> <nl> * / <nl> namespace CryAudio <nl> { <nl> - class CObjectTransformation ; <nl> + class CObjectTransformation ; <nl> <nl> / * * <nl> * @ struct CryAudio : : IListener <nl> struct IListener <nl> virtual ~ IListener ( ) = default ; <nl> / * * @ endcond * / <nl> <nl> + / * * <nl> + * Gets the listener ' s unique id . <nl> + * @ return id of the listener . <nl> + * / <nl> + virtual ListenerId GetId ( ) const = 0 ; <nl> + <nl> / * * <nl> * Sets the listener ' s transformation . <nl> * @ param transformation - constant reference to an object holding the transformation to apply . <nl> mmm a / Code / CryEngine / CryCommon / CryAudio / IObject . h <nl> ppp b / Code / CryEngine / CryCommon / CryAudio / IObject . h <nl> struct IObject <nl> * / <nl> virtual void SetName ( char const * const szName , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) = 0 ; <nl> <nl> + / * * <nl> + * Adds a listener with the given id to the audio object . <nl> + * @ param id - id of the listener to add . <nl> + * @ return void <nl> + * / <nl> + virtual void AddListener ( ListenerId const id , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) = 0 ; <nl> + <nl> + / * * <nl> + * Removes a listener with the given id from the audio object . <nl> + * @ param id - id of the listener to remove . <nl> + * @ return void <nl> + * / <nl> + virtual void RemoveListener ( ListenerId const id , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) = 0 ; <nl> + <nl> / * * <nl> * Toggles whether this audio object should track and update its absolute velocity . <nl> * @ param enable - if true enables absolute velocity tracking otherwise disables it . <nl> mmm a / Code / CryEngine / CryCommon / CryEntitySystem / IEntityComponent . h <nl> ppp b / Code / CryEngine / CryCommon / CryEntitySystem / IEntityComponent . h <nl> struct IEntityAudioComponent : public IEntityComponent <nl> virtual void RemoveAsListenerFromAudioAuxObject ( CryAudio : : AuxObjectId const audioAuxObjectId , void ( * func ) ( CryAudio : : SRequestInfo const * const ) ) = 0 ; <nl> virtual void ToggleAbsoluteVelocityTracking ( bool const enable , CryAudio : : AuxObjectId const audioAuxObjectId = CryAudio : : DefaultAuxObjectId , CryAudio : : SRequestUserData const & userData = CryAudio : : SRequestUserData : : GetEmptyObject ( ) ) = 0 ; <nl> virtual void ToggleRelativeVelocityTracking ( bool const enable , CryAudio : : AuxObjectId const audioAuxObjectId = CryAudio : : DefaultAuxObjectId , CryAudio : : SRequestUserData const & userData = CryAudio : : SRequestUserData : : GetEmptyObject ( ) ) = 0 ; <nl> + virtual void AddListener ( CryAudio : : ListenerId const listenerId ) = 0 ; <nl> + virtual void RemoveListener ( CryAudio : : ListenerId const listenerId ) = 0 ; <nl> } ; <nl> <nl> / / ! Type of an area managed by IEntityAreaComponent . <nl> mmm a / Code / CryEngine / CryCommon / CrySerialization / Decorators / ResourcesAudio . h <nl> ppp b / Code / CryEngine / CryCommon / CrySerialization / Decorators / ResourcesAudio . h <nl> template < class T > ResourceSelector < T > AudioParameter ( T & s ) { return Resourc <nl> template < class T > ResourceSelector < T > AudioEnvironment ( T & s ) { return ResourceSelector < T > ( s , " AudioEnvironment " ) ; } <nl> template < class T > ResourceSelector < T > AudioPreloadRequest ( T & s ) { return ResourceSelector < T > ( s , " AudioPreloadRequest " ) ; } <nl> template < class T > ResourceSelector < T > AudioSetting ( T & s ) { return ResourceSelector < T > ( s , " AudioSetting " ) ; } <nl> + template < class T > ResourceSelector < T > AudioListener ( T & s ) { return ResourceSelector < T > ( s , " AudioListener " ) ; } <nl> } ; <nl> mmm a / Code / CryEngine / CryEntitySystem / EntityAudioProxy . cpp <nl> ppp b / Code / CryEngine / CryEntitySystem / EntityAudioProxy . cpp <nl> void CEntityComponentAudio : : ToggleRelativeVelocityTracking ( bool const enable , Cr <nl> std : : for_each ( m_mapAuxObjects . begin ( ) , m_mapAuxObjects . end ( ) , SToggleRelativeVelocityTracking ( enable ) ) ; <nl> } <nl> } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CEntityComponentAudio : : AddListener ( CryAudio : : ListenerId const listenerId ) <nl> + { <nl> + for ( auto const & objectPair : m_mapAuxObjects ) <nl> + { <nl> + objectPair . second . pIObject - > AddListener ( listenerId ) ; <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CEntityComponentAudio : : RemoveListener ( CryAudio : : ListenerId const listenerId ) <nl> + { <nl> + for ( auto const & objectPair : m_mapAuxObjects ) <nl> + { <nl> + objectPair . second . pIObject - > RemoveListener ( listenerId ) ; <nl> + } <nl> + } <nl> mmm a / Code / CryEngine / CryEntitySystem / EntityAudioProxy . h <nl> ppp b / Code / CryEngine / CryEntitySystem / EntityAudioProxy . h <nl> class CEntityComponentAudio final : public IEntityAudioComponent <nl> virtual void AudioAuxObjectsMoveWithEntity ( bool const bCanMoveWithEntity ) override ; <nl> virtual void AddAsListenerToAudioAuxObject ( CryAudio : : AuxObjectId const audioAuxObjectId , void ( * func ) ( CryAudio : : SRequestInfo const * const ) , CryAudio : : ESystemEvents const eventMask ) override ; <nl> virtual void RemoveAsListenerFromAudioAuxObject ( CryAudio : : AuxObjectId const audioAuxObjectId , void ( * func ) ( CryAudio : : SRequestInfo const * const ) ) override ; <nl> - void ToggleAbsoluteVelocityTracking ( bool const enable , CryAudio : : AuxObjectId const audioAuxObjectId = CryAudio : : DefaultAuxObjectId , CryAudio : : SRequestUserData const & userData = CryAudio : : SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> - void ToggleRelativeVelocityTracking ( bool const enable , CryAudio : : AuxObjectId const audioAuxObjectId = CryAudio : : DefaultAuxObjectId , CryAudio : : SRequestUserData const & userData = CryAudio : : SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> + virtual void ToggleAbsoluteVelocityTracking ( bool const enable , CryAudio : : AuxObjectId const audioAuxObjectId = CryAudio : : DefaultAuxObjectId , CryAudio : : SRequestUserData const & userData = CryAudio : : SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> + virtual void ToggleRelativeVelocityTracking ( bool const enable , CryAudio : : AuxObjectId const audioAuxObjectId = CryAudio : : DefaultAuxObjectId , CryAudio : : SRequestUserData const & userData = CryAudio : : SRequestUserData : : GetEmptyObject ( ) ) override ; <nl> + virtual void AddListener ( CryAudio : : ListenerId const listenerId ) override ; <nl> + virtual void RemoveListener ( CryAudio : : ListenerId const listenerId ) override ; <nl> / / ~ IEntityAudioComponent <nl> <nl> private : <nl> mmm a / Code / CryEngine / CrySystem / NullImplementation / NULLAudioSystems . h <nl> ppp b / Code / CryEngine / CrySystem / NullImplementation / NULLAudioSystems . h <nl> class CObject final : public IObject <nl> virtual void SetOcclusionType ( EOcclusionType const occlusionType , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override { } <nl> virtual void SetOcclusionRayOffset ( float const occlusionRayOffset , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override { } <nl> virtual void SetName ( char const * const szName , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override { } <nl> + virtual void AddListener ( ListenerId const id , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override { } <nl> + virtual void RemoveListener ( ListenerId const id , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override { } <nl> virtual void ToggleAbsoluteVelocityTracking ( bool const enable , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override { } <nl> virtual void ToggleRelativeVelocityTracking ( bool const enable , SRequestUserData const & userData = SRequestUserData : : GetEmptyObject ( ) ) override { } <nl> } ; <nl> class CSystem final : public IAudioSystem <nl> virtual char const * GetConfigPath ( ) const override { return " " ; } <nl> virtual IListener * CreateListener ( CTransformation const & transformation , char const * const szName = nullptr ) override { return nullptr ; } <nl> virtual void ReleaseListener ( IListener * const pIListener ) override { } <nl> + virtual IListener * GetListener ( ListenerId const id = DefaultListenerId ) override { return nullptr ; } <nl> virtual IObject * CreateObject ( SCreateObjectData const & objectData = SCreateObjectData : : GetEmptyObject ( ) ) override { return static_cast < IObject * > ( & m_object ) ; } <nl> virtual void ReleaseObject ( IObject * const pIObject ) override { } <nl> virtual void GetTriggerData ( ControlId const triggerId , STriggerData & triggerData ) override { } <nl> mmm a / Code / CryManaged / CryMonoBridge / NativeToManagedInterfaces / Audio . cpp <nl> ppp b / Code / CryManaged / CryMonoBridge / NativeToManagedInterfaces / Audio . cpp <nl> static void RemoveAudioRequestListener ( AudioRequestListener listener ) <nl> gEnv - > pAudioSystem - > RemoveRequestListener ( listener , nullptr ) ; <nl> } <nl> <nl> - static CryAudio : : IListener * CreateAudioListener ( CryAudio : : CTransformation const & transformation ) <nl> + static CryAudio : : IListener * CreateAudioListener ( CryAudio : : CTransformation const & transformation , const char * szName ) <nl> { <nl> - return gEnv - > pAudioSystem - > CreateListener ( transformation ) ; <nl> + return gEnv - > pAudioSystem - > CreateListener ( transformation , szName ) ; <nl> } <nl> <nl> static void SetAudioListenerTransformation ( CryAudio : : IListener * pAudioListener , CryAudio : : CTransformation * pCObjectTransformation ) <nl> mmm a / Code / CryPlugins / CryDefaultEntities / Module / CMakeLists . txt <nl> ppp b / Code / CryPlugins / CryDefaultEntities / Module / CMakeLists . txt <nl> add_sources ( " CryDefaultEntities_uber_0 . cpp " <nl> SOURCE_GROUP " Audio " <nl> " DefaultComponents / Audio / AreaComponent . cpp " <nl> " DefaultComponents / Audio / AreaComponent . h " <nl> + " DefaultComponents / Audio / DefaultListenerComponent . cpp " <nl> + " DefaultComponents / Audio / DefaultListenerComponent . h " <nl> " DefaultComponents / Audio / DefaultTriggerComponent . cpp " <nl> " DefaultComponents / Audio / DefaultTriggerComponent . h " <nl> " DefaultComponents / Audio / EnvironmentComponent . cpp " <nl> " DefaultComponents / Audio / EnvironmentComponent . h " <nl> " DefaultComponents / Audio / ListenerComponent . cpp " <nl> " DefaultComponents / Audio / ListenerComponent . h " <nl> + " DefaultComponents / Audio / MultiListenerComponent . cpp " <nl> + " DefaultComponents / Audio / MultiListenerComponent . h " <nl> " DefaultComponents / Audio / OcclusionComponent . cpp " <nl> " DefaultComponents / Audio / OcclusionComponent . h " <nl> " DefaultComponents / Audio / ParameterComponent . cpp " <nl> new file mode 100644 <nl> index 0000000000 . . a2ce6c0544 <nl> mmm / dev / null <nl> ppp b / Code / CryPlugins / CryDefaultEntities / Module / DefaultComponents / Audio / DefaultListenerComponent . cpp <nl> <nl> + / / Copyright 2001 - 2018 Crytek GmbH / Crytek Group . All rights reserved . <nl> + <nl> + # include " StdAfx . h " <nl> + # include " DefaultListenerComponent . h " <nl> + # include < CryAudio / IAudioSystem . h > <nl> + <nl> + namespace Cry <nl> + { <nl> + namespace Audio <nl> + { <nl> + namespace DefaultComponents <nl> + { <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CDefaultListenerComponent : : Register ( Schematyc : : CEnvRegistrationScope & componentScope ) <nl> + { <nl> + { <nl> + auto pFunction = SCHEMATYC_MAKE_ENV_FUNCTION ( & CDefaultListenerComponent : : SetActive , " 2EC40D99 - 6F72 - 49FA - 95E5 - 23AB486C0FCA " _cry_guid , " SetActive " ) ; <nl> + pFunction - > SetDescription ( " Enables / Disables the component . " ) ; <nl> + pFunction - > SetFlags ( Schematyc : : EEnvFunctionFlags : : Construction ) ; <nl> + pFunction - > BindInput ( 1 , ' val ' , " Activate " ) ; <nl> + componentScope . Register ( pFunction ) ; <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CDefaultListenerComponent : : Initialize ( ) <nl> + { <nl> + if ( m_pIListener = = nullptr ) <nl> + { <nl> + Matrix34 const tm = GetWorldTransformMatrix ( ) ; <nl> + CRY_ASSERT_MESSAGE ( tm . IsValid ( ) , " Invalid Matrix34 during CDefaultListenerComponent : : Initialize " ) ; <nl> + m_previousTransformation = tm ; <nl> + <nl> + SetName ( " DefaultListener " ) ; <nl> + m_pIListener = gEnv - > pAudioSystem - > GetListener ( ) ; <nl> + <nl> + if ( m_pIListener ! = nullptr ) <nl> + { <nl> + m_pIListener - > SetTransformation ( m_previousTransformation ) ; <nl> + m_pEntity - > SetFlags ( m_pEntity - > GetFlags ( ) | ENTITY_FLAG_TRIGGER_AREAS ) ; <nl> + m_pEntity - > SetFlagsExtended ( m_pEntity - > GetFlagsExtended ( ) | ENTITY_FLAG_EXTENDED_AUDIO_LISTENER ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CDefaultListenerComponent : : OnShutDown ( ) <nl> + { <nl> + if ( m_pIListener ! = nullptr ) <nl> + { <nl> + gEnv - > pEntitySystem - > GetAreaManager ( ) - > ExitAllAreas ( GetEntityId ( ) ) ; <nl> + m_pIListener = nullptr ; <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + Cry : : Entity : : EventFlags CDefaultListenerComponent : : GetEventMask ( ) const <nl> + { <nl> + return ENTITY_EVENT_XFORM ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CDefaultListenerComponent : : ProcessEvent ( const SEntityEvent & event ) <nl> + { <nl> + if ( m_isActive & & ( m_pIListener ! = nullptr ) ) <nl> + { <nl> + switch ( event . event ) <nl> + { <nl> + case ENTITY_EVENT_XFORM : <nl> + { <nl> + auto const flags = static_cast < int > ( event . nParam [ 0 ] ) ; <nl> + <nl> + if ( ( flags & ( ENTITY_XFORM_POS | ENTITY_XFORM_ROT ) ) ! = 0 ) <nl> + { <nl> + OnTransformChanged ( ) ; <nl> + } <nl> + <nl> + break ; <nl> + } <nl> + default : <nl> + { <nl> + break ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CDefaultListenerComponent : : OnTransformChanged ( ) <nl> + { <nl> + Matrix34 const tm = GetWorldTransformMatrix ( ) ; <nl> + <nl> + / / Listener needs to move at least 1 cm to trigger an update . <nl> + if ( ! m_previousTransformation . IsEquivalent ( tm , 0 . 01f ) ) <nl> + { <nl> + m_previousTransformation = tm ; <nl> + m_pIListener - > SetTransformation ( m_previousTransformation ) ; <nl> + <nl> + / / Add entity to the AreaManager for raising audio relevant events . <nl> + gEnv - > pEntitySystem - > GetAreaManager ( ) - > MarkEntityForUpdate ( m_pEntity - > GetId ( ) ) ; <nl> + } <nl> + } <nl> + } / / namespace DefaultComponents <nl> + } / / namespace Audio <nl> + } / / namespace Cry <nl> new file mode 100644 <nl> index 0000000000 . . 359153bbdd <nl> mmm / dev / null <nl> ppp b / Code / CryPlugins / CryDefaultEntities / Module / DefaultComponents / Audio / DefaultListenerComponent . h <nl> <nl> + / / Copyright 2001 - 2018 Crytek GmbH / Crytek Group . All rights reserved . <nl> + <nl> + # pragma once <nl> + <nl> + # include < CryAudio / IAudioInterfacesCommonData . h > <nl> + # include < CryAudio / IListener . h > <nl> + # include < CrySerialization / Forward . h > <nl> + # include < CrySchematyc / Reflection / TypeDesc . h > <nl> + # include < CrySchematyc / Env / IEnvRegistrar . h > <nl> + # include < CryEntitySystem / IEntityComponent . h > <nl> + <nl> + class CPlugin_CryDefaultEntities ; <nl> + <nl> + namespace Cry <nl> + { <nl> + namespace Audio <nl> + { <nl> + namespace DefaultComponents <nl> + { <nl> + class CDefaultListenerComponent final : public IEntityComponent <nl> + { <nl> + protected : <nl> + <nl> + friend CPlugin_CryDefaultEntities ; <nl> + static void Register ( Schematyc : : CEnvRegistrationScope & componentScope ) ; <nl> + <nl> + / / IEntityComponent <nl> + virtual void Initialize ( ) override ; <nl> + virtual void OnShutDown ( ) override ; <nl> + virtual Cry : : Entity : : EventFlags GetEventMask ( ) const override ; <nl> + virtual void ProcessEvent ( const SEntityEvent & event ) override ; <nl> + virtual void OnTransformChanged ( ) override ; <nl> + / / ~ IEntityComponent <nl> + <nl> + public : <nl> + <nl> + CDefaultListenerComponent ( ) = default ; <nl> + <nl> + inline static void ReflectType ( Schematyc : : CTypeDesc < CDefaultListenerComponent > & desc ) <nl> + { <nl> + desc . SetGUID ( " 56B7CEF6 - 1725 - 440D - 9794 - 8C31819BB0D2 " _cry_guid ) ; <nl> + desc . SetEditorCategory ( " Audio " ) ; <nl> + desc . SetLabel ( " DefaultListener " ) ; <nl> + desc . SetDescription ( " Audio Default Listener from which transformation the audio is recorded . " ) ; <nl> + desc . SetIcon ( " icons : Audio / component_audio_listener . ico " ) ; <nl> + desc . SetComponentFlags ( { IEntityComponent : : EFlags : : ClientOnly , IEntityComponent : : EFlags : : HideFromInspector , IEntityComponent : : EFlags : : HiddenFromUser } ) ; <nl> + } <nl> + <nl> + inline void SetActive ( bool const bValue ) <nl> + { <nl> + m_isActive = bValue ; <nl> + <nl> + if ( ! m_isActive ) <nl> + { <nl> + gEnv - > pEntitySystem - > GetAreaManager ( ) - > ExitAllAreas ( GetEntityId ( ) ) ; <nl> + } <nl> + } <nl> + <nl> + private : <nl> + <nl> + CryAudio : : IListener * m_pIListener = nullptr ; <nl> + CryAudio : : CTransformation m_previousTransformation ; <nl> + bool m_isActive = true ; <nl> + } ; <nl> + } / / namespace DefaultComponents <nl> + } / / namespace Audio <nl> + } / / namespace Cry <nl> new file mode 100644 <nl> index 0000000000 . . 7ee9a2ca74 <nl> mmm / dev / null <nl> ppp b / Code / CryPlugins / CryDefaultEntities / Module / DefaultComponents / Audio / MultiListenerComponent . cpp <nl> <nl> + / / Copyright 2001 - 2018 Crytek GmbH / Crytek Group . All rights reserved . <nl> + <nl> + # include " StdAfx . h " <nl> + # include " MultiListenerComponent . h " <nl> + # include < CryAudio / IAudioSystem . h > <nl> + <nl> + namespace Cry <nl> + { <nl> + namespace Audio <nl> + { <nl> + namespace DefaultComponents <nl> + { <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + inline void ReflectType ( Schematyc : : CTypeDesc < SSingleListenerSerializeHelper > & desc ) <nl> + { <nl> + desc . SetGUID ( " 9DAF1238 - 4BA6 - 4255 - BE64 - CC7E542C1D33 " _cry_guid ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + inline void SSingleListenerSerializeHelper : : Serialize ( Serialization : : IArchive & archive ) <nl> + { <nl> + archive ( Serialization : : AudioListener < string > ( m_name ) , " name " , " Name " ) ; <nl> + <nl> + if ( archive . isInput ( ) ) <nl> + { <nl> + m_id = CryAudio : : StringToId ( m_name . c_str ( ) ) ; <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + inline void ReflectType ( Schematyc : : CTypeDesc < SMultiListenerSerializeHelper > & desc ) <nl> + { <nl> + desc . SetGUID ( " B3B11959 - 6312 - 4833 - 969D - 649607A9B536 " _cry_guid ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + inline void SMultiListenerSerializeHelper : : Serialize ( Serialization : : IArchive & archive ) <nl> + { <nl> + archive ( m_listeners , " listeners " , " Listeners " ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + bool SMultiListenerSerializeHelper : : operator = = ( SMultiListenerSerializeHelper const & other ) const <nl> + { <nl> + bool isEqual = true ; <nl> + size_t const numListeners = m_listeners . size ( ) ; <nl> + <nl> + if ( numListeners = = other . m_listeners . size ( ) ) <nl> + { <nl> + for ( size_t i = 0 ; i < numListeners ; + + i ) <nl> + { <nl> + if ( m_listeners [ i ] ! = other . m_listeners [ i ] ) <nl> + { <nl> + isEqual = false ; <nl> + break ; <nl> + } <nl> + } <nl> + } <nl> + else <nl> + { <nl> + isEqual = false ; <nl> + } <nl> + <nl> + return isEqual ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CMultiListenerComponent : : ReflectType ( Schematyc : : CTypeDesc < CMultiListenerComponent > & desc ) <nl> + { <nl> + desc . SetGUID ( " 6477010F - 2841 - 4C99 - 9ED9 - 55B6E1F594AB " _cry_guid ) ; <nl> + desc . SetEditorCategory ( " Audio " ) ; <nl> + desc . SetLabel ( " Multi - Listener " ) ; <nl> + desc . SetDescription ( " Defines which Audio Listener ( s ) will be used on the audio object . " ) ; <nl> + desc . SetIcon ( " icons : Audio / component_audio_listener . ico " ) ; <nl> + desc . SetComponentFlags ( { IEntityComponent : : EFlags : : Attach , IEntityComponent : : EFlags : : ClientOnly , IEntityComponent : : EFlags : : HideFromInspector } ) ; <nl> + <nl> + desc . AddMember ( & CMultiListenerComponent : : m_listenerHelper , ' list ' , " listeners " , " Listeners " , " The listeners are set on the audio object . " , SMultiListenerSerializeHelper ( ) ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CMultiListenerComponent : : Register ( Schematyc : : CEnvRegistrationScope & componentScope ) <nl> + { <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CMultiListenerComponent : : Initialize ( ) <nl> + { <nl> + m_pIEntityAudioComponent = m_pEntity - > GetComponent < IEntityAudioComponent > ( ) ; <nl> + <nl> + if ( m_pIEntityAudioComponent ! = nullptr ) <nl> + { <nl> + SetDefaultListener ( ) ; <nl> + SetListeners ( ) ; <nl> + } <nl> + else <nl> + { <nl> + m_pIEntityAudioComponent = m_pEntity - > CreateComponent < IEntityAudioComponent > ( ) ; <nl> + SetDefaultListener ( ) ; <nl> + SetListeners ( ) ; <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CMultiListenerComponent : : OnShutDown ( ) <nl> + { <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + Cry : : Entity : : EventFlags CMultiListenerComponent : : GetEventMask ( ) const <nl> + { <nl> + # if defined ( INCLUDE_DEFAULT_PLUGINS_PRODUCTION_CODE ) <nl> + return ENTITY_EVENT_COMPONENT_PROPERTY_CHANGED ; <nl> + # else <nl> + return Cry : : Entity : : EventFlags ( ) ; <nl> + # endif / / INCLUDE_DEFAULT_PLUGINS_PRODUCTION_CODE <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CMultiListenerComponent : : ProcessEvent ( const SEntityEvent & event ) <nl> + { <nl> + # if defined ( INCLUDE_DEFAULT_PLUGINS_PRODUCTION_CODE ) <nl> + if ( ( event . event = = ENTITY_EVENT_COMPONENT_PROPERTY_CHANGED ) & & ( m_pIEntityAudioComponent ! = nullptr ) ) <nl> + { <nl> + for ( auto const id : m_previousListenerIds ) <nl> + { <nl> + m_pIEntityAudioComponent - > RemoveListener ( id ) ; <nl> + } <nl> + <nl> + m_previousListenerIds . clear ( ) ; <nl> + SetListeners ( ) ; <nl> + } <nl> + # endif / / INCLUDE_DEFAULT_PLUGINS_PRODUCTION_CODE <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CMultiListenerComponent : : SetListeners ( ) <nl> + { <nl> + if ( m_pIEntityAudioComponent ! = nullptr ) <nl> + { <nl> + for ( auto const & listener : m_listenerHelper . m_listeners ) <nl> + { <nl> + if ( listener . m_id ! = CryAudio : : InvalidListenerId ) <nl> + { <nl> + m_pIEntityAudioComponent - > AddListener ( listener . m_id ) ; <nl> + <nl> + # if defined ( INCLUDE_DEFAULT_PLUGINS_PRODUCTION_CODE ) <nl> + m_previousListenerIds . emplace_back ( listener . m_id ) ; <nl> + # endif / / INCLUDE_DEFAULT_PLUGINS_PRODUCTION_CODE <nl> + } <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CMultiListenerComponent : : SetDefaultListener ( ) <nl> + { <nl> + if ( m_pIEntityAudioComponent ! = nullptr ) <nl> + { <nl> + if ( m_listenerHelper . m_listeners . empty ( ) ) <nl> + { <nl> + m_listenerHelper . m_listeners . emplace_back ( CryAudio : : g_szDefaultListenerName ) ; <nl> + <nl> + # if defined ( INCLUDE_DEFAULT_PLUGINS_PRODUCTION_CODE ) <nl> + m_previousListenerIds . emplace_back ( CryAudio : : DefaultListenerId ) ; <nl> + # endif / / INCLUDE_DEFAULT_PLUGINS_PRODUCTION_CODE <nl> + } <nl> + else <nl> + { <nl> + m_pIEntityAudioComponent - > RemoveListener ( CryAudio : : DefaultListenerId ) ; <nl> + } <nl> + } <nl> + } <nl> + } / / namespace DefaultComponents <nl> + } / / namespace Audio <nl> + } / / namespace Cry <nl> new file mode 100644 <nl> index 0000000000 . . d5f6659ab5 <nl> mmm / dev / null <nl> ppp b / Code / CryPlugins / CryDefaultEntities / Module / DefaultComponents / Audio / MultiListenerComponent . h <nl> <nl> + / / Copyright 2001 - 2018 Crytek GmbH / Crytek Group . All rights reserved . <nl> + <nl> + # pragma once <nl> + <nl> + # include < CryAudio / IAudioInterfacesCommonData . h > <nl> + # include < CryAudio / IListener . h > <nl> + # include < CrySerialization / Forward . h > <nl> + # include < CrySchematyc / Reflection / TypeDesc . h > <nl> + # include < CrySchematyc / Env / IEnvRegistrar . h > <nl> + # include < CryEntitySystem / IEntityComponent . h > <nl> + <nl> + class CPlugin_CryDefaultEntities ; <nl> + <nl> + namespace Cry <nl> + { <nl> + namespace Audio <nl> + { <nl> + namespace DefaultComponents <nl> + { <nl> + struct SSingleListenerSerializeHelper final <nl> + { <nl> + SSingleListenerSerializeHelper ( ) = default ; <nl> + <nl> + explicit SSingleListenerSerializeHelper ( char const * const szName ) <nl> + : m_name ( szName ) <nl> + { <nl> + m_id = CryAudio : : StringToId ( m_name . c_str ( ) ) ; <nl> + } <nl> + <nl> + void Serialize ( Serialization : : IArchive & archive ) ; <nl> + bool operator = = ( SSingleListenerSerializeHelper const & other ) const { return ( m_id = = other . m_id ) ; } <nl> + bool operator ! = ( SSingleListenerSerializeHelper const & other ) const { return ( m_id ! = other . m_id ) ; } <nl> + <nl> + CryAudio : : ListenerId m_id = CryAudio : : InvalidListenerId ; <nl> + string m_name ; <nl> + } ; <nl> + <nl> + struct SMultiListenerSerializeHelper final <nl> + { <nl> + void Serialize ( Serialization : : IArchive & archive ) ; <nl> + bool operator = = ( SMultiListenerSerializeHelper const & other ) const ; <nl> + <nl> + std : : vector < SSingleListenerSerializeHelper > m_listeners ; <nl> + } ; <nl> + <nl> + class CMultiListenerComponent final : public IEntityComponent <nl> + { <nl> + protected : <nl> + <nl> + friend CPlugin_CryDefaultEntities ; <nl> + static void Register ( Schematyc : : CEnvRegistrationScope & componentScope ) ; <nl> + <nl> + / / IEntityComponent <nl> + virtual void Initialize ( ) override ; <nl> + virtual void OnShutDown ( ) override ; <nl> + virtual Cry : : Entity : : EventFlags GetEventMask ( ) const override ; <nl> + virtual void ProcessEvent ( const SEntityEvent & event ) override ; <nl> + / / ~ IEntityComponent <nl> + <nl> + public : <nl> + <nl> + CMultiListenerComponent ( ) = default ; <nl> + <nl> + static void ReflectType ( Schematyc : : CTypeDesc < CMultiListenerComponent > & desc ) ; <nl> + <nl> + private : <nl> + <nl> + void SetListeners ( ) ; <nl> + void SetDefaultListener ( ) ; <nl> + <nl> + IEntityAudioComponent * m_pIEntityAudioComponent = nullptr ; <nl> + SMultiListenerSerializeHelper m_listenerHelper ; <nl> + <nl> + # if defined ( INCLUDE_DEFAULT_PLUGINS_PRODUCTION_CODE ) <nl> + std : : vector < CryAudio : : ListenerId > m_previousListenerIds ; <nl> + # endif / / INCLUDE_DEFAULT_PLUGINS_PRODUCTION_CODE <nl> + } ; <nl> + } / / namespace DefaultComponents <nl> + } / / namespace Audio <nl> + } / / namespace Cry <nl> mmm a / Code / CryPlugins / CryDefaultEntities / Module / PluginDll . cpp <nl> ppp b / Code / CryPlugins / CryDefaultEntities / Module / PluginDll . cpp <nl> <nl> <nl> # include " DefaultComponents / AI / PathfindingComponent . h " <nl> # include " DefaultComponents / Audio / AreaComponent . h " <nl> + # include " DefaultComponents / Audio / DefaultListenerComponent . h " <nl> # include " DefaultComponents / Audio / DefaultTriggerComponent . h " <nl> # include " DefaultComponents / Audio / EnvironmentComponent . h " <nl> # include " DefaultComponents / Audio / ListenerComponent . h " <nl> + # include " DefaultComponents / Audio / MultiListenerComponent . h " <nl> # include " DefaultComponents / Audio / OcclusionComponent . h " <nl> # include " DefaultComponents / Audio / ParameterComponent . h " <nl> # include " DefaultComponents / Audio / PreloadComponent . h " <nl> void CPlugin_CryDefaultEntities : : RegisterComponents ( Schematyc : : IEnvRegistrar & re <nl> Schematyc : : CEnvRegistrationScope componentScope = scope . Register ( SCHEMATYC_MAKE_ENV_COMPONENT ( Cry : : Audio : : DefaultComponents : : CAreaComponent ) ) ; <nl> Cry : : Audio : : DefaultComponents : : CAreaComponent : : Register ( componentScope ) ; <nl> } <nl> + { <nl> + Schematyc : : CEnvRegistrationScope componentScope = scope . Register ( SCHEMATYC_MAKE_ENV_COMPONENT ( Cry : : Audio : : DefaultComponents : : CDefaultListenerComponent ) ) ; <nl> + Cry : : Audio : : DefaultComponents : : CDefaultListenerComponent : : Register ( componentScope ) ; <nl> + } <nl> { <nl> Schematyc : : CEnvRegistrationScope componentScope = scope . Register ( SCHEMATYC_MAKE_ENV_COMPONENT ( Cry : : Audio : : DefaultComponents : : CDefaultTriggerComponent ) ) ; <nl> Cry : : Audio : : DefaultComponents : : CDefaultTriggerComponent : : Register ( componentScope ) ; <nl> void CPlugin_CryDefaultEntities : : RegisterComponents ( Schematyc : : IEnvRegistrar & re <nl> Schematyc : : CEnvRegistrationScope componentScope = scope . Register ( SCHEMATYC_MAKE_ENV_COMPONENT ( Cry : : Audio : : DefaultComponents : : CListenerComponent ) ) ; <nl> Cry : : Audio : : DefaultComponents : : CListenerComponent : : Register ( componentScope ) ; <nl> } <nl> + { <nl> + Schematyc : : CEnvRegistrationScope componentScope = scope . Register ( SCHEMATYC_MAKE_ENV_COMPONENT ( Cry : : Audio : : DefaultComponents : : CMultiListenerComponent ) ) ; <nl> + Cry : : Audio : : DefaultComponents : : CMultiListenerComponent : : Register ( componentScope ) ; <nl> + } <nl> { <nl> Schematyc : : CEnvRegistrationScope componentScope = scope . Register ( SCHEMATYC_MAKE_ENV_COMPONENT ( Cry : : Audio : : DefaultComponents : : COcclusionComponent ) ) ; <nl> Cry : : Audio : : DefaultComponents : : COcclusionComponent : : Register ( componentScope ) ; <nl> mmm a / Code / Sandbox / Plugins / EditorAnimation / CharacterTool / AnimEventPlayers . cpp <nl> ppp b / Code / Sandbox / Plugins / EditorAnimation / CharacterTool / AnimEventPlayers . cpp <nl> class AnimEventPlayer_AudioTranslationLayer : public IAnimEventPlayer <nl> if ( enableAudio & & m_pIAudioListener = = nullptr ) <nl> { <nl> static const Matrix34 identityMatrix ( IDENTITY ) ; <nl> - m_pIAudioListener = gEnv - > pAudioSystem - > CreateListener ( identityMatrix ) ; <nl> + m_pIAudioListener = gEnv - > pAudioSystem - > CreateListener ( identityMatrix , " AnimEventPlayer " ) ; <nl> } <nl> else if ( m_pIAudioListener ! = nullptr ) <nl> { <nl> mmm a / Code / Sandbox / Plugins / EditorAudioControlsEditor / AssetIcons . h <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / AssetIcons . h <nl> static CryIcon s_settingIcon ; <nl> static CryIcon s_stateIcon ; <nl> static CryIcon s_switchIcon ; <nl> static CryIcon s_triggerIcon ; <nl> + static CryIcon s_listenerIcon ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> inline void InitAssetIcons ( ) <nl> inline void InitAssetIcons ( ) <nl> s_stateIcon = CryIcon ( " icons : audio / assets / state . ico " ) ; <nl> s_switchIcon = CryIcon ( " icons : audio / assets / switch . ico " ) ; <nl> s_triggerIcon = CryIcon ( " icons : audio / assets / trigger . ico " ) ; <nl> + s_listenerIcon = CryIcon ( " icons : audio / assets / listener . ico " ) ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> mmm a / Code / Sandbox / Plugins / EditorAudioControlsEditor / AudioControlsEditorPlugin . cpp <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / AudioControlsEditorPlugin . cpp <nl> <nl> # include " FileWriter . h " <nl> # include " FileLoader . h " <nl> # include " ImplManager . h " <nl> + # include " ListenerManager . h " <nl> # include " NameValidator . h " <nl> # include " AssetIcons . h " <nl> # include " Common / IImpl . h " <nl> CAudioControlsEditorPlugin : : CAudioControlsEditorPlugin ( ) <nl> g_assetsManager . Initialize ( ) ; <nl> g_contextManager . Initialize ( ) ; <nl> g_implManager . LoadImpl ( ) ; <nl> + g_listenerManager . Initialize ( ) ; <nl> <nl> ReloadData ( EReloadFlags : : ReloadSystemControls | EReloadFlags : : SendSignals ) ; <nl> <nl> mmm a / Code / Sandbox / Plugins / EditorAudioControlsEditor / AudioControlsEditorUI . qrc <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / AudioControlsEditorUI . qrc <nl> <nl> < RCC > <nl> < qresource prefix = " / icons " > <nl> < file alias = " audio / assets / environment . ico " > Icons / assets / environment . ico < / file > <nl> + < file alias = " audio / assets / listener . ico " > Icons / assets / listener . ico < / file > <nl> < file alias = " audio / assets / parameter . ico " > Icons / assets / parameter . ico < / file > <nl> < file alias = " audio / assets / preload . ico " > Icons / assets / preload . ico < / file > <nl> < file alias = " audio / assets / setting . ico " > Icons / assets / setting . ico < / file > <nl> mmm a / Code / Sandbox / Plugins / EditorAudioControlsEditor / CMakeLists . txt <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / CMakeLists . txt <nl> add_sources ( " EditorAudioControlsEditor_uber_0 . cpp " <nl> " FileWriter . cpp " <nl> " FileWriter . h " <nl> " LibraryScope . h " <nl> + SOURCE_GROUP " Listeners " <nl> + " ListenerManager . cpp " <nl> + " ListenerManager . h " <nl> + " ListenerSelectorDialog . cpp " <nl> + " ListenerSelectorDialog . h " <nl> + " ListenerSelectorModel . cpp " <nl> + " ListenerSelectorModel . h " <nl> SOURCE_GROUP " MiddlewareDataPanel " <nl> " MiddlewareDataWidget . cpp " <nl> " MiddlewareDataWidget . h " <nl> mmm a / Code / Sandbox / Plugins / EditorAudioControlsEditor / Common . cpp <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / Common . cpp <nl> <nl> # include " AssetsManager . h " <nl> # include " ContextManager . h " <nl> # include " ImplManager . h " <nl> + # include " ListenerManager . h " <nl> # include " NameValidator . h " <nl> <nl> namespace ACE <nl> ContextIds g_activeUserDefinedContexts ; <nl> CAssetsManager g_assetsManager ; <nl> CContextManager g_contextManager ; <nl> CImplManager g_implManager ; <nl> + CListenerManager g_listenerManager ; <nl> Impl : : IImpl * g_pIImpl = nullptr ; <nl> CMainWindow * g_pMainWindow = nullptr ; <nl> CSystemControlsWidget * g_pSystemControlsWidget = nullptr ; <nl> mmm a / Code / Sandbox / Plugins / EditorAudioControlsEditor / Common . h <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / Common . h <nl> struct IImpl ; <nl> class CAssetsManager ; <nl> class CContextManager ; <nl> class CImplManager ; <nl> + class CListenerManager ; <nl> class CAsset ; <nl> class CControl ; <nl> class CLibrary ; <nl> extern ContextIds g_activeUserDefinedContexts ; <nl> extern CAssetsManager g_assetsManager ; <nl> extern CContextManager g_contextManager ; <nl> extern CImplManager g_implManager ; <nl> + extern CListenerManager g_listenerManager ; <nl> extern Impl : : IImpl * g_pIImpl ; <nl> extern CMainWindow * g_pMainWindow ; <nl> extern CSystemControlsWidget * g_pSystemControlsWidget ; <nl> new file mode 100644 <nl> index 0000000000 . . 6647b1e407 <nl> Binary files / dev / null and b / Code / Sandbox / Plugins / EditorAudioControlsEditor / Icons / assets / listener . ico differ <nl> mmm a / Code / Sandbox / Plugins / EditorAudioControlsEditor / ImplManager . cpp <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / ImplManager . cpp <nl> bool CImplManager : : LoadImpl ( ) <nl> GetIEditor ( ) - > GetIUndoManager ( ) - > Suspend ( ) ; <nl> <nl> bool isLoaded = true ; <nl> - ICVar const * const pCVar = gEnv - > pConsole - > GetCVar ( CryAudio : : g_implCVarName ) ; <nl> + ICVar const * const pCVar = gEnv - > pConsole - > GetCVar ( CryAudio : : g_szImplCVarName ) ; <nl> <nl> if ( pCVar ! = nullptr ) <nl> { <nl> bool CImplManager : : LoadImpl ( ) <nl> } <nl> else <nl> { <nl> - CryWarning ( VALIDATOR_MODULE_EDITOR , VALIDATOR_WARNING , " [ Audio Controls Editor ] CVar % s not defined . Needed to derive the Editor plugin name . " , CryAudio : : g_implCVarName ) ; <nl> + CryWarning ( VALIDATOR_MODULE_EDITOR , VALIDATOR_WARNING , " [ Audio Controls Editor ] CVar % s not defined . Needed to derive the Editor plugin name . " , CryAudio : : g_szImplCVarName ) ; <nl> isLoaded = false ; <nl> } <nl> <nl> new file mode 100644 <nl> index 0000000000 . . a8d97634c7 <nl> mmm / dev / null <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / ListenerManager . cpp <nl> <nl> + / / Copyright 2001 - 2018 Crytek GmbH / Crytek Group . All rights reserved . <nl> + <nl> + # include " StdAfx . h " <nl> + # include " ListenerManager . h " <nl> + # include < CrySystem / IConsole . h > <nl> + <nl> + namespace ACE <nl> + { <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CListenerManager : : Initialize ( ) <nl> + { <nl> + m_listeners . emplace_back ( CryAudio : : g_szDefaultListenerName ) ; <nl> + <nl> + ICVar const * const pCVar = gEnv - > pConsole - > GetCVar ( CryAudio : : g_szListenersCVarName ) ; <nl> + <nl> + if ( pCVar ! = nullptr ) <nl> + { <nl> + string const listenerNames = pCVar - > GetString ( ) ; <nl> + <nl> + if ( ! listenerNames . empty ( ) ) <nl> + { <nl> + int curPos = 0 ; <nl> + string listenerName = listenerNames . Tokenize ( " , " , curPos ) ; <nl> + <nl> + while ( ! listenerName . empty ( ) ) <nl> + { <nl> + listenerName . Trim ( ) ; <nl> + <nl> + GenerateUniqueListenerName ( listenerName ) ; <nl> + m_listeners . emplace_back ( listenerName ) ; <nl> + <nl> + listenerName = listenerNames . Tokenize ( " , " , curPos ) ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CListenerManager : : GenerateUniqueListenerName ( string & name ) <nl> + { <nl> + bool nameChanged = false ; <nl> + <nl> + for ( auto const & listenerName : m_listeners ) <nl> + { <nl> + if ( listenerName . compareNoCase ( name ) = = 0 ) <nl> + { <nl> + name + = " _1 " ; <nl> + nameChanged = true ; <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + if ( nameChanged ) <nl> + { <nl> + GenerateUniqueListenerName ( name ) ; <nl> + } <nl> + } <nl> + } / / namespace ACE <nl> new file mode 100644 <nl> index 0000000000 . . 5c4409b407 <nl> mmm / dev / null <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / ListenerManager . h <nl> <nl> + / / Copyright 2001 - 2018 Crytek GmbH / Crytek Group . All rights reserved . <nl> + <nl> + # pragma once <nl> + <nl> + # include " Common . h " <nl> + <nl> + namespace ACE <nl> + { <nl> + class CListener ; <nl> + <nl> + class CListenerManager final <nl> + { <nl> + public : <nl> + <nl> + CListenerManager ( CListenerManager const & ) = delete ; <nl> + CListenerManager ( CListenerManager & & ) = delete ; <nl> + CListenerManager & operator = ( CListenerManager const & ) = delete ; <nl> + CListenerManager & operator = ( CListenerManager & & ) = delete ; <nl> + <nl> + CListenerManager ( ) = default ; <nl> + <nl> + void Initialize ( ) ; <nl> + size_t GetNumListeners ( ) const { return m_listeners . size ( ) ; } <nl> + string const & GetListenerName ( size_t const index ) const { return m_listeners [ index ] ; } <nl> + <nl> + private : <nl> + <nl> + void GenerateUniqueListenerName ( string & name ) ; <nl> + <nl> + AssetNames m_listeners ; <nl> + } ; <nl> + } / / namespace ACE <nl> new file mode 100644 <nl> index 0000000000 . . 3dde6773b3 <nl> mmm / dev / null <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / ListenerSelectorDialog . cpp <nl> <nl> + / / Copyright 2001 - 2018 Crytek GmbH / Crytek Group . All rights reserved . <nl> + <nl> + # include " StdAfx . h " <nl> + # include " ListenerSelectorDialog . h " <nl> + # include " ListenerSelectorModel . h " <nl> + # include " TreeView . h " <nl> + <nl> + # include < QtUtil . h > <nl> + # include < QSearchBox . h > <nl> + # include < ProxyModels / AttributeFilterProxyModel . h > <nl> + <nl> + # include < QDialogButtonBox > <nl> + # include < QHeaderView > <nl> + # include < QVBoxLayout > <nl> + # include < QPushButton > <nl> + <nl> + namespace ACE <nl> + { <nl> + string CListenerSelectorDialog : : s_previousListenerName = " " ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + CListenerSelectorDialog : : CListenerSelectorDialog ( QWidget * const pParent ) <nl> + : CEditorDialog ( " AudioListenerSelectorDialog " , pParent ) <nl> + , m_selectionIsValid ( false ) <nl> + , m_pModel ( new CListenerSelectorModel ( this ) ) <nl> + , m_pAttributeFilterProxyModel ( new QAttributeFilterProxyModel ( QAttributeFilterProxyModel : : BaseBehavior , this ) ) <nl> + , m_pTreeView ( new CTreeView ( this , QAdvancedTreeView : : Behavior : : None ) ) <nl> + , m_pSearchBox ( new QSearchBox ( this ) ) <nl> + , m_pDialogButtons ( new QDialogButtonBox ( this ) ) <nl> + { <nl> + setWindowTitle ( " Select Audio Listener " ) ; <nl> + setModal ( true ) ; <nl> + <nl> + m_pAttributeFilterProxyModel - > setSourceModel ( m_pModel ) ; <nl> + <nl> + m_pTreeView - > setEditTriggers ( QAbstractItemView : : NoEditTriggers ) ; <nl> + m_pTreeView - > setDragEnabled ( false ) ; <nl> + m_pTreeView - > setDragDropMode ( QAbstractItemView : : NoDragDrop ) ; <nl> + m_pTreeView - > setSelectionMode ( QAbstractItemView : : SingleSelection ) ; <nl> + m_pTreeView - > setUniformRowHeights ( true ) ; <nl> + m_pTreeView - > setContextMenuPolicy ( Qt : : NoContextMenu ) ; <nl> + m_pTreeView - > setModel ( m_pAttributeFilterProxyModel ) ; <nl> + m_pTreeView - > sortByColumn ( 0 , Qt : : AscendingOrder ) ; <nl> + m_pTreeView - > setItemsExpandable ( false ) ; <nl> + m_pTreeView - > setRootIsDecorated ( false ) ; <nl> + m_pTreeView - > header ( ) - > setContextMenuPolicy ( Qt : : PreventContextMenu ) ; <nl> + <nl> + m_pSearchBox - > SetModel ( m_pAttributeFilterProxyModel ) ; <nl> + m_pSearchBox - > SetAutoExpandOnSearch ( m_pTreeView ) ; <nl> + m_pSearchBox - > EnableContinuousSearch ( true ) ; <nl> + <nl> + m_pDialogButtons - > setStandardButtons ( QDialogButtonBox : : Ok | QDialogButtonBox : : Cancel ) ; <nl> + m_pDialogButtons - > button ( QDialogButtonBox : : Ok ) - > setEnabled ( false ) ; <nl> + <nl> + auto const pWindowLayout = new QVBoxLayout ( this ) ; <nl> + setLayout ( pWindowLayout ) ; <nl> + pWindowLayout - > addWidget ( m_pSearchBox ) ; <nl> + pWindowLayout - > addWidget ( m_pTreeView ) ; <nl> + pWindowLayout - > addWidget ( m_pDialogButtons ) ; <nl> + <nl> + QObject : : connect ( m_pTreeView , & CTreeView : : doubleClicked , this , & CListenerSelectorDialog : : OnItemDoubleClicked ) ; <nl> + QObject : : connect ( m_pTreeView - > selectionModel ( ) , & QItemSelectionModel : : selectionChanged , this , & CListenerSelectorDialog : : OnUpdateSelectedListener ) ; <nl> + QObject : : connect ( m_pDialogButtons , & QDialogButtonBox : : accepted , this , & CListenerSelectorDialog : : accept ) ; <nl> + QObject : : connect ( m_pDialogButtons , & QDialogButtonBox : : rejected , this , & CListenerSelectorDialog : : reject ) ; <nl> + <nl> + m_pSearchBox - > signalOnSearch . Connect ( [ & ] ( ) <nl> + { <nl> + m_pTreeView - > scrollTo ( m_pTreeView - > currentIndex ( ) ) ; <nl> + } , reinterpret_cast < uintptr_t > ( this ) ) ; <nl> + <nl> + OnUpdateSelectedListener ( ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + CListenerSelectorDialog : : ~ CListenerSelectorDialog ( ) <nl> + { <nl> + m_pSearchBox - > signalOnSearch . DisconnectById ( reinterpret_cast < uintptr_t > ( this ) ) ; <nl> + m_pModel - > deleteLater ( ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + QSize CListenerSelectorDialog : : sizeHint ( ) const <nl> + { <nl> + return QSize ( 400 , 900 ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + CListenerSelectorDialog : : SResourceSelectionDialogResult CListenerSelectorDialog : : ChooseListener ( char const * szCurrentValue ) <nl> + { <nl> + SResourceSelectionDialogResult result { szCurrentValue , false } ; <nl> + <nl> + if ( strcmp ( szCurrentValue , " " ) ! = 0 ) <nl> + { <nl> + s_previousListenerName = szCurrentValue ; <nl> + } <nl> + <nl> + / / Automatically select the previous listener <nl> + if ( ( m_pAttributeFilterProxyModel ! = nullptr ) & & ! s_previousListenerName . empty ( ) ) <nl> + { <nl> + QModelIndex const & index = FindListenerIndex ( s_previousListenerName ) ; <nl> + <nl> + if ( index . isValid ( ) ) <nl> + { <nl> + m_pTreeView - > setCurrentIndex ( index ) ; <nl> + } <nl> + } <nl> + <nl> + bool accepted = exec ( ) = = QDialog : : Accepted ; <nl> + result . selectionAccepted = accepted ; <nl> + <nl> + if ( accepted ) <nl> + { <nl> + result . selectedListener = s_previousListenerName . c_str ( ) ; <nl> + } <nl> + <nl> + return result ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CListenerSelectorDialog : : OnUpdateSelectedListener ( ) <nl> + { <nl> + QModelIndex const & index = m_pTreeView - > currentIndex ( ) ; <nl> + <nl> + if ( index . isValid ( ) ) <nl> + { <nl> + string const name = m_pModel - > GetListenerNameFromIndex ( index ) ; <nl> + m_selectionIsValid = ! name . empty ( ) ; <nl> + <nl> + if ( m_selectionIsValid ) <nl> + { <nl> + s_previousListenerName = name ; <nl> + } <nl> + <nl> + m_pDialogButtons - > button ( QDialogButtonBox : : Ok ) - > setEnabled ( m_selectionIsValid ) ; <nl> + } <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + QModelIndex CListenerSelectorDialog : : FindListenerIndex ( string const & listenerName ) <nl> + { <nl> + QModelIndex modelIndex = QModelIndex ( ) ; <nl> + <nl> + auto const & matches = m_pAttributeFilterProxyModel - > match ( m_pAttributeFilterProxyModel - > index ( 0 , 0 , QModelIndex ( ) ) , Qt : : DisplayRole , QtUtil : : ToQString ( listenerName ) , 1 , Qt : : MatchRecursive ) ; <nl> + <nl> + if ( ! matches . empty ( ) ) <nl> + { <nl> + modelIndex = matches [ 0 ] ; <nl> + } <nl> + <nl> + return modelIndex ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void CListenerSelectorDialog : : OnItemDoubleClicked ( QModelIndex const & index ) <nl> + { <nl> + if ( m_selectionIsValid ) <nl> + { <nl> + string const name = m_pModel - > GetListenerNameFromIndex ( index ) ; <nl> + <nl> + if ( ! name . empty ( ) ) <nl> + { <nl> + s_previousListenerName = name ; <nl> + accept ( ) ; <nl> + } <nl> + } <nl> + } <nl> + } / / namespace ACE <nl> new file mode 100644 <nl> index 0000000000 . . 9d8ae79d87 <nl> mmm / dev / null <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / ListenerSelectorDialog . h <nl> <nl> + / / Copyright 2001 - 2018 Crytek GmbH / Crytek Group . All rights reserved . <nl> + <nl> + # pragma once <nl> + <nl> + # include " Common . h " <nl> + # include < Controls / EditorDialog . h > <nl> + <nl> + class QAttributeFilterProxyModel ; <nl> + class QSearchBox ; <nl> + class QDialogButtonBox ; <nl> + <nl> + namespace ACE <nl> + { <nl> + class CListenerSelectorModel ; <nl> + class CTreeView ; <nl> + <nl> + class CListenerSelectorDialog final : public CEditorDialog <nl> + { <nl> + Q_OBJECT <nl> + <nl> + public : <nl> + <nl> + struct SResourceSelectionDialogResult final <nl> + { <nl> + string selectedListener ; <nl> + bool selectionAccepted ; <nl> + } ; <nl> + <nl> + CListenerSelectorDialog ( ) = delete ; <nl> + CListenerSelectorDialog ( CListenerSelectorDialog const & ) = delete ; <nl> + CListenerSelectorDialog ( CListenerSelectorDialog & & ) = delete ; <nl> + CListenerSelectorDialog & operator = ( CListenerSelectorDialog const & ) = delete ; <nl> + CListenerSelectorDialog & operator = ( CListenerSelectorDialog & & ) = delete ; <nl> + <nl> + explicit CListenerSelectorDialog ( QWidget * const pParent ) ; <nl> + virtual ~ CListenerSelectorDialog ( ) override ; <nl> + <nl> + / / ! Returns if the operation was accepted or not . If the operation was accepted the newly selected item is in selectedListener . If the operation was canceled selectedListener will be set to szCurrentValue <nl> + SResourceSelectionDialogResult ChooseListener ( char const * szCurrentValue ) ; <nl> + <nl> + virtual QSize sizeHint ( ) const override ; <nl> + <nl> + private slots : <nl> + <nl> + void OnUpdateSelectedListener ( ) ; <nl> + void OnItemDoubleClicked ( QModelIndex const & index ) ; <nl> + <nl> + private : <nl> + <nl> + QModelIndex FindListenerIndex ( string const & listenerName ) ; <nl> + <nl> + bool m_selectionIsValid ; <nl> + <nl> + CListenerSelectorModel * const m_pModel ; <nl> + QAttributeFilterProxyModel * const m_pAttributeFilterProxyModel ; <nl> + QSearchBox * const m_pSearchBox ; <nl> + CTreeView * const m_pTreeView ; <nl> + QDialogButtonBox * const m_pDialogButtons ; <nl> + <nl> + static string s_previousListenerName ; <nl> + } ; <nl> + } / / namespace ACE <nl> new file mode 100644 <nl> index 0000000000 . . 767ec245b8 <nl> mmm / dev / null <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / ListenerSelectorModel . cpp <nl> <nl> + / / Copyright 2001 - 2018 Crytek GmbH / Crytek Group . All rights reserved . <nl> + <nl> + # include " StdAfx . h " <nl> + # include " ListenerSelectorModel . h " <nl> + # include " Common . h " <nl> + # include " ListenerManager . h " <nl> + # include " AssetIcons . h " <nl> + <nl> + # include < QtUtil . h > <nl> + <nl> + namespace ACE <nl> + { <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + int CListenerSelectorModel : : rowCount ( QModelIndex const & parent ) const <nl> + { <nl> + int rowCount = 0 ; <nl> + <nl> + if ( ( parent . row ( ) < 0 ) | | ( parent . column ( ) < 0 ) ) <nl> + { <nl> + rowCount = static_cast < int > ( g_listenerManager . GetNumListeners ( ) ) ; <nl> + } <nl> + <nl> + return rowCount ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + int CListenerSelectorModel : : columnCount ( QModelIndex const & parent ) const <nl> + { <nl> + return 1 ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + QVariant CListenerSelectorModel : : data ( QModelIndex const & index , int role ) const <nl> + { <nl> + QVariant variant ; <nl> + <nl> + if ( index . isValid ( ) & & ( index . row ( ) < static_cast < int > ( g_listenerManager . GetNumListeners ( ) ) ) ) <nl> + { <nl> + switch ( role ) <nl> + { <nl> + case Qt : : DisplayRole : / / Intentional fall - through . <nl> + case Qt : : ToolTipRole : <nl> + { <nl> + variant = QtUtil : : ToQString ( g_listenerManager . GetListenerName ( static_cast < size_t > ( index . row ( ) ) ) ) ; <nl> + break ; <nl> + } <nl> + case Qt : : DecorationRole : <nl> + { <nl> + variant = s_listenerIcon ; <nl> + break ; <nl> + } <nl> + default : <nl> + { <nl> + break ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + return variant ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + bool CListenerSelectorModel : : setData ( QModelIndex const & index , QVariant const & value , int role ) <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + QVariant CListenerSelectorModel : : headerData ( int section , Qt : : Orientation orientation , int role ) const <nl> + { <nl> + QVariant variant ; <nl> + <nl> + if ( ( orientation = = Qt : : Horizontal ) & & ( ( role = = Qt : : DisplayRole ) | | ( role = = Qt : : ToolTipRole ) ) ) <nl> + { <nl> + variant = " Name " ; <nl> + } <nl> + <nl> + return variant ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + Qt : : ItemFlags CListenerSelectorModel : : flags ( QModelIndex const & index ) const <nl> + { <nl> + return index . isValid ( ) ? ( QAbstractItemModel : : flags ( index ) | Qt : : ItemIsSelectable ) : Qt : : NoItemFlags ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + QModelIndex CListenerSelectorModel : : index ( int row , int column , QModelIndex const & parent / * = QModelIndex ( ) * / ) const <nl> + { <nl> + QModelIndex modelIndex = QModelIndex ( ) ; <nl> + <nl> + if ( ( row > = 0 ) & & ( column > = 0 ) & & ( row < static_cast < int > ( g_listenerManager . GetNumListeners ( ) ) ) ) <nl> + { <nl> + modelIndex = createIndex ( row , column ) ; <nl> + } <nl> + <nl> + return modelIndex ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + QModelIndex CListenerSelectorModel : : parent ( QModelIndex const & index ) const <nl> + { <nl> + return QModelIndex ( ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + bool CListenerSelectorModel : : canDropMimeData ( QMimeData const * pData , Qt : : DropAction action , int row , int column , QModelIndex const & parent ) const <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + bool CListenerSelectorModel : : dropMimeData ( QMimeData const * pData , Qt : : DropAction action , int row , int column , QModelIndex const & parent ) <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + Qt : : DropActions CListenerSelectorModel : : supportedDropActions ( ) const <nl> + { <nl> + return Qt : : IgnoreAction ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + string CListenerSelectorModel : : GetListenerNameFromIndex ( QModelIndex const & index ) <nl> + { <nl> + return QtUtil : : ToString ( index . sibling ( index . row ( ) , 0 ) . data ( Qt : : DisplayRole ) . toString ( ) ) ; <nl> + } <nl> + } / / namespace ACE <nl> new file mode 100644 <nl> index 0000000000 . . 1266419e7b <nl> mmm / dev / null <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / ListenerSelectorModel . h <nl> <nl> + / / Copyright 2001 - 2018 Crytek GmbH / Crytek Group . All rights reserved . <nl> + <nl> + # pragma once <nl> + <nl> + # include < QAbstractItemModel > <nl> + <nl> + namespace ACE <nl> + { <nl> + class CListenerSelectorModel final : public QAbstractItemModel <nl> + { <nl> + Q_OBJECT <nl> + <nl> + public : <nl> + <nl> + CListenerSelectorModel ( ) = delete ; <nl> + CListenerSelectorModel ( CListenerSelectorModel const & ) = delete ; <nl> + CListenerSelectorModel ( CListenerSelectorModel & & ) = delete ; <nl> + CListenerSelectorModel & operator = ( CListenerSelectorModel const & ) = delete ; <nl> + CListenerSelectorModel & operator = ( CListenerSelectorModel & & ) = delete ; <nl> + <nl> + explicit CListenerSelectorModel ( QObject * const pParent ) <nl> + : QAbstractItemModel ( pParent ) <nl> + { } <nl> + <nl> + virtual ~ CListenerSelectorModel ( ) override = default ; <nl> + <nl> + / / QAbstractItemModel <nl> + virtual int rowCount ( QModelIndex const & parent ) const override ; <nl> + virtual int columnCount ( QModelIndex const & parent ) const override ; <nl> + virtual QVariant data ( QModelIndex const & index , int role ) const override ; <nl> + virtual bool setData ( QModelIndex const & index , QVariant const & value , int role ) override ; <nl> + virtual QVariant headerData ( int section , Qt : : Orientation orientation , int role ) const override ; <nl> + virtual Qt : : ItemFlags flags ( QModelIndex const & index ) const override ; <nl> + virtual QModelIndex index ( int row , int column , QModelIndex const & parent = QModelIndex ( ) ) const override ; <nl> + virtual QModelIndex parent ( QModelIndex const & index ) const override ; <nl> + virtual bool canDropMimeData ( QMimeData const * pData , Qt : : DropAction action , int row , int column , QModelIndex const & parent ) const override ; <nl> + virtual bool dropMimeData ( QMimeData const * pData , Qt : : DropAction action , int row , int column , QModelIndex const & parent ) override ; <nl> + virtual Qt : : DropActions supportedDropActions ( ) const override ; <nl> + / / ~ QAbstractItemModel <nl> + <nl> + static string GetListenerNameFromIndex ( QModelIndex const & index ) ; <nl> + } ; <nl> + } / / namespace ACE <nl> mmm a / Code / Sandbox / Plugins / EditorAudioControlsEditor / ResourceSelectors . cpp <nl> ppp b / Code / Sandbox / Plugins / EditorAudioControlsEditor / ResourceSelectors . cpp <nl> <nl> <nl> # include " AssetsManager . h " <nl> # include " ResourceSelectorDialog . h " <nl> + # include " ListenerSelectorDialog . h " <nl> <nl> # include < IResourceSelectorHost . h > <nl> # include < ListSelectionDialog . h > <nl> SResourceSelectionResult AudioSettingSelector ( SResourceSelectorContext const & co <nl> return ShowSelectDialog ( context , szPreviousValue , EAssetType : : Setting , false ) ; <nl> } <nl> <nl> + SResourceSelectionResult AudioListenerSelector ( SResourceSelectorContext const & context , char const * szPreviousValue ) <nl> + { <nl> + CListenerSelectorDialog dialog ( context . parentWidget ) ; <nl> + CListenerSelectorDialog : : SResourceSelectionDialogResult dialogResult = dialog . ChooseListener ( szPreviousValue ) ; <nl> + SResourceSelectionResult result { dialogResult . selectionAccepted , dialogResult . selectedListener . c_str ( ) } ; <nl> + return result ; <nl> + } <nl> + <nl> REGISTER_RESOURCE_SELECTOR ( " AudioTrigger " , AudioTriggerSelector , " " ) <nl> REGISTER_RESOURCE_SELECTOR ( " AudioSwitch " , AudioSwitchSelector , " " ) / / Deprecated . <nl> REGISTER_RESOURCE_SELECTOR ( " AudioState " , AudioStateSelector , " " ) / / Deprecated . <nl> REGISTER_RESOURCE_SELECTOR ( " AudioParameter " , AudioParameterSelector , " " ) <nl> REGISTER_RESOURCE_SELECTOR ( " AudioEnvironment " , AudioEnvironmentSelector , " " ) <nl> REGISTER_RESOURCE_SELECTOR ( " AudioPreloadRequest " , AudioPreloadRequestSelector , " " ) <nl> REGISTER_RESOURCE_SELECTOR ( " AudioSetting " , AudioSettingSelector , " " ) <nl> + REGISTER_RESOURCE_SELECTOR ( " AudioListener " , AudioListenerSelector , " " ) <nl> } / / namespace ACE <nl> mmm a / Code / Sandbox / Plugins / EditorCommon / ModelViewport . cpp <nl> ppp b / Code / Sandbox / Plugins / EditorCommon / ModelViewport . cpp <nl> CModelViewport : : CModelViewport ( const char * settingsPath ) <nl> gEnv - > pInput - > AddEventListener ( this ) ; <nl> } <nl> <nl> - m_pIAudioListener = gEnv - > pAudioSystem - > CreateListener ( m_viewTM ) ; <nl> + m_pIAudioListener = gEnv - > pAudioSystem - > CreateListener ( m_viewTM , " ModelViewport " ) ; <nl> m_AABB . Reset ( ) ; <nl> } <nl> <nl> | ! I integrate from / / ce / main . . . | CRYTEK/CRYENGINE | 8a1ef969f5909f41d48a505e6541f6715f0a0a3b | 2019-05-20T07:02:07Z |
mmm a / src / video_core / engines / kepler_compute . cpp <nl> ppp b / src / video_core / engines / kepler_compute . cpp <nl> <nl> <nl> # include " common / assert . h " <nl> # include " common / logging / log . h " <nl> + # include " core / core . h " <nl> # include " video_core / engines / kepler_compute . h " <nl> + # include " video_core / engines / maxwell_3d . h " <nl> # include " video_core / memory_manager . h " <nl> + # include " video_core / rasterizer_interface . h " <nl> + # include " video_core / renderer_base . h " <nl> + # include " video_core / textures / decoders . h " <nl> <nl> namespace Tegra : : Engines { <nl> <nl> - KeplerCompute : : KeplerCompute ( MemoryManager & memory_manager ) : memory_manager { memory_manager } { } <nl> + KeplerCompute : : KeplerCompute ( Core : : System & system , VideoCore : : RasterizerInterface & rasterizer , <nl> + MemoryManager & memory_manager ) <nl> + : system { system } , rasterizer { rasterizer } , memory_manager { memory_manager } , upload_state { <nl> + memory_manager , <nl> + regs . upload } { } <nl> <nl> KeplerCompute : : ~ KeplerCompute ( ) = default ; <nl> <nl> void KeplerCompute : : CallMethod ( const GPU : : MethodCall & method_call ) { <nl> regs . reg_array [ method_call . method ] = method_call . argument ; <nl> <nl> switch ( method_call . method ) { <nl> + case KEPLER_COMPUTE_REG_INDEX ( exec_upload ) : { <nl> + upload_state . ProcessExec ( regs . exec_upload . linear ! = 0 ) ; <nl> + break ; <nl> + } <nl> + case KEPLER_COMPUTE_REG_INDEX ( data_upload ) : { <nl> + bool is_last_call = method_call . IsLastCall ( ) ; <nl> + upload_state . ProcessData ( method_call . argument , is_last_call ) ; <nl> + if ( is_last_call ) { <nl> + system . GPU ( ) . Maxwell3D ( ) . dirty_flags . OnMemoryWrite ( ) ; <nl> + } <nl> + break ; <nl> + } <nl> case KEPLER_COMPUTE_REG_INDEX ( launch ) : <nl> - / / Abort execution since compute shaders can be used to alter game memory ( e . g . CUDA <nl> - / / kernels ) <nl> - UNREACHABLE_MSG ( " Compute shaders are not implemented " ) ; <nl> + ProcessLaunch ( ) ; <nl> break ; <nl> default : <nl> break ; <nl> } <nl> } <nl> <nl> + void KeplerCompute : : ProcessLaunch ( ) { <nl> + <nl> + const GPUVAddr launch_desc_loc = regs . launch_desc_loc . Address ( ) ; <nl> + memory_manager . ReadBlockUnsafe ( launch_desc_loc , & launch_description , <nl> + LaunchParams : : NUM_LAUNCH_PARAMETERS * sizeof ( u32 ) ) ; <nl> + <nl> + const GPUVAddr code_loc = regs . code_loc . Address ( ) + launch_description . program_start ; <nl> + LOG_WARNING ( HW_GPU , " Compute Kernel Execute at Address 0x { : 016x } , STUBBED " , code_loc ) ; <nl> + } <nl> + <nl> } / / namespace Tegra : : Engines <nl> mmm a / src / video_core / engines / kepler_compute . h <nl> ppp b / src / video_core / engines / kepler_compute . h <nl> <nl> <nl> # include < array > <nl> # include < cstddef > <nl> + # include < vector > <nl> + # include " common / bit_field . h " <nl> # include " common / common_funcs . h " <nl> # include " common / common_types . h " <nl> + # include " video_core / engines / engine_upload . h " <nl> # include " video_core / gpu . h " <nl> <nl> + namespace Core { <nl> + class System ; <nl> + } <nl> + <nl> namespace Tegra { <nl> class MemoryManager ; <nl> } <nl> <nl> + namespace VideoCore { <nl> + class RasterizerInterface ; <nl> + } <nl> + <nl> namespace Tegra : : Engines { <nl> <nl> # define KEPLER_COMPUTE_REG_INDEX ( field_name ) \ <nl> namespace Tegra : : Engines { <nl> <nl> class KeplerCompute final { <nl> public : <nl> - explicit KeplerCompute ( MemoryManager & memory_manager ) ; <nl> + explicit KeplerCompute ( Core : : System & system , VideoCore : : RasterizerInterface & rasterizer , <nl> + MemoryManager & memory_manager ) ; <nl> ~ KeplerCompute ( ) ; <nl> <nl> static constexpr std : : size_t NumConstBuffers = 8 ; <nl> class KeplerCompute final { <nl> <nl> union { <nl> struct { <nl> - INSERT_PADDING_WORDS ( 0xAF ) ; <nl> + INSERT_PADDING_WORDS ( 0x60 ) ; <nl> + <nl> + Upload : : Data upload ; <nl> + <nl> + struct { <nl> + union { <nl> + BitField < 0 , 1 , u32 > linear ; <nl> + } ; <nl> + } exec_upload ; <nl> + <nl> + u32 data_upload ; <nl> + <nl> + INSERT_PADDING_WORDS ( 0x3F ) ; <nl> + <nl> + struct { <nl> + u32 address ; <nl> + GPUVAddr Address ( ) const { <nl> + return static_cast < GPUVAddr > ( ( static_cast < GPUVAddr > ( address ) < < 8 ) ) ; <nl> + } <nl> + } launch_desc_loc ; <nl> + <nl> + INSERT_PADDING_WORDS ( 0x1 ) ; <nl> <nl> u32 launch ; <nl> <nl> - INSERT_PADDING_WORDS ( 0xC48 ) ; <nl> + INSERT_PADDING_WORDS ( 0x4A7 ) ; <nl> + <nl> + struct { <nl> + u32 address_high ; <nl> + u32 address_low ; <nl> + u32 limit ; <nl> + GPUVAddr Address ( ) const { <nl> + return static_cast < GPUVAddr > ( ( static_cast < GPUVAddr > ( address_high ) < < 32 ) | <nl> + address_low ) ; <nl> + } <nl> + } tsc ; <nl> + <nl> + INSERT_PADDING_WORDS ( 0x3 ) ; <nl> + <nl> + struct { <nl> + u32 address_high ; <nl> + u32 address_low ; <nl> + u32 limit ; <nl> + GPUVAddr Address ( ) const { <nl> + return static_cast < GPUVAddr > ( ( static_cast < GPUVAddr > ( address_high ) < < 32 ) | <nl> + address_low ) ; <nl> + } <nl> + } tic ; <nl> + <nl> + INSERT_PADDING_WORDS ( 0x22 ) ; <nl> + <nl> + struct { <nl> + u32 address_high ; <nl> + u32 address_low ; <nl> + GPUVAddr Address ( ) const { <nl> + return static_cast < GPUVAddr > ( ( static_cast < GPUVAddr > ( address_high ) < < 32 ) | <nl> + address_low ) ; <nl> + } <nl> + } code_loc ; <nl> + <nl> + INSERT_PADDING_WORDS ( 0x3FE ) ; <nl> + <nl> + u32 texture_const_buffer_index ; <nl> + <nl> + INSERT_PADDING_WORDS ( 0x374 ) ; <nl> } ; <nl> std : : array < u32 , NUM_REGS > reg_array ; <nl> } ; <nl> } regs { } ; <nl> + <nl> + struct LaunchParams { <nl> + static constexpr std : : size_t NUM_LAUNCH_PARAMETERS = 0x40 ; <nl> + <nl> + INSERT_PADDING_WORDS ( 0x8 ) ; <nl> + <nl> + u32 program_start ; <nl> + <nl> + INSERT_PADDING_WORDS ( 0x2 ) ; <nl> + <nl> + BitField < 30 , 1 , u32 > linked_tsc ; <nl> + <nl> + BitField < 0 , 31 , u32 > grid_dim_x ; <nl> + <nl> + union { <nl> + BitField < 0 , 16 , u32 > grid_dim_y ; <nl> + BitField < 16 , 16 , u32 > grid_dim_z ; <nl> + } ; <nl> + <nl> + INSERT_PADDING_WORDS ( 0x3 ) ; <nl> + <nl> + BitField < 0 , 16 , u32 > shared_alloc ; <nl> + <nl> + BitField < 0 , 31 , u32 > block_dim_x ; <nl> + <nl> + union { <nl> + BitField < 0 , 16 , u32 > block_dim_y ; <nl> + BitField < 16 , 16 , u32 > block_dim_z ; <nl> + } ; <nl> + <nl> + union { <nl> + BitField < 0 , 8 , u32 > const_buffer_enable_mask ; <nl> + BitField < 29 , 2 , u32 > cache_layout ; <nl> + } memory_config ; <nl> + <nl> + INSERT_PADDING_WORDS ( 0x8 ) ; <nl> + <nl> + struct { <nl> + u32 address_low ; <nl> + union { <nl> + BitField < 0 , 8 , u32 > address_high ; <nl> + BitField < 15 , 17 , u32 > size ; <nl> + } ; <nl> + GPUVAddr Address ( ) const { <nl> + return static_cast < GPUVAddr > ( ( static_cast < GPUVAddr > ( address_high . Value ( ) ) < < 32 ) | <nl> + address_low ) ; <nl> + } <nl> + } const_buffer_config [ 8 ] ; <nl> + <nl> + union { <nl> + BitField < 0 , 20 , u32 > local_pos_alloc ; <nl> + BitField < 27 , 5 , u32 > barrier_alloc ; <nl> + } ; <nl> + <nl> + union { <nl> + BitField < 0 , 20 , u32 > local_neg_alloc ; <nl> + BitField < 24 , 5 , u32 > gpr_alloc ; <nl> + } ; <nl> + <nl> + INSERT_PADDING_WORDS ( 0x11 ) ; <nl> + } launch_description ; <nl> + <nl> + struct { <nl> + u32 write_offset = 0 ; <nl> + u32 copy_size = 0 ; <nl> + std : : vector < u8 > inner_buffer ; <nl> + } state { } ; <nl> + <nl> static_assert ( sizeof ( Regs ) = = Regs : : NUM_REGS * sizeof ( u32 ) , <nl> " KeplerCompute Regs has wrong size " ) ; <nl> <nl> + static_assert ( sizeof ( LaunchParams ) = = LaunchParams : : NUM_LAUNCH_PARAMETERS * sizeof ( u32 ) , <nl> + " KeplerCompute LaunchParams has wrong size " ) ; <nl> + <nl> / / / Write the value to the register identified by method . <nl> void CallMethod ( const GPU : : MethodCall & method_call ) ; <nl> <nl> private : <nl> + Core : : System & system ; <nl> + VideoCore : : RasterizerInterface & rasterizer ; <nl> MemoryManager & memory_manager ; <nl> + Upload : : State upload_state ; <nl> + <nl> + void ProcessLaunch ( ) ; <nl> } ; <nl> <nl> # define ASSERT_REG_POSITION ( field_name , position ) \ <nl> static_assert ( offsetof ( KeplerCompute : : Regs , field_name ) = = position * 4 , \ <nl> " Field " # field_name " has invalid position " ) <nl> <nl> + # define ASSERT_LAUNCH_PARAM_POSITION ( field_name , position ) \ <nl> + static_assert ( offsetof ( KeplerCompute : : LaunchParams , field_name ) = = position * 4 , \ <nl> + " Field " # field_name " has invalid position " ) <nl> + <nl> + ASSERT_REG_POSITION ( upload , 0x60 ) ; <nl> + ASSERT_REG_POSITION ( exec_upload , 0x6C ) ; <nl> + ASSERT_REG_POSITION ( data_upload , 0x6D ) ; <nl> ASSERT_REG_POSITION ( launch , 0xAF ) ; <nl> + ASSERT_REG_POSITION ( tsc , 0x557 ) ; <nl> + ASSERT_REG_POSITION ( tic , 0x55D ) ; <nl> + ASSERT_REG_POSITION ( code_loc , 0x582 ) ; <nl> + ASSERT_REG_POSITION ( texture_const_buffer_index , 0x982 ) ; <nl> + ASSERT_LAUNCH_PARAM_POSITION ( program_start , 0x8 ) ; <nl> + ASSERT_LAUNCH_PARAM_POSITION ( grid_dim_x , 0xC ) ; <nl> + ASSERT_LAUNCH_PARAM_POSITION ( shared_alloc , 0x11 ) ; <nl> + ASSERT_LAUNCH_PARAM_POSITION ( block_dim_x , 0x12 ) ; <nl> + ASSERT_LAUNCH_PARAM_POSITION ( memory_config , 0x14 ) ; <nl> + ASSERT_LAUNCH_PARAM_POSITION ( const_buffer_config , 0x1D ) ; <nl> <nl> # undef ASSERT_REG_POSITION <nl> <nl> mmm a / src / video_core / gpu . cpp <nl> ppp b / src / video_core / gpu . cpp <nl> GPU : : GPU ( Core : : System & system , VideoCore : : RendererBase & renderer ) : renderer { ren <nl> dma_pusher = std : : make_unique < Tegra : : DmaPusher > ( * this ) ; <nl> maxwell_3d = std : : make_unique < Engines : : Maxwell3D > ( system , rasterizer , * memory_manager ) ; <nl> fermi_2d = std : : make_unique < Engines : : Fermi2D > ( rasterizer , * memory_manager ) ; <nl> - kepler_compute = std : : make_unique < Engines : : KeplerCompute > ( * memory_manager ) ; <nl> + kepler_compute = std : : make_unique < Engines : : KeplerCompute > ( system , rasterizer , * memory_manager ) ; <nl> maxwell_dma = std : : make_unique < Engines : : MaxwellDMA > ( system , rasterizer , * memory_manager ) ; <nl> kepler_memory = std : : make_unique < Engines : : KeplerMemory > ( system , * memory_manager ) ; <nl> } <nl> | Introduce skeleton of the GPU Compute Engine . | yuzu-emu/yuzu | e4ff140b99339589d87836f865fc437719adbbe9 | 2019-04-22T23:05:43Z |
mmm a / src / rpc / blockchain . cpp <nl> ppp b / src / rpc / blockchain . cpp <nl> static UniValue getmempoolancestors ( const JSONRPCRequest & request ) <nl> RPCResult : : Type : : ARR , " " , " " , <nl> { { RPCResult : : Type : : STR_HEX , " " , " The transaction id of an in - mempool ancestor transaction " } } } , <nl> RPCResult { " for verbose = true " , <nl> - RPCResult : : Type : : OBJ , " transactionid " , " " , MempoolEntryDescription ( ) } , <nl> + RPCResult : : Type : : OBJ_DYN , " " , " " , <nl> + { <nl> + { RPCResult : : Type : : OBJ , " transactionid " , " " , MempoolEntryDescription ( ) } , <nl> + } } , <nl> } , <nl> RPCExamples { <nl> HelpExampleCli ( " getmempoolancestors " , " \ " mytxid \ " " ) <nl> static UniValue getmempoolancestors ( const JSONRPCRequest & request ) <nl> for ( CTxMemPool : : txiter ancestorIt : setAncestors ) { <nl> o . push_back ( ancestorIt - > GetTx ( ) . GetHash ( ) . ToString ( ) ) ; <nl> } <nl> - <nl> return o ; <nl> } else { <nl> UniValue o ( UniValue : : VOBJ ) ; <nl> | doc : Fix getmempoolancestor RPC result doc | bitcoin/bitcoin | 333329dbda423b00098ec9f8702d75d24468c56e | 2020-08-19T08:41:27Z |
mmm a / src / compiler / ast - graph - builder . cc <nl> ppp b / src / compiler / ast - graph - builder . cc <nl> bool AstGraphBuilder : : CreateGraph ( bool stack_check ) { <nl> / / Initialize control scope . <nl> ControlScope control ( this ) ; <nl> <nl> + / / TODO ( mstarzinger ) : For now we cannot assume that the { this } parameter is <nl> + / / not { the_hole } , because for derived classes { this } has a TDZ and the <nl> + / / JSConstructStubForDerived magically passes { the_hole } as a receiver . <nl> + if ( scope - > has_this_declaration ( ) & & scope - > receiver ( ) - > is_const_mode ( ) ) { <nl> + env . RawParameterBind ( 0 , jsgraph ( ) - > TheHoleConstant ( ) ) ; <nl> + } <nl> + <nl> / / Build receiver check for sloppy mode if necessary . <nl> / / TODO ( mstarzinger / verwaest ) : Should this be moved back into the CallIC ? <nl> if ( scope - > has_this_declaration ( ) ) { <nl> Node * AstGraphBuilder : : BuildVariableLoad ( Variable * variable , <nl> } <nl> } else if ( mode = = LET | | mode = = CONST ) { <nl> / / Perform check for uninitialized let / const variables . <nl> - / / TODO ( mstarzinger ) : For now we cannot use the below optimization for <nl> - / / the { this } parameter , because JSConstructStubForDerived magically <nl> - / / passes { the_hole } as a receiver . <nl> if ( value - > op ( ) = = the_hole - > op ( ) ) { <nl> value = BuildThrowReferenceError ( variable , bailout_id ) ; <nl> - } else if ( value - > opcode ( ) = = IrOpcode : : kPhi | | variable - > is_this ( ) ) { <nl> + } else if ( value - > opcode ( ) = = IrOpcode : : kPhi ) { <nl> value = BuildHoleCheckThenThrow ( value , variable , value , bailout_id ) ; <nl> } <nl> } <nl> | [ turbofan ] Move workaround with TDZ of ' this ' variable . | v8/v8 | d67e07f3971b3fe6ecff612b5b73e9191b0e32c4 | 2015-07-20T16:02:17Z |
mmm a / src / RowLoader . cpp <nl> ppp b / src / RowLoader . cpp <nl> void RowLoader : : process ( Task & t ) <nl> sqlite3_finalize ( stmt ) ; <nl> } <nl> <nl> - if ( row ! = t . row_begin ) <nl> - emit fetched ( t . token , t . row_begin , row ) ; <nl> + emit fetched ( t . token , t . row_begin , row ) ; <nl> } <nl> | Send the fetched signal in RowLoader even when no rows where fetched | sqlitebrowser/sqlitebrowser | 9594115ef3b50cb9fc26bc3830c43fd4f9f14f61 | 2019-07-06T21:05:57Z |
mmm a / src / ruby / lib / grpc / errors . rb <nl> ppp b / src / ruby / lib / grpc / errors . rb <nl> class BadStatus < StandardError <nl> <nl> # @ param code [ Numeric ] the status code <nl> # @ param details [ String ] the details of the exception <nl> - def initialize ( code , details = ' unknown cause ' , * * kw ) <nl> + # @ param metadata [ Hash ] the error ' s metadata <nl> + def initialize ( code , details = ' unknown cause ' , metadata = { } ) <nl> super ( " # { code } : # { details } " ) <nl> @ code = code <nl> @ details = details <nl> - @ metadata = kw <nl> + @ metadata = metadata <nl> end <nl> <nl> # Converts the exception to a GRPC : : Status for use in the networking <nl> mmm a / src / ruby / lib / grpc / generic / active_call . rb <nl> ppp b / src / ruby / lib / grpc / generic / active_call . rb <nl> def check_status <nl> # raise BadStatus , propagating the metadata if present . <nl> md = status . metadata <nl> with_sym_keys = Hash [ md . each_pair . collect { | x , y | [ x . to_sym , y ] } ] <nl> - fail GRPC : : BadStatus . new ( status . code , status . details , * * with_sym_keys ) <nl> + fail GRPC : : BadStatus . new ( status . code , status . details , with_sym_keys ) <nl> end <nl> status <nl> end <nl> class ActiveCall <nl> # <nl> # @ param call [ Call ] a call on which to start and invocation <nl> # @ param q [ CompletionQueue ] the completion queue <nl> - def self . client_invoke ( call , q , * * kw ) <nl> + # @ param metadata [ Hash ] the metadata <nl> + def self . client_invoke ( call , q , metadata = { } ) <nl> fail ( TypeError , ' ! Core : : Call ' ) unless call . is_a ? Core : : Call <nl> unless q . is_a ? Core : : CompletionQueue <nl> fail ( TypeError , ' ! Core : : CompletionQueue ' ) <nl> end <nl> metadata_tag = Object . new <nl> call . run_batch ( q , metadata_tag , INFINITE_FUTURE , <nl> - SEND_INITIAL_METADATA = > kw ) <nl> + SEND_INITIAL_METADATA = > metadata ) <nl> metadata_tag <nl> end <nl> <nl> def remote_send ( req , marshalled = false ) <nl> # @ param details [ String ] details <nl> # @ param assert_finished [ true , false ] when true ( default ) , waits for <nl> # FINISHED . <nl> - # <nl> - # = = Keyword Arguments = = <nl> - # any keyword arguments are treated as metadata to be sent to the server <nl> - # if a keyword value is a list , multiple metadata for it ' s key are sent <nl> - def send_status ( code = OK , details = ' ' , assert_finished = false , * * kw ) <nl> + # @ param metadata [ Hash ] metadata to send to the server . If a value is a <nl> + # list , mulitple metadata for its key are sent <nl> + def send_status ( code = OK , details = ' ' , assert_finished = false , <nl> + metadata : { } ) <nl> ops = { <nl> - SEND_STATUS_FROM_SERVER = > Struct : : Status . new ( code , details , kw ) <nl> + SEND_STATUS_FROM_SERVER = > Struct : : Status . new ( code , details , metadata ) <nl> } <nl> ops [ RECV_CLOSE_ON_SERVER ] = nil if assert_finished <nl> @ call . run_batch ( @ cq , self , INFINITE_FUTURE , ops ) <nl> def each_remote_read_then_finish <nl> # request_response sends a request to a GRPC server , and returns the <nl> # response . <nl> # <nl> - # = = Keyword Arguments = = <nl> - # any keyword arguments are treated as metadata to be sent to the server <nl> - # if a keyword value is a list , multiple metadata for it ' s key are sent <nl> - # <nl> # @ param req [ Object ] the request sent to the server <nl> + # @ param metadata [ Hash ] metadata to be sent to the server . If a value is <nl> + # a list , multiple metadata for its key are sent <nl> # @ return [ Object ] the response received from the server <nl> - def request_response ( req , * * kw ) <nl> - start_call ( * * kw ) unless @ started <nl> + def request_response ( req , metadata : { } ) <nl> + start_call ( metadata ) unless @ started <nl> remote_send ( req ) <nl> writes_done ( false ) <nl> response = remote_read <nl> def request_response ( req , * * kw ) <nl> # array of marshallable objects ; in typical case it will be an Enumerable <nl> # that allows dynamic construction of the marshallable objects . <nl> # <nl> - # = = Keyword Arguments = = <nl> - # any keyword arguments are treated as metadata to be sent to the server <nl> - # if a keyword value is a list , multiple metadata for it ' s key are sent <nl> - # <nl> # @ param requests [ Object ] an Enumerable of requests to send <nl> + # @ param metadata [ Hash ] metadata to be sent to the server . If a value is <nl> + # a list , multiple metadata for its key are sent <nl> # @ return [ Object ] the response received from the server <nl> - def client_streamer ( requests , * * kw ) <nl> - start_call ( * * kw ) unless @ started <nl> + def client_streamer ( requests , metadata : { } ) <nl> + start_call ( metadata ) unless @ started <nl> requests . each { | r | remote_send ( r ) } <nl> writes_done ( false ) <nl> response = remote_read <nl> def client_streamer ( requests , * * kw ) <nl> # it is executed with each response as the argument and no result is <nl> # returned . <nl> # <nl> - # = = Keyword Arguments = = <nl> - # any keyword arguments are treated as metadata to be sent to the server <nl> - # if a keyword value is a list , multiple metadata for it ' s key are sent <nl> - # any keyword arguments are treated as metadata to be sent to the server . <nl> - # <nl> # @ param req [ Object ] the request sent to the server <nl> + # @ param metadata [ Hash ] metadata to be sent to the server . If a value is <nl> + # a list , multiple metadata for its key are sent <nl> # @ return [ Enumerator | nil ] a response Enumerator <nl> - def server_streamer ( req , * * kw ) <nl> - start_call ( * * kw ) unless @ started <nl> + def server_streamer ( req , metadata : { } ) <nl> + start_call ( metadata ) unless @ started <nl> remote_send ( req ) <nl> writes_done ( false ) <nl> replies = enum_for ( : each_remote_read_then_finish ) <nl> def server_streamer ( req , * * kw ) <nl> # the_call # writes_done has been called , otherwise the block will loop <nl> # forever . <nl> # <nl> - # = = Keyword Arguments = = <nl> - # any keyword arguments are treated as metadata to be sent to the server <nl> - # if a keyword value is a list , multiple metadata for it ' s key are sent <nl> - # <nl> # @ param requests [ Object ] an Enumerable of requests to send <nl> + # @ param metadata [ Hash ] metadata to be sent to the server . If a value is <nl> + # a list , multiple metadata for its key are sent <nl> # @ return [ Enumerator , nil ] a response Enumerator <nl> - def bidi_streamer ( requests , * * kw , & blk ) <nl> - start_call ( * * kw ) unless @ started <nl> + def bidi_streamer ( requests , metadata : { } , & blk ) <nl> + start_call ( metadata ) unless @ started <nl> bd = BidiCall . new ( @ call , @ cq , @ marshal , @ unmarshal , <nl> metadata_tag : @ metadata_tag ) <nl> @ metadata_tag = nil # run_on_client ensures metadata is read <nl> def op_is_done <nl> private <nl> <nl> # Starts the call if not already started <nl> - def start_call ( * * kw ) <nl> + # @ param metadata [ Hash ] metadata to be sent to the server . If a value is <nl> + # a list , multiple metadata for its key are sent <nl> + def start_call ( metadata = { } ) <nl> return if @ started <nl> - @ metadata_tag = ActiveCall . client_invoke ( @ call , @ cq , * * kw ) <nl> + @ metadata_tag = ActiveCall . client_invoke ( @ call , @ cq , metadata ) <nl> @ started = true <nl> end <nl> <nl> mmm a / src / ruby / lib / grpc / generic / client_stub . rb <nl> ppp b / src / ruby / lib / grpc / generic / client_stub . rb <nl> class ClientStub <nl> <nl> # setup_channel is used by # initialize to constuct a channel from its <nl> # arguments . <nl> - def self . setup_channel ( alt_chan , host , creds , * * kw ) <nl> + def self . setup_channel ( alt_chan , host , creds , channel_args = { } ) <nl> unless alt_chan . nil ? <nl> fail ( TypeError , ' ! Channel ' ) unless alt_chan . is_a ? ( Core : : Channel ) <nl> return alt_chan <nl> end <nl> - if kw [ ' grpc . primary_user_agent ' ] . nil ? <nl> - kw [ ' grpc . primary_user_agent ' ] = ' ' <nl> + if channel_args [ ' grpc . primary_user_agent ' ] . nil ? <nl> + channel_args [ ' grpc . primary_user_agent ' ] = ' ' <nl> else <nl> - kw [ ' grpc . primary_user_agent ' ] + = ' ' <nl> + channel_args [ ' grpc . primary_user_agent ' ] + = ' ' <nl> end <nl> - kw [ ' grpc . primary_user_agent ' ] + = " grpc - ruby / # { VERSION } " <nl> + channel_args [ ' grpc . primary_user_agent ' ] + = " grpc - ruby / # { VERSION } " <nl> unless creds . is_a ? ( Core : : ChannelCredentials ) | | creds . is_a ? ( Symbol ) <nl> fail ( TypeError , ' ! ChannelCredentials or Symbol ' ) <nl> end <nl> - Core : : Channel . new ( host , kw , creds ) <nl> + Core : : Channel . new ( host , channel_args , creds ) <nl> end <nl> <nl> # Allows users of the stub to modify the propagate mask . <nl> def self . setup_channel ( alt_chan , host , creds , * * kw ) <nl> # : this_channel_is_insecure <nl> # @ param channel_override [ Core : : Channel ] a pre - created channel <nl> # @ param timeout [ Number ] the default timeout to use in requests <nl> - # @ param kw [ KeywordArgs ] the channel arguments <nl> + # @ param channel_args [ Hash ] the channel arguments <nl> def initialize ( host , q , creds , <nl> channel_override : nil , <nl> timeout : nil , <nl> propagate_mask : nil , <nl> - * * kw ) <nl> + channel_args : { } ) <nl> fail ( TypeError , ' ! CompletionQueue ' ) unless q . is_a ? ( Core : : CompletionQueue ) <nl> - @ ch = ClientStub . setup_channel ( channel_override , host , creds , * * kw ) <nl> - alt_host = kw [ Core : : Channel : : SSL_TARGET ] <nl> + @ ch = ClientStub . setup_channel ( channel_override , host , creds , <nl> + channel_args ) <nl> + alt_host = channel_args [ Core : : Channel : : SSL_TARGET ] <nl> @ host = alt_host . nil ? ? host : alt_host <nl> @ propagate_mask = propagate_mask <nl> @ timeout = timeout . nil ? ? DEFAULT_TIMEOUT : timeout <nl> def initialize ( host , q , creds , <nl> # If return_op is true , the call returns an Operation , calling execute <nl> # on the Operation returns the response . <nl> # <nl> - # = = Keyword Args = = <nl> - # <nl> - # Unspecified keyword arguments are treated as metadata to be sent to the <nl> - # server . <nl> - # <nl> # @ param method [ String ] the RPC method to call on the GRPC server <nl> # @ param req [ Object ] the request sent to the server <nl> # @ param marshal [ Function ] f ( obj ) - > string that marshals requests <nl> # @ param unmarshal [ Function ] f ( string ) - > obj that unmarshals responses <nl> - # @ param timeout [ Numeric ] ( optional ) the max completion time in seconds <nl> # @ param deadline [ Time ] ( optional ) the time the request should complete <nl> + # @ param return_op [ true | false ] return an Operation if true <nl> # @ param parent [ Core : : Call ] a prior call whose reserved metadata <nl> # will be propagated by this one . <nl> # @ param credentials [ Core : : CallCredentials ] credentials to use when making <nl> # the call <nl> - # @ param return_op [ true | false ] return an Operation if true <nl> + # @ param metadata [ Hash ] metadata to be sent to the server <nl> # @ return [ Object ] the response received from the server <nl> def request_response ( method , req , marshal , unmarshal , <nl> deadline : nil , <nl> - timeout : nil , <nl> return_op : false , <nl> parent : nil , <nl> credentials : nil , <nl> - * * kw ) <nl> + metadata : { } ) <nl> c = new_active_call ( method , marshal , unmarshal , <nl> deadline : deadline , <nl> - timeout : timeout , <nl> parent : parent , <nl> credentials : credentials ) <nl> - return c . request_response ( req , * * kw ) unless return_op <nl> + return c . request_response ( req , metadata : metadata ) unless return_op <nl> <nl> # return the operation view of the active_call ; define # execute as a <nl> # new method for this instance that invokes # request_response . <nl> op = c . operation <nl> op . define_singleton_method ( : execute ) do <nl> - c . request_response ( req , * * kw ) <nl> + c . request_response ( req , metadata : metadata ) <nl> end <nl> op <nl> end <nl> def request_response ( method , req , marshal , unmarshal , <nl> # <nl> # If return_op is true , the call returns the response . <nl> # <nl> - # = = Keyword Args = = <nl> - # <nl> - # Unspecified keyword arguments are treated as metadata to be sent to the <nl> - # server . <nl> - # <nl> # @ param method [ String ] the RPC method to call on the GRPC server <nl> # @ param requests [ Object ] an Enumerable of requests to send <nl> # @ param marshal [ Function ] f ( obj ) - > string that marshals requests <nl> # @ param unmarshal [ Function ] f ( string ) - > obj that unmarshals responses <nl> - # @ param timeout [ Numeric ] ( optional ) the max completion time in seconds <nl> # @ param deadline [ Time ] ( optional ) the time the request should complete <nl> # @ param return_op [ true | false ] return an Operation if true <nl> # @ param parent [ Core : : Call ] a prior call whose reserved metadata <nl> # will be propagated by this one . <nl> # @ param credentials [ Core : : CallCredentials ] credentials to use when making <nl> # the call <nl> + # @ param metadata [ Hash ] metadata to be sent to the server <nl> # @ return [ Object | Operation ] the response received from the server <nl> def client_streamer ( method , requests , marshal , unmarshal , <nl> deadline : nil , <nl> - timeout : nil , <nl> return_op : false , <nl> parent : nil , <nl> credentials : nil , <nl> - * * kw ) <nl> + metadata : { } ) <nl> c = new_active_call ( method , marshal , unmarshal , <nl> deadline : deadline , <nl> - timeout : timeout , <nl> parent : parent , <nl> credentials : credentials ) <nl> - return c . client_streamer ( requests , * * kw ) unless return_op <nl> + return c . client_streamer ( requests , metadata : metadata ) unless return_op <nl> <nl> # return the operation view of the active_call ; define # execute as a <nl> # new method for this instance that invokes # client_streamer . <nl> op = c . operation <nl> op . define_singleton_method ( : execute ) do <nl> - c . client_streamer ( requests , * * kw ) <nl> + c . client_streamer ( requests , metadata : metadata ) <nl> end <nl> op <nl> end <nl> def client_streamer ( method , requests , marshal , unmarshal , <nl> # @ param req [ Object ] the request sent to the server <nl> # @ param marshal [ Function ] f ( obj ) - > string that marshals requests <nl> # @ param unmarshal [ Function ] f ( string ) - > obj that unmarshals responses <nl> - # @ param timeout [ Numeric ] ( optional ) the max completion time in seconds <nl> # @ param deadline [ Time ] ( optional ) the time the request should complete <nl> # @ param return_op [ true | false ] return an Operation if true <nl> # @ param parent [ Core : : Call ] a prior call whose reserved metadata <nl> # will be propagated by this one . <nl> # @ param credentials [ Core : : CallCredentials ] credentials to use when making <nl> # the call <nl> + # @ param metadata [ Hash ] metadata to be sent to the server <nl> # @ param blk [ Block ] when provided , is executed for each response <nl> # @ return [ Enumerator | Operation | nil ] as discussed above <nl> def server_streamer ( method , req , marshal , unmarshal , <nl> deadline : nil , <nl> - timeout : nil , <nl> return_op : false , <nl> parent : nil , <nl> credentials : nil , <nl> - * * kw , <nl> + metadata : { } , <nl> & blk ) <nl> c = new_active_call ( method , marshal , unmarshal , <nl> deadline : deadline , <nl> - timeout : timeout , <nl> parent : parent , <nl> credentials : credentials ) <nl> - return c . server_streamer ( req , * * kw , & blk ) unless return_op <nl> + return c . server_streamer ( req , metadata : metadata , & blk ) unless return_op <nl> <nl> # return the operation view of the active_call ; define # execute <nl> # as a new method for this instance that invokes # server_streamer <nl> op = c . operation <nl> op . define_singleton_method ( : execute ) do <nl> - c . server_streamer ( req , * * kw , & blk ) <nl> + c . server_streamer ( req , metadata : metadata , & blk ) <nl> end <nl> op <nl> end <nl> def server_streamer ( method , req , marshal , unmarshal , <nl> # * the deadline is exceeded <nl> # <nl> # <nl> - # = = Keyword Args = = <nl> - # <nl> - # Unspecified keyword arguments are treated as metadata to be sent to the <nl> - # server . <nl> - # <nl> # = = Return Value = = <nl> # <nl> # if the return_op is false , the return value is an Enumerator of the <nl> def server_streamer ( method , req , marshal , unmarshal , <nl> # @ param requests [ Object ] an Enumerable of requests to send <nl> # @ param marshal [ Function ] f ( obj ) - > string that marshals requests <nl> # @ param unmarshal [ Function ] f ( string ) - > obj that unmarshals responses <nl> - # @ param timeout [ Numeric ] ( optional ) the max completion time in seconds <nl> # @ param deadline [ Time ] ( optional ) the time the request should complete <nl> # @ param parent [ Core : : Call ] a prior call whose reserved metadata <nl> # will be propagated by this one . <nl> # @ param credentials [ Core : : CallCredentials ] credentials to use when making <nl> # the call <nl> # @ param return_op [ true | false ] return an Operation if true <nl> + # @ param metadata [ Hash ] metadata to be sent to the server <nl> # @ param blk [ Block ] when provided , is executed for each response <nl> # @ return [ Enumerator | nil | Operation ] as discussed above <nl> def bidi_streamer ( method , requests , marshal , unmarshal , <nl> deadline : nil , <nl> - timeout : nil , <nl> return_op : false , <nl> parent : nil , <nl> credentials : nil , <nl> - * * kw , <nl> + metadata : { } , <nl> & blk ) <nl> c = new_active_call ( method , marshal , unmarshal , <nl> deadline : deadline , <nl> - timeout : timeout , <nl> parent : parent , <nl> credentials : credentials ) <nl> <nl> - return c . bidi_streamer ( requests , * * kw , & blk ) unless return_op <nl> + return c . bidi_streamer ( requests , metadata : metadata , <nl> + & blk ) unless return_op <nl> <nl> # return the operation view of the active_call ; define # execute <nl> # as a new method for this instance that invokes # bidi_streamer <nl> op = c . operation <nl> op . define_singleton_method ( : execute ) do <nl> - c . bidi_streamer ( requests , * * kw , & blk ) <nl> + c . bidi_streamer ( requests , metadata : metadata , & blk ) <nl> end <nl> op <nl> end <nl> def bidi_streamer ( method , requests , marshal , unmarshal , <nl> # @ param timeout [ TimeConst ] <nl> def new_active_call ( method , marshal , unmarshal , <nl> deadline : nil , <nl> - timeout : nil , <nl> parent : nil , <nl> credentials : nil ) <nl> - if deadline . nil ? <nl> - deadline = from_relative_time ( timeout . nil ? ? @ timeout : timeout ) <nl> - end <nl> + <nl> + deadline = from_relative_time ( @ timeout ) if deadline . nil ? <nl> # Provide each new client call with its own completion queue <nl> call_queue = Core : : CompletionQueue . new <nl> call = @ ch . create_call ( call_queue , <nl> mmm a / src / ruby / lib / grpc / generic / rpc_desc . rb <nl> ppp b / src / ruby / lib / grpc / generic / rpc_desc . rb <nl> def run_server_method ( active_call , mth ) <nl> else # is a bidi_stream <nl> active_call . run_server_bidi ( mth ) <nl> end <nl> - send_status ( active_call , OK , ' OK ' , * * active_call . output_metadata ) <nl> + send_status ( active_call , OK , ' OK ' , active_call . output_metadata ) <nl> rescue BadStatus = > e <nl> # this is raised by handlers that want GRPC to send an application error <nl> # code and detail message and some additional app - specific metadata . <nl> GRPC . logger . debug ( " app err : # { active_call } , status : # { e . code } : # { e . details } " ) <nl> - send_status ( active_call , e . code , e . details , * * e . metadata ) <nl> + send_status ( active_call , e . code , e . details , e . metadata ) <nl> rescue Core : : CallError = > e <nl> # This is raised by GRPC internals but should rarely , if ever happen . <nl> # Log it , but don ' t notify the other endpoint . . <nl> def arity_error ( mth , want , msg ) <nl> " # # { mth . name } : bad arg count ; got : # { mth . arity } , want : # { want } , # { msg } " <nl> end <nl> <nl> - def send_status ( active_client , code , details , * * kw ) <nl> + def send_status ( active_client , code , details , metadata = { } ) <nl> details = ' Not sure why ' if details . nil ? <nl> GRPC . logger . debug ( " Sending status # { code } : # { details } " ) <nl> - active_client . send_status ( code , details , code = = OK , * * kw ) <nl> + active_client . send_status ( code , details , code = = OK , metadata : metadata ) <nl> rescue StandardError = > e <nl> GRPC . logger . warn ( " Could not send status # { code } : # { details } " ) <nl> GRPC . logger . warn ( e ) <nl> mmm a / src / ruby / lib / grpc / generic / rpc_server . rb <nl> ppp b / src / ruby / lib / grpc / generic / rpc_server . rb <nl> def self . setup_cq ( alt_cq ) <nl> alt_cq <nl> end <nl> <nl> - # setup_srv is used by # initialize to constuct a Core : : Server from its <nl> - # arguments . <nl> - def self . setup_srv ( alt_srv , cq , * * kw ) <nl> - return Core : : Server . new ( cq , kw ) if alt_srv . nil ? <nl> - fail ( TypeError , ' ! Server ' ) unless alt_srv . is_a ? Core : : Server <nl> - alt_srv <nl> - end <nl> - <nl> # setup_connect_md_proc is used by # initialize to validate the <nl> # connect_md_proc . <nl> def self . setup_connect_md_proc ( a_proc ) <nl> def self . setup_connect_md_proc ( a_proc ) <nl> # instance , however other arbitrary are allowed and when present are used <nl> # to configure the listeninng connection set up by the RpcServer . <nl> # <nl> - # * server_override : which if passed must be a [ GRPC : : Core : : Server ] . When <nl> - # present . <nl> - # <nl> # * poll_period : when present , the server polls for new events with this <nl> # period <nl> # <nl> def self . setup_connect_md_proc ( a_proc ) <nl> # when non - nil is a proc for determining metadata to to send back the client <nl> # on receiving an invocation req . The proc signature is : <nl> # { key : val , . . } func ( method_name , { key : val , . . . } ) <nl> + # <nl> + # * server_args : <nl> + # A server arguments hash to be passed down to the underlying core server <nl> def initialize ( pool_size : DEFAULT_POOL_SIZE , <nl> max_waiting_requests : DEFAULT_MAX_WAITING_REQUESTS , <nl> poll_period : DEFAULT_POLL_PERIOD , <nl> completion_queue_override : nil , <nl> - server_override : nil , <nl> connect_md_proc : nil , <nl> - * * kw ) <nl> + server_args : { } ) <nl> @ connect_md_proc = RpcServer . setup_connect_md_proc ( connect_md_proc ) <nl> @ cq = RpcServer . setup_cq ( completion_queue_override ) <nl> @ max_waiting_requests = max_waiting_requests <nl> def initialize ( pool_size : DEFAULT_POOL_SIZE , <nl> # running_state can take 4 values : : not_started , : running , : stopping , and <nl> # : stopped . State transitions can only proceed in that order . <nl> @ running_state = : not_started <nl> - @ server = RpcServer . setup_srv ( server_override , @ cq , * * kw ) <nl> + @ server = Core : : Server . new ( @ cq , server_args ) <nl> end <nl> <nl> # stops a running server <nl> mmm a / src / ruby / lib / grpc / generic / service . rb <nl> ppp b / src / ruby / lib / grpc / generic / service . rb <nl> def initialize ( host , creds , * * kw ) <nl> unmarshal = desc . unmarshal_proc ( : output ) <nl> route = " / # { route_prefix } / # { name } " <nl> if desc . request_response ? <nl> - define_method ( mth_name ) do | req , * * kw | <nl> + define_method ( mth_name ) do | req , metadata = { } | <nl> GRPC . logger . debug ( " calling # { @ host } : # { route } " ) <nl> - request_response ( route , req , marshal , unmarshal , * * kw ) <nl> + request_response ( route , req , marshal , unmarshal , metadata ) <nl> end <nl> elsif desc . client_streamer ? <nl> - define_method ( mth_name ) do | reqs , * * kw | <nl> + define_method ( mth_name ) do | reqs , metadata = { } | <nl> GRPC . logger . debug ( " calling # { @ host } : # { route } " ) <nl> - client_streamer ( route , reqs , marshal , unmarshal , * * kw ) <nl> + client_streamer ( route , reqs , marshal , unmarshal , metadata ) <nl> end <nl> elsif desc . server_streamer ? <nl> - define_method ( mth_name ) do | req , * * kw , & blk | <nl> + define_method ( mth_name ) do | req , metadata = { } , & blk | <nl> GRPC . logger . debug ( " calling # { @ host } : # { route } " ) <nl> - server_streamer ( route , req , marshal , unmarshal , * * kw , & blk ) <nl> + server_streamer ( route , req , marshal , unmarshal , metadata , & blk ) <nl> end <nl> else # is a bidi_stream <nl> - define_method ( mth_name ) do | reqs , * * kw , & blk | <nl> + define_method ( mth_name ) do | reqs , metadata = { } , & blk | <nl> GRPC . logger . debug ( " calling # { @ host } : # { route } " ) <nl> - bidi_streamer ( route , reqs , marshal , unmarshal , * * kw , & blk ) <nl> + bidi_streamer ( route , reqs , marshal , unmarshal , metadata , & blk ) <nl> end <nl> end <nl> end <nl> mmm a / src / ruby / pb / test / client . rb <nl> ppp b / src / ruby / pb / test / client . rb <nl> def create_stub ( opts ) <nl> if opts . secure <nl> creds = ssl_creds ( opts . use_test_ca ) <nl> stub_opts = { <nl> - GRPC : : Core : : Channel : : SSL_TARGET = > opts . host_override <nl> + channel_args : { <nl> + GRPC : : Core : : Channel : : SSL_TARGET = > opts . host_override <nl> + } <nl> } <nl> <nl> # Add service account creds if specified <nl> def ping_pong <nl> def timeout_on_sleeping_server <nl> msg_sizes = [ [ 27_182 , 31_415 ] ] <nl> ppp = PingPongPlayer . new ( msg_sizes ) <nl> - resps = @ stub . full_duplex_call ( ppp . each_item , timeout : 0 . 001 ) <nl> + deadline = GRPC : : Core : : TimeConsts : : from_relative_time ( 0 . 001 ) <nl> + resps = @ stub . full_duplex_call ( ppp . each_item , deadline : deadline ) <nl> resps . each { | r | ppp . queue . push ( r ) } <nl> fail ' Should have raised GRPC : : BadStatus ( DEADLINE_EXCEEDED ) ' <nl> rescue GRPC : : BadStatus = > e <nl> mmm a / src / ruby / qps / client . rb <nl> ppp b / src / ruby / qps / client . rb <nl> def initialize ( config ) <nl> cred = GRPC : : Core : : ChannelCredentials . new ( ) <nl> end <nl> if config . security_params . server_host_override <nl> - opts [ GRPC : : Core : : Channel : : SSL_TARGET ] = <nl> + channel_args = { } <nl> + channel_args [ GRPC : : Core : : Channel : : SSL_TARGET ] = <nl> config . security_params . server_host_override <nl> + opts [ : channel_args ] = channel_args <nl> end <nl> else <nl> cred = : this_channel_is_insecure <nl> mmm a / src / ruby / qps / server . rb <nl> ppp b / src / ruby / qps / server . rb <nl> def initialize ( config , port ) <nl> @ port = @ server . add_http2_port ( " 0 . 0 . 0 . 0 : " + port . to_s , cred ) <nl> @ server . handle ( BenchmarkServiceImpl . new ) <nl> @ start_time = Time . now <nl> - Thread . new { <nl> + t = Thread . new { <nl> @ server . run <nl> } <nl> + t . abort_on_exception <nl> end <nl> def mark ( reset ) <nl> s = Grpc : : Testing : : ServerStats . new ( time_elapsed : <nl> - ( Time . now - @ start_time ) . to_f ) <nl> + ( Time . now - @ start_time ) . to_f ) <nl> @ start_time = Time . now if reset <nl> s <nl> end <nl> mmm a / src / ruby / spec / generic / active_call_spec . rb <nl> ppp b / src / ruby / spec / generic / active_call_spec . rb <nl> <nl> end <nl> <nl> describe ' # client_invoke ' do <nl> - it ' sends keywords as metadata to the server when the are present ' do <nl> + it ' sends metadata to the server when present ' do <nl> call = make_test_call <nl> - ActiveCall . client_invoke ( call , @ client_queue , k1 : ' v1 ' , k2 : ' v2 ' ) <nl> + metadata = { k1 : ' v1 ' , k2 : ' v2 ' } <nl> + ActiveCall . client_invoke ( call , @ client_queue , metadata ) <nl> recvd_rpc = @ server . request_call ( @ server_queue , @ server_tag , deadline ) <nl> recvd_call = recvd_rpc . call <nl> expect ( recvd_call ) . to_not be_nil <nl> mmm a / src / ruby / spec / generic / client_stub_spec . rb <nl> ppp b / src / ruby / spec / generic / client_stub_spec . rb <nl> def load_test_certs <nl> describe ' # new ' do <nl> let ( : fake_host ) { ' localhost : 0 ' } <nl> it ' can be created from a host and args ' do <nl> - opts = { a_channel_arg : ' an_arg ' } <nl> - blk = proc do <nl> - GRPC : : ClientStub . new ( fake_host , @ cq , : this_channel_is_insecure , * * opts ) <nl> - end <nl> - expect ( & blk ) . not_to raise_error <nl> - end <nl> - <nl> - it ' can be created with a default deadline ' do <nl> - opts = { a_channel_arg : ' an_arg ' , deadline : 5 } <nl> + opts = { channel_args : { a_channel_arg : ' an_arg ' } } <nl> blk = proc do <nl> GRPC : : ClientStub . new ( fake_host , @ cq , : this_channel_is_insecure , * * opts ) <nl> end <nl> def load_test_certs <nl> end <nl> <nl> it ' can be created with an channel override ' do <nl> - opts = { a_channel_arg : ' an_arg ' , channel_override : @ ch } <nl> + opts = { <nl> + channel_args : { a_channel_arg : ' an_arg ' } , <nl> + channel_override : @ ch <nl> + } <nl> blk = proc do <nl> GRPC : : ClientStub . new ( fake_host , @ cq , : this_channel_is_insecure , * * opts ) <nl> end <nl> def load_test_certs <nl> <nl> it ' cannot be created with a bad channel override ' do <nl> blk = proc do <nl> - opts = { a_channel_arg : ' an_arg ' , channel_override : Object . new } <nl> + opts = { <nl> + channel_args : { a_channel_arg : ' an_arg ' } , <nl> + channel_override : Object . new <nl> + } <nl> GRPC : : ClientStub . new ( fake_host , @ cq , : this_channel_is_insecure , * * opts ) <nl> end <nl> expect ( & blk ) . to raise_error <nl> def load_test_certs <nl> <nl> it ' cannot be created with bad credentials ' do <nl> blk = proc do <nl> - opts = { a_channel_arg : ' an_arg ' } <nl> + opts = { channel_args : { a_channel_arg : ' an_arg ' } } <nl> GRPC : : ClientStub . new ( fake_host , @ cq , Object . new , * * opts ) <nl> end <nl> expect ( & blk ) . to raise_error <nl> def load_test_certs <nl> certs = load_test_certs <nl> blk = proc do <nl> opts = { <nl> - GRPC : : Core : : Channel : : SSL_TARGET = > ' foo . test . google . fr ' , <nl> - a_channel_arg : ' an_arg ' <nl> + channel_args : { <nl> + GRPC : : Core : : Channel : : SSL_TARGET = > ' foo . test . google . fr ' , <nl> + a_channel_arg : ' an_arg ' <nl> + } <nl> } <nl> creds = GRPC : : Core : : ChannelCredentials . new ( certs [ 0 ] , nil , nil ) <nl> GRPC : : ClientStub . new ( fake_host , @ cq , creds , * * opts ) <nl> def load_test_certs <nl> describe ' without a call operation ' do <nl> def get_response ( stub ) <nl> stub . request_response ( @ method , @ sent_msg , noop , noop , <nl> - k1 : ' v1 ' , k2 : ' v2 ' ) <nl> + metadata : { k1 : ' v1 ' , k2 : ' v2 ' } ) <nl> end <nl> <nl> it_behaves_like ' request response ' <nl> def get_response ( stub ) <nl> describe ' via a call operation ' do <nl> def get_response ( stub ) <nl> op = stub . request_response ( @ method , @ sent_msg , noop , noop , <nl> - return_op : true , k1 : ' v1 ' , k2 : ' v2 ' ) <nl> + return_op : true , <nl> + metadata : { k1 : ' v1 ' , k2 : ' v2 ' } ) <nl> expect ( op ) . to be_a ( GRPC : : ActiveCall : : Operation ) <nl> op . execute <nl> end <nl> def get_response ( stub ) <nl> server_port = create_test_server <nl> host = " localhost : # { server_port } " <nl> @ stub = GRPC : : ClientStub . new ( host , @ cq , : this_channel_is_insecure ) <nl> - @ options = { k1 : ' v1 ' , k2 : ' v2 ' } <nl> + @ metadata = { k1 : ' v1 ' , k2 : ' v2 ' } <nl> @ sent_msgs = Array . new ( 3 ) { | i | ' msg_ ' + ( i + 1 ) . to_s } <nl> @ resp = ' a_reply ' <nl> end <nl> def get_response ( stub ) <nl> end <nl> <nl> it ' should send metadata to the server ok ' do <nl> - th = run_client_streamer ( @ sent_msgs , @ resp , @ pass , @ options ) <nl> + th = run_client_streamer ( @ sent_msgs , @ resp , @ pass , * * @ metadata ) <nl> expect ( get_response ( @ stub ) ) . to eq ( @ resp ) <nl> th . join <nl> end <nl> def get_response ( stub ) <nl> end <nl> <nl> it ' should raise ArgumentError if metadata contains invalid values ' do <nl> - @ options . merge ! ( k3 : 3 ) <nl> + @ metadata . merge ! ( k3 : 3 ) <nl> expect do <nl> get_response ( @ stub ) <nl> end . to raise_error ( ArgumentError , <nl> def get_response ( stub ) <nl> <nl> describe ' without a call operation ' do <nl> def get_response ( stub ) <nl> - stub . client_streamer ( @ method , @ sent_msgs , noop , noop , @ options ) <nl> + stub . client_streamer ( @ method , @ sent_msgs , noop , noop , <nl> + metadata : @ metadata ) <nl> end <nl> <nl> it_behaves_like ' client streaming ' <nl> def get_response ( stub ) <nl> describe ' via a call operation ' do <nl> def get_response ( stub ) <nl> op = stub . client_streamer ( @ method , @ sent_msgs , noop , noop , <nl> - @ options . merge ( return_op : true ) ) <nl> + return_op : true , metadata : @ metadata ) <nl> expect ( op ) . to be_a ( GRPC : : ActiveCall : : Operation ) <nl> op . execute <nl> end <nl> def get_response ( stub ) <nl> describe ' without a call operation ' do <nl> def get_responses ( stub ) <nl> e = stub . server_streamer ( @ method , @ sent_msg , noop , noop , <nl> - k1 : ' v1 ' , k2 : ' v2 ' ) <nl> + metadata : { k1 : ' v1 ' , k2 : ' v2 ' } ) <nl> expect ( e ) . to be_a ( Enumerator ) <nl> e <nl> end <nl> def get_responses ( stub ) <nl> describe ' via a call operation ' do <nl> def get_responses ( stub ) <nl> op = stub . server_streamer ( @ method , @ sent_msg , noop , noop , <nl> - return_op : true , k1 : ' v1 ' , k2 : ' v2 ' ) <nl> + return_op : true , <nl> + metadata : { k1 : ' v1 ' , k2 : ' v2 ' } ) <nl> expect ( op ) . to be_a ( GRPC : : ActiveCall : : Operation ) <nl> e = op . execute <nl> expect ( e ) . to be_a ( Enumerator ) <nl> def get_responses ( stub ) <nl> stub = GRPC : : ClientStub . new ( @ host , @ cq , : this_channel_is_insecure ) <nl> blk = proc do <nl> e = stub . bidi_streamer ( @ method , @ sent_msgs , noop , noop , <nl> - timeout : 0 . 001 ) <nl> + deadline : from_relative_time ( 0 . 001 ) ) <nl> e . collect { | r | r } <nl> end <nl> expect ( & blk ) . to raise_error GRPC : : BadStatus , / Deadline Exceeded / <nl> mmm a / src / ruby / spec / generic / rpc_desc_spec . rb <nl> ppp b / src / ruby / spec / generic / rpc_desc_spec . rb <nl> <nl> it ' sends the specified status if BadStatus is raised ' do <nl> expect ( @ call ) . to receive ( : remote_read ) . once . and_return ( Object . new ) <nl> expect ( @ call ) . to receive ( : send_status ) . once . with ( @ bs_code , ' NOK ' , false , <nl> - { } ) <nl> + metadata : { } ) <nl> this_desc . run_server_method ( @ call , method ( : bad_status ) ) <nl> end <nl> <nl> it ' sends status UNKNOWN if other StandardErrors are raised ' do <nl> expect ( @ call ) . to receive ( : remote_read ) . once . and_return ( Object . new ) <nl> expect ( @ call ) . to receive ( : send_status ) . once . with ( UNKNOWN , @ no_reason , <nl> - false , { } ) <nl> + false , metadata : { } ) <nl> this_desc . run_server_method ( @ call , method ( : other_error ) ) <nl> end <nl> <nl> <nl> expect ( @ call ) . to receive ( : remote_send ) . once . with ( @ ok_response ) <nl> expect ( @ call ) . to receive ( : output_metadata ) . and_return ( fake_md ) <nl> expect ( @ call ) . to receive ( : send_status ) . once . with ( OK , ' OK ' , true , <nl> - * * fake_md ) <nl> + metadata : fake_md ) <nl> this_desc . run_server_method ( @ call , method ( : fake_reqresp ) ) <nl> end <nl> end <nl> <nl> <nl> it ' sends the specified status if BadStatus is raised ' do <nl> expect ( @ call ) . to receive ( : send_status ) . once . with ( @ bs_code , ' NOK ' , false , <nl> - { } ) <nl> + metadata : { } ) <nl> @ client_streamer . run_server_method ( @ call , method ( : bad_status_alt ) ) <nl> end <nl> <nl> it ' sends status UNKNOWN if other StandardErrors are raised ' do <nl> - expect ( @ call ) . to receive ( : send_status ) . once . with ( UNKNOWN , @ no_reason , <nl> - false , { } ) <nl> + expect ( @ call ) . to receive ( : send_status ) . once . with ( UNKNOWN , @ no_reason , <nl> + false , metadata : { } ) <nl> @ client_streamer . run_server_method ( @ call , method ( : other_error_alt ) ) <nl> end <nl> <nl> <nl> expect ( @ call ) . to receive ( : remote_send ) . once . with ( @ ok_response ) <nl> expect ( @ call ) . to receive ( : output_metadata ) . and_return ( fake_md ) <nl> expect ( @ call ) . to receive ( : send_status ) . once . with ( OK , ' OK ' , true , <nl> - * * fake_md ) <nl> + metadata : fake_md ) <nl> @ client_streamer . run_server_method ( @ call , method ( : fake_clstream ) ) <nl> end <nl> end <nl> <nl> expect ( @ call ) . to receive ( : remote_send ) . twice . with ( @ ok_response ) <nl> expect ( @ call ) . to receive ( : output_metadata ) . and_return ( fake_md ) <nl> expect ( @ call ) . to receive ( : send_status ) . once . with ( OK , ' OK ' , true , <nl> - * * fake_md ) <nl> + metadata : fake_md ) <nl> @ server_streamer . run_server_method ( @ call , method ( : fake_svstream ) ) <nl> end <nl> end <nl> <nl> e = GRPC : : BadStatus . new ( @ bs_code , ' NOK ' ) <nl> expect ( @ call ) . to receive ( : run_server_bidi ) . and_raise ( e ) <nl> expect ( @ call ) . to receive ( : send_status ) . once . with ( @ bs_code , ' NOK ' , false , <nl> - { } ) <nl> + metadata : { } ) <nl> @ bidi_streamer . run_server_method ( @ call , method ( : bad_status_alt ) ) <nl> end <nl> <nl> it ' sends status UNKNOWN if other StandardErrors are raised ' do <nl> expect ( @ call ) . to receive ( : run_server_bidi ) . and_raise ( StandardError ) <nl> expect ( @ call ) . to receive ( : send_status ) . once . with ( UNKNOWN , @ no_reason , <nl> - false , { } ) <nl> + false , metadata : { } ) <nl> @ bidi_streamer . run_server_method ( @ call , method ( : other_error_alt ) ) <nl> end <nl> <nl> <nl> expect ( @ call ) . to receive ( : run_server_bidi ) <nl> expect ( @ call ) . to receive ( : output_metadata ) . and_return ( fake_md ) <nl> expect ( @ call ) . to receive ( : send_status ) . once . with ( OK , ' OK ' , true , <nl> - * * fake_md ) <nl> + metadata : fake_md ) <nl> @ bidi_streamer . run_server_method ( @ call , method ( : fake_bidistream ) ) <nl> end <nl> end <nl> mmm a / src / ruby / spec / generic / rpc_server_spec . rb <nl> ppp b / src / ruby / spec / generic / rpc_server_spec . rb <nl> def initialize ( _default_var = ' ignored ' ) <nl> end <nl> <nl> def an_rpc ( _req , _call ) <nl> - fail GRPC : : BadStatus . new ( @ code , @ details , * * @ md ) <nl> + fail GRPC : : BadStatus . new ( @ code , @ details , @ md ) <nl> end <nl> end <nl> <nl> def an_rpc ( req , call ) <nl> @ noop = proc { | x | x } <nl> <nl> @ server_queue = GRPC : : Core : : CompletionQueue . new <nl> - server_host = ' 0 . 0 . 0 . 0 : 0 ' <nl> - @ server = GRPC : : Core : : Server . new ( @ server_queue , nil ) <nl> - server_port = @ server . add_http2_port ( server_host , : this_port_is_insecure ) <nl> - @ host = " localhost : # { server_port } " <nl> - @ ch = GRPC : : Core : : Channel . new ( @ host , nil , : this_channel_is_insecure ) <nl> end <nl> <nl> describe ' # new ' do <nl> it ' can be created with just some args ' do <nl> - opts = { a_channel_arg : ' an_arg ' } <nl> - blk = proc do <nl> - RpcServer . new ( * * opts ) <nl> - end <nl> - expect ( & blk ) . not_to raise_error <nl> - end <nl> - <nl> - it ' can be created with a default deadline ' do <nl> - opts = { a_channel_arg : ' an_arg ' , deadline : 5 } <nl> + opts = { server_args : { a_channel_arg : ' an_arg ' } } <nl> blk = proc do <nl> RpcServer . new ( * * opts ) <nl> end <nl> def an_rpc ( req , call ) <nl> <nl> it ' can be created with a completion queue override ' do <nl> opts = { <nl> - a_channel_arg : ' an_arg ' , <nl> + server_args : { a_channel_arg : ' an_arg ' } , <nl> completion_queue_override : @ server_queue <nl> } <nl> blk = proc do <nl> def an_rpc ( req , call ) <nl> it ' cannot be created with a bad completion queue override ' do <nl> blk = proc do <nl> opts = { <nl> - a_channel_arg : ' an_arg ' , <nl> + server_args : { a_channel_arg : ' an_arg ' } , <nl> completion_queue_override : Object . new <nl> } <nl> RpcServer . new ( * * opts ) <nl> def an_rpc ( req , call ) <nl> it ' cannot be created with invalid ServerCredentials ' do <nl> blk = proc do <nl> opts = { <nl> - a_channel_arg : ' an_arg ' , <nl> + server_args : { a_channel_arg : ' an_arg ' } , <nl> creds : Object . new <nl> } <nl> RpcServer . new ( * * opts ) <nl> end <nl> expect ( & blk ) . to raise_error <nl> end <nl> - <nl> - it ' can be created with a server override ' do <nl> - opts = { a_channel_arg : ' an_arg ' , server_override : @ server } <nl> - blk = proc do <nl> - RpcServer . new ( * * opts ) <nl> - end <nl> - expect ( & blk ) . not_to raise_error <nl> - end <nl> - <nl> - it ' cannot be created with a bad server override ' do <nl> - blk = proc do <nl> - opts = { <nl> - a_channel_arg : ' an_arg ' , <nl> - server_override : Object . new <nl> - } <nl> - RpcServer . new ( * * opts ) <nl> - end <nl> - expect ( & blk ) . to raise_error <nl> - end <nl> end <nl> <nl> describe ' # stopped ? ' do <nl> before ( : each ) do <nl> - opts = { a_channel_arg : ' an_arg ' , poll_period : 1 . 5 } <nl> + opts = { server_args : { a_channel_arg : ' an_arg ' } , poll_period : 1 . 5 } <nl> @ srv = RpcServer . new ( * * opts ) <nl> + @ srv . add_http2_port ( ' 0 . 0 . 0 . 0 : 0 ' , : this_port_is_insecure ) <nl> end <nl> <nl> it ' starts out false ' do <nl> def an_rpc ( req , call ) <nl> <nl> describe ' # running ? ' do <nl> it ' starts out false ' do <nl> - opts = { a_channel_arg : ' an_arg ' , server_override : @ server } <nl> + opts = { <nl> + server_args : { a_channel_arg : ' an_arg ' } <nl> + } <nl> r = RpcServer . new ( * * opts ) <nl> expect ( r . running ? ) . to be ( false ) <nl> end <nl> <nl> it ' is false if run is called with no services registered ' , server : true do <nl> opts = { <nl> - a_channel_arg : ' an_arg ' , <nl> - poll_period : 2 , <nl> - server_override : @ server <nl> + server_args : { a_channel_arg : ' an_arg ' } , <nl> + poll_period : 2 <nl> } <nl> r = RpcServer . new ( * * opts ) <nl> + r . add_http2_port ( ' 0 . 0 . 0 . 0 : 0 ' , : this_port_is_insecure ) <nl> expect { r . run } . to raise_error ( RuntimeError ) <nl> end <nl> <nl> it ' is true after run is called with a registered service ' do <nl> opts = { <nl> - a_channel_arg : ' an_arg ' , <nl> - poll_period : 2 . 5 , <nl> - server_override : @ server <nl> + server_args : { a_channel_arg : ' an_arg ' } , <nl> + poll_period : 2 . 5 <nl> } <nl> r = RpcServer . new ( * * opts ) <nl> + r . add_http2_port ( ' 0 . 0 . 0 . 0 : 0 ' , : this_port_is_insecure ) <nl> r . handle ( EchoService ) <nl> t = Thread . new { r . run } <nl> r . wait_till_running <nl> def an_rpc ( req , call ) <nl> <nl> describe ' # handle ' do <nl> before ( : each ) do <nl> - @ opts = { a_channel_arg : ' an_arg ' , poll_period : 1 } <nl> + @ opts = { server_args : { a_channel_arg : ' an_arg ' } , poll_period : 1 } <nl> @ srv = RpcServer . new ( * * @ opts ) <nl> + @ srv . add_http2_port ( ' 0 . 0 . 0 . 0 : 0 ' , : this_port_is_insecure ) <nl> end <nl> <nl> it ' raises if # run has already been called ' do <nl> def an_rpc ( req , call ) <nl> context ' with no connect_metadata ' do <nl> before ( : each ) do <nl> server_opts = { <nl> - server_override : @ server , <nl> completion_queue_override : @ server_queue , <nl> poll_period : 1 <nl> } <nl> @ srv = RpcServer . new ( * * server_opts ) <nl> + server_port = @ srv . add_http2_port ( ' 0 . 0 . 0 . 0 : 0 ' , : this_port_is_insecure ) <nl> + @ host = " localhost : # { server_port } " <nl> + @ ch = GRPC : : Core : : Channel . new ( @ host , nil , : this_channel_is_insecure ) <nl> end <nl> <nl> it ' should return NOT_FOUND status on unknown methods ' , server : true do <nl> def an_rpc ( req , call ) <nl> @ srv . wait_till_running <nl> req = EchoMsg . new <nl> stub = EchoStub . new ( @ host , : this_channel_is_insecure , * * client_opts ) <nl> - expect ( stub . an_rpc ( req , k1 : ' v1 ' , k2 : ' v2 ' ) ) . to be_a ( EchoMsg ) <nl> + expect ( stub . an_rpc ( req , metadata : { k1 : ' v1 ' , k2 : ' v2 ' } ) ) <nl> + . to be_a ( EchoMsg ) <nl> wanted_md = [ { ' k1 ' = > ' v1 ' , ' k2 ' = > ' v2 ' } ] <nl> check_md ( wanted_md , service . received_md ) <nl> @ srv . stop <nl> def an_rpc ( req , call ) <nl> @ srv . wait_till_running <nl> req = EchoMsg . new <nl> stub = SlowStub . new ( @ host , : this_channel_is_insecure , * * client_opts ) <nl> - timeout = service . delay + 1 . 0 # wait for long enough <nl> - resp = stub . an_rpc ( req , timeout : timeout , k1 : ' v1 ' , k2 : ' v2 ' ) <nl> + timeout = service . delay + 1 . 0 <nl> + deadline = GRPC : : Core : : TimeConsts . from_relative_time ( timeout ) <nl> + resp = stub . an_rpc ( req , <nl> + deadline : deadline , <nl> + metadata : { k1 : ' v1 ' , k2 : ' v2 ' } ) <nl> expect ( resp ) . to be_a ( EchoMsg ) <nl> wanted_md = [ { ' k1 ' = > ' v1 ' , ' k2 ' = > ' v2 ' } ] <nl> check_md ( wanted_md , service . received_md ) <nl> def an_rpc ( req , call ) <nl> @ srv . wait_till_running <nl> req = EchoMsg . new <nl> stub = SlowStub . new ( @ host , : this_channel_is_insecure , * * client_opts ) <nl> - op = stub . an_rpc ( req , k1 : ' v1 ' , k2 : ' v2 ' , return_op : true ) <nl> + op = stub . an_rpc ( req , metadata : { k1 : ' v1 ' , k2 : ' v2 ' } , return_op : true ) <nl> Thread . new do # cancel the call <nl> sleep 0 . 1 <nl> op . cancel <nl> def an_rpc ( req , call ) <nl> <nl> it ' should return RESOURCE_EXHAUSTED on too many jobs ' , server : true do <nl> opts = { <nl> - a_channel_arg : ' an_arg ' , <nl> - server_override : @ server , <nl> + server_args : { a_channel_arg : ' an_arg ' } , <nl> completion_queue_override : @ server_queue , <nl> pool_size : 1 , <nl> poll_period : 1 , <nl> def an_rpc ( req , call ) <nl> } <nl> alt_srv = RpcServer . new ( * * opts ) <nl> alt_srv . handle ( SlowService ) <nl> + alt_port = alt_srv . add_http2_port ( ' 0 . 0 . 0 . 0 : 0 ' , : this_port_is_insecure ) <nl> + alt_host = " 0 . 0 . 0 . 0 : # { alt_port } " <nl> t = Thread . new { alt_srv . run } <nl> alt_srv . wait_till_running <nl> req = EchoMsg . new <nl> def an_rpc ( req , call ) <nl> one_failed_as_unavailable = false <nl> n . times do <nl> threads < < Thread . new do <nl> - stub = SlowStub . new ( @ host , : this_channel_is_insecure , * * client_opts ) <nl> + stub = SlowStub . new ( alt_host , : this_channel_is_insecure ) <nl> begin <nl> stub . an_rpc ( req ) <nl> rescue GRPC : : BadStatus = > e <nl> def an_rpc ( req , call ) <nl> end <nl> before ( : each ) do <nl> server_opts = { <nl> - server_override : @ server , <nl> completion_queue_override : @ server_queue , <nl> poll_period : 1 , <nl> connect_md_proc : test_md_proc <nl> } <nl> @ srv = RpcServer . new ( * * server_opts ) <nl> + alt_port = @ srv . add_http2_port ( ' 0 . 0 . 0 . 0 : 0 ' , : this_port_is_insecure ) <nl> + @ alt_host = " 0 . 0 . 0 . 0 : # { alt_port } " <nl> end <nl> <nl> it ' should send connect metadata to the client ' , server : true do <nl> def an_rpc ( req , call ) <nl> t = Thread . new { @ srv . run } <nl> @ srv . wait_till_running <nl> req = EchoMsg . new <nl> - stub = EchoStub . new ( @ host , : this_channel_is_insecure , * * client_opts ) <nl> - op = stub . an_rpc ( req , k1 : ' v1 ' , k2 : ' v2 ' , return_op : true ) <nl> + stub = EchoStub . new ( @ alt_host , : this_channel_is_insecure ) <nl> + op = stub . an_rpc ( req , metadata : { k1 : ' v1 ' , k2 : ' v2 ' } , return_op : true ) <nl> expect ( op . metadata ) . to be nil <nl> expect ( op . execute ) . to be_a ( EchoMsg ) <nl> wanted_md = { <nl> def an_rpc ( req , call ) <nl> context ' with trailing metadata ' do <nl> before ( : each ) do <nl> server_opts = { <nl> - server_override : @ server , <nl> completion_queue_override : @ server_queue , <nl> poll_period : 1 <nl> } <nl> @ srv = RpcServer . new ( * * server_opts ) <nl> + alt_port = @ srv . add_http2_port ( ' 0 . 0 . 0 . 0 : 0 ' , : this_port_is_insecure ) <nl> + @ alt_host = " 0 . 0 . 0 . 0 : # { alt_port } " <nl> end <nl> <nl> it ' should be added to BadStatus when requests fail ' , server : true do <nl> def an_rpc ( req , call ) <nl> t = Thread . new { @ srv . run } <nl> @ srv . wait_till_running <nl> req = EchoMsg . new <nl> - stub = FailingStub . new ( @ host , : this_channel_is_insecure , * * client_opts ) <nl> + stub = FailingStub . new ( @ alt_host , : this_channel_is_insecure ) <nl> blk = proc { stub . an_rpc ( req ) } <nl> <nl> # confirm it raise the expected error <nl> def an_rpc ( req , call ) <nl> t = Thread . new { @ srv . run } <nl> @ srv . wait_till_running <nl> req = EchoMsg . new <nl> - stub = EchoStub . new ( @ host , : this_channel_is_insecure , * * client_opts ) <nl> - op = stub . an_rpc ( req , k1 : ' v1 ' , k2 : ' v2 ' , return_op : true ) <nl> + stub = EchoStub . new ( @ alt_host , : this_channel_is_insecure ) <nl> + op = stub . an_rpc ( req , return_op : true , metadata : { k1 : ' v1 ' , k2 : ' v2 ' } ) <nl> expect ( op . metadata ) . to be nil <nl> expect ( op . execute ) . to be_a ( EchoMsg ) <nl> expect ( op . metadata ) . to eq ( wanted_trailers ) <nl> mmm a / src / ruby / spec / pb / health / checker_spec . rb <nl> ppp b / src / ruby / spec / pb / health / checker_spec . rb <nl> def can_run_codegen_check <nl> before ( : each ) do <nl> @ server_queue = GRPC : : Core : : CompletionQueue . new <nl> server_host = ' 0 . 0 . 0 . 0 : 0 ' <nl> - @ server = GRPC : : Core : : Server . new ( @ server_queue , nil ) <nl> - server_port = @ server . add_http2_port ( server_host , : this_port_is_insecure ) <nl> - @ host = " localhost : # { server_port } " <nl> - @ ch = GRPC : : Core : : Channel . new ( @ host , nil , : this_channel_is_insecure ) <nl> @ client_opts = { channel_override : @ ch } <nl> server_opts = { <nl> - server_override : @ server , <nl> completion_queue_override : @ server_queue , <nl> poll_period : 1 <nl> } <nl> @ srv = RpcServer . new ( * * server_opts ) <nl> + server_port = @ srv . add_http2_port ( server_host , : this_port_is_insecure ) <nl> + @ host = " localhost : # { server_port } " <nl> + @ ch = GRPC : : Core : : Channel . new ( @ host , nil , : this_channel_is_insecure ) <nl> end <nl> <nl> after ( : each ) do <nl> | Merge pull request from murgatroid99 / ruby_explicit_kw_args | grpc/grpc | 6db0232c3abe800a302d5cc889e4cadf060e221c | 2016-05-24T13:30:50Z |
mmm a / trunk / src / app / srs_app_rtmp_conn . cpp <nl> ppp b / trunk / src / app / srs_app_rtmp_conn . cpp <nl> int SrsRtmpConn : : do_playing ( SrsSource * source , SrsQueueRecvThread * trd ) <nl> / / collect elapse for pithy print . <nl> pithy_print . elapse ( ) ; <nl> <nl> + # ifdef SRS_PERF_QUEUE_COND_WAIT <nl> + / / wait for message to incoming . <nl> + / / @ see https : / / github . com / winlinvip / simple - rtmp - server / issues / 251 <nl> + consumer - > wait ( SRS_PERF_MW_MIN_MSGS , mw_sleep ) ; <nl> + # endif <nl> + <nl> / / get messages from consumer . <nl> / / each msg in msgs . msgs must be free , for the SrsMessageArray never free them . <nl> int count = 0 ; <nl> int SrsRtmpConn : : do_playing ( SrsSource * source , SrsQueueRecvThread * trd ) <nl> srs_error ( " get messages from consumer failed . ret = % d " , ret ) ; <nl> return ret ; <nl> } <nl> - <nl> - / / no messages , sleep for a while . <nl> + <nl> + # ifdef SRS_PERF_QUEUE_COND_WAIT <nl> + / / we use wait to get messages , so the count must be positive . <nl> + srs_assert ( count > 0 ) ; <nl> + # else <nl> if ( count < = 0 ) { <nl> st_usleep ( mw_sleep * 1000 ) ; <nl> } <nl> - srs_info ( " got % d msgs , mw = % d " , count , mw_sleep ) ; <nl> + # endif <nl> + srs_info ( " got % d msgs , min = % d , mw = % d " , count , SRS_PERF_MW_MIN_MSGS , mw_sleep ) ; <nl> <nl> / / reportable <nl> if ( pithy_print . can_print ( ) ) { <nl> void SrsRtmpConn : : change_mw_sleep ( int sleep_ms ) <nl> return ; <nl> } <nl> <nl> + / / get the sock buffer size . <nl> + int fd = st_netfd_fileno ( stfd ) ; <nl> + int onb_sbuf = 0 ; <nl> + socklen_t sock_buf_size = sizeof ( int ) ; <nl> + getsockopt ( fd , SOL_SOCKET , SO_SNDBUF , & onb_sbuf , & sock_buf_size ) ; <nl> + <nl> + # ifdef SRS_PERF_MW_SO_SNDBUF <nl> / / the bytes : <nl> / / 4KB = 4096 , 8KB = 8192 , 16KB = 16384 , 32KB = 32768 , 64KB = 65536 , <nl> / / 128KB = 131072 , 256KB = 262144 , 512KB = 524288 <nl> void SrsRtmpConn : : change_mw_sleep ( int sleep_ms ) <nl> / / 2000 * 5000 / 8 = 1250000B ( about 1220KB ) . <nl> int kbps = 5000 ; <nl> int socket_buffer_size = sleep_ms * kbps / 8 ; <nl> - <nl> - int fd = st_netfd_fileno ( stfd ) ; <nl> - int onb_sbuf = 0 ; <nl> - socklen_t sock_buf_size = sizeof ( int ) ; <nl> - getsockopt ( fd , SOL_SOCKET , SO_SNDBUF , & onb_sbuf , & sock_buf_size ) ; <nl> <nl> / / socket send buffer , system will double it . <nl> int nb_sbuf = socket_buffer_size / 2 ; <nl> void SrsRtmpConn : : change_mw_sleep ( int sleep_ms ) <nl> } <nl> getsockopt ( fd , SOL_SOCKET , SO_SNDBUF , & nb_sbuf , & sock_buf_size ) ; <nl> <nl> - srs_trace ( " mw change sleep % d = > % d , max_msgs = % d , esbuf = % d , sbuf % d = > % d " , <nl> + srs_trace ( " mw changed sleep % d = > % d , max_msgs = % d , esbuf = % d , sbuf % d = > % d " , <nl> mw_sleep , sleep_ms , SRS_PERF_MW_MSGS , socket_buffer_size , <nl> onb_sbuf , nb_sbuf ) ; <nl> + # else <nl> + srs_trace ( " mw changed sleep % d = > % d , max_msgs = % d , sbuf % d " , <nl> + mw_sleep , sleep_ms , SRS_PERF_MW_MSGS , onb_sbuf ) ; <nl> + # endif <nl> <nl> mw_sleep = sleep_ms ; <nl> } <nl> mmm a / trunk / src / app / srs_app_source . cpp <nl> ppp b / trunk / src / app / srs_app_source . cpp <nl> void SrsMessageQueue : : set_queue_size ( double queue_size ) <nl> queue_size_ms = ( int ) ( queue_size * 1000 ) ; <nl> } <nl> <nl> - int SrsMessageQueue : : enqueue ( SrsSharedPtrMessage * msg , bool * is_overflow ) <nl> + int SrsMessageQueue : : enqueue ( SrsSharedPtrMessage * msg ) <nl> { <nl> int ret = ERROR_SUCCESS ; <nl> <nl> int SrsMessageQueue : : enqueue ( SrsSharedPtrMessage * msg , bool * is_overflow ) <nl> msgs . push_back ( msg ) ; <nl> <nl> while ( av_end_time - av_start_time > queue_size_ms ) { <nl> - / / notice the caller queue already overflow and shrinked . <nl> - if ( is_overflow ) { <nl> - * is_overflow = true ; <nl> - } <nl> - <nl> shrink ( ) ; <nl> } <nl> <nl> int SrsMessageQueue : : enqueue ( SrsSharedPtrMessage * msg , bool * is_overflow ) <nl> int SrsMessageQueue : : dump_packets ( int max_count , SrsSharedPtrMessage * * pmsgs , int & count ) <nl> { <nl> int ret = ERROR_SUCCESS ; <nl> - <nl> + <nl> int nb_msgs = ( int ) msgs . size ( ) ; <nl> if ( nb_msgs < = 0 ) { <nl> return ret ; <nl> SrsConsumer : : SrsConsumer ( SrsSource * _source ) <nl> jitter = new SrsRtmpJitter ( ) ; <nl> queue = new SrsMessageQueue ( ) ; <nl> should_update_source_id = false ; <nl> + <nl> + # ifdef SRS_PERF_QUEUE_COND_WAIT <nl> + mw_wait = st_cond_new ( ) ; <nl> + mw_min_msgs = 0 ; <nl> + mw_duration = 0 ; <nl> + mw_waiting = false ; <nl> + # endif <nl> } <nl> <nl> SrsConsumer : : ~ SrsConsumer ( ) <nl> SrsConsumer : : ~ SrsConsumer ( ) <nl> source - > on_consumer_destroy ( this ) ; <nl> srs_freep ( jitter ) ; <nl> srs_freep ( queue ) ; <nl> + <nl> + # ifdef SRS_PERF_QUEUE_COND_WAIT <nl> + st_cond_destroy ( mw_wait ) ; <nl> + # endif <nl> } <nl> <nl> void SrsConsumer : : set_queue_size ( double queue_size ) <nl> int SrsConsumer : : enqueue ( SrsSharedPtrMessage * __msg , bool atc , int tba , int tbv , <nl> return ret ; <nl> } <nl> } <nl> - <nl> - if ( ( ret = queue - > enqueue ( msg , NULL ) ) ! = ERROR_SUCCESS ) { <nl> + <nl> + if ( ( ret = queue - > enqueue ( msg ) ) ! = ERROR_SUCCESS ) { <nl> return ret ; <nl> } <nl> <nl> + # ifdef SRS_PERF_QUEUE_COND_WAIT <nl> + / / fire the mw when msgs is enough . <nl> + if ( mw_waiting ) { <nl> + int duration_ms = queue - > duration ( ) ; <nl> + bool match_min_msgs = queue - > size ( ) > mw_min_msgs ; <nl> + <nl> + / / when duration ok , signal to flush . <nl> + if ( match_min_msgs & & duration_ms > mw_duration ) { <nl> + st_cond_signal ( mw_wait ) ; <nl> + mw_waiting = false ; <nl> + } <nl> + } <nl> + # endif <nl> + <nl> return ret ; <nl> } <nl> <nl> int SrsConsumer : : dump_packets ( SrsMessageArray * msgs , int & count ) <nl> return ret ; <nl> } <nl> <nl> + # ifdef SRS_PERF_QUEUE_COND_WAIT <nl> + void SrsConsumer : : wait ( int nb_msgs , int duration ) <nl> + { <nl> + mw_min_msgs = nb_msgs ; <nl> + mw_duration = duration ; <nl> + <nl> + int duration_ms = queue - > duration ( ) ; <nl> + bool match_min_msgs = queue - > size ( ) > mw_min_msgs ; <nl> + <nl> + / / when duration ok , signal to flush . <nl> + if ( match_min_msgs & & duration_ms > mw_duration ) { <nl> + return ; <nl> + } <nl> + <nl> + / / the enqueue will notify this cond . <nl> + mw_waiting = true ; <nl> + / / wait for msgs to incoming . <nl> + st_cond_wait ( mw_wait ) ; <nl> + } <nl> + # endif <nl> + <nl> int SrsConsumer : : on_play_client_pause ( bool is_pause ) <nl> { <nl> int ret = ERROR_SUCCESS ; <nl> mmm a / trunk / src / app / srs_app_source . hpp <nl> ppp b / trunk / src / app / srs_app_source . hpp <nl> class SrsMessageQueue <nl> / * * <nl> * enqueue the message , the timestamp always monotonically . <nl> * @ param msg , the msg to enqueue , user never free it whatever the return code . <nl> - * @ param is_overflow , whether overflow and shrinked . NULL to ignore . <nl> * / <nl> - virtual int enqueue ( SrsSharedPtrMessage * msg , bool * is_overflow = NULL ) ; <nl> + virtual int enqueue ( SrsSharedPtrMessage * msg ) ; <nl> / * * <nl> * get packets in consumer queue . <nl> - * @ pmsgs SrsCommonMessages * [ ] , used to store the msgs , user must alloc it . <nl> + * @ pmsgs SrsSharedPtrMessage * [ ] , used to store the msgs , user must alloc it . <nl> * @ count the count in array , output param . <nl> * @ max_count the max count to dequeue , must be positive . <nl> * / <nl> class SrsConsumer <nl> bool paused ; <nl> / / when source id changed , notice all consumers <nl> bool should_update_source_id ; <nl> + # ifdef SRS_PERF_QUEUE_COND_WAIT <nl> + / / the cond wait for mw . <nl> + / / @ see https : / / github . com / winlinvip / simple - rtmp - server / issues / 251 <nl> + st_cond_t mw_wait ; <nl> + bool mw_waiting ; <nl> + int mw_min_msgs ; <nl> + int mw_duration ; <nl> + # endif <nl> public : <nl> SrsConsumer ( SrsSource * _source ) ; <nl> virtual ~ SrsConsumer ( ) ; <nl> class SrsConsumer <nl> * @ max_count the max count to dequeue , must be positive . <nl> * / <nl> virtual int dump_packets ( SrsMessageArray * msgs , int & count ) ; <nl> + # ifdef SRS_PERF_QUEUE_COND_WAIT <nl> + / * * <nl> + * wait for messages incomming , atleast nb_msgs and in duration . <nl> + * @ param nb_msgs the messages count to wait . <nl> + * @ param duration the messgae duration to wait . <nl> + * / <nl> + virtual void wait ( int nb_msgs , int duration ) ; <nl> + # endif <nl> / * * <nl> * when client send the pause message . <nl> * / <nl> mmm a / trunk / src / core / srs_core_performance . hpp <nl> ppp b / trunk / src / core / srs_core_performance . hpp <nl> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . <nl> * @ remark , recomment to 128 . <nl> * / <nl> # define SRS_PERF_MW_MSGS 128 <nl> + / * * <nl> + * whether set the socket send buffer size . <nl> + * @ see https : / / github . com / winlinvip / simple - rtmp - server / issues / 251 <nl> + * / <nl> + # undef SRS_PERF_MW_SO_SNDBUF <nl> + / * * <nl> + * whether set the socket recv buffer size . <nl> + * @ see https : / / github . com / winlinvip / simple - rtmp - server / issues / 251 <nl> + * / <nl> + # undef SRS_PERF_MW_SO_RCVBUF <nl> + / * * <nl> + * whether use cond wait to send messages . <nl> + * @ remark this improve performance for large connectios . <nl> + * @ see https : / / github . com / winlinvip / simple - rtmp - server / issues / 251 <nl> + * / <nl> + # undef SRS_PERF_QUEUE_COND_WAIT <nl> <nl> / * * <nl> * how many chunk stream to cache , [ 0 , N ] . <nl> mmm a / trunk / src / rtmp / srs_protocol_rtmp . hpp <nl> ppp b / trunk / src / rtmp / srs_protocol_rtmp . hpp <nl> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . <nl> <nl> class SrsProtocol ; <nl> class ISrsProtocolReaderWriter ; <nl> - class ISrsCommonMessage ; <nl> class SrsCommonMessage ; <nl> class SrsCreateStreamPacket ; <nl> class SrsFMLEStartPacket ; <nl> mmm a / trunk / src / rtmp / srs_protocol_stack . cpp <nl> ppp b / trunk / src / rtmp / srs_protocol_stack . cpp <nl> int SrsProtocol : : do_send_messages ( SrsSharedPtrMessage * * msgs , int nb_msgs ) <nl> <nl> / / always write the header event payload is empty . <nl> while ( p < pend ) { <nl> - / / header use iov [ 0 ] . <nl> - generate_chunk_header ( c0c3_cache , & msg - > header , p = = msg - > payload , iov ) ; <nl> + / / always has header <nl> + int nbh = 0 ; <nl> + char * header = NULL ; <nl> + generate_chunk_header ( c0c3_cache , & msg - > header , p = = msg - > payload , & nbh , & header ) ; <nl> + srs_assert ( nbh > 0 ) ; <nl> <nl> - / / payload use iov [ 1 ] . <nl> + / / header iov <nl> + iov [ 0 ] . iov_base = header ; <nl> + iov [ 0 ] . iov_len = nbh ; <nl> + <nl> + / / payload iov <nl> int payload_size = pend - p ; <nl> if ( payload_size > out_chunk_size ) { <nl> payload_size = out_chunk_size ; <nl> int SrsProtocol : : do_send_messages ( SrsSharedPtrMessage * * msgs , int nb_msgs ) <nl> int realloc_size = sizeof ( iovec ) * nb_out_iovs ; <nl> out_iovs = ( iovec * ) realloc ( out_iovs , realloc_size ) ; <nl> } <nl> - <nl> - / / to next c0c3 header cache <nl> - c0c3_cache_index + = iov [ 0 ] . iov_len ; <nl> - c0c3_cache = out_c0c3_caches + c0c3_cache_index ; <nl> <nl> / / to next pair of iovs <nl> iov_index + = 2 ; <nl> iov = out_iovs + iov_index ; <nl> + <nl> + / / to next c0c3 header cache <nl> + c0c3_cache_index + = nbh ; <nl> + c0c3_cache = out_c0c3_caches + c0c3_cache_index ; <nl> <nl> / / the cache header should never be realloc again , <nl> / / for the ptr is set to iovs , so we just warn user to set larger <nl> int SrsProtocol : : do_send_and_free_packet ( SrsPacket * packet , int stream_id ) <nl> return ret ; <nl> } <nl> <nl> - void SrsProtocol : : generate_chunk_header ( char * cache , SrsMessageHeader * mh , bool c0 , iovec * iov ) <nl> + void SrsProtocol : : generate_chunk_header ( char * cache , SrsMessageHeader * mh , bool c0 , int * pnbh , char * * ph ) <nl> { <nl> / / to directly set the field . <nl> char * pp = NULL ; <nl> void SrsProtocol : : generate_chunk_header ( char * cache , SrsMessageHeader * mh , bool <nl> } <nl> <nl> / / always has header <nl> - iov - > iov_base = cache ; <nl> - iov - > iov_len = p - cache ; <nl> + * pnbh = p - cache ; <nl> + * ph = cache ; <nl> } <nl> <nl> int SrsProtocol : : do_decode_message ( SrsMessageHeader & header , SrsStream * stream , SrsPacket * * ppacket ) <nl> mmm a / trunk / src / rtmp / srs_protocol_stack . hpp <nl> ppp b / trunk / src / rtmp / srs_protocol_stack . hpp <nl> class SrsProtocol <nl> * generate the chunk header for msg . <nl> * @ param mh , the header of msg to send . <nl> * @ param c0 , whether the first chunk , the c0 chunk . <nl> - * @ param iov , output the header and size to iovec . <nl> + * @ param pnbh , output the size of header . <nl> + * @ param ph , output the header cache . <nl> + * user should never free it , it ' s cached header . <nl> * / <nl> - virtual void generate_chunk_header ( char * cache , SrsMessageHeader * mh , bool c0 , iovec * iov ) ; <nl> + virtual void generate_chunk_header ( char * cache , SrsMessageHeader * mh , bool c0 , int * pnbh , char * * ph ) ; <nl> / * * <nl> * imp for decode_message <nl> * / <nl> | for bug , merge the performance refines . | ossrs/srs | d827928eebcf019993eaf943df8bd3480cf2c77e | 2014-12-06T01:55:51Z |
mmm a / cocos / 3d / CCTerrain . cpp <nl> ppp b / cocos / 3d / CCTerrain . cpp <nl> bool Terrain : : initHeightMap ( const char * heightMap ) <nl> Terrain : : Terrain ( ) <nl> { <nl> _alphaMap = nullptr ; <nl> + _customCommand . setTransparent ( false ) ; <nl> + _customCommand . set3D ( true ) ; <nl> # if ( CC_TARGET_PLATFORM = = CC_PLATFORM_ANDROID | | CC_TARGET_PLATFORM = = CC_PLATFORM_WP8 | | CC_TARGET_PLATFORM = = CC_PLATFORM_WINRT ) <nl> auto _backToForegroundListener = EventListenerCustom : : create ( EVENT_RENDERER_RECREATED , <nl> [ this ] ( EventCustom * ) <nl> mmm a / cocos / renderer / ccShader_3D_Terrain . frag <nl> ppp b / cocos / renderer / ccShader_3D_Terrain . frag <nl> if ( u_has_alpha < = 0 ) <nl> texture2D ( u_texture1 , v_texCoord * u_detailSize [ 1 ] ) * blendFactor . g + texture2D ( u_texture2 , v_texCoord * u_detailSize [ 2 ] ) * blendFactor . b ; \ n <nl> float grayFactor = dot ( blendFactor . rgb , vec3 ( 1 , 1 , 1 ) ) ; <nl> color + = texture2D ( u_texture3 , v_texCoord * u_detailSize [ 3 ] ) * ( 1 . 0 - grayFactor ) ; <nl> - gl_FragColor = color * lightFactor ; <nl> + gl_FragColor = vec4 ( color . rgb * lightFactor , 1 . 0 ) ; <nl> } <nl> } <nl> ) ; <nl> mmm a / tests / cpp - tests / Classes / TerrainTest / TerrainTest . cpp <nl> ppp b / tests / cpp - tests / Classes / TerrainTest / TerrainTest . cpp <nl> TerrainSimple : : TerrainSimple ( ) <nl> auto listener = EventListenerTouchAllAtOnce : : create ( ) ; <nl> listener - > onTouchesMoved = CC_CALLBACK_2 ( TerrainSimple : : onTouchesMoved , this ) ; <nl> _eventDispatcher - > addEventListenerWithSceneGraphPriority ( listener , this ) ; <nl> + / / add Particle3D for test blend <nl> + auto rootps = PUParticleSystem3D : : create ( " Particle3D / scripts / mp_torch . pu " ) ; <nl> + rootps - > setCameraMask ( ( unsigned short ) CameraFlag : : USER1 ) ; <nl> + rootps - > startParticleSystem ( ) ; <nl> + <nl> + this - > addChild ( rootps , 0 , 0 ) ; <nl> } <nl> <nl> std : : string TerrainSimple : : title ( ) const <nl> TerrainWalkThru : : TerrainWalkThru ( ) <nl> _player - > setCameraMask ( 2 ) ; <nl> _player - > setScale ( 0 . 08 ) ; <nl> _player - > setPositionY ( _terrain - > getHeight ( _player - > getPositionX ( ) , _player - > getPositionZ ( ) ) + PLAYER_HEIGHT ) ; <nl> + <nl> + / / add Particle3D for test blend <nl> + auto rootps = PUParticleSystem3D : : create ( " Particle3D / scripts / mp_torch . pu " ) ; <nl> + rootps - > setCameraMask ( ( unsigned short ) CameraFlag : : USER1 ) ; <nl> + rootps - > setScale ( 30 . 0f ) ; <nl> + rootps - > startParticleSystem ( ) ; <nl> + _player - > addChild ( rootps ) ; <nl> + <nl> + / / add BillBoard for test blend <nl> + auto billboard = BillBoard : : create ( " Images / btn - play - normal . png " ) ; <nl> + billboard - > setPosition3D ( Vec3 ( 0 , 180 , 0 ) ) ; <nl> + billboard - > setCameraMask ( ( unsigned short ) CameraFlag : : USER1 ) ; <nl> + _player - > addChild ( billboard ) ; <nl> <nl> auto animation = Animation3D : : create ( " Sprite3DTest / girl . c3b " , " Take 001 " ) ; <nl> if ( animation ) <nl> | fix bugs of terrain | cocos2d/cocos2d-x | f25c02f230b8a2f4a4de9c0d9be16c0a17d36064 | 2015-05-11T04:02:32Z |
mmm a / admin / static / coffee / namespaceview . coffee <nl> ppp b / admin / static / coffee / namespaceview . coffee <nl> module ' NamespaceView ' , - > <nl> id : dc . get ( ' id ' ) <nl> name : dc . get ( ' name ' ) <nl> # create json <nl> + primary_replica_count = @ model . get ( ' replica_affinities ' ) [ @ model . get ( ' primary_uuid ' ) ] <nl> json = _ . extend @ model . toJSON ( ) , <nl> primary : <nl> id : @ model . get ( ' primary_uuid ' ) <nl> name : datacenters . get ( @ model . get ( ' primary_uuid ' ) ) . get ( ' name ' ) <nl> - replicas : @ model . get ( ' replica_affinities ' ) [ @ model . get ( ' primary_uuid ' ) ] <nl> - acks : @ model . get ( ' replica_affinities ' ) [ @ model . get ( ' primary_uuid ' ) ] <nl> + replicas : if primary_replica_count > 0 then ' ' + ( primary_replica_count + 1 ) + ' ( Master + ' + primary_replica_count + ' ) ' else ' 1 ( Master only ) ' <nl> + acks : ' TBD ' <nl> secondaries : <nl> _ . map secondary_affinities , ( replica_count , uuid ) = > <nl> id : uuid <nl> name : datacenters . get ( uuid ) . get ( ' name ' ) <nl> replicas : replica_count <nl> - acks : replica_count <nl> + acks : ' TBD ' <nl> nothings : nothings <nl> <nl> @ . $ el . html @ template ( json ) <nl> module ' NamespaceView ' , - > <nl> <nl> # TODO ( Holy TODO ) this is a copy / paste of AbstractModal ! Holy crap ! <nl> @ $ container . append @ template <nl> - ' datacenter ' : @ datacenter <nl> - ' replicas ' : <nl> - ' adding ' : adding <nl> - ' removing ' : removing <nl> - ' num_changed ' : num_changed <nl> - ' num ' : num_replicas <nl> - ' shards ' : shards # # # # # # Pay attention to this this is where the action happens <nl> - ' acks ' : <nl> - ' num ' : num_acks <nl> + datacenter : @ datacenter <nl> + replicas : <nl> + adding : adding <nl> + removing : removing <nl> + num_changed : num_changed <nl> + num : num_replicas <nl> + shards : shards # # # # # # Pay attention to this this is where the action happens <nl> + acks : <nl> + num : num_acks <nl> <nl> for view in shard_views <nl> renderee = view . render ( ) . el <nl> module ' NamespaceView ' , - > <nl> # Generate faked data TODO <nl> num_replicas = @ namespace . get ( ' replica_affinities ' ) [ @ datacenter . id ] <nl> json = <nl> - ' namespace ' : @ namespace . toJSON ( ) <nl> - ' datacenter ' : @ datacenter . toJSON ( ) <nl> - # Faked data TODO <nl> - ' num_replicas ' : num_replicas <nl> - ' num_acks ' : num_replicas <nl> + namespace : @ namespace . toJSON ( ) <nl> + datacenter : @ datacenter . toJSON ( ) <nl> + num_replicas : num_replicas <nl> + num_acks : ' TBD ' <nl> # random machines | faked TODO <nl> - ' replica_machines ' : @ machine_json ( _ . shuffle machines . models ) [ 0 . . . num_replicas ] <nl> + replica_machines : @ machine_json ( _ . shuffle machines . models ) [ 0 . . . num_replicas ] <nl> <nl> if server_error ? <nl> json [ ' server_error ' ] = server_error <nl> mmm a / admin / static / coffee / util . coffee <nl> ppp b / admin / static / coffee / util . coffee <nl> Handlebars . registerHelper ' humanize_role ' , ( role ) - > <nl> <nl> # Helpers for printing reachability <nl> Handlebars . registerHelper ' humanize_machine_reachability ' , ( status ) - > <nl> - if status . reachable <nl> - result = " Reachable " <nl> + if not status ? <nl> + result = ' N / A ' <nl> else <nl> - _last_seen = if status . last_seen ? then status . last_seen else ' unknown ' <nl> - result = ' Unreachable ( < abbr class = " timeago " title = " ' + _last_seen + ' " > since ' + _last_seen + ' < / abbr > ) ' <nl> + if status . reachable <nl> + result = " Reachable " <nl> + else <nl> + _last_seen = if status . last_seen ? then status . last_seen else ' unknown ' <nl> + result = ' Unreachable ( < abbr class = " timeago " title = " ' + _last_seen + ' " > since ' + _last_seen + ' < / abbr > ) ' <nl> return new Handlebars . SafeString ( result ) ; <nl> <nl> Handlebars . registerHelper ' humanize_datacenter_reachability ' , ( status ) - > <nl> mmm a / admin / templates / cluster . html <nl> ppp b / admin / templates / cluster . html <nl> < h3 class = " title " > Sharding settings < / h3 > <nl> < table class = " datacenters table " > <nl> < ! - - Header row - - > <nl> < tr > <nl> - < th > Role < / th > <nl> < th > Datacenter < / th > <nl> + < th > Role < / th > <nl> < th > Replicas < / th > <nl> < th > Write acks < / th > <nl> < th > Status < / th > <nl> < h3 class = " title " > Sharding settings < / h3 > <nl> < ! - - Primary datacenter - - > <nl> { { # with primary } } <nl> < tr > <nl> - < td > Primary < / td > <nl> < td > { { name } } < / td > <nl> + < td > Primary < / td > <nl> < td > { { replicas } } < / td > <nl> < td > { { acks } } < / td > <nl> < td > < font color = " green " > ok < / font > < / td > <nl> - < td > < a id = " edit - primary " href = " # " > Edit < / a > | < a class = " edit - machines { { this . id } } " href = " # " > Change machines < / a > < / td > <nl> + < td > < a id = " edit - primary " href = " # " > Edit replicas < / a > | < a class = " edit - machines { { this . id } } " href = " # " > Pin machines < / a > < / td > <nl> < / tr > <nl> { { / with } } <nl> < ! - - Secondary datacenters - - > <nl> { { # each secondaries } } <nl> < tr > <nl> - < td > Secondary < / td > <nl> < td > { { name } } < / td > <nl> + < td > Secondary < / td > <nl> < td > { { replicas } } < / td > <nl> < td > { { acks } } < / td > <nl> < td > < font color = " green " > ok < / font > < / td > <nl> - < td > < a class = " edit - secondary { { this . id } } " href = " # " > Edit < / a > | < a class = " edit - machines { { this . id } } " href = " # " > Change machines < / a > | < a class = " make - primary { { this . id } } " href = " # " > Make primary < / a > < / td > <nl> + < td > < a class = " edit - secondary { { this . id } } " href = " # " > Edit replicas < / a > | < a class = " edit - machines { { this . id } } " href = " # " > Pin machines < / a > | < a class = " make - primary { { this . id } } " href = " # " > Make primary < / a > < / td > <nl> < / tr > <nl> { { / each } } <nl> < ! - - Rest of the datacenters ( ones we ' re not replicating to ) - - > <nl> { { # each nothings } } <nl> < tr > <nl> - < td > Nothing < / td > <nl> < td > { { name } } < / td > <nl> + < td > Nothing < / td > <nl> < td colspan = " 3 " > N / A < / td > <nl> - < td > < a class = " edit - nothing { { this . id } } " href = " # " > Edit < / a > < / td > <nl> + < td > < a class = " edit - nothing { { this . id } } " href = " # " > Edit replicas < / a > < / td > <nl> < / tr > <nl> { { / each } } <nl> < / table > <nl> | More changes to the namespace view | rethinkdb/rethinkdb | 7bbf44ff5462ecfbe9a8359b78e3aaff736b8d01 | 2012-04-14T01:04:19Z |
new file mode 100644 <nl> index 00000000000 . . 200905d4f3f <nl> mmm / dev / null <nl> ppp b / templates / tools / distrib / python / grpcio_tools / grpc_version . py . template <nl> <nl> + % YAML 1 . 2 <nl> + mmm | <nl> + # Copyright 2015 , Google Inc . <nl> + # All rights reserved . <nl> + # <nl> + # Redistribution and use in source and binary forms , with or without <nl> + # modification , are permitted provided that the following conditions are <nl> + # met : <nl> + # <nl> + # * Redistributions of source code must retain the above copyright <nl> + # notice , this list of conditions and the following disclaimer . <nl> + # * Redistributions in binary form must reproduce the above <nl> + # copyright notice , this list of conditions and the following disclaimer <nl> + # in the documentation and / or other materials provided with the <nl> + # distribution . <nl> + # * Neither the name of Google Inc . nor the names of its <nl> + # contributors may be used to endorse or promote products derived from <nl> + # this software without specific prior written permission . <nl> + # <nl> + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <nl> + # " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT <nl> + # LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR <nl> + # A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT <nl> + # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , <nl> + # SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT <nl> + # LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + # DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + # THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + # ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE <nl> + # OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + <nl> + # AUTO - GENERATED FROM ` $ REPO_ROOT / templates / tools / distrib / python / grpcio_tools / grpc_version . py . template ` ! ! ! <nl> + <nl> + VERSION = ' $ { settings . python_version . pep440 ( ) } ' <nl> new file mode 100644 <nl> index 00000000000 . . b8ae8e20b8b <nl> mmm / dev / null <nl> ppp b / tools / distrib / python / grpcio_tools / grpc_version . py <nl> <nl> + # Copyright 2015 , Google Inc . <nl> + # All rights reserved . <nl> + # <nl> + # Redistribution and use in source and binary forms , with or without <nl> + # modification , are permitted provided that the following conditions are <nl> + # met : <nl> + # <nl> + # * Redistributions of source code must retain the above copyright <nl> + # notice , this list of conditions and the following disclaimer . <nl> + # * Redistributions in binary form must reproduce the above <nl> + # copyright notice , this list of conditions and the following disclaimer <nl> + # in the documentation and / or other materials provided with the <nl> + # distribution . <nl> + # * Neither the name of Google Inc . nor the names of its <nl> + # contributors may be used to endorse or promote products derived from <nl> + # this software without specific prior written permission . <nl> + # <nl> + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <nl> + # " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT <nl> + # LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR <nl> + # A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT <nl> + # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , <nl> + # SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT <nl> + # LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + # DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + # THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + # ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE <nl> + # OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + <nl> + # AUTO - GENERATED FROM ` $ REPO_ROOT / templates / tools / distrib / python / grpcio_tools / grpc_version . py . template ` ! ! ! <nl> + <nl> + VERSION = ' 0 . 14 . 0 . dev0 ' <nl> mmm a / tools / distrib / python / grpcio_tools / setup . py <nl> ppp b / tools / distrib / python / grpcio_tools / setup . py <nl> <nl> sys . path . insert ( 0 , os . path . abspath ( ' . ' ) ) <nl> <nl> import protoc_lib_deps <nl> + import grpc_version <nl> <nl> def protoc_ext_module ( ) : <nl> plugin_sources = [ <nl> def maybe_cythonize ( exts ) : <nl> <nl> setuptools . setup ( <nl> name = ' grpcio_tools ' , <nl> - version = ' 0 . 14 . 0rc1 ' , <nl> + version = grpc_version . VERSION , <nl> license = ' ' , <nl> ext_modules = maybe_cythonize ( [ <nl> protoc_ext_module ( ) , <nl> | Keep grpcio_tools version in sync with rest of project | grpc/grpc | 955887928f1ac6d9b39599d14b6b7a522db026d9 | 2016-05-04T22:30:30Z |
mmm a / src / builtins / builtins - array . cc <nl> ppp b / src / builtins / builtins - array . cc <nl> <nl> # include " src / contexts . h " <nl> # include " src / counters . h " <nl> # include " src / elements . h " <nl> + # include " src / global - handles . h " <nl> # include " src / isolate . h " <nl> # include " src / lookup . h " <nl> # include " src / objects - inl . h " <nl> mmm a / src / isolate . h <nl> ppp b / src / isolate . h <nl> <nl> # include < queue > <nl> # include < vector > <nl> <nl> + # include " include / v8 . h " <nl> # include " src / allocation . h " <nl> # include " src / base / atomicops . h " <nl> + # include " src / base / macros . h " <nl> # include " src / builtins / builtins . h " <nl> # include " src / contexts . h " <nl> # include " src / date . h " <nl> # include " src / debug / debug - interface . h " <nl> # include " src / execution . h " <nl> # include " src / futex - emulation . h " <nl> - # include " src / global - handles . h " <nl> + # include " src / globals . h " <nl> # include " src / handles . h " <nl> # include " src / heap / heap . h " <nl> # include " src / messages . h " <nl> # include " src / objects / code . h " <nl> - # include " src / regexp / regexp - stack . h " <nl> # include " src / runtime / runtime . h " <nl> - # include " src / zone / zone . h " <nl> + # include " src / unicode . h " <nl> <nl> namespace v8 { <nl> <nl> class Debug ; <nl> class DeoptimizerData ; <nl> class DescriptorLookupCache ; <nl> class EmptyStatement ; <nl> + class EternalHandles ; <nl> class ExternalCallbackScope ; <nl> class ExternalReferenceTable ; <nl> class Factory ; <nl> mmm a / src / objects / intl - objects . cc <nl> ppp b / src / objects / intl - objects . cc <nl> <nl> <nl> # include " src / api . h " <nl> # include " src / factory . h " <nl> + # include " src / global - handles . h " <nl> # include " src / isolate . h " <nl> # include " src / objects - inl . h " <nl> # include " src / property - descriptor . h " <nl> mmm a / src / profiler / allocation - tracker . cc <nl> ppp b / src / profiler / allocation - tracker . cc <nl> <nl> # include " src / profiler / allocation - tracker . h " <nl> <nl> # include " src / frames - inl . h " <nl> + # include " src / global - handles . h " <nl> # include " src / objects - inl . h " <nl> # include " src / profiler / heap - snapshot - generator - inl . h " <nl> <nl> mmm a / src / profiler / heap - profiler . h <nl> ppp b / src / profiler / heap - profiler . h <nl> <nl> # include < memory > <nl> # include < vector > <nl> <nl> - # include " src / isolate . h " <nl> + # include " include / v8 - profiler . h " <nl> + # include " src / base / platform / mutex . h " <nl> + # include " src / debug / debug - interface . h " <nl> + # include " src / globals . h " <nl> + # include " src / heap / heap . h " <nl> <nl> namespace v8 { <nl> namespace internal { <nl> mmm a / src / profiler / heap - snapshot - generator . cc <nl> ppp b / src / profiler / heap - snapshot - generator . cc <nl> <nl> # include " src / code - stubs . h " <nl> # include " src / conversions . h " <nl> # include " src / debug / debug . h " <nl> + # include " src / global - handles . h " <nl> # include " src / layout - descriptor . h " <nl> # include " src / objects - body - descriptors . h " <nl> # include " src / objects - inl . h " <nl> mmm a / src / profiler / profile - generator . h <nl> ppp b / src / profiler / profile - generator . h <nl> <nl> # include < map > <nl> # include < vector > <nl> <nl> + # include " include / v8 - profiler . h " <nl> # include " src / allocation . h " <nl> # include " src / base / hashmap . h " <nl> # include " src / log . h " <nl> mmm a / src / runtime / runtime - intl . cc <nl> ppp b / src / runtime / runtime - intl . cc <nl> <nl> # include " src / api . h " <nl> # include " src / arguments . h " <nl> # include " src / factory . h " <nl> + # include " src / global - handles . h " <nl> # include " src / intl . h " <nl> # include " src / isolate - inl . h " <nl> # include " src / messages . h " <nl> mmm a / src / snapshot / startup - serializer . cc <nl> ppp b / src / snapshot / startup - serializer . cc <nl> <nl> # include " src / snapshot / startup - serializer . h " <nl> <nl> # include " src / api . h " <nl> + # include " src / global - handles . h " <nl> # include " src / objects - inl . h " <nl> # include " src / v8threads . h " <nl> <nl> mmm a / test / cctest / test - api . cc <nl> ppp b / test / cctest / test - api . cc <nl> <nl> # include " src / debug / debug . h " <nl> # include " src / execution . h " <nl> # include " src / futex - emulation . h " <nl> + # include " src / global - handles . h " <nl> # include " src / heap / incremental - marking . h " <nl> # include " src / heap / local - allocator . h " <nl> # include " src / lookup . h " <nl> | [ iwyu ] Fixes related to isolate . h | v8/v8 | bdec7137ecc7ec9ba9dfcc49a2ecbe6ef29837fe | 2018-02-23T16:03:37Z |
mmm a / build / standalone . gypi <nl> ppp b / build / standalone . gypi <nl> <nl> ' host_arch % ' : ' < ( host_arch ) ' , <nl> ' target_arch % ' : ' < ( host_arch ) ' , <nl> ' base_dir % ' : ' < ! ( cd < ( DEPTH ) & & python - c " import os ; print os . getcwd ( ) " ) ' , <nl> + <nl> + # Instrument for code coverage with gcov . <nl> + ' coverage % ' : 0 , <nl> } , <nl> ' base_dir % ' : ' < ( base_dir ) ' , <nl> ' host_arch % ' : ' < ( host_arch ) ' , <nl> ' target_arch % ' : ' < ( target_arch ) ' , <nl> ' v8_target_arch % ' : ' < ( target_arch ) ' , <nl> + ' coverage % ' : ' < ( coverage ) ' , <nl> ' asan % ' : 0 , <nl> ' lsan % ' : 0 , <nl> ' msan % ' : 0 , <nl> <nl> # If no gomadir is set , it uses the default gomadir . <nl> ' use_goma % ' : 0 , <nl> ' gomadir % ' : ' ' , <nl> + <nl> ' conditions ' : [ <nl> # Set default gomadir . <nl> [ ' OS = = " win " ' , { <nl> <nl> } , { <nl> ' gomadir ' : ' < ! ( / bin / echo - n $ { HOME } / goma ) ' , <nl> } ] , <nl> - [ ' host_arch ! = " ppc " and host_arch ! = " ppc64 " and host_arch ! = " ppc64le " ' , { <nl> - ' host_clang % ' : ' 1 ' , <nl> + [ ' host_arch ! = " ppc " and host_arch ! = " ppc64 " and host_arch ! = " ppc64le " and \ <nl> + coverage = = 0 ' , { <nl> + ' host_clang % ' : 1 , <nl> } , { <nl> - ' host_clang % ' : ' 0 ' , <nl> + ' host_clang % ' : 0 , <nl> } ] , <nl> # linux_use_bundled_gold : whether to use the gold linker binary checked <nl> # into third_party / binutils . Force this off via GYP_DEFINES when you <nl> <nl> ' cfi_blacklist % ' : ' < ( cfi_blacklist ) ' , <nl> ' test_isolation_mode % ' : ' < ( test_isolation_mode ) ' , <nl> ' fastbuild % ' : ' < ( fastbuild ) ' , <nl> + ' coverage % ' : ' < ( coverage ) ' , <nl> <nl> # Add a simple extras solely for the purpose of the cctests <nl> ' v8_extra_library_files ' : [ ' . . / test / cctest / test - extra . js ' ] , <nl> <nl> ' v8_enable_gdbjit % ' : 0 , <nl> } ] , <nl> [ ' ( OS = = " linux " or OS = = " mac " ) and ( target_arch = = " ia32 " or target_arch = = " x64 " ) and \ <nl> - ( v8_target_arch ! = " x87 " and v8_target_arch ! = " x32 " ) ' , { <nl> + ( v8_target_arch ! = " x87 " and v8_target_arch ! = " x32 " ) and coverage = = 0 ' , { <nl> ' clang % ' : 1 , <nl> } , { <nl> ' clang % ' : 0 , <nl> <nl> [ ' component = = " shared_library " ' , { <nl> ' cflags ' : [ ' - fPIC ' , ] , <nl> } ] , <nl> + [ ' coverage = = 1 ' , { <nl> + ' cflags ! ' : [ ' - O3 ' , ' - O2 ' , ' - O1 ' , ] , <nl> + ' cflags ' : [ ' - fprofile - arcs ' , ' - ftest - coverage ' , ' - O0 ' ] , <nl> + ' ldflags ' : [ ' - fprofile - arcs ' ] , <nl> + } ] , <nl> ] , <nl> } , <nl> } ] , <nl> | [ build system ] Support code coverage . | v8/v8 | ce47fc8b7228c4b9c6b3b549dff7dafca05ca26d | 2015-12-10T10:11:16Z |
mmm a / test / IRGen / errors . sil <nl> ppp b / test / IRGen / errors . sil <nl> entry : <nl> unreachable <nl> } <nl> <nl> - / / CHECK : define { { ( protected ) ? } } void @ throws ( % swift . refcounted * , % swift . error * * ) { { . * } } { <nl> + / / CHECK - LABEL : define { { ( protected ) ? } } void @ throws ( % swift . refcounted * , % swift . error * * ) { { . * } } { <nl> sil @ throws : $ @ convention ( thin ) ( ) - > @ error ErrorProtocol { <nl> / / CHECK : [ [ T0 : % . * ] ] = call % swift . error * @ create_error ( ) <nl> % 0 = function_ref @ create_error : $ @ convention ( thin ) ( ) - > @ owned ErrorProtocol <nl> sil @ throws : $ @ convention ( thin ) ( ) - > @ error ErrorProtocol { <nl> throw % 1 : $ ErrorProtocol <nl> } <nl> <nl> - / / CHECK : define { { ( protected ) ? } } void @ doesnt_throw ( % swift . refcounted * , % swift . error * * ) { { . * } } { <nl> + / / CHECK - LABEL : define { { ( protected ) ? } } void @ doesnt_throw ( % swift . refcounted * , % swift . error * * ) { { . * } } { <nl> sil @ doesnt_throw : $ @ convention ( thin ) ( ) - > @ error ErrorProtocol { <nl> / / We don ' t have to do anything here because the caller always <nl> / / zeroes the error slot before a call . <nl> sil @ doesnt_throw : $ @ convention ( thin ) ( ) - > @ error ErrorProtocol { <nl> <nl> sil @ try_apply_helper : $ @ convention ( thin ) ( @ owned AnyObject ) - > ( @ owned AnyObject , @ error ErrorProtocol ) <nl> <nl> - / / CHECK - objc : define { { ( protected ) ? } } void @ try_apply ( % objc_object * ) <nl> - / / CHECK - native : define { { ( protected ) ? } } void @ try_apply ( % swift . refcounted * ) <nl> + / / CHECK - objc - LABEL : define { { ( protected ) ? } } void @ try_apply ( % objc_object * ) <nl> + / / CHECK - native - LABEL : define { { ( protected ) ? } } void @ try_apply ( % swift . refcounted * ) <nl> sil @ try_apply : $ @ convention ( thin ) ( @ owned AnyObject ) - > ( ) { <nl> entry ( % 0 : $ AnyObject ) : <nl> / / CHECK : [ [ ERRORSLOT : % . * ] ] = alloca % swift . error * , align <nl> | Fix a test | apple/swift | 10653a43c9d8fe82acae446c09c0968728e6966b | 2016-06-04T05:56:01Z |
mmm a / NEWS . md <nl> ppp b / NEWS . md <nl> <nl> Note : <nl> * You have to enable your Mouse manually in Preferences & gt ; Devices tab . <nl> * Karabiner - Elements cannot modify Apple ' s pointing devices . <nl> + * ` to_delayed_action ` has been added . <nl> + * Examples <nl> + * Quit application by pressing command - q twice <nl> + * src : https : / / github . com / pqrs - org / KE - complex_modifications / blob / master / src / json / command_q . json . erb <nl> + * json : https : / / github . com / pqrs - org / KE - complex_modifications / blob / master / docs / json / command_q . json <nl> + * Emacs key bindings [ C - x key strokes ] <nl> + * src : https : / / github . com / pqrs - org / KE - complex_modifications / blob / master / src / json / emacs_key_bindings . json . erb <nl> + * json : https : / / github . com / pqrs - org / KE - complex_modifications / blob / master / docs / json / emacs_key_bindings . json <nl> * ` input_source_if ` and ` input_source_unless ` has been added to ` conditions ` . <nl> * Examples <nl> * https : / / github . com / pqrs - org / KE - complex_modifications / blob / master / docs / json / example_input_source . json <nl> | update NEWS | pqrs-org/Karabiner-Elements | 5220a213b0b5da89138ef6044a8e6b90e0f3429b | 2017-11-04T14:01:05Z |
mmm a / db / repl / rs_config . cpp <nl> ppp b / db / repl / rs_config . cpp <nl> namespace mongo { <nl> / * TODO : use of string exceptions may be problematic for reconfig case ! * / <nl> throw " _id must be numeric " ; <nl> } <nl> - string s ; <nl> try { <nl> - s = mobj [ " host " ] . String ( ) ; <nl> + string s = mobj [ " host " ] . String ( ) ; <nl> m . h = HostAndPort ( s ) ; <nl> + if ( ! m . h . hasPort ( ) ) { <nl> + m . h . setPort ( m . h . port ( ) ) ; <nl> + } <nl> } <nl> catch ( . . . ) { <nl> throw string ( " bad or missing host field ? " ) + mobj . toString ( ) ; <nl> | always set port when for rs config | mongodb/mongo | 510c4a6fc3eff8569c5d45e611037a9f412cfe8d | 2011-06-10T18:36:41Z |
mmm a / xbmc / Profile . h <nl> ppp b / xbmc / Profile . h <nl> class CProfile <nl> void setPicturesLocked ( bool bLocked ) { _bLockPictures = bLocked ; } <nl> void setProgramsLocked ( bool bLocked ) { _bLockPrograms = bLocked ; } <nl> <nl> + private : <nl> CStdString _directory ; <nl> CStdString _name ; <nl> CStdString _date ; <nl> class CProfile <nl> bool _bCanWriteSources ; <nl> bool _bAddons ; <nl> <nl> + public : <nl> / / lock stuff <nl> LockType _iLockMode ; <nl> CStdString _strLockCode ; <nl> | cleanup : Move CProfile members to private where we can | xbmc/xbmc | 62d7c1530dd86c3731ede8857b58860a75395eab | 2010-03-09T19:04:33Z |
mmm a / db / mr . cpp <nl> ppp b / db / mr . cpp <nl> namespace mongo { <nl> if ( values . size ( ) ) <nl> db . insert ( fulloutput , reduceValues ( values , s . get ( ) , reduceFunction ) ) ; <nl> <nl> + for ( set < ServerAndQuery > : : iterator i = servers . begin ( ) ; i ! = servers . end ( ) ; i + + ) { <nl> + ScopedDbConnection conn ( i - > _server ) ; <nl> + conn - > dropCollection ( dbname + " . " + shardedOutputCollection ) ; <nl> + } <nl> <nl> return 1 ; <nl> } <nl> | delete temp shard collections on shards SHARDING - 37 | mongodb/mongo | d8fbead145525c2c79c798cc4b9b129b93c71083 | 2009-11-03T17:17:56Z |
mmm a / utils / build - script <nl> ppp b / utils / build - script <nl> def main_preset ( ) : <nl> " build - presets . ini " ) <nl> ] <nl> <nl> - user_presets_file = os . path . join ( os . getenv ( " HOME " , " / " ) , ' . swift - build - presets ' ) <nl> + user_presets_file = os . path . join ( os . getenv ( " HOME " , " / " ) , <nl> + ' . swift - build - presets ' ) <nl> if os . path . isfile ( user_presets_file ) : <nl> args . preset_file_names . append ( user_presets_file ) <nl> <nl> | Update utils / build - script | apple/swift | de373246b8bb1376deaeb827794a0740d50877f2 | 2020-11-22T03:15:20Z |
mmm a / src / ast / scopes . cc <nl> ppp b / src / ast / scopes . cc <nl> Scope : : Scope ( Zone * zone , const AstRawString * catch_variable_name ) <nl> # ifdef DEBUG <nl> already_resolved_ = true ; <nl> # endif <nl> - Variable * variable = <nl> - variables_ . Declare ( zone , this , catch_variable_name , VAR , Variable : : NORMAL , <nl> - kCreatedInitialized ) ; <nl> + Variable * variable = Declare ( zone , this , catch_variable_name , VAR , <nl> + Variable : : NORMAL , kCreatedInitialized ) ; <nl> AllocateHeapSlot ( variable ) ; <nl> } <nl> <nl> | Fully setup the catch variable for catch scopes | v8/v8 | 1937d90085013ce5441bfdd346eaa6c32a2de027 | 2016-08-25T20:45:11Z |
mmm a / tensorflow / go / op / wrappers . go <nl> ppp b / tensorflow / go / op / wrappers . go <nl> func DepthwiseConv2dNativeBackpropFilterDataFormat ( value string ) DepthwiseConv2d <nl> / / element on that dimension . The dimension order is determined by the value of <nl> / / ` data_format ` , see above for details . Dilations in the batch and depth <nl> / / dimensions must be 1 . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> func DepthwiseConv2dNativeBackpropFilterDilations ( value [ ] int64 ) DepthwiseConv2dNativeBackpropFilterAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func SampleDistortedBoundingBoxV2Seed2 ( value int64 ) SampleDistortedBoundingBoxV2 <nl> / / <nl> / / value : The cropped area of the image must have an aspect ratio = <nl> / / width / height within this range . <nl> - / / If not specified , defaults to { f : 0 . 75 f : 1 . 33 } <nl> + / / If not specified , defaults to { f : 0 . 75 f : 1 . 33 } <nl> func SampleDistortedBoundingBoxV2AspectRatioRange ( value [ ] float32 ) SampleDistortedBoundingBoxV2Attr { <nl> return func ( m optionalAttr ) { <nl> m [ " aspect_ratio_range " ] = value <nl> func SampleDistortedBoundingBoxV2AspectRatioRange ( value [ ] float32 ) SampleDistort <nl> / / <nl> / / value : The cropped area of the image must contain a fraction of the <nl> / / supplied image within this range . <nl> - / / If not specified , defaults to { f : 0 . 05 f : 1 } <nl> + / / If not specified , defaults to { f : 0 . 05 f : 1 } <nl> func SampleDistortedBoundingBoxV2AreaRange ( value [ ] float32 ) SampleDistortedBoundingBoxV2Attr { <nl> return func ( m optionalAttr ) { <nl> m [ " area_range " ] = value <nl> func SampleDistortedBoundingBoxMinObjectCovered ( value float32 ) SampleDistortedBo <nl> / / <nl> / / value : The cropped area of the image must have an aspect ratio = <nl> / / width / height within this range . <nl> - / / If not specified , defaults to { f : 0 . 75 f : 1 . 33 } <nl> + / / If not specified , defaults to { f : 0 . 75 f : 1 . 33 } <nl> func SampleDistortedBoundingBoxAspectRatioRange ( value [ ] float32 ) SampleDistortedBoundingBoxAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " aspect_ratio_range " ] = value <nl> func SampleDistortedBoundingBoxAspectRatioRange ( value [ ] float32 ) SampleDistorted <nl> / / <nl> / / value : The cropped area of the image must contain a fraction of the <nl> / / supplied image within this range . <nl> - / / If not specified , defaults to { f : 0 . 05 f : 1 } <nl> + / / If not specified , defaults to { f : 0 . 05 f : 1 } <nl> func SampleDistortedBoundingBoxAreaRange ( value [ ] float32 ) SampleDistortedBoundingBoxAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " area_range " ] = value <nl> func ImageSummaryMaxImages ( value int64 ) ImageSummaryAttr { <nl> / / ImageSummaryBadColor sets the optional bad_color attribute to value . <nl> / / <nl> / / value : Color to use for pixels with non - finite values . <nl> - / / If not specified , defaults to { dtype : DT_UINT8 tensor_shape : { dim : { size : 4 } } int_val : 255 int_val : 0 int_val : 0 int_val : 255 } <nl> + / / If not specified , defaults to { dtype : DT_UINT8 tensor_shape : { dim : { size : 4 } } int_val : 255 int_val : 0 int_val : 0 int_val : 255 } <nl> func ImageSummaryBadColor ( value tf . Tensor ) ImageSummaryAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " bad_color " ] = value <nl> func Conv3DBackpropFilterV2DataFormat ( value string ) Conv3DBackpropFilterV2Attr { <nl> / / filter element on that dimension . The dimension order is determined by the <nl> / / value of ` data_format ` , see above for details . Dilations in the batch and <nl> / / depth dimensions must be 1 . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 i : 1 } <nl> func Conv3DBackpropFilterV2Dilations ( value [ ] int64 ) Conv3DBackpropFilterV2Attr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func Conv2DBackpropInputDataFormat ( value string ) Conv2DBackpropInputAttr { <nl> / / element on that dimension . The dimension order is determined by the value of <nl> / / ` data_format ` , see above for details . Dilations in the batch and depth <nl> / / dimensions must be 1 . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> func Conv2DBackpropInputDilations ( value [ ] int64 ) Conv2DBackpropInputAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func Conv2DDataFormat ( value string ) Conv2DAttr { <nl> / / filter element on that dimension . The dimension order is determined by the <nl> / / value of ` data_format ` , see above for details . Dilations in the batch and <nl> / / depth dimensions must be 1 . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> func Conv2DDilations ( value [ ] int64 ) Conv2DAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func QuantizedDepthwiseConv2DWithBiasAndReluAndRequantizeOutType ( value tf . DataTy <nl> / / QuantizedDepthwiseConv2DWithBiasAndReluAndRequantizeDilations sets the optional dilations attribute to value . <nl> / / <nl> / / value : List of dilation values . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> func QuantizedDepthwiseConv2DWithBiasAndReluAndRequantizeDilations ( value [ ] int64 ) QuantizedDepthwiseConv2DWithBiasAndReluAndRequantizeAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func QuantizedDepthwiseConv2DWithBiasAndReluOutType ( value tf . DataType ) Quantized <nl> / / QuantizedDepthwiseConv2DWithBiasAndReluDilations sets the optional dilations attribute to value . <nl> / / <nl> / / value : List of dilation values . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> func QuantizedDepthwiseConv2DWithBiasAndReluDilations ( value [ ] int64 ) QuantizedDepthwiseConv2DWithBiasAndReluAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func QuantizedDepthwiseConv2DWithBiasOutType ( value tf . DataType ) QuantizedDepthwi <nl> / / QuantizedDepthwiseConv2DWithBiasDilations sets the optional dilations attribute to value . <nl> / / <nl> / / value : List of dilation values . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> func QuantizedDepthwiseConv2DWithBiasDilations ( value [ ] int64 ) QuantizedDepthwiseConv2DWithBiasAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func QuantizedDepthwiseConv2DOutType ( value tf . DataType ) QuantizedDepthwiseConv2D <nl> / / QuantizedDepthwiseConv2DDilations sets the optional dilations attribute to value . <nl> / / <nl> / / value : List of dilation values . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> func QuantizedDepthwiseConv2DDilations ( value [ ] int64 ) QuantizedDepthwiseConv2DAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func QuantizedConv2DPerChannelOutType ( value tf . DataType ) QuantizedConv2DPerChann <nl> / / QuantizedConv2DPerChannelDilations sets the optional dilations attribute to value . <nl> / / <nl> / / value : list of dilation values . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> func QuantizedConv2DPerChannelDilations ( value [ ] int64 ) QuantizedConv2DPerChannelAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func Conv3DBackpropInputV2DataFormat ( value string ) Conv3DBackpropInputV2Attr { <nl> / / filter element on that dimension . The dimension order is determined by the <nl> / / value of ` data_format ` , see above for details . Dilations in the batch and <nl> / / depth dimensions must be 1 . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 i : 1 } <nl> func Conv3DBackpropInputV2Dilations ( value [ ] int64 ) Conv3DBackpropInputV2Attr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func AvgPool3DGrad ( scope * Scope , orig_input_shape tf . Output , grad tf . Output , ksi <nl> type Conv3DBackpropFilterAttr func ( optionalAttr ) <nl> <nl> / / Conv3DBackpropFilterDilations sets the optional dilations attribute to value . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 i : 1 } <nl> func Conv3DBackpropFilterDilations ( value [ ] int64 ) Conv3DBackpropFilterAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func DepthwiseConv2dNativeBackpropInputDataFormat ( value string ) DepthwiseConv2dN <nl> / / element on that dimension . The dimension order is determined by the value of <nl> / / ` data_format ` , see above for details . Dilations in the batch and depth <nl> / / dimensions must be 1 . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> func DepthwiseConv2dNativeBackpropInputDilations ( value [ ] int64 ) DepthwiseConv2dNativeBackpropInputAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func DepthwiseConv2dNativeBackpropInput ( scope * Scope , input_sizes tf . Output , fil <nl> type Conv3DBackpropInputAttr func ( optionalAttr ) <nl> <nl> / / Conv3DBackpropInputDilations sets the optional dilations attribute to value . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 i : 1 } <nl> func Conv3DBackpropInputDilations ( value [ ] int64 ) Conv3DBackpropInputAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func DepthwiseConv2dNativeDataFormat ( value string ) DepthwiseConv2dNativeAttr { <nl> / / element on that dimension . The dimension order is determined by the value of <nl> / / ` data_format ` , see above for details . Dilations in the batch and depth <nl> / / dimensions must be 1 . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> func DepthwiseConv2dNativeDilations ( value [ ] int64 ) DepthwiseConv2dNativeAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func QuantizedConv2DOutType ( value tf . DataType ) QuantizedConv2DAttr { <nl> / / filter element on that dimension . The dimension order is determined by the <nl> / / value of ` data_format ` , see above for details . Dilations in the batch and <nl> / / depth dimensions must be 1 . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> func QuantizedConv2DDilations ( value [ ] int64 ) QuantizedConv2DAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func Conv3DDataFormat ( value string ) Conv3DAttr { <nl> / / filter element on that dimension . The dimension order is determined by the <nl> / / value of ` data_format ` , see above for details . Dilations in the batch and <nl> / / depth dimensions must be 1 . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 i : 1 } <nl> func Conv3DDilations ( value [ ] int64 ) Conv3DAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> func Conv2DBackpropFilterDataFormat ( value string ) Conv2DBackpropFilterAttr { <nl> / / element on that dimension . The dimension order is determined by the value of <nl> / / ` data_format ` , see above for details . Dilations in the batch and depth <nl> / / dimensions must be 1 . <nl> - / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> + / / If not specified , defaults to { i : 1 i : 1 i : 1 i : 1 } <nl> func Conv2DBackpropFilterDilations ( value [ ] int64 ) Conv2DBackpropFilterAttr { <nl> return func ( m optionalAttr ) { <nl> m [ " dilations " ] = value <nl> | Go : Update generated wrapper functions for TensorFlow ops . | tensorflow/tensorflow | 595dbdf4b5119bb9193679f4320902fbcfc13608 | 2020-02-27T01:16:20Z |
deleted file mode 100644 <nl> index 003a6679 . . 00000000 <nl> mmm a / include / spdlog / fmt / bundled / colors . h <nl> ppp / dev / null <nl> <nl> - / / Formatting library for C + + - the core API <nl> - / / <nl> - / / Copyright ( c ) 2012 - present , Victor Zverovich <nl> - / / All rights reserved . <nl> - / / <nl> - / / For the license information refer to format . h . <nl> - / / <nl> - / / Copyright ( c ) 2018 - present , Remotion ( Igor Schulz ) <nl> - / / All Rights Reserved <nl> - / / { fmt } support for rgb color output . <nl> - <nl> - # ifndef FMT_COLORS_H_ <nl> - # define FMT_COLORS_H_ <nl> - <nl> - # include " format . h " <nl> - <nl> - FMT_BEGIN_NAMESPACE <nl> - <nl> - / / rgb is a struct for red , green and blue colors . <nl> - / / We use rgb as name because some editors will show it as color direct in the <nl> - / / editor . <nl> - struct rgb <nl> - { <nl> - FMT_CONSTEXPR_DECL rgb ( ) <nl> - : r ( 0 ) <nl> - , g ( 0 ) <nl> - , b ( 0 ) <nl> - { <nl> - } <nl> - FMT_CONSTEXPR_DECL rgb ( uint8_t r_ , uint8_t g_ , uint8_t b_ ) <nl> - : r ( r_ ) <nl> - , g ( g_ ) <nl> - , b ( b_ ) <nl> - { <nl> - } <nl> - FMT_CONSTEXPR_DECL rgb ( uint32_t hex ) <nl> - : r ( ( hex > > 16 ) & 0xFF ) <nl> - , g ( ( hex > > 8 ) & 0xFF ) <nl> - , b ( ( hex ) & 0xFF ) <nl> - { <nl> - } <nl> - uint8_t r ; <nl> - uint8_t g ; <nl> - uint8_t b ; <nl> - } ; <nl> - <nl> - namespace internal { <nl> - <nl> - FMT_CONSTEXPR inline void to_esc ( uint8_t c , char out [ ] , int offset ) <nl> - { <nl> - out [ offset + 0 ] = static_cast < char > ( ' 0 ' + c / 100 ) ; <nl> - out [ offset + 1 ] = static_cast < char > ( ' 0 ' + c / 10 % 10 ) ; <nl> - out [ offset + 2 ] = static_cast < char > ( ' 0 ' + c % 10 ) ; <nl> - } <nl> - <nl> - } / / namespace internal <nl> - <nl> - FMT_FUNC void vprint_rgb ( rgb fd , string_view format , format_args args ) <nl> - { <nl> - char escape_fd [ ] = " \ x1b [ 38 ; 2 ; 000 ; 000 ; 000m " ; <nl> - static FMT_CONSTEXPR_DECL const char RESET_COLOR [ ] = " \ x1b [ 0m " ; <nl> - internal : : to_esc ( fd . r , escape_fd , 7 ) ; <nl> - internal : : to_esc ( fd . g , escape_fd , 11 ) ; <nl> - internal : : to_esc ( fd . b , escape_fd , 15 ) ; <nl> - <nl> - std : : fputs ( escape_fd , stdout ) ; <nl> - vprint ( format , args ) ; <nl> - std : : fputs ( RESET_COLOR , stdout ) ; <nl> - } <nl> - <nl> - FMT_FUNC void vprint_rgb ( rgb fd , rgb bg , string_view format , format_args args ) <nl> - { <nl> - char escape_fd [ ] = " \ x1b [ 38 ; 2 ; 000 ; 000 ; 000m " ; / / foreground color <nl> - char escape_bg [ ] = " \ x1b [ 48 ; 2 ; 000 ; 000 ; 000m " ; / / background color <nl> - static FMT_CONSTEXPR_DECL const char RESET_COLOR [ ] = " \ x1b [ 0m " ; <nl> - internal : : to_esc ( fd . r , escape_fd , 7 ) ; <nl> - internal : : to_esc ( fd . g , escape_fd , 11 ) ; <nl> - internal : : to_esc ( fd . b , escape_fd , 15 ) ; <nl> - <nl> - internal : : to_esc ( bg . r , escape_bg , 7 ) ; <nl> - internal : : to_esc ( bg . g , escape_bg , 11 ) ; <nl> - internal : : to_esc ( bg . b , escape_bg , 15 ) ; <nl> - <nl> - std : : fputs ( escape_fd , stdout ) ; <nl> - std : : fputs ( escape_bg , stdout ) ; <nl> - vprint ( format , args ) ; <nl> - std : : fputs ( RESET_COLOR , stdout ) ; <nl> - } <nl> - <nl> - template < typename . . . Args > <nl> - inline void print_rgb ( rgb fd , string_view format_str , const Args & . . . args ) <nl> - { <nl> - vprint_rgb ( fd , format_str , make_format_args ( args . . . ) ) ; <nl> - } <nl> - <nl> - / / rgb foreground color <nl> - template < typename . . . Args > <nl> - inline void print ( rgb fd , string_view format_str , const Args & . . . args ) <nl> - { <nl> - vprint_rgb ( fd , format_str , make_format_args ( args . . . ) ) ; <nl> - } <nl> - <nl> - / / rgb foreground color and background color <nl> - template < typename . . . Args > <nl> - inline void print ( rgb fd , rgb bg , string_view format_str , const Args & . . . args ) <nl> - { <nl> - vprint_rgb ( fd , bg , format_str , make_format_args ( args . . . ) ) ; <nl> - } <nl> - <nl> - enum class color : uint32_t <nl> - { <nl> - alice_blue = 0xF0F8FF , / / rgb ( 240 , 248 , 255 ) <nl> - antique_white = 0xFAEBD7 , / / rgb ( 250 , 235 , 215 ) <nl> - aqua = 0x00FFFF , / / rgb ( 0 , 255 , 255 ) <nl> - aquamarine = 0x7FFFD4 , / / rgb ( 127 , 255 , 212 ) <nl> - azure = 0xF0FFFF , / / rgb ( 240 , 255 , 255 ) <nl> - beige = 0xF5F5DC , / / rgb ( 245 , 245 , 220 ) <nl> - bisque = 0xFFE4C4 , / / rgb ( 255 , 228 , 196 ) <nl> - black = 0x000000 , / / rgb ( 0 , 0 , 0 ) <nl> - blanched_almond = 0xFFEBCD , / / rgb ( 255 , 235 , 205 ) <nl> - blue = 0x0000FF , / / rgb ( 0 , 0 , 255 ) <nl> - blue_violet = 0x8A2BE2 , / / rgb ( 138 , 43 , 226 ) <nl> - brown = 0xA52A2A , / / rgb ( 165 , 42 , 42 ) <nl> - burly_wood = 0xDEB887 , / / rgb ( 222 , 184 , 135 ) <nl> - cadet_blue = 0x5F9EA0 , / / rgb ( 95 , 158 , 160 ) <nl> - chartreuse = 0x7FFF00 , / / rgb ( 127 , 255 , 0 ) <nl> - chocolate = 0xD2691E , / / rgb ( 210 , 105 , 30 ) <nl> - coral = 0xFF7F50 , / / rgb ( 255 , 127 , 80 ) <nl> - cornflower_blue = 0x6495ED , / / rgb ( 100 , 149 , 237 ) <nl> - cornsilk = 0xFFF8DC , / / rgb ( 255 , 248 , 220 ) <nl> - crimson = 0xDC143C , / / rgb ( 220 , 20 , 60 ) <nl> - cyan = 0x00FFFF , / / rgb ( 0 , 255 , 255 ) <nl> - dark_blue = 0x00008B , / / rgb ( 0 , 0 , 139 ) <nl> - dark_cyan = 0x008B8B , / / rgb ( 0 , 139 , 139 ) <nl> - dark_golden_rod = 0xB8860B , / / rgb ( 184 , 134 , 11 ) <nl> - dark_gray = 0xA9A9A9 , / / rgb ( 169 , 169 , 169 ) <nl> - dark_green = 0x006400 , / / rgb ( 0 , 100 , 0 ) <nl> - dark_khaki = 0xBDB76B , / / rgb ( 189 , 183 , 107 ) <nl> - dark_magenta = 0x8B008B , / / rgb ( 139 , 0 , 139 ) <nl> - dark_olive_green = 0x556B2F , / / rgb ( 85 , 107 , 47 ) <nl> - dark_orange = 0xFF8C00 , / / rgb ( 255 , 140 , 0 ) <nl> - dark_orchid = 0x9932CC , / / rgb ( 153 , 50 , 204 ) <nl> - dark_red = 0x8B0000 , / / rgb ( 139 , 0 , 0 ) <nl> - dark_salmon = 0xE9967A , / / rgb ( 233 , 150 , 122 ) <nl> - dark_sea_green = 0x8FBC8F , / / rgb ( 143 , 188 , 143 ) <nl> - dark_slate_blue = 0x483D8B , / / rgb ( 72 , 61 , 139 ) <nl> - dark_slate_gray = 0x2F4F4F , / / rgb ( 47 , 79 , 79 ) <nl> - dark_turquoise = 0x00CED1 , / / rgb ( 0 , 206 , 209 ) <nl> - dark_violet = 0x9400D3 , / / rgb ( 148 , 0 , 211 ) <nl> - deep_pink = 0xFF1493 , / / rgb ( 255 , 20 , 147 ) <nl> - deep_sky_blue = 0x00BFFF , / / rgb ( 0 , 191 , 255 ) <nl> - dim_gray = 0x696969 , / / rgb ( 105 , 105 , 105 ) <nl> - dodger_blue = 0x1E90FF , / / rgb ( 30 , 144 , 255 ) <nl> - fire_brick = 0xB22222 , / / rgb ( 178 , 34 , 34 ) <nl> - floral_white = 0xFFFAF0 , / / rgb ( 255 , 250 , 240 ) <nl> - forest_green = 0x228B22 , / / rgb ( 34 , 139 , 34 ) <nl> - fuchsia = 0xFF00FF , / / rgb ( 255 , 0 , 255 ) <nl> - gainsboro = 0xDCDCDC , / / rgb ( 220 , 220 , 220 ) <nl> - ghost_white = 0xF8F8FF , / / rgb ( 248 , 248 , 255 ) <nl> - gold = 0xFFD700 , / / rgb ( 255 , 215 , 0 ) <nl> - golden_rod = 0xDAA520 , / / rgb ( 218 , 165 , 32 ) <nl> - gray = 0x808080 , / / rgb ( 128 , 128 , 128 ) <nl> - green = 0x008000 , / / rgb ( 0 , 128 , 0 ) <nl> - green_yellow = 0xADFF2F , / / rgb ( 173 , 255 , 47 ) <nl> - honey_dew = 0xF0FFF0 , / / rgb ( 240 , 255 , 240 ) <nl> - hot_pink = 0xFF69B4 , / / rgb ( 255 , 105 , 180 ) <nl> - indian_red = 0xCD5C5C , / / rgb ( 205 , 92 , 92 ) <nl> - indigo = 0x4B0082 , / / rgb ( 75 , 0 , 130 ) <nl> - ivory = 0xFFFFF0 , / / rgb ( 255 , 255 , 240 ) <nl> - khaki = 0xF0E68C , / / rgb ( 240 , 230 , 140 ) <nl> - lavender = 0xE6E6FA , / / rgb ( 230 , 230 , 250 ) <nl> - lavender_blush = 0xFFF0F5 , / / rgb ( 255 , 240 , 245 ) <nl> - lawn_green = 0x7CFC00 , / / rgb ( 124 , 252 , 0 ) <nl> - lemon_chiffon = 0xFFFACD , / / rgb ( 255 , 250 , 205 ) <nl> - light_blue = 0xADD8E6 , / / rgb ( 173 , 216 , 230 ) <nl> - light_coral = 0xF08080 , / / rgb ( 240 , 128 , 128 ) <nl> - light_cyan = 0xE0FFFF , / / rgb ( 224 , 255 , 255 ) <nl> - light_golden_rod_yellow = 0xFAFAD2 , / / rgb ( 250 , 250 , 210 ) <nl> - light_gray = 0xD3D3D3 , / / rgb ( 211 , 211 , 211 ) <nl> - light_green = 0x90EE90 , / / rgb ( 144 , 238 , 144 ) <nl> - light_pink = 0xFFB6C1 , / / rgb ( 255 , 182 , 193 ) <nl> - light_salmon = 0xFFA07A , / / rgb ( 255 , 160 , 122 ) <nl> - light_sea_green = 0x20B2AA , / / rgb ( 32 , 178 , 170 ) <nl> - light_sky_blue = 0x87CEFA , / / rgb ( 135 , 206 , 250 ) <nl> - light_slate_gray = 0x778899 , / / rgb ( 119 , 136 , 153 ) <nl> - light_steel_blue = 0xB0C4DE , / / rgb ( 176 , 196 , 222 ) <nl> - light_yellow = 0xFFFFE0 , / / rgb ( 255 , 255 , 224 ) <nl> - lime = 0x00FF00 , / / rgb ( 0 , 255 , 0 ) <nl> - lime_green = 0x32CD32 , / / rgb ( 50 , 205 , 50 ) <nl> - linen = 0xFAF0E6 , / / rgb ( 250 , 240 , 230 ) <nl> - magenta = 0xFF00FF , / / rgb ( 255 , 0 , 255 ) <nl> - maroon = 0x800000 , / / rgb ( 128 , 0 , 0 ) <nl> - medium_aqua_marine = 0x66CDAA , / / rgb ( 102 , 205 , 170 ) <nl> - medium_blue = 0x0000CD , / / rgb ( 0 , 0 , 205 ) <nl> - medium_orchid = 0xBA55D3 , / / rgb ( 186 , 85 , 211 ) <nl> - medium_purple = 0x9370DB , / / rgb ( 147 , 112 , 219 ) <nl> - medium_sea_green = 0x3CB371 , / / rgb ( 60 , 179 , 113 ) <nl> - medium_slate_blue = 0x7B68EE , / / rgb ( 123 , 104 , 238 ) <nl> - medium_spring_green = 0x00FA9A , / / rgb ( 0 , 250 , 154 ) <nl> - medium_turquoise = 0x48D1CC , / / rgb ( 72 , 209 , 204 ) <nl> - medium_violet_red = 0xC71585 , / / rgb ( 199 , 21 , 133 ) <nl> - midnight_blue = 0x191970 , / / rgb ( 25 , 25 , 112 ) <nl> - mint_cream = 0xF5FFFA , / / rgb ( 245 , 255 , 250 ) <nl> - misty_rose = 0xFFE4E1 , / / rgb ( 255 , 228 , 225 ) <nl> - moccasin = 0xFFE4B5 , / / rgb ( 255 , 228 , 181 ) <nl> - navajo_white = 0xFFDEAD , / / rgb ( 255 , 222 , 173 ) <nl> - navy = 0x000080 , / / rgb ( 0 , 0 , 128 ) <nl> - old_lace = 0xFDF5E6 , / / rgb ( 253 , 245 , 230 ) <nl> - olive = 0x808000 , / / rgb ( 128 , 128 , 0 ) <nl> - olive_drab = 0x6B8E23 , / / rgb ( 107 , 142 , 35 ) <nl> - orange = 0xFFA500 , / / rgb ( 255 , 165 , 0 ) <nl> - orange_red = 0xFF4500 , / / rgb ( 255 , 69 , 0 ) <nl> - orchid = 0xDA70D6 , / / rgb ( 218 , 112 , 214 ) <nl> - pale_golden_rod = 0xEEE8AA , / / rgb ( 238 , 232 , 170 ) <nl> - pale_green = 0x98FB98 , / / rgb ( 152 , 251 , 152 ) <nl> - pale_turquoise = 0xAFEEEE , / / rgb ( 175 , 238 , 238 ) <nl> - pale_violet_red = 0xDB7093 , / / rgb ( 219 , 112 , 147 ) <nl> - papaya_whip = 0xFFEFD5 , / / rgb ( 255 , 239 , 213 ) <nl> - peach_puff = 0xFFDAB9 , / / rgb ( 255 , 218 , 185 ) <nl> - peru = 0xCD853F , / / rgb ( 205 , 133 , 63 ) <nl> - pink = 0xFFC0CB , / / rgb ( 255 , 192 , 203 ) <nl> - plum = 0xDDA0DD , / / rgb ( 221 , 160 , 221 ) <nl> - powder_blue = 0xB0E0E6 , / / rgb ( 176 , 224 , 230 ) <nl> - purple = 0x800080 , / / rgb ( 128 , 0 , 128 ) <nl> - rebecca_purple = 0x663399 , / / rgb ( 102 , 51 , 153 ) <nl> - red = 0xFF0000 , / / rgb ( 255 , 0 , 0 ) <nl> - rosy_brown = 0xBC8F8F , / / rgb ( 188 , 143 , 143 ) <nl> - royal_blue = 0x4169E1 , / / rgb ( 65 , 105 , 225 ) <nl> - saddle_brown = 0x8B4513 , / / rgb ( 139 , 69 , 19 ) <nl> - salmon = 0xFA8072 , / / rgb ( 250 , 128 , 114 ) <nl> - sandy_brown = 0xF4A460 , / / rgb ( 244 , 164 , 96 ) <nl> - sea_green = 0x2E8B57 , / / rgb ( 46 , 139 , 87 ) <nl> - sea_shell = 0xFFF5EE , / / rgb ( 255 , 245 , 238 ) <nl> - sienna = 0xA0522D , / / rgb ( 160 , 82 , 45 ) <nl> - silver = 0xC0C0C0 , / / rgb ( 192 , 192 , 192 ) <nl> - sky_blue = 0x87CEEB , / / rgb ( 135 , 206 , 235 ) <nl> - slate_blue = 0x6A5ACD , / / rgb ( 106 , 90 , 205 ) <nl> - slate_gray = 0x708090 , / / rgb ( 112 , 128 , 144 ) <nl> - snow = 0xFFFAFA , / / rgb ( 255 , 250 , 250 ) <nl> - spring_green = 0x00FF7F , / / rgb ( 0 , 255 , 127 ) <nl> - steel_blue = 0x4682B4 , / / rgb ( 70 , 130 , 180 ) <nl> - tan = 0xD2B48C , / / rgb ( 210 , 180 , 140 ) <nl> - teal = 0x008080 , / / rgb ( 0 , 128 , 128 ) <nl> - thistle = 0xD8BFD8 , / / rgb ( 216 , 191 , 216 ) <nl> - tomato = 0xFF6347 , / / rgb ( 255 , 99 , 71 ) <nl> - turquoise = 0x40E0D0 , / / rgb ( 64 , 224 , 208 ) <nl> - violet = 0xEE82EE , / / rgb ( 238 , 130 , 238 ) <nl> - wheat = 0xF5DEB3 , / / rgb ( 245 , 222 , 179 ) <nl> - white = 0xFFFFFF , / / rgb ( 255 , 255 , 255 ) <nl> - white_smoke = 0xF5F5F5 , / / rgb ( 245 , 245 , 245 ) <nl> - yellow = 0xFFFF00 , / / rgb ( 255 , 255 , 0 ) <nl> - yellow_green = 0x9ACD32 , / / rgb ( 154 , 205 , 50 ) <nl> - } ; / / enum class colors <nl> - <nl> - FMT_END_NAMESPACE <nl> - <nl> - # endif / / FMT_COLORS_H_ <nl> | Removed old header | gabime/spdlog | 58fb0decbfe8274778a443fe7b081b21826e719e | 2019-01-09T09:28:22Z |
mmm a / cocos / 2d / CCRenderTexture . cpp <nl> ppp b / cocos / 2d / CCRenderTexture . cpp <nl> Image * RenderTexture : : newImage ( bool fliimage ) <nl> return image ; <nl> } <nl> <nl> + void RenderTexture : : onBegin ( ) <nl> + { <nl> + / / <nl> + kmGLGetMatrix ( KM_GL_PROJECTION , & _oldProjMatrix ) ; <nl> + kmGLMatrixMode ( KM_GL_PROJECTION ) ; <nl> + kmGLLoadMatrix ( & _projectionMatrix ) ; <nl> + <nl> + kmGLGetMatrix ( KM_GL_MODELVIEW , & _oldTransMatrix ) ; <nl> + kmGLMatrixMode ( KM_GL_MODELVIEW ) ; <nl> + kmGLLoadMatrix ( & _transformMatrix ) ; <nl> + <nl> + Director * director = Director : : getInstance ( ) ; <nl> + director - > setProjection ( director - > getProjection ( ) ) ; <nl> + <nl> + const Size & texSize = _texture - > getContentSizeInPixels ( ) ; <nl> + <nl> + / / Calculate the adjustment ratios based on the old and new projections <nl> + Size size = director - > getWinSizeInPixels ( ) ; <nl> + float widthRatio = size . width / texSize . width ; <nl> + float heightRatio = size . height / texSize . height ; <nl> + <nl> + / / Adjust the orthographic projection and viewport <nl> + glViewport ( 0 , 0 , ( GLsizei ) texSize . width , ( GLsizei ) texSize . height ) ; <nl> + <nl> + <nl> + kmMat4 orthoMatrix ; <nl> + kmMat4OrthographicProjection ( & orthoMatrix , ( float ) - 1 . 0 / widthRatio , ( float ) 1 . 0 / widthRatio , <nl> + ( float ) - 1 . 0 / heightRatio , ( float ) 1 . 0 / heightRatio , - 1 , 1 ) ; <nl> + kmGLMultMatrix ( & orthoMatrix ) ; <nl> + <nl> + glGetIntegerv ( GL_FRAMEBUFFER_BINDING , & _oldFBO ) ; <nl> + glBindFramebuffer ( GL_FRAMEBUFFER , _FBO ) ; <nl> + <nl> + / / TODO move this to configration , so we don ' t check it every time <nl> + / * Certain Qualcomm Andreno gpu ' s will retain data in memory after a frame buffer switch which corrupts the render to the texture . The solution is to clear the frame buffer before rendering to the texture . However , calling glClear has the unintended result of clearing the current texture . Create a temporary texture to overcome this . At the end of RenderTexture : : begin ( ) , switch the attached texture to the second one , call glClear , and then switch back to the original texture . This solution is unnecessary for other devices as they don ' t have the same issue with switching frame buffers . <nl> + * / <nl> + if ( Configuration : : getInstance ( ) - > checkForGLExtension ( " GL_QCOM " ) ) <nl> + { <nl> + / / - - bind a temporary texture so we can clear the render buffer without losing our texture <nl> + glFramebufferTexture2D ( GL_FRAMEBUFFER , GL_COLOR_ATTACHMENT0 , GL_TEXTURE_2D , _textureCopy - > getName ( ) , 0 ) ; <nl> + CHECK_GL_ERROR_DEBUG ( ) ; <nl> + glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) ; <nl> + glFramebufferTexture2D ( GL_FRAMEBUFFER , GL_COLOR_ATTACHMENT0 , GL_TEXTURE_2D , _texture - > getName ( ) , 0 ) ; <nl> + } <nl> + } <nl> + <nl> + void RenderTexture : : onEnd ( ) <nl> + { <nl> + Director * director = Director : : getInstance ( ) ; <nl> + <nl> + glBindFramebuffer ( GL_FRAMEBUFFER , _oldFBO ) ; <nl> + <nl> + / / restore viewport <nl> + director - > setViewport ( ) ; <nl> + <nl> + / / <nl> + kmGLMatrixMode ( KM_GL_PROJECTION ) ; <nl> + kmGLLoadMatrix ( & _oldProjMatrix ) ; <nl> + <nl> + kmGLMatrixMode ( KM_GL_MODELVIEW ) ; <nl> + kmGLLoadMatrix ( & _oldTransMatrix ) ; <nl> + } <nl> + <nl> + void RenderTexture : : onClear ( ) <nl> + { <nl> + / / save clear color <nl> + GLfloat oldClearColor [ 4 ] = { 0 . 0f } ; <nl> + GLfloat oldDepthClearValue = 0 . 0f ; <nl> + GLint oldStencilClearValue = 0 ; <nl> + <nl> + / / backup and set <nl> + if ( _clearFlags & GL_COLOR_BUFFER_BIT ) <nl> + { <nl> + glGetFloatv ( GL_COLOR_CLEAR_VALUE , oldClearColor ) ; <nl> + glClearColor ( _clearColor . r , _clearColor . g , _clearColor . b , _clearColor . a ) ; <nl> + } <nl> + <nl> + if ( _clearFlags & GL_DEPTH_BUFFER_BIT ) <nl> + { <nl> + glGetFloatv ( GL_DEPTH_CLEAR_VALUE , & oldDepthClearValue ) ; <nl> + glClearDepth ( _clearDepth ) ; <nl> + } <nl> + <nl> + if ( _clearFlags & GL_STENCIL_BUFFER_BIT ) <nl> + { <nl> + glGetIntegerv ( GL_STENCIL_CLEAR_VALUE , & oldStencilClearValue ) ; <nl> + glClearStencil ( _clearStencil ) ; <nl> + } <nl> + <nl> + / / clear <nl> + glClear ( _clearFlags ) ; <nl> + <nl> + / / restore <nl> + if ( _clearFlags & GL_COLOR_BUFFER_BIT ) <nl> + { <nl> + glClearColor ( oldClearColor [ 0 ] , oldClearColor [ 1 ] , oldClearColor [ 2 ] , oldClearColor [ 3 ] ) ; <nl> + } <nl> + if ( _clearFlags & GL_DEPTH_BUFFER_BIT ) <nl> + { <nl> + glClearDepth ( oldDepthClearValue ) ; <nl> + } <nl> + if ( _clearFlags & GL_STENCIL_BUFFER_BIT ) <nl> + { <nl> + glClearStencil ( oldStencilClearValue ) ; <nl> + } <nl> + } <nl> + <nl> + void RenderTexture : : onClearDepth ( ) <nl> + { <nl> + / / ! save old depth value <nl> + GLfloat depthClearValue ; <nl> + glGetFloatv ( GL_DEPTH_CLEAR_VALUE , & depthClearValue ) ; <nl> + <nl> + glClearDepth ( _clearDepth ) ; <nl> + glClear ( GL_DEPTH_BUFFER_BIT ) ; <nl> + <nl> + / / restore clear color <nl> + glClearDepth ( depthClearValue ) ; <nl> + } <nl> + <nl> NS_CC_END <nl> mmm a / cocos / 2d / CCRenderTexture . h <nl> ppp b / cocos / 2d / CCRenderTexture . h <nl> class CC_DLL RenderTexture : public Node <nl> - [ [ renderTexture sprite ] setBlendFunc : ( BlendFunc ) { GL_ONE , GL_ONE_MINUS_SRC_ALPHA } ] ; <nl> * / <nl> Sprite * _sprite ; <nl> + protected : <nl> + / / renderer caches and callbacks <nl> + void onBegin ( ) ; <nl> + void onEnd ( ) ; <nl> <nl> + void onClear ( ) ; <nl> + void onClearDepth ( ) ; <nl> + <nl> + kmMat4 _oldTransMatrix , _oldProjMatrix ; <nl> + kmMat4 _transformMatrix , _projectionMatrix ; <nl> private : <nl> CC_DISALLOW_COPY_AND_ASSIGN ( RenderTexture ) ; <nl> <nl> mmm a / cocos / 2d / renderer / CCNewRenderTexture . cpp <nl> ppp b / cocos / 2d / renderer / CCNewRenderTexture . cpp <nl> void NewRenderTexture : : end ( ) <nl> renderer - > popGroup ( ) ; <nl> } <nl> <nl> - void NewRenderTexture : : onBegin ( ) <nl> - { <nl> - / / <nl> - kmGLGetMatrix ( KM_GL_PROJECTION , & _oldProjMatrix ) ; <nl> - kmGLMatrixMode ( KM_GL_PROJECTION ) ; <nl> - kmGLLoadMatrix ( & _projectionMatrix ) ; <nl> - <nl> - kmGLGetMatrix ( KM_GL_MODELVIEW , & _oldTransMatrix ) ; <nl> - kmGLMatrixMode ( KM_GL_MODELVIEW ) ; <nl> - kmGLLoadMatrix ( & _transformMatrix ) ; <nl> - <nl> - Director * director = Director : : getInstance ( ) ; <nl> - director - > setProjection ( director - > getProjection ( ) ) ; <nl> - <nl> - const Size & texSize = _texture - > getContentSizeInPixels ( ) ; <nl> - <nl> - / / Calculate the adjustment ratios based on the old and new projections <nl> - Size size = director - > getWinSizeInPixels ( ) ; <nl> - float widthRatio = size . width / texSize . width ; <nl> - float heightRatio = size . height / texSize . height ; <nl> - <nl> - / / Adjust the orthographic projection and viewport <nl> - glViewport ( 0 , 0 , ( GLsizei ) texSize . width , ( GLsizei ) texSize . height ) ; <nl> - <nl> - <nl> - kmMat4 orthoMatrix ; <nl> - kmMat4OrthographicProjection ( & orthoMatrix , ( float ) - 1 . 0 / widthRatio , ( float ) 1 . 0 / widthRatio , <nl> - ( float ) - 1 . 0 / heightRatio , ( float ) 1 . 0 / heightRatio , - 1 , 1 ) ; <nl> - kmGLMultMatrix ( & orthoMatrix ) ; <nl> - <nl> - glGetIntegerv ( GL_FRAMEBUFFER_BINDING , & _oldFBO ) ; <nl> - glBindFramebuffer ( GL_FRAMEBUFFER , _FBO ) ; <nl> - <nl> - / / TODO move this to configration , so we don ' t check it every time <nl> - / * Certain Qualcomm Andreno gpu ' s will retain data in memory after a frame buffer switch which corrupts the render to the texture . The solution is to clear the frame buffer before rendering to the texture . However , calling glClear has the unintended result of clearing the current texture . Create a temporary texture to overcome this . At the end of RenderTexture : : begin ( ) , switch the attached texture to the second one , call glClear , and then switch back to the original texture . This solution is unnecessary for other devices as they don ' t have the same issue with switching frame buffers . <nl> - * / <nl> - if ( Configuration : : getInstance ( ) - > checkForGLExtension ( " GL_QCOM " ) ) <nl> - { <nl> - / / - - bind a temporary texture so we can clear the render buffer without losing our texture <nl> - glFramebufferTexture2D ( GL_FRAMEBUFFER , GL_COLOR_ATTACHMENT0 , GL_TEXTURE_2D , _textureCopy - > getName ( ) , 0 ) ; <nl> - CHECK_GL_ERROR_DEBUG ( ) ; <nl> - glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) ; <nl> - glFramebufferTexture2D ( GL_FRAMEBUFFER , GL_COLOR_ATTACHMENT0 , GL_TEXTURE_2D , _texture - > getName ( ) , 0 ) ; <nl> - } <nl> - } <nl> - <nl> - void NewRenderTexture : : onEnd ( ) <nl> - { <nl> - Director * director = Director : : getInstance ( ) ; <nl> - <nl> - glBindFramebuffer ( GL_FRAMEBUFFER , _oldFBO ) ; <nl> - <nl> - / / restore viewport <nl> - director - > setViewport ( ) ; <nl> - <nl> - / / <nl> - kmGLMatrixMode ( KM_GL_PROJECTION ) ; <nl> - kmGLLoadMatrix ( & _oldProjMatrix ) ; <nl> - <nl> - kmGLMatrixMode ( KM_GL_MODELVIEW ) ; <nl> - kmGLLoadMatrix ( & _oldTransMatrix ) ; <nl> - } <nl> - <nl> - void NewRenderTexture : : onClear ( ) <nl> - { <nl> - / / save clear color <nl> - GLfloat oldClearColor [ 4 ] = { 0 . 0f } ; <nl> - GLfloat oldDepthClearValue = 0 . 0f ; <nl> - GLint oldStencilClearValue = 0 ; <nl> - <nl> - / / backup and set <nl> - if ( _clearFlags & GL_COLOR_BUFFER_BIT ) <nl> - { <nl> - glGetFloatv ( GL_COLOR_CLEAR_VALUE , oldClearColor ) ; <nl> - glClearColor ( _clearColor . r , _clearColor . g , _clearColor . b , _clearColor . a ) ; <nl> - } <nl> - <nl> - if ( _clearFlags & GL_DEPTH_BUFFER_BIT ) <nl> - { <nl> - glGetFloatv ( GL_DEPTH_CLEAR_VALUE , & oldDepthClearValue ) ; <nl> - glClearDepth ( _clearDepth ) ; <nl> - } <nl> - <nl> - if ( _clearFlags & GL_STENCIL_BUFFER_BIT ) <nl> - { <nl> - glGetIntegerv ( GL_STENCIL_CLEAR_VALUE , & oldStencilClearValue ) ; <nl> - glClearStencil ( _clearStencil ) ; <nl> - } <nl> - <nl> - / / clear <nl> - glClear ( _clearFlags ) ; <nl> - <nl> - / / restore <nl> - if ( _clearFlags & GL_COLOR_BUFFER_BIT ) <nl> - { <nl> - glClearColor ( oldClearColor [ 0 ] , oldClearColor [ 1 ] , oldClearColor [ 2 ] , oldClearColor [ 3 ] ) ; <nl> - } <nl> - if ( _clearFlags & GL_DEPTH_BUFFER_BIT ) <nl> - { <nl> - glClearDepth ( oldDepthClearValue ) ; <nl> - } <nl> - if ( _clearFlags & GL_STENCIL_BUFFER_BIT ) <nl> - { <nl> - glClearStencil ( oldStencilClearValue ) ; <nl> - } <nl> - } <nl> - <nl> void NewRenderTexture : : clearDepth ( float depthValue ) <nl> { <nl> setClearDepth ( depthValue ) ; <nl> void NewRenderTexture : : clearDepth ( float depthValue ) <nl> this - > end ( ) ; <nl> } <nl> <nl> - void NewRenderTexture : : onClearDepth ( ) <nl> - { <nl> - / / ! save old depth value <nl> - GLfloat depthClearValue ; <nl> - glGetFloatv ( GL_DEPTH_CLEAR_VALUE , & depthClearValue ) ; <nl> - <nl> - glClearDepth ( _clearDepth ) ; <nl> - glClear ( GL_DEPTH_BUFFER_BIT ) ; <nl> - <nl> - / / restore clear color <nl> - glClearDepth ( depthClearValue ) ; <nl> - } <nl> - <nl> NewRenderTexture : : NewRenderTexture ( ) <nl> : RenderTexture ( ) <nl> { <nl> mmm a / cocos / 2d / renderer / CCNewRenderTexture . h <nl> ppp b / cocos / 2d / renderer / CCNewRenderTexture . h <nl> class NewRenderTexture : public RenderTexture <nl> protected : <nl> NewRenderTexture ( ) ; <nl> virtual ~ NewRenderTexture ( ) ; <nl> - <nl> - void onBegin ( ) ; <nl> - void onEnd ( ) ; <nl> - <nl> - / / Clear render buffer <nl> - void onClear ( ) ; <nl> - void onClearDepth ( ) ; <nl> - <nl> - kmMat4 _oldTransMatrix , _oldProjMatrix ; <nl> - kmMat4 _transformMatrix , _projectionMatrix ; <nl> } ; <nl> <nl> NS_CC_END <nl> | move rendering callback to RenderTexture | cocos2d/cocos2d-x | fad585fbefe8a1e28897d0309177a4cd18ed132d | 2013-12-23T07:59:47Z |
mmm a / toolsrc / include / triplet . h <nl> ppp b / toolsrc / include / triplet . h <nl> namespace std <nl> } <nl> } ; <nl> <nl> - template < > <nl> - struct equal_to < vcpkg : : triplet > <nl> - { <nl> - bool operator ( ) ( const vcpkg : : triplet & left , const vcpkg : : triplet & right ) const <nl> - { <nl> - return left = = right ; <nl> - } <nl> - } ; <nl> } / / namespace std <nl> | [ vcpkg ] Clean up triplet . h | microsoft/vcpkg | 8dd90aa9766811ccfb74bcf578364eca573f0c6c | 2017-03-20T23:20:02Z |
mmm a / src / Makefile . am <nl> ppp b / src / Makefile . am <nl> DIST_SUBDIRS = . qt test <nl> . PHONY : FORCE <nl> # bitcoin core # <nl> BITCOIN_CORE_H = addrman . h alert . h allocators . h base58 . h bignum . h \ <nl> - bitcoinrpc . h bloom . h chainparams . h checkpoints . h checkqueue . h \ <nl> + rpcclient . h \ <nl> + rpcprotocol . h \ <nl> + rpcserver . h \ <nl> + bloom . h chainparams . h checkpoints . h checkqueue . h \ <nl> clientversion . h coincontrol . h compat . h core . h coins . h crypter . h db . h hash . h init . h \ <nl> key . h keystore . h leveldbwrapper . h limitedmap . h main . h miner . h mruset . h \ <nl> netbase . h net . h noui . h protocol . h script . h serialize . h sync . h threadsafety . h \ <nl> obj / build . h : FORCE <nl> $ ( abs_top_srcdir ) <nl> version . o : obj / build . h <nl> <nl> - libbitcoin_a_SOURCES = addrman . cpp alert . cpp allocators . cpp bitcoinrpc . cpp bloom . cpp \ <nl> + libbitcoin_a_SOURCES = addrman . cpp alert . cpp allocators . cpp \ <nl> + rpcclient . cpp \ <nl> + rpcprotocol . cpp \ <nl> + rpcserver . cpp \ <nl> + bloom . cpp \ <nl> chainparams . cpp checkpoints . cpp core . cpp coins . cpp crypter . cpp db . cpp hash . cpp \ <nl> init . cpp key . cpp keystore . cpp leveldbwrapper . cpp main . cpp miner . cpp \ <nl> netbase . cpp net . cpp noui . cpp protocol . cpp rpcblockchain . cpp rpcdump . cpp \ <nl> mmm a / src / bitcoin - cli . cpp <nl> ppp b / src / bitcoin - cli . cpp <nl> <nl> <nl> # include " util . h " <nl> # include " init . h " <nl> - # include " bitcoinrpc . h " <nl> + # include " rpcclient . h " <nl> # include " ui_interface . h " / * for _ ( . . . ) * / <nl> <nl> # include < boost / filesystem / operations . hpp > <nl> mmm a / src / bitcoind . cpp <nl> ppp b / src / bitcoind . cpp <nl> <nl> / / Distributed under the MIT / X11 software license , see the accompanying <nl> / / file COPYING or http : / / www . opensource . org / licenses / mit - license . php . <nl> <nl> - # include " bitcoinrpc . h " <nl> + # include " rpcserver . h " <nl> + # include " rpcclient . h " <nl> # include " init . h " <nl> # include " main . h " <nl> # include " noui . h " <nl> mmm a / src / init . cpp <nl> ppp b / src / init . cpp <nl> <nl> # include " init . h " <nl> <nl> # include " addrman . h " <nl> - # include " bitcoinrpc . h " <nl> + # include " rpcserver . h " <nl> # include " checkpoints . h " <nl> # include " miner . h " <nl> # include " net . h " <nl> mmm a / src / qt / rpcconsole . cpp <nl> ppp b / src / qt / rpcconsole . cpp <nl> <nl> # include " clientmodel . h " <nl> # include " guiutil . h " <nl> <nl> - # include " bitcoinrpc . h " <nl> + # include " rpcserver . h " <nl> + # include " rpcclient . h " <nl> <nl> # include " json / json_spirit_value . h " <nl> # include < openssl / crypto . h > <nl> mmm a / src / rpcblockchain . cpp <nl> ppp b / src / rpcblockchain . cpp <nl> <nl> / / Distributed under the MIT / X11 software license , see the accompanying <nl> / / file COPYING or http : / / www . opensource . org / licenses / mit - license . php . <nl> <nl> - <nl> - <nl> - # include " bitcoinrpc . h " <nl> + # include " rpcserver . h " <nl> # include " main . h " <nl> # include " sync . h " <nl> <nl> new file mode 100644 <nl> index 000000000000 . . 2667a5d5a5ce <nl> mmm / dev / null <nl> ppp b / src / rpcclient . cpp <nl> <nl> + / / Copyright ( c ) 2010 Satoshi Nakamoto <nl> + / / Copyright ( c ) 2009 - 2013 The Bitcoin developers <nl> + / / Distributed under the MIT / X11 software license , see the accompanying <nl> + / / file COPYING or http : / / www . opensource . org / licenses / mit - license . php . <nl> + <nl> + # include " rpcclient . h " <nl> + <nl> + # include " rpcprotocol . h " <nl> + # include " util . h " <nl> + # include " ui_interface . h " <nl> + # include " chainparams . h " / / for Params ( ) . RPCPort ( ) <nl> + <nl> + # include < stdint . h > <nl> + <nl> + # include < boost / algorithm / string . hpp > <nl> + # include < boost / asio . hpp > <nl> + # include < boost / asio / ssl . hpp > <nl> + # include < boost / bind . hpp > <nl> + # include < boost / filesystem . hpp > <nl> + # include < boost / foreach . hpp > <nl> + # include < boost / iostreams / concepts . hpp > <nl> + # include < boost / iostreams / stream . hpp > <nl> + # include < boost / lexical_cast . hpp > <nl> + # include < boost / shared_ptr . hpp > <nl> + # include " json / json_spirit_writer_template . h " <nl> + <nl> + using namespace std ; <nl> + using namespace boost ; <nl> + using namespace boost : : asio ; <nl> + using namespace json_spirit ; <nl> + <nl> + Object CallRPC ( const string & strMethod , const Array & params ) <nl> + { <nl> + if ( mapArgs [ " - rpcuser " ] = = " " & & mapArgs [ " - rpcpassword " ] = = " " ) <nl> + throw runtime_error ( strprintf ( <nl> + _ ( " You must set rpcpassword = < password > in the configuration file : \ n % s \ n " <nl> + " If the file does not exist , create it with owner - readable - only file permissions . " ) , <nl> + GetConfigFile ( ) . string ( ) . c_str ( ) ) ) ; <nl> + <nl> + / / Connect to localhost <nl> + bool fUseSSL = GetBoolArg ( " - rpcssl " , false ) ; <nl> + asio : : io_service io_service ; <nl> + ssl : : context context ( io_service , ssl : : context : : sslv23 ) ; <nl> + context . set_options ( ssl : : context : : no_sslv2 ) ; <nl> + asio : : ssl : : stream < asio : : ip : : tcp : : socket > sslStream ( io_service , context ) ; <nl> + SSLIOStreamDevice < asio : : ip : : tcp > d ( sslStream , fUseSSL ) ; <nl> + iostreams : : stream < SSLIOStreamDevice < asio : : ip : : tcp > > stream ( d ) ; <nl> + <nl> + bool fWait = GetBoolArg ( " - rpcwait " , false ) ; / / - rpcwait means try until server has started <nl> + do { <nl> + bool fConnected = d . connect ( GetArg ( " - rpcconnect " , " 127 . 0 . 0 . 1 " ) , GetArg ( " - rpcport " , itostr ( Params ( ) . RPCPort ( ) ) ) ) ; <nl> + if ( fConnected ) break ; <nl> + if ( fWait ) <nl> + MilliSleep ( 1000 ) ; <nl> + else <nl> + throw runtime_error ( " couldn ' t connect to server " ) ; <nl> + } while ( fWait ) ; <nl> + <nl> + / / HTTP basic authentication <nl> + string strUserPass64 = EncodeBase64 ( mapArgs [ " - rpcuser " ] + " : " + mapArgs [ " - rpcpassword " ] ) ; <nl> + map < string , string > mapRequestHeaders ; <nl> + mapRequestHeaders [ " Authorization " ] = string ( " Basic " ) + strUserPass64 ; <nl> + <nl> + / / Send request <nl> + string strRequest = JSONRPCRequest ( strMethod , params , 1 ) ; <nl> + string strPost = HTTPPost ( strRequest , mapRequestHeaders ) ; <nl> + stream < < strPost < < std : : flush ; <nl> + <nl> + / / Receive HTTP reply status <nl> + int nProto = 0 ; <nl> + int nStatus = ReadHTTPStatus ( stream , nProto ) ; <nl> + <nl> + / / Receive HTTP reply message headers and body <nl> + map < string , string > mapHeaders ; <nl> + string strReply ; <nl> + ReadHTTPMessage ( stream , mapHeaders , strReply , nProto ) ; <nl> + <nl> + if ( nStatus = = HTTP_UNAUTHORIZED ) <nl> + throw runtime_error ( " incorrect rpcuser or rpcpassword ( authorization failed ) " ) ; <nl> + else if ( nStatus > = 400 & & nStatus ! = HTTP_BAD_REQUEST & & nStatus ! = HTTP_NOT_FOUND & & nStatus ! = HTTP_INTERNAL_SERVER_ERROR ) <nl> + throw runtime_error ( strprintf ( " server returned HTTP error % d " , nStatus ) ) ; <nl> + else if ( strReply . empty ( ) ) <nl> + throw runtime_error ( " no response from server " ) ; <nl> + <nl> + / / Parse reply <nl> + Value valReply ; <nl> + if ( ! read_string ( strReply , valReply ) ) <nl> + throw runtime_error ( " couldn ' t parse reply from server " ) ; <nl> + const Object & reply = valReply . get_obj ( ) ; <nl> + if ( reply . empty ( ) ) <nl> + throw runtime_error ( " expected reply to have result , error and id properties " ) ; <nl> + <nl> + return reply ; <nl> + } <nl> + <nl> + template < typename T > <nl> + void ConvertTo ( Value & value , bool fAllowNull = false ) <nl> + { <nl> + if ( fAllowNull & & value . type ( ) = = null_type ) <nl> + return ; <nl> + if ( value . type ( ) = = str_type ) <nl> + { <nl> + / / reinterpret string as unquoted json value <nl> + Value value2 ; <nl> + string strJSON = value . get_str ( ) ; <nl> + if ( ! read_string ( strJSON , value2 ) ) <nl> + throw runtime_error ( string ( " Error parsing JSON : " ) + strJSON ) ; <nl> + ConvertTo < T > ( value2 , fAllowNull ) ; <nl> + value = value2 ; <nl> + } <nl> + else <nl> + { <nl> + value = value . get_value < T > ( ) ; <nl> + } <nl> + } <nl> + <nl> + / / Convert strings to command - specific RPC representation <nl> + Array RPCConvertValues ( const std : : string & strMethod , const std : : vector < std : : string > & strParams ) <nl> + { <nl> + Array params ; <nl> + BOOST_FOREACH ( const std : : string & param , strParams ) <nl> + params . push_back ( param ) ; <nl> + <nl> + int n = params . size ( ) ; <nl> + <nl> + / / <nl> + / / Special case non - string parameter types <nl> + / / <nl> + if ( strMethod = = " stop " & & n > 0 ) ConvertTo < bool > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " getaddednodeinfo " & & n > 0 ) ConvertTo < bool > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " setgenerate " & & n > 0 ) ConvertTo < bool > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " setgenerate " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " getnetworkhashps " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " getnetworkhashps " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " sendtoaddress " & & n > 1 ) ConvertTo < double > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " settxfee " & & n > 0 ) ConvertTo < double > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " getreceivedbyaddress " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " getreceivedbyaccount " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " listreceivedbyaddress " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " listreceivedbyaddress " & & n > 1 ) ConvertTo < bool > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " listreceivedbyaccount " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " listreceivedbyaccount " & & n > 1 ) ConvertTo < bool > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " getbalance " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " getblockhash " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " move " & & n > 2 ) ConvertTo < double > ( params [ 2 ] ) ; <nl> + if ( strMethod = = " move " & & n > 3 ) ConvertTo < boost : : int64_t > ( params [ 3 ] ) ; <nl> + if ( strMethod = = " sendfrom " & & n > 2 ) ConvertTo < double > ( params [ 2 ] ) ; <nl> + if ( strMethod = = " sendfrom " & & n > 3 ) ConvertTo < boost : : int64_t > ( params [ 3 ] ) ; <nl> + if ( strMethod = = " listtransactions " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " listtransactions " & & n > 2 ) ConvertTo < boost : : int64_t > ( params [ 2 ] ) ; <nl> + if ( strMethod = = " listaccounts " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " walletpassphrase " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " getblocktemplate " & & n > 0 ) ConvertTo < Object > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " listsinceblock " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " sendmany " & & n > 1 ) ConvertTo < Object > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " sendmany " & & n > 2 ) ConvertTo < boost : : int64_t > ( params [ 2 ] ) ; <nl> + if ( strMethod = = " addmultisigaddress " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " addmultisigaddress " & & n > 1 ) ConvertTo < Array > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " createmultisig " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " createmultisig " & & n > 1 ) ConvertTo < Array > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " listunspent " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " listunspent " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " listunspent " & & n > 2 ) ConvertTo < Array > ( params [ 2 ] ) ; <nl> + if ( strMethod = = " getblock " & & n > 1 ) ConvertTo < bool > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " getrawtransaction " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " createrawtransaction " & & n > 0 ) ConvertTo < Array > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " createrawtransaction " & & n > 1 ) ConvertTo < Object > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " signrawtransaction " & & n > 1 ) ConvertTo < Array > ( params [ 1 ] , true ) ; <nl> + if ( strMethod = = " signrawtransaction " & & n > 2 ) ConvertTo < Array > ( params [ 2 ] , true ) ; <nl> + if ( strMethod = = " sendrawtransaction " & & n > 1 ) ConvertTo < bool > ( params [ 1 ] , true ) ; <nl> + if ( strMethod = = " gettxout " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " gettxout " & & n > 2 ) ConvertTo < bool > ( params [ 2 ] ) ; <nl> + if ( strMethod = = " lockunspent " & & n > 0 ) ConvertTo < bool > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " lockunspent " & & n > 1 ) ConvertTo < Array > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " importprivkey " & & n > 2 ) ConvertTo < bool > ( params [ 2 ] ) ; <nl> + if ( strMethod = = " verifychain " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> + if ( strMethod = = " verifychain " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> + if ( strMethod = = " keypoolrefill " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> + <nl> + return params ; <nl> + } <nl> + <nl> + int CommandLineRPC ( int argc , char * argv [ ] ) <nl> + { <nl> + string strPrint ; <nl> + int nRet = 0 ; <nl> + try <nl> + { <nl> + / / Skip switches <nl> + while ( argc > 1 & & IsSwitchChar ( argv [ 1 ] [ 0 ] ) ) <nl> + { <nl> + argc - - ; <nl> + argv + + ; <nl> + } <nl> + <nl> + / / Method <nl> + if ( argc < 2 ) <nl> + throw runtime_error ( " too few parameters " ) ; <nl> + string strMethod = argv [ 1 ] ; <nl> + <nl> + / / Parameters default to strings <nl> + std : : vector < std : : string > strParams ( & argv [ 2 ] , & argv [ argc ] ) ; <nl> + Array params = RPCConvertValues ( strMethod , strParams ) ; <nl> + <nl> + / / Execute <nl> + Object reply = CallRPC ( strMethod , params ) ; <nl> + <nl> + / / Parse reply <nl> + const Value & result = find_value ( reply , " result " ) ; <nl> + const Value & error = find_value ( reply , " error " ) ; <nl> + <nl> + if ( error . type ( ) ! = null_type ) <nl> + { <nl> + / / Error <nl> + strPrint = " error : " + write_string ( error , false ) ; <nl> + int code = find_value ( error . get_obj ( ) , " code " ) . get_int ( ) ; <nl> + nRet = abs ( code ) ; <nl> + } <nl> + else <nl> + { <nl> + / / Result <nl> + if ( result . type ( ) = = null_type ) <nl> + strPrint = " " ; <nl> + else if ( result . type ( ) = = str_type ) <nl> + strPrint = result . get_str ( ) ; <nl> + else <nl> + strPrint = write_string ( result , true ) ; <nl> + } <nl> + } <nl> + catch ( boost : : thread_interrupted ) { <nl> + throw ; <nl> + } <nl> + catch ( std : : exception & e ) { <nl> + strPrint = string ( " error : " ) + e . what ( ) ; <nl> + nRet = 87 ; <nl> + } <nl> + catch ( . . . ) { <nl> + PrintException ( NULL , " CommandLineRPC ( ) " ) ; <nl> + } <nl> + <nl> + if ( strPrint ! = " " ) <nl> + { <nl> + fprintf ( ( nRet = = 0 ? stdout : stderr ) , " % s \ n " , strPrint . c_str ( ) ) ; <nl> + } <nl> + return nRet ; <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . f3ea56c25b98 <nl> mmm / dev / null <nl> ppp b / src / rpcclient . h <nl> <nl> + / / Copyright ( c ) 2010 Satoshi Nakamoto <nl> + / / Copyright ( c ) 2009 - 2013 The Bitcoin developers <nl> + / / Distributed under the MIT / X11 software license , see the accompanying <nl> + / / file COPYING or http : / / www . opensource . org / licenses / mit - license . php . <nl> + <nl> + # ifndef _BITCOINRPC_CLIENT_H_ <nl> + # define _BITCOINRPC_CLIENT_H_ 1 <nl> + <nl> + # include " json / json_spirit_reader_template . h " <nl> + # include " json / json_spirit_utils . h " <nl> + # include " json / json_spirit_writer_template . h " <nl> + <nl> + int CommandLineRPC ( int argc , char * argv [ ] ) ; <nl> + <nl> + json_spirit : : Array RPCConvertValues ( const std : : string & strMethod , const std : : vector < std : : string > & strParams ) ; <nl> + <nl> + # endif <nl> mmm a / src / rpcdump . cpp <nl> ppp b / src / rpcdump . cpp <nl> <nl> / / Distributed under the MIT / X11 software license , see the accompanying <nl> / / file COPYING or http : / / www . opensource . org / licenses / mit - license . php . <nl> <nl> - <nl> - <nl> # include " base58 . h " <nl> - # include " bitcoinrpc . h " <nl> + # include " rpcserver . h " <nl> # include " init . h " <nl> # include " main . h " <nl> # include " sync . h " <nl> mmm a / src / rpcmining . cpp <nl> ppp b / src / rpcmining . cpp <nl> <nl> / / Distributed under the MIT / X11 software license , see the accompanying <nl> / / file COPYING or http : / / www . opensource . org / licenses / mit - license . php . <nl> <nl> - # include " bitcoinrpc . h " <nl> + # include " rpcserver . h " <nl> # include " chainparams . h " <nl> # include " db . h " <nl> # include " init . h " <nl> mmm a / src / rpcnet . cpp <nl> ppp b / src / rpcnet . cpp <nl> <nl> / / Distributed under the MIT / X11 software license , see the accompanying <nl> / / file COPYING or http : / / www . opensource . org / licenses / mit - license . php . <nl> <nl> - <nl> - <nl> - # include " bitcoinrpc . h " <nl> + # include " rpcserver . h " <nl> # include " net . h " <nl> # include " netbase . h " <nl> # include " protocol . h " <nl> new file mode 100644 <nl> index 000000000000 . . 4a2241edaa5a <nl> mmm / dev / null <nl> ppp b / src / rpcprotocol . cpp <nl> <nl> + / / Copyright ( c ) 2010 Satoshi Nakamoto <nl> + / / Copyright ( c ) 2009 - 2013 The Bitcoin developers <nl> + / / Distributed under the MIT / X11 software license , see the accompanying <nl> + / / file COPYING or http : / / www . opensource . org / licenses / mit - license . php . <nl> + <nl> + # include " rpcprotocol . h " <nl> + <nl> + # include " util . h " <nl> + <nl> + # include < stdint . h > <nl> + <nl> + # include < boost / algorithm / string . hpp > <nl> + # include < boost / asio . hpp > <nl> + # include < boost / asio / ssl . hpp > <nl> + # include < boost / bind . hpp > <nl> + # include < boost / filesystem . hpp > <nl> + # include < boost / foreach . hpp > <nl> + # include < boost / iostreams / concepts . hpp > <nl> + # include < boost / iostreams / stream . hpp > <nl> + # include < boost / lexical_cast . hpp > <nl> + # include < boost / shared_ptr . hpp > <nl> + # include " json / json_spirit_writer_template . h " <nl> + <nl> + using namespace std ; <nl> + using namespace boost ; <nl> + using namespace boost : : asio ; <nl> + using namespace json_spirit ; <nl> + <nl> + / / <nl> + / / HTTP protocol <nl> + / / <nl> + / / This ain ' t Apache . We ' re just using HTTP header for the length field <nl> + / / and to be compatible with other JSON - RPC implementations . <nl> + / / <nl> + <nl> + string HTTPPost ( const string & strMsg , const map < string , string > & mapRequestHeaders ) <nl> + { <nl> + ostringstream s ; <nl> + s < < " POST / HTTP / 1 . 1 \ r \ n " <nl> + < < " User - Agent : bitcoin - json - rpc / " < < FormatFullVersion ( ) < < " \ r \ n " <nl> + < < " Host : 127 . 0 . 0 . 1 \ r \ n " <nl> + < < " Content - Type : application / json \ r \ n " <nl> + < < " Content - Length : " < < strMsg . size ( ) < < " \ r \ n " <nl> + < < " Connection : close \ r \ n " <nl> + < < " Accept : application / json \ r \ n " ; <nl> + BOOST_FOREACH ( const PAIRTYPE ( string , string ) & item , mapRequestHeaders ) <nl> + s < < item . first < < " : " < < item . second < < " \ r \ n " ; <nl> + s < < " \ r \ n " < < strMsg ; <nl> + <nl> + return s . str ( ) ; <nl> + } <nl> + <nl> + static string rfc1123Time ( ) <nl> + { <nl> + char buffer [ 64 ] ; <nl> + time_t now ; <nl> + time ( & now ) ; <nl> + struct tm * now_gmt = gmtime ( & now ) ; <nl> + string locale ( setlocale ( LC_TIME , NULL ) ) ; <nl> + setlocale ( LC_TIME , " C " ) ; / / we want POSIX ( aka " C " ) weekday / month strings <nl> + strftime ( buffer , sizeof ( buffer ) , " % a , % d % b % Y % H : % M : % S + 0000 " , now_gmt ) ; <nl> + setlocale ( LC_TIME , locale . c_str ( ) ) ; <nl> + return string ( buffer ) ; <nl> + } <nl> + <nl> + string HTTPReply ( int nStatus , const string & strMsg , bool keepalive ) <nl> + { <nl> + if ( nStatus = = HTTP_UNAUTHORIZED ) <nl> + return strprintf ( " HTTP / 1 . 0 401 Authorization Required \ r \ n " <nl> + " Date : % s \ r \ n " <nl> + " Server : bitcoin - json - rpc / % s \ r \ n " <nl> + " WWW - Authenticate : Basic realm = \ " jsonrpc \ " \ r \ n " <nl> + " Content - Type : text / html \ r \ n " <nl> + " Content - Length : 296 \ r \ n " <nl> + " \ r \ n " <nl> + " < ! DOCTYPE HTML PUBLIC \ " - / / W3C / / DTD HTML 4 . 01 Transitional / / EN \ " \ r \ n " <nl> + " \ " http : / / www . w3 . org / TR / 1999 / REC - html401 - 19991224 / loose . dtd \ " > \ r \ n " <nl> + " < HTML > \ r \ n " <nl> + " < HEAD > \ r \ n " <nl> + " < TITLE > Error < / TITLE > \ r \ n " <nl> + " < META HTTP - EQUIV = ' Content - Type ' CONTENT = ' text / html ; charset = ISO - 8859 - 1 ' > \ r \ n " <nl> + " < / HEAD > \ r \ n " <nl> + " < BODY > < H1 > 401 Unauthorized . < / H1 > < / BODY > \ r \ n " <nl> + " < / HTML > \ r \ n " , rfc1123Time ( ) . c_str ( ) , FormatFullVersion ( ) . c_str ( ) ) ; <nl> + const char * cStatus ; <nl> + if ( nStatus = = HTTP_OK ) cStatus = " OK " ; <nl> + else if ( nStatus = = HTTP_BAD_REQUEST ) cStatus = " Bad Request " ; <nl> + else if ( nStatus = = HTTP_FORBIDDEN ) cStatus = " Forbidden " ; <nl> + else if ( nStatus = = HTTP_NOT_FOUND ) cStatus = " Not Found " ; <nl> + else if ( nStatus = = HTTP_INTERNAL_SERVER_ERROR ) cStatus = " Internal Server Error " ; <nl> + else cStatus = " " ; <nl> + return strprintf ( <nl> + " HTTP / 1 . 1 % d % s \ r \ n " <nl> + " Date : % s \ r \ n " <nl> + " Connection : % s \ r \ n " <nl> + " Content - Length : % " PRIszu " \ r \ n " <nl> + " Content - Type : application / json \ r \ n " <nl> + " Server : bitcoin - json - rpc / % s \ r \ n " <nl> + " \ r \ n " <nl> + " % s " , <nl> + nStatus , <nl> + cStatus , <nl> + rfc1123Time ( ) . c_str ( ) , <nl> + keepalive ? " keep - alive " : " close " , <nl> + strMsg . size ( ) , <nl> + FormatFullVersion ( ) . c_str ( ) , <nl> + strMsg . c_str ( ) ) ; <nl> + } <nl> + <nl> + bool ReadHTTPRequestLine ( std : : basic_istream < char > & stream , int & proto , <nl> + string & http_method , string & http_uri ) <nl> + { <nl> + string str ; <nl> + getline ( stream , str ) ; <nl> + <nl> + / / HTTP request line is space - delimited <nl> + vector < string > vWords ; <nl> + boost : : split ( vWords , str , boost : : is_any_of ( " " ) ) ; <nl> + if ( vWords . size ( ) < 2 ) <nl> + return false ; <nl> + <nl> + / / HTTP methods permitted : GET , POST <nl> + http_method = vWords [ 0 ] ; <nl> + if ( http_method ! = " GET " & & http_method ! = " POST " ) <nl> + return false ; <nl> + <nl> + / / HTTP URI must be an absolute path , relative to current host <nl> + http_uri = vWords [ 1 ] ; <nl> + if ( http_uri . size ( ) = = 0 | | http_uri [ 0 ] ! = ' / ' ) <nl> + return false ; <nl> + <nl> + / / parse proto , if present <nl> + string strProto = " " ; <nl> + if ( vWords . size ( ) > 2 ) <nl> + strProto = vWords [ 2 ] ; <nl> + <nl> + proto = 0 ; <nl> + const char * ver = strstr ( strProto . c_str ( ) , " HTTP / 1 . " ) ; <nl> + if ( ver ! = NULL ) <nl> + proto = atoi ( ver + 7 ) ; <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + int ReadHTTPStatus ( std : : basic_istream < char > & stream , int & proto ) <nl> + { <nl> + string str ; <nl> + getline ( stream , str ) ; <nl> + vector < string > vWords ; <nl> + boost : : split ( vWords , str , boost : : is_any_of ( " " ) ) ; <nl> + if ( vWords . size ( ) < 2 ) <nl> + return HTTP_INTERNAL_SERVER_ERROR ; <nl> + proto = 0 ; <nl> + const char * ver = strstr ( str . c_str ( ) , " HTTP / 1 . " ) ; <nl> + if ( ver ! = NULL ) <nl> + proto = atoi ( ver + 7 ) ; <nl> + return atoi ( vWords [ 1 ] . c_str ( ) ) ; <nl> + } <nl> + <nl> + int ReadHTTPHeaders ( std : : basic_istream < char > & stream , map < string , string > & mapHeadersRet ) <nl> + { <nl> + int nLen = 0 ; <nl> + while ( true ) <nl> + { <nl> + string str ; <nl> + std : : getline ( stream , str ) ; <nl> + if ( str . empty ( ) | | str = = " \ r " ) <nl> + break ; <nl> + string : : size_type nColon = str . find ( " : " ) ; <nl> + if ( nColon ! = string : : npos ) <nl> + { <nl> + string strHeader = str . substr ( 0 , nColon ) ; <nl> + boost : : trim ( strHeader ) ; <nl> + boost : : to_lower ( strHeader ) ; <nl> + string strValue = str . substr ( nColon + 1 ) ; <nl> + boost : : trim ( strValue ) ; <nl> + mapHeadersRet [ strHeader ] = strValue ; <nl> + if ( strHeader = = " content - length " ) <nl> + nLen = atoi ( strValue . c_str ( ) ) ; <nl> + } <nl> + } <nl> + return nLen ; <nl> + } <nl> + <nl> + <nl> + int ReadHTTPMessage ( std : : basic_istream < char > & stream , map < string , <nl> + string > & mapHeadersRet , string & strMessageRet , <nl> + int nProto ) <nl> + { <nl> + mapHeadersRet . clear ( ) ; <nl> + strMessageRet = " " ; <nl> + <nl> + / / Read header <nl> + int nLen = ReadHTTPHeaders ( stream , mapHeadersRet ) ; <nl> + if ( nLen < 0 | | nLen > ( int ) MAX_SIZE ) <nl> + return HTTP_INTERNAL_SERVER_ERROR ; <nl> + <nl> + / / Read message <nl> + if ( nLen > 0 ) <nl> + { <nl> + vector < char > vch ( nLen ) ; <nl> + stream . read ( & vch [ 0 ] , nLen ) ; <nl> + strMessageRet = string ( vch . begin ( ) , vch . end ( ) ) ; <nl> + } <nl> + <nl> + string sConHdr = mapHeadersRet [ " connection " ] ; <nl> + <nl> + if ( ( sConHdr ! = " close " ) & & ( sConHdr ! = " keep - alive " ) ) <nl> + { <nl> + if ( nProto > = 1 ) <nl> + mapHeadersRet [ " connection " ] = " keep - alive " ; <nl> + else <nl> + mapHeadersRet [ " connection " ] = " close " ; <nl> + } <nl> + <nl> + return HTTP_OK ; <nl> + } <nl> + <nl> + / / <nl> + / / JSON - RPC protocol . Bitcoin speaks version 1 . 0 for maximum compatibility , <nl> + / / but uses JSON - RPC 1 . 1 / 2 . 0 standards for parts of the 1 . 0 standard that were <nl> + / / unspecified ( HTTP errors and contents of ' error ' ) . <nl> + / / <nl> + / / 1 . 0 spec : http : / / json - rpc . org / wiki / specification <nl> + / / 1 . 2 spec : http : / / groups . google . com / group / json - rpc / web / json - rpc - over - http <nl> + / / http : / / www . codeproject . com / KB / recipes / JSON_Spirit . aspx <nl> + / / <nl> + <nl> + string JSONRPCRequest ( const string & strMethod , const Array & params , const Value & id ) <nl> + { <nl> + Object request ; <nl> + request . push_back ( Pair ( " method " , strMethod ) ) ; <nl> + request . push_back ( Pair ( " params " , params ) ) ; <nl> + request . push_back ( Pair ( " id " , id ) ) ; <nl> + return write_string ( Value ( request ) , false ) + " \ n " ; <nl> + } <nl> + <nl> + Object JSONRPCReplyObj ( const Value & result , const Value & error , const Value & id ) <nl> + { <nl> + Object reply ; <nl> + if ( error . type ( ) ! = null_type ) <nl> + reply . push_back ( Pair ( " result " , Value : : null ) ) ; <nl> + else <nl> + reply . push_back ( Pair ( " result " , result ) ) ; <nl> + reply . push_back ( Pair ( " error " , error ) ) ; <nl> + reply . push_back ( Pair ( " id " , id ) ) ; <nl> + return reply ; <nl> + } <nl> + <nl> + string JSONRPCReply ( const Value & result , const Value & error , const Value & id ) <nl> + { <nl> + Object reply = JSONRPCReplyObj ( result , error , id ) ; <nl> + return write_string ( Value ( reply ) , false ) + " \ n " ; <nl> + } <nl> + <nl> + Object JSONRPCError ( int code , const string & message ) <nl> + { <nl> + Object error ; <nl> + error . push_back ( Pair ( " code " , code ) ) ; <nl> + error . push_back ( Pair ( " message " , message ) ) ; <nl> + return error ; <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . 6bf371e759a8 <nl> mmm / dev / null <nl> ppp b / src / rpcprotocol . h <nl> <nl> + / / Copyright ( c ) 2010 Satoshi Nakamoto <nl> + / / Copyright ( c ) 2009 - 2013 The Bitcoin developers <nl> + / / Distributed under the MIT / X11 software license , see the accompanying <nl> + / / file COPYING or http : / / www . opensource . org / licenses / mit - license . php . <nl> + <nl> + # ifndef _BITCOINRPC_PROTOCOL_H_ <nl> + # define _BITCOINRPC_PROTOCOL_H_ 1 <nl> + <nl> + # include < list > <nl> + # include < map > <nl> + # include < stdint . h > <nl> + # include < string > <nl> + # include < boost / iostreams / concepts . hpp > <nl> + # include < boost / iostreams / stream . hpp > <nl> + # include < boost / asio . hpp > <nl> + # include < boost / asio / ssl . hpp > <nl> + <nl> + # include " json / json_spirit_reader_template . h " <nl> + # include " json / json_spirit_utils . h " <nl> + # include " json / json_spirit_writer_template . h " <nl> + <nl> + / / HTTP status codes <nl> + enum HTTPStatusCode <nl> + { <nl> + HTTP_OK = 200 , <nl> + HTTP_BAD_REQUEST = 400 , <nl> + HTTP_UNAUTHORIZED = 401 , <nl> + HTTP_FORBIDDEN = 403 , <nl> + HTTP_NOT_FOUND = 404 , <nl> + HTTP_INTERNAL_SERVER_ERROR = 500 , <nl> + } ; <nl> + <nl> + / / Bitcoin RPC error codes <nl> + enum RPCErrorCode <nl> + { <nl> + / / Standard JSON - RPC 2 . 0 errors <nl> + RPC_INVALID_REQUEST = - 32600 , <nl> + RPC_METHOD_NOT_FOUND = - 32601 , <nl> + RPC_INVALID_PARAMS = - 32602 , <nl> + RPC_INTERNAL_ERROR = - 32603 , <nl> + RPC_PARSE_ERROR = - 32700 , <nl> + <nl> + / / General application defined errors <nl> + RPC_MISC_ERROR = - 1 , / / std : : exception thrown in command handling <nl> + RPC_FORBIDDEN_BY_SAFE_MODE = - 2 , / / Server is in safe mode , and command is not allowed in safe mode <nl> + RPC_TYPE_ERROR = - 3 , / / Unexpected type was passed as parameter <nl> + RPC_INVALID_ADDRESS_OR_KEY = - 5 , / / Invalid address or key <nl> + RPC_OUT_OF_MEMORY = - 7 , / / Ran out of memory during operation <nl> + RPC_INVALID_PARAMETER = - 8 , / / Invalid , missing or duplicate parameter <nl> + RPC_DATABASE_ERROR = - 20 , / / Database error <nl> + RPC_DESERIALIZATION_ERROR = - 22 , / / Error parsing or validating structure in raw format <nl> + RPC_SERVER_NOT_STARTED = - 18 , / / RPC server was not started ( StartRPCThreads ( ) not called ) <nl> + <nl> + / / P2P client errors <nl> + RPC_CLIENT_NOT_CONNECTED = - 9 , / / Bitcoin is not connected <nl> + RPC_CLIENT_IN_INITIAL_DOWNLOAD = - 10 , / / Still downloading initial blocks <nl> + RPC_CLIENT_NODE_ALREADY_ADDED = - 23 , / / Node is already added <nl> + RPC_CLIENT_NODE_NOT_ADDED = - 24 , / / Node has not been added before <nl> + <nl> + / / Wallet errors <nl> + RPC_WALLET_ERROR = - 4 , / / Unspecified problem with wallet ( key not found etc . ) <nl> + RPC_WALLET_INSUFFICIENT_FUNDS = - 6 , / / Not enough funds in wallet or account <nl> + RPC_WALLET_INVALID_ACCOUNT_NAME = - 11 , / / Invalid account name <nl> + RPC_WALLET_KEYPOOL_RAN_OUT = - 12 , / / Keypool ran out , call keypoolrefill first <nl> + RPC_WALLET_UNLOCK_NEEDED = - 13 , / / Enter the wallet passphrase with walletpassphrase first <nl> + RPC_WALLET_PASSPHRASE_INCORRECT = - 14 , / / The wallet passphrase entered was incorrect <nl> + RPC_WALLET_WRONG_ENC_STATE = - 15 , / / Command given in wrong wallet encryption state ( encrypting an encrypted wallet etc . ) <nl> + RPC_WALLET_ENCRYPTION_FAILED = - 16 , / / Failed to encrypt the wallet <nl> + RPC_WALLET_ALREADY_UNLOCKED = - 17 , / / Wallet is already unlocked <nl> + } ; <nl> + <nl> + / / <nl> + / / IOStream device that speaks SSL but can also speak non - SSL <nl> + / / <nl> + template < typename Protocol > <nl> + class SSLIOStreamDevice : public boost : : iostreams : : device < boost : : iostreams : : bidirectional > { <nl> + public : <nl> + SSLIOStreamDevice ( boost : : asio : : ssl : : stream < typename Protocol : : socket > & streamIn , bool fUseSSLIn ) : stream ( streamIn ) <nl> + { <nl> + fUseSSL = fUseSSLIn ; <nl> + fNeedHandshake = fUseSSLIn ; <nl> + } <nl> + <nl> + void handshake ( boost : : asio : : ssl : : stream_base : : handshake_type role ) <nl> + { <nl> + if ( ! fNeedHandshake ) return ; <nl> + fNeedHandshake = false ; <nl> + stream . handshake ( role ) ; <nl> + } <nl> + std : : streamsize read ( char * s , std : : streamsize n ) <nl> + { <nl> + handshake ( boost : : asio : : ssl : : stream_base : : server ) ; / / HTTPS servers read first <nl> + if ( fUseSSL ) return stream . read_some ( boost : : asio : : buffer ( s , n ) ) ; <nl> + return stream . next_layer ( ) . read_some ( boost : : asio : : buffer ( s , n ) ) ; <nl> + } <nl> + std : : streamsize write ( const char * s , std : : streamsize n ) <nl> + { <nl> + handshake ( boost : : asio : : ssl : : stream_base : : client ) ; / / HTTPS clients write first <nl> + if ( fUseSSL ) return boost : : asio : : write ( stream , boost : : asio : : buffer ( s , n ) ) ; <nl> + return boost : : asio : : write ( stream . next_layer ( ) , boost : : asio : : buffer ( s , n ) ) ; <nl> + } <nl> + bool connect ( const std : : string & server , const std : : string & port ) <nl> + { <nl> + boost : : asio : : ip : : tcp : : resolver resolver ( stream . get_io_service ( ) ) ; <nl> + boost : : asio : : ip : : tcp : : resolver : : query query ( server . c_str ( ) , port . c_str ( ) ) ; <nl> + boost : : asio : : ip : : tcp : : resolver : : iterator endpoint_iterator = resolver . resolve ( query ) ; <nl> + boost : : asio : : ip : : tcp : : resolver : : iterator end ; <nl> + boost : : system : : error_code error = boost : : asio : : error : : host_not_found ; <nl> + while ( error & & endpoint_iterator ! = end ) <nl> + { <nl> + stream . lowest_layer ( ) . close ( ) ; <nl> + stream . lowest_layer ( ) . connect ( * endpoint_iterator + + , error ) ; <nl> + } <nl> + if ( error ) <nl> + return false ; <nl> + return true ; <nl> + } <nl> + <nl> + private : <nl> + bool fNeedHandshake ; <nl> + bool fUseSSL ; <nl> + boost : : asio : : ssl : : stream < typename Protocol : : socket > & stream ; <nl> + } ; <nl> + <nl> + std : : string HTTPPost ( const std : : string & strMsg , const std : : map < std : : string , std : : string > & mapRequestHeaders ) ; <nl> + std : : string HTTPReply ( int nStatus , const std : : string & strMsg , bool keepalive ) ; <nl> + bool ReadHTTPRequestLine ( std : : basic_istream < char > & stream , int & proto , <nl> + std : : string & http_method , std : : string & http_uri ) ; <nl> + int ReadHTTPStatus ( std : : basic_istream < char > & stream , int & proto ) ; <nl> + int ReadHTTPHeaders ( std : : basic_istream < char > & stream , std : : map < std : : string , std : : string > & mapHeadersRet ) ; <nl> + int ReadHTTPMessage ( std : : basic_istream < char > & stream , std : : map < std : : string , std : : string > & mapHeadersRet , <nl> + std : : string & strMessageRet , int nProto ) ; <nl> + std : : string JSONRPCRequest ( const std : : string & strMethod , const json_spirit : : Array & params , const json_spirit : : Value & id ) ; <nl> + json_spirit : : Object JSONRPCReplyObj ( const json_spirit : : Value & result , const json_spirit : : Value & error , const json_spirit : : Value & id ) ; <nl> + std : : string JSONRPCReply ( const json_spirit : : Value & result , const json_spirit : : Value & error , const json_spirit : : Value & id ) ; <nl> + json_spirit : : Object JSONRPCError ( int code , const std : : string & message ) ; <nl> + <nl> + # endif <nl> mmm a / src / rpcrawtransaction . cpp <nl> ppp b / src / rpcrawtransaction . cpp <nl> <nl> / / Distributed under the MIT / X11 software license , see the accompanying <nl> / / file COPYING or http : / / www . opensource . org / licenses / mit - license . php . <nl> <nl> - <nl> - <nl> # include " base58 . h " <nl> - # include " bitcoinrpc . h " <nl> + # include " rpcserver . h " <nl> # include " init . h " <nl> # include " net . h " <nl> # include " uint256 . h " <nl> similarity index 61 % <nl> rename from src / bitcoinrpc . cpp <nl> rename to src / rpcserver . cpp <nl> mmm a / src / bitcoinrpc . cpp <nl> ppp b / src / rpcserver . cpp <nl> <nl> / / Distributed under the MIT / X11 software license , see the accompanying <nl> / / file COPYING or http : / / www . opensource . org / licenses / mit - license . php . <nl> <nl> - # include " bitcoinrpc . h " <nl> + # include " rpcserver . h " <nl> <nl> # include " base58 . h " <nl> # include " init . h " <nl> static map < string , boost : : shared_ptr < deadline_timer > > deadlineTimers ; <nl> static ssl : : context * rpc_ssl_context = NULL ; <nl> static boost : : thread_group * rpc_worker_group = NULL ; <nl> <nl> - Object JSONRPCError ( int code , const string & message ) <nl> - { <nl> - Object error ; <nl> - error . push_back ( Pair ( " code " , code ) ) ; <nl> - error . push_back ( Pair ( " message " , message ) ) ; <nl> - return error ; <nl> - } <nl> - <nl> void RPCTypeCheck ( const Array & params , <nl> const list < Value_type > & typesExpected , <nl> bool fAllowNull ) <nl> const CRPCCommand * CRPCTable : : operator [ ] ( string name ) const <nl> return ( * it ) . second ; <nl> } <nl> <nl> - / / <nl> - / / HTTP protocol <nl> - / / <nl> - / / This ain ' t Apache . We ' re just using HTTP header for the length field <nl> - / / and to be compatible with other JSON - RPC implementations . <nl> - / / <nl> - <nl> - string HTTPPost ( const string & strMsg , const map < string , string > & mapRequestHeaders ) <nl> - { <nl> - ostringstream s ; <nl> - s < < " POST / HTTP / 1 . 1 \ r \ n " <nl> - < < " User - Agent : bitcoin - json - rpc / " < < FormatFullVersion ( ) < < " \ r \ n " <nl> - < < " Host : 127 . 0 . 0 . 1 \ r \ n " <nl> - < < " Content - Type : application / json \ r \ n " <nl> - < < " Content - Length : " < < strMsg . size ( ) < < " \ r \ n " <nl> - < < " Connection : close \ r \ n " <nl> - < < " Accept : application / json \ r \ n " ; <nl> - BOOST_FOREACH ( const PAIRTYPE ( string , string ) & item , mapRequestHeaders ) <nl> - s < < item . first < < " : " < < item . second < < " \ r \ n " ; <nl> - s < < " \ r \ n " < < strMsg ; <nl> - <nl> - return s . str ( ) ; <nl> - } <nl> - <nl> - string rfc1123Time ( ) <nl> - { <nl> - char buffer [ 64 ] ; <nl> - time_t now ; <nl> - time ( & now ) ; <nl> - struct tm * now_gmt = gmtime ( & now ) ; <nl> - string locale ( setlocale ( LC_TIME , NULL ) ) ; <nl> - setlocale ( LC_TIME , " C " ) ; / / we want POSIX ( aka " C " ) weekday / month strings <nl> - strftime ( buffer , sizeof ( buffer ) , " % a , % d % b % Y % H : % M : % S + 0000 " , now_gmt ) ; <nl> - setlocale ( LC_TIME , locale . c_str ( ) ) ; <nl> - return string ( buffer ) ; <nl> - } <nl> - <nl> - static string HTTPReply ( int nStatus , const string & strMsg , bool keepalive ) <nl> - { <nl> - if ( nStatus = = HTTP_UNAUTHORIZED ) <nl> - return strprintf ( " HTTP / 1 . 0 401 Authorization Required \ r \ n " <nl> - " Date : % s \ r \ n " <nl> - " Server : bitcoin - json - rpc / % s \ r \ n " <nl> - " WWW - Authenticate : Basic realm = \ " jsonrpc \ " \ r \ n " <nl> - " Content - Type : text / html \ r \ n " <nl> - " Content - Length : 296 \ r \ n " <nl> - " \ r \ n " <nl> - " < ! DOCTYPE HTML PUBLIC \ " - / / W3C / / DTD HTML 4 . 01 Transitional / / EN \ " \ r \ n " <nl> - " \ " http : / / www . w3 . org / TR / 1999 / REC - html401 - 19991224 / loose . dtd \ " > \ r \ n " <nl> - " < HTML > \ r \ n " <nl> - " < HEAD > \ r \ n " <nl> - " < TITLE > Error < / TITLE > \ r \ n " <nl> - " < META HTTP - EQUIV = ' Content - Type ' CONTENT = ' text / html ; charset = ISO - 8859 - 1 ' > \ r \ n " <nl> - " < / HEAD > \ r \ n " <nl> - " < BODY > < H1 > 401 Unauthorized . < / H1 > < / BODY > \ r \ n " <nl> - " < / HTML > \ r \ n " , rfc1123Time ( ) . c_str ( ) , FormatFullVersion ( ) . c_str ( ) ) ; <nl> - const char * cStatus ; <nl> - if ( nStatus = = HTTP_OK ) cStatus = " OK " ; <nl> - else if ( nStatus = = HTTP_BAD_REQUEST ) cStatus = " Bad Request " ; <nl> - else if ( nStatus = = HTTP_FORBIDDEN ) cStatus = " Forbidden " ; <nl> - else if ( nStatus = = HTTP_NOT_FOUND ) cStatus = " Not Found " ; <nl> - else if ( nStatus = = HTTP_INTERNAL_SERVER_ERROR ) cStatus = " Internal Server Error " ; <nl> - else cStatus = " " ; <nl> - return strprintf ( <nl> - " HTTP / 1 . 1 % d % s \ r \ n " <nl> - " Date : % s \ r \ n " <nl> - " Connection : % s \ r \ n " <nl> - " Content - Length : % " PRIszu " \ r \ n " <nl> - " Content - Type : application / json \ r \ n " <nl> - " Server : bitcoin - json - rpc / % s \ r \ n " <nl> - " \ r \ n " <nl> - " % s " , <nl> - nStatus , <nl> - cStatus , <nl> - rfc1123Time ( ) . c_str ( ) , <nl> - keepalive ? " keep - alive " : " close " , <nl> - strMsg . size ( ) , <nl> - FormatFullVersion ( ) . c_str ( ) , <nl> - strMsg . c_str ( ) ) ; <nl> - } <nl> - <nl> - bool ReadHTTPRequestLine ( std : : basic_istream < char > & stream , int & proto , <nl> - string & http_method , string & http_uri ) <nl> - { <nl> - string str ; <nl> - getline ( stream , str ) ; <nl> - <nl> - / / HTTP request line is space - delimited <nl> - vector < string > vWords ; <nl> - boost : : split ( vWords , str , boost : : is_any_of ( " " ) ) ; <nl> - if ( vWords . size ( ) < 2 ) <nl> - return false ; <nl> - <nl> - / / HTTP methods permitted : GET , POST <nl> - http_method = vWords [ 0 ] ; <nl> - if ( http_method ! = " GET " & & http_method ! = " POST " ) <nl> - return false ; <nl> - <nl> - / / HTTP URI must be an absolute path , relative to current host <nl> - http_uri = vWords [ 1 ] ; <nl> - if ( http_uri . size ( ) = = 0 | | http_uri [ 0 ] ! = ' / ' ) <nl> - return false ; <nl> - <nl> - / / parse proto , if present <nl> - string strProto = " " ; <nl> - if ( vWords . size ( ) > 2 ) <nl> - strProto = vWords [ 2 ] ; <nl> - <nl> - proto = 0 ; <nl> - const char * ver = strstr ( strProto . c_str ( ) , " HTTP / 1 . " ) ; <nl> - if ( ver ! = NULL ) <nl> - proto = atoi ( ver + 7 ) ; <nl> - <nl> - return true ; <nl> - } <nl> - <nl> - int ReadHTTPStatus ( std : : basic_istream < char > & stream , int & proto ) <nl> - { <nl> - string str ; <nl> - getline ( stream , str ) ; <nl> - vector < string > vWords ; <nl> - boost : : split ( vWords , str , boost : : is_any_of ( " " ) ) ; <nl> - if ( vWords . size ( ) < 2 ) <nl> - return HTTP_INTERNAL_SERVER_ERROR ; <nl> - proto = 0 ; <nl> - const char * ver = strstr ( str . c_str ( ) , " HTTP / 1 . " ) ; <nl> - if ( ver ! = NULL ) <nl> - proto = atoi ( ver + 7 ) ; <nl> - return atoi ( vWords [ 1 ] . c_str ( ) ) ; <nl> - } <nl> - <nl> - int ReadHTTPHeaders ( std : : basic_istream < char > & stream , map < string , string > & mapHeadersRet ) <nl> - { <nl> - int nLen = 0 ; <nl> - while ( true ) <nl> - { <nl> - string str ; <nl> - std : : getline ( stream , str ) ; <nl> - if ( str . empty ( ) | | str = = " \ r " ) <nl> - break ; <nl> - string : : size_type nColon = str . find ( " : " ) ; <nl> - if ( nColon ! = string : : npos ) <nl> - { <nl> - string strHeader = str . substr ( 0 , nColon ) ; <nl> - boost : : trim ( strHeader ) ; <nl> - boost : : to_lower ( strHeader ) ; <nl> - string strValue = str . substr ( nColon + 1 ) ; <nl> - boost : : trim ( strValue ) ; <nl> - mapHeadersRet [ strHeader ] = strValue ; <nl> - if ( strHeader = = " content - length " ) <nl> - nLen = atoi ( strValue . c_str ( ) ) ; <nl> - } <nl> - } <nl> - return nLen ; <nl> - } <nl> - <nl> - int ReadHTTPMessage ( std : : basic_istream < char > & stream , map < string , <nl> - string > & mapHeadersRet , string & strMessageRet , <nl> - int nProto ) <nl> - { <nl> - mapHeadersRet . clear ( ) ; <nl> - strMessageRet = " " ; <nl> - <nl> - / / Read header <nl> - int nLen = ReadHTTPHeaders ( stream , mapHeadersRet ) ; <nl> - if ( nLen < 0 | | nLen > ( int ) MAX_SIZE ) <nl> - return HTTP_INTERNAL_SERVER_ERROR ; <nl> - <nl> - / / Read message <nl> - if ( nLen > 0 ) <nl> - { <nl> - vector < char > vch ( nLen ) ; <nl> - stream . read ( & vch [ 0 ] , nLen ) ; <nl> - strMessageRet = string ( vch . begin ( ) , vch . end ( ) ) ; <nl> - } <nl> - <nl> - string sConHdr = mapHeadersRet [ " connection " ] ; <nl> - <nl> - if ( ( sConHdr ! = " close " ) & & ( sConHdr ! = " keep - alive " ) ) <nl> - { <nl> - if ( nProto > = 1 ) <nl> - mapHeadersRet [ " connection " ] = " keep - alive " ; <nl> - else <nl> - mapHeadersRet [ " connection " ] = " close " ; <nl> - } <nl> - <nl> - return HTTP_OK ; <nl> - } <nl> <nl> bool HTTPAuthorized ( map < string , string > & mapHeaders ) <nl> { <nl> bool HTTPAuthorized ( map < string , string > & mapHeaders ) <nl> return TimingResistantEqual ( strUserPass , strRPCUserColonPass ) ; <nl> } <nl> <nl> - / / <nl> - / / JSON - RPC protocol . Bitcoin speaks version 1 . 0 for maximum compatibility , <nl> - / / but uses JSON - RPC 1 . 1 / 2 . 0 standards for parts of the 1 . 0 standard that were <nl> - / / unspecified ( HTTP errors and contents of ' error ' ) . <nl> - / / <nl> - / / 1 . 0 spec : http : / / json - rpc . org / wiki / specification <nl> - / / 1 . 2 spec : http : / / groups . google . com / group / json - rpc / web / json - rpc - over - http <nl> - / / http : / / www . codeproject . com / KB / recipes / JSON_Spirit . aspx <nl> - / / <nl> - <nl> - string JSONRPCRequest ( const string & strMethod , const Array & params , const Value & id ) <nl> - { <nl> - Object request ; <nl> - request . push_back ( Pair ( " method " , strMethod ) ) ; <nl> - request . push_back ( Pair ( " params " , params ) ) ; <nl> - request . push_back ( Pair ( " id " , id ) ) ; <nl> - return write_string ( Value ( request ) , false ) + " \ n " ; <nl> - } <nl> - <nl> - Object JSONRPCReplyObj ( const Value & result , const Value & error , const Value & id ) <nl> - { <nl> - Object reply ; <nl> - if ( error . type ( ) ! = null_type ) <nl> - reply . push_back ( Pair ( " result " , Value : : null ) ) ; <nl> - else <nl> - reply . push_back ( Pair ( " result " , result ) ) ; <nl> - reply . push_back ( Pair ( " error " , error ) ) ; <nl> - reply . push_back ( Pair ( " id " , id ) ) ; <nl> - return reply ; <nl> - } <nl> - <nl> - string JSONRPCReply ( const Value & result , const Value & error , const Value & id ) <nl> - { <nl> - Object reply = JSONRPCReplyObj ( result , error , id ) ; <nl> - return write_string ( Value ( reply ) , false ) + " \ n " ; <nl> - } <nl> - <nl> void ErrorReply ( std : : ostream & stream , const Object & objError , const Value & id ) <nl> { <nl> / / Send error reply from json - rpc error object <nl> bool ClientAllowed ( const boost : : asio : : ip : : address & address ) <nl> return false ; <nl> } <nl> <nl> - / / <nl> - / / IOStream device that speaks SSL but can also speak non - SSL <nl> - / / <nl> - template < typename Protocol > <nl> - class SSLIOStreamDevice : public iostreams : : device < iostreams : : bidirectional > { <nl> - public : <nl> - SSLIOStreamDevice ( asio : : ssl : : stream < typename Protocol : : socket > & streamIn , bool fUseSSLIn ) : stream ( streamIn ) <nl> - { <nl> - fUseSSL = fUseSSLIn ; <nl> - fNeedHandshake = fUseSSLIn ; <nl> - } <nl> - <nl> - void handshake ( ssl : : stream_base : : handshake_type role ) <nl> - { <nl> - if ( ! fNeedHandshake ) return ; <nl> - fNeedHandshake = false ; <nl> - stream . handshake ( role ) ; <nl> - } <nl> - std : : streamsize read ( char * s , std : : streamsize n ) <nl> - { <nl> - handshake ( ssl : : stream_base : : server ) ; / / HTTPS servers read first <nl> - if ( fUseSSL ) return stream . read_some ( asio : : buffer ( s , n ) ) ; <nl> - return stream . next_layer ( ) . read_some ( asio : : buffer ( s , n ) ) ; <nl> - } <nl> - std : : streamsize write ( const char * s , std : : streamsize n ) <nl> - { <nl> - handshake ( ssl : : stream_base : : client ) ; / / HTTPS clients write first <nl> - if ( fUseSSL ) return asio : : write ( stream , asio : : buffer ( s , n ) ) ; <nl> - return asio : : write ( stream . next_layer ( ) , asio : : buffer ( s , n ) ) ; <nl> - } <nl> - bool connect ( const std : : string & server , const std : : string & port ) <nl> - { <nl> - ip : : tcp : : resolver resolver ( stream . get_io_service ( ) ) ; <nl> - ip : : tcp : : resolver : : query query ( server . c_str ( ) , port . c_str ( ) ) ; <nl> - ip : : tcp : : resolver : : iterator endpoint_iterator = resolver . resolve ( query ) ; <nl> - ip : : tcp : : resolver : : iterator end ; <nl> - boost : : system : : error_code error = asio : : error : : host_not_found ; <nl> - while ( error & & endpoint_iterator ! = end ) <nl> - { <nl> - stream . lowest_layer ( ) . close ( ) ; <nl> - stream . lowest_layer ( ) . connect ( * endpoint_iterator + + , error ) ; <nl> - } <nl> - if ( error ) <nl> - return false ; <nl> - return true ; <nl> - } <nl> - <nl> - private : <nl> - bool fNeedHandshake ; <nl> - bool fUseSSL ; <nl> - asio : : ssl : : stream < typename Protocol : : socket > & stream ; <nl> - } ; <nl> - <nl> class AcceptedConnection <nl> { <nl> public : <nl> static void RPCListen ( boost : : shared_ptr < basic_socket_acceptor < Protocol , SocketA <nl> boost : : asio : : placeholders : : error ) ) ; <nl> } <nl> <nl> + <nl> / * * <nl> * Accept and handle incoming connection . <nl> * / <nl> void RPCRunLater ( const std : : string & name , boost : : function < void ( void ) > func , int6 <nl> deadlineTimers [ name ] - > async_wait ( boost : : bind ( RPCRunHandler , _1 , func ) ) ; <nl> } <nl> <nl> - <nl> class JSONRequest <nl> { <nl> public : <nl> void JSONRequest : : parse ( const Value & valRequest ) <nl> throw JSONRPCError ( RPC_INVALID_REQUEST , " Params must be an array " ) ; <nl> } <nl> <nl> + <nl> static Object JSONRPCExecOne ( const Value & req ) <nl> { <nl> Object rpc_result ; <nl> json_spirit : : Value CRPCTable : : execute ( const std : : string & strMethod , const json_s <nl> } <nl> } <nl> <nl> - <nl> - Object CallRPC ( const string & strMethod , const Array & params ) <nl> - { <nl> - if ( mapArgs [ " - rpcuser " ] = = " " & & mapArgs [ " - rpcpassword " ] = = " " ) <nl> - throw runtime_error ( strprintf ( <nl> - _ ( " You must set rpcpassword = < password > in the configuration file : \ n % s \ n " <nl> - " If the file does not exist , create it with owner - readable - only file permissions . " ) , <nl> - GetConfigFile ( ) . string ( ) . c_str ( ) ) ) ; <nl> - <nl> - / / Connect to localhost <nl> - bool fUseSSL = GetBoolArg ( " - rpcssl " , false ) ; <nl> - asio : : io_service io_service ; <nl> - ssl : : context context ( io_service , ssl : : context : : sslv23 ) ; <nl> - context . set_options ( ssl : : context : : no_sslv2 ) ; <nl> - asio : : ssl : : stream < asio : : ip : : tcp : : socket > sslStream ( io_service , context ) ; <nl> - SSLIOStreamDevice < asio : : ip : : tcp > d ( sslStream , fUseSSL ) ; <nl> - iostreams : : stream < SSLIOStreamDevice < asio : : ip : : tcp > > stream ( d ) ; <nl> - <nl> - bool fWait = GetBoolArg ( " - rpcwait " , false ) ; / / - rpcwait means try until server has started <nl> - do { <nl> - bool fConnected = d . connect ( GetArg ( " - rpcconnect " , " 127 . 0 . 0 . 1 " ) , GetArg ( " - rpcport " , itostr ( Params ( ) . RPCPort ( ) ) ) ) ; <nl> - if ( fConnected ) break ; <nl> - if ( fWait ) <nl> - MilliSleep ( 1000 ) ; <nl> - else <nl> - throw runtime_error ( " couldn ' t connect to server " ) ; <nl> - } while ( fWait ) ; <nl> - <nl> - / / HTTP basic authentication <nl> - string strUserPass64 = EncodeBase64 ( mapArgs [ " - rpcuser " ] + " : " + mapArgs [ " - rpcpassword " ] ) ; <nl> - map < string , string > mapRequestHeaders ; <nl> - mapRequestHeaders [ " Authorization " ] = string ( " Basic " ) + strUserPass64 ; <nl> - <nl> - / / Send request <nl> - string strRequest = JSONRPCRequest ( strMethod , params , 1 ) ; <nl> - string strPost = HTTPPost ( strRequest , mapRequestHeaders ) ; <nl> - stream < < strPost < < std : : flush ; <nl> - <nl> - / / Receive HTTP reply status <nl> - int nProto = 0 ; <nl> - int nStatus = ReadHTTPStatus ( stream , nProto ) ; <nl> - <nl> - / / Receive HTTP reply message headers and body <nl> - map < string , string > mapHeaders ; <nl> - string strReply ; <nl> - ReadHTTPMessage ( stream , mapHeaders , strReply , nProto ) ; <nl> - <nl> - if ( nStatus = = HTTP_UNAUTHORIZED ) <nl> - throw runtime_error ( " incorrect rpcuser or rpcpassword ( authorization failed ) " ) ; <nl> - else if ( nStatus > = 400 & & nStatus ! = HTTP_BAD_REQUEST & & nStatus ! = HTTP_NOT_FOUND & & nStatus ! = HTTP_INTERNAL_SERVER_ERROR ) <nl> - throw runtime_error ( strprintf ( " server returned HTTP error % d " , nStatus ) ) ; <nl> - else if ( strReply . empty ( ) ) <nl> - throw runtime_error ( " no response from server " ) ; <nl> - <nl> - / / Parse reply <nl> - Value valReply ; <nl> - if ( ! read_string ( strReply , valReply ) ) <nl> - throw runtime_error ( " couldn ' t parse reply from server " ) ; <nl> - const Object & reply = valReply . get_obj ( ) ; <nl> - if ( reply . empty ( ) ) <nl> - throw runtime_error ( " expected reply to have result , error and id properties " ) ; <nl> - <nl> - return reply ; <nl> - } <nl> - <nl> - <nl> - <nl> - <nl> - template < typename T > <nl> - void ConvertTo ( Value & value , bool fAllowNull = false ) <nl> - { <nl> - if ( fAllowNull & & value . type ( ) = = null_type ) <nl> - return ; <nl> - if ( value . type ( ) = = str_type ) <nl> - { <nl> - / / reinterpret string as unquoted json value <nl> - Value value2 ; <nl> - string strJSON = value . get_str ( ) ; <nl> - if ( ! read_string ( strJSON , value2 ) ) <nl> - throw runtime_error ( string ( " Error parsing JSON : " ) + strJSON ) ; <nl> - ConvertTo < T > ( value2 , fAllowNull ) ; <nl> - value = value2 ; <nl> - } <nl> - else <nl> - { <nl> - value = value . get_value < T > ( ) ; <nl> - } <nl> - } <nl> - <nl> - / / Convert strings to command - specific RPC representation <nl> - Array RPCConvertValues ( const std : : string & strMethod , const std : : vector < std : : string > & strParams ) <nl> - { <nl> - Array params ; <nl> - BOOST_FOREACH ( const std : : string & param , strParams ) <nl> - params . push_back ( param ) ; <nl> - <nl> - int n = params . size ( ) ; <nl> - <nl> - / / <nl> - / / Special case non - string parameter types <nl> - / / <nl> - if ( strMethod = = " stop " & & n > 0 ) ConvertTo < bool > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " getaddednodeinfo " & & n > 0 ) ConvertTo < bool > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " setgenerate " & & n > 0 ) ConvertTo < bool > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " setgenerate " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " getnetworkhashps " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " getnetworkhashps " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " sendtoaddress " & & n > 1 ) ConvertTo < double > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " settxfee " & & n > 0 ) ConvertTo < double > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " getreceivedbyaddress " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " getreceivedbyaccount " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " listreceivedbyaddress " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " listreceivedbyaddress " & & n > 1 ) ConvertTo < bool > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " listreceivedbyaccount " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " listreceivedbyaccount " & & n > 1 ) ConvertTo < bool > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " getbalance " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " getblockhash " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " move " & & n > 2 ) ConvertTo < double > ( params [ 2 ] ) ; <nl> - if ( strMethod = = " move " & & n > 3 ) ConvertTo < boost : : int64_t > ( params [ 3 ] ) ; <nl> - if ( strMethod = = " sendfrom " & & n > 2 ) ConvertTo < double > ( params [ 2 ] ) ; <nl> - if ( strMethod = = " sendfrom " & & n > 3 ) ConvertTo < boost : : int64_t > ( params [ 3 ] ) ; <nl> - if ( strMethod = = " listtransactions " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " listtransactions " & & n > 2 ) ConvertTo < boost : : int64_t > ( params [ 2 ] ) ; <nl> - if ( strMethod = = " listaccounts " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " walletpassphrase " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " getblocktemplate " & & n > 0 ) ConvertTo < Object > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " listsinceblock " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " sendmany " & & n > 1 ) ConvertTo < Object > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " sendmany " & & n > 2 ) ConvertTo < boost : : int64_t > ( params [ 2 ] ) ; <nl> - if ( strMethod = = " addmultisigaddress " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " addmultisigaddress " & & n > 1 ) ConvertTo < Array > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " createmultisig " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " createmultisig " & & n > 1 ) ConvertTo < Array > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " listunspent " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " listunspent " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " listunspent " & & n > 2 ) ConvertTo < Array > ( params [ 2 ] ) ; <nl> - if ( strMethod = = " getblock " & & n > 1 ) ConvertTo < bool > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " getrawtransaction " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " createrawtransaction " & & n > 0 ) ConvertTo < Array > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " createrawtransaction " & & n > 1 ) ConvertTo < Object > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " signrawtransaction " & & n > 1 ) ConvertTo < Array > ( params [ 1 ] , true ) ; <nl> - if ( strMethod = = " signrawtransaction " & & n > 2 ) ConvertTo < Array > ( params [ 2 ] , true ) ; <nl> - if ( strMethod = = " sendrawtransaction " & & n > 1 ) ConvertTo < bool > ( params [ 1 ] , true ) ; <nl> - if ( strMethod = = " gettxout " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " gettxout " & & n > 2 ) ConvertTo < bool > ( params [ 2 ] ) ; <nl> - if ( strMethod = = " lockunspent " & & n > 0 ) ConvertTo < bool > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " lockunspent " & & n > 1 ) ConvertTo < Array > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " importprivkey " & & n > 2 ) ConvertTo < bool > ( params [ 2 ] ) ; <nl> - if ( strMethod = = " verifychain " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> - if ( strMethod = = " verifychain " & & n > 1 ) ConvertTo < boost : : int64_t > ( params [ 1 ] ) ; <nl> - if ( strMethod = = " keypoolrefill " & & n > 0 ) ConvertTo < boost : : int64_t > ( params [ 0 ] ) ; <nl> - <nl> - return params ; <nl> - } <nl> - <nl> - int CommandLineRPC ( int argc , char * argv [ ] ) <nl> - { <nl> - string strPrint ; <nl> - int nRet = 0 ; <nl> - try <nl> - { <nl> - / / Skip switches <nl> - while ( argc > 1 & & IsSwitchChar ( argv [ 1 ] [ 0 ] ) ) <nl> - { <nl> - argc - - ; <nl> - argv + + ; <nl> - } <nl> - <nl> - / / Method <nl> - if ( argc < 2 ) <nl> - throw runtime_error ( " too few parameters " ) ; <nl> - string strMethod = argv [ 1 ] ; <nl> - <nl> - / / Parameters default to strings <nl> - std : : vector < std : : string > strParams ( & argv [ 2 ] , & argv [ argc ] ) ; <nl> - Array params = RPCConvertValues ( strMethod , strParams ) ; <nl> - <nl> - / / Execute <nl> - Object reply = CallRPC ( strMethod , params ) ; <nl> - <nl> - / / Parse reply <nl> - const Value & result = find_value ( reply , " result " ) ; <nl> - const Value & error = find_value ( reply , " error " ) ; <nl> - <nl> - if ( error . type ( ) ! = null_type ) <nl> - { <nl> - / / Error <nl> - strPrint = " error : " + write_string ( error , false ) ; <nl> - int code = find_value ( error . get_obj ( ) , " code " ) . get_int ( ) ; <nl> - nRet = abs ( code ) ; <nl> - } <nl> - else <nl> - { <nl> - / / Result <nl> - if ( result . type ( ) = = null_type ) <nl> - strPrint = " " ; <nl> - else if ( result . type ( ) = = str_type ) <nl> - strPrint = result . get_str ( ) ; <nl> - else <nl> - strPrint = write_string ( result , true ) ; <nl> - } <nl> - } <nl> - catch ( boost : : thread_interrupted ) { <nl> - throw ; <nl> - } <nl> - catch ( std : : exception & e ) { <nl> - strPrint = string ( " error : " ) + e . what ( ) ; <nl> - nRet = 87 ; <nl> - } <nl> - catch ( . . . ) { <nl> - PrintException ( NULL , " CommandLineRPC ( ) " ) ; <nl> - } <nl> - <nl> - if ( strPrint ! = " " ) <nl> - { <nl> - fprintf ( ( nRet = = 0 ? stdout : stderr ) , " % s \ n " , strPrint . c_str ( ) ) ; <nl> - } <nl> - return nRet ; <nl> - } <nl> - <nl> - <nl> - <nl> - <nl> - # ifdef TEST <nl> - int main ( int argc , char * argv [ ] ) <nl> - { <nl> - # ifdef _MSC_VER <nl> - / / Turn off Microsoft heap dump noise <nl> - _CrtSetReportMode ( _CRT_WARN , _CRTDBG_MODE_FILE ) ; <nl> - _CrtSetReportFile ( _CRT_WARN , CreateFile ( " NUL " , GENERIC_WRITE , 0 , NULL , OPEN_EXISTING , 0 , 0 ) ) ; <nl> - # endif <nl> - setbuf ( stdin , NULL ) ; <nl> - setbuf ( stdout , NULL ) ; <nl> - setbuf ( stderr , NULL ) ; <nl> - <nl> - try <nl> - { <nl> - if ( argc > = 2 & & string ( argv [ 1 ] ) = = " - server " ) <nl> - { <nl> - LogPrintf ( " server ready \ n " ) ; <nl> - ThreadRPCServer ( NULL ) ; <nl> - } <nl> - else <nl> - { <nl> - return CommandLineRPC ( argc , argv ) ; <nl> - } <nl> - } <nl> - catch ( boost : : thread_interrupted ) { <nl> - throw ; <nl> - } <nl> - catch ( std : : exception & e ) { <nl> - PrintException ( & e , " main ( ) " ) ; <nl> - } catch ( . . . ) { <nl> - PrintException ( NULL , " main ( ) " ) ; <nl> - } <nl> - return 0 ; <nl> - } <nl> - # endif <nl> - <nl> const CRPCTable tableRPC ; <nl> similarity index 76 % <nl> rename from src / bitcoinrpc . h <nl> rename to src / rpcserver . h <nl> mmm a / src / bitcoinrpc . h <nl> ppp b / src / rpcserver . h <nl> <nl> / / Distributed under the MIT / X11 software license , see the accompanying <nl> / / file COPYING or http : / / www . opensource . org / licenses / mit - license . php . <nl> <nl> - # ifndef _BITCOINRPC_H_ <nl> - # define _BITCOINRPC_H_ 1 <nl> + # ifndef _BITCOINRPC_SERVER_H_ <nl> + # define _BITCOINRPC_SERVER_H_ 1 <nl> <nl> # include " uint256 . h " <nl> + # include " rpcprotocol . h " <nl> <nl> # include < list > <nl> # include < map > <nl> <nl> # include " json / json_spirit_writer_template . h " <nl> <nl> class CBlockIndex ; <nl> - class CReserveKey ; <nl> - <nl> - / / HTTP status codes <nl> - enum HTTPStatusCode <nl> - { <nl> - HTTP_OK = 200 , <nl> - HTTP_BAD_REQUEST = 400 , <nl> - HTTP_UNAUTHORIZED = 401 , <nl> - HTTP_FORBIDDEN = 403 , <nl> - HTTP_NOT_FOUND = 404 , <nl> - HTTP_INTERNAL_SERVER_ERROR = 500 , <nl> - } ; <nl> - <nl> - / / Bitcoin RPC error codes <nl> - enum RPCErrorCode <nl> - { <nl> - / / Standard JSON - RPC 2 . 0 errors <nl> - RPC_INVALID_REQUEST = - 32600 , <nl> - RPC_METHOD_NOT_FOUND = - 32601 , <nl> - RPC_INVALID_PARAMS = - 32602 , <nl> - RPC_INTERNAL_ERROR = - 32603 , <nl> - RPC_PARSE_ERROR = - 32700 , <nl> - <nl> - / / General application defined errors <nl> - RPC_MISC_ERROR = - 1 , / / std : : exception thrown in command handling <nl> - RPC_FORBIDDEN_BY_SAFE_MODE = - 2 , / / Server is in safe mode , and command is not allowed in safe mode <nl> - RPC_TYPE_ERROR = - 3 , / / Unexpected type was passed as parameter <nl> - RPC_INVALID_ADDRESS_OR_KEY = - 5 , / / Invalid address or key <nl> - RPC_OUT_OF_MEMORY = - 7 , / / Ran out of memory during operation <nl> - RPC_INVALID_PARAMETER = - 8 , / / Invalid , missing or duplicate parameter <nl> - RPC_DATABASE_ERROR = - 20 , / / Database error <nl> - RPC_DESERIALIZATION_ERROR = - 22 , / / Error parsing or validating structure in raw format <nl> - RPC_SERVER_NOT_STARTED = - 18 , / / RPC server was not started ( StartRPCThreads ( ) not called ) <nl> - <nl> - / / P2P client errors <nl> - RPC_CLIENT_NOT_CONNECTED = - 9 , / / Bitcoin is not connected <nl> - RPC_CLIENT_IN_INITIAL_DOWNLOAD = - 10 , / / Still downloading initial blocks <nl> - RPC_CLIENT_NODE_ALREADY_ADDED = - 23 , / / Node is already added <nl> - RPC_CLIENT_NODE_NOT_ADDED = - 24 , / / Node has not been added before <nl> - <nl> - / / Wallet errors <nl> - RPC_WALLET_ERROR = - 4 , / / Unspecified problem with wallet ( key not found etc . ) <nl> - RPC_WALLET_INSUFFICIENT_FUNDS = - 6 , / / Not enough funds in wallet or account <nl> - RPC_WALLET_INVALID_ACCOUNT_NAME = - 11 , / / Invalid account name <nl> - RPC_WALLET_KEYPOOL_RAN_OUT = - 12 , / / Keypool ran out , call keypoolrefill first <nl> - RPC_WALLET_UNLOCK_NEEDED = - 13 , / / Enter the wallet passphrase with walletpassphrase first <nl> - RPC_WALLET_PASSPHRASE_INCORRECT = - 14 , / / The wallet passphrase entered was incorrect <nl> - RPC_WALLET_WRONG_ENC_STATE = - 15 , / / Command given in wrong wallet encryption state ( encrypting an encrypted wallet etc . ) <nl> - RPC_WALLET_ENCRYPTION_FAILED = - 16 , / / Failed to encrypt the wallet <nl> - RPC_WALLET_ALREADY_UNLOCKED = - 17 , / / Wallet is already unlocked <nl> - } ; <nl> - <nl> - json_spirit : : Object JSONRPCError ( int code , const std : : string & message ) ; <nl> <nl> void StartRPCThreads ( ) ; <nl> void StopRPCThreads ( ) ; <nl> - int CommandLineRPC ( int argc , char * argv [ ] ) ; <nl> - <nl> - / * * Convert parameter values for RPC call from strings to command - specific JSON objects . * / <nl> - json_spirit : : Array RPCConvertValues ( const std : : string & strMethod , const std : : vector < std : : string > & strParams ) ; <nl> <nl> / * <nl> Type - check arguments ; throws JSONRPCError if wrong type given . Does not check that <nl> mmm a / src / rpcwallet . cpp <nl> ppp b / src / rpcwallet . cpp <nl> <nl> / / Distributed under the MIT / X11 software license , see the accompanying <nl> / / file COPYING or http : / / www . opensource . org / licenses / mit - license . php . <nl> <nl> - <nl> - <nl> # include " base58 . h " <nl> - # include " bitcoinrpc . h " <nl> + # include " rpcserver . h " <nl> # include " init . h " <nl> # include " net . h " <nl> # include " netbase . h " <nl> mmm a / src / test / rpc_tests . cpp <nl> ppp b / src / test / rpc_tests . cpp <nl> <nl> - # include " bitcoinrpc . h " <nl> + # include " rpcserver . h " <nl> + # include " rpcclient . h " <nl> <nl> # include " base58 . h " <nl> <nl> | Split up bitcoinrpc ( code movement only ) | bitcoin/bitcoin | fb78cc23784b2fa478324aac35ca76c7cfe683a4 | 2013-11-27T05:00:29Z |
mmm a / config / openalpr . conf <nl> ppp b / config / openalpr . conf <nl> detection_strictness = 3 <nl> max_detection_input_width = 1280 <nl> max_detection_input_height = 720 <nl> <nl> - multithreading_cores = 1 <nl> - <nl> <nl> <nl> max_plate_angle_degrees = 15 <nl> mmm a / src / openalpr / alpr_impl . cpp <nl> ppp b / src / openalpr / alpr_impl . cpp <nl> AlprFullDetails AlprImpl : : recognizeFullDetails ( cv : : Mat img , std : : vector < cv : : Rect <nl> / / Find all the candidate regions <nl> response . plateRegions = plateDetector - > detect ( img , regionsOfInterest ) ; <nl> <nl> - / / Get the number of threads specified and make sure the value is sane ( cannot be greater than CPU cores or less than 1 ) <nl> - uint numThreads = config - > multithreading_cores ; <nl> - if ( numThreads > tthread : : thread : : hardware_concurrency ( ) ) <nl> - numThreads = tthread : : thread : : hardware_concurrency ( ) ; <nl> - if ( numThreads < = 0 ) <nl> - numThreads = 1 ; <nl> + queue < PlateRegion > plateQueue ; <nl> + for ( uint i = 0 ; i < response . plateRegions . size ( ) ; i + + ) <nl> + plateQueue . push ( response . plateRegions [ i ] ) ; <nl> + <nl> + while ( ! plateQueue . empty ( ) ) <nl> + { <nl> + PlateRegion plateRegion = plateQueue . front ( ) ; <nl> + plateQueue . pop ( ) ; <nl> + <nl> + PipelineData pipeline_data ( img , plateRegion . rect , config ) ; <nl> + <nl> + timespec platestarttime ; <nl> + getTime ( & platestarttime ) ; <nl> + <nl> + LicensePlateCandidate lp ( & pipeline_data ) ; <nl> + <nl> + lp . recognize ( ) ; <nl> + <nl> + bool plateDetected = false ; <nl> + if ( pipeline_data . plate_area_confidence > 10 ) <nl> + { <nl> + AlprResult plateResult ; <nl> + plateResult . region = defaultRegion ; <nl> + plateResult . regionConfidence = 0 ; <nl> + <nl> + for ( int pointidx = 0 ; pointidx < 4 ; pointidx + + ) <nl> + { <nl> + plateResult . plate_points [ pointidx ] . x = ( int ) pipeline_data . plate_corners [ pointidx ] . x ; <nl> + plateResult . plate_points [ pointidx ] . y = ( int ) pipeline_data . plate_corners [ pointidx ] . y ; <nl> + } <nl> + <nl> + if ( detectRegion ) <nl> + { <nl> + char statecode [ 4 ] ; <nl> + plateResult . regionConfidence = stateIdentifier - > recognize ( & pipeline_data ) ; <nl> + if ( plateResult . regionConfidence > 0 ) <nl> + { <nl> + plateResult . region = statecode ; <nl> + } <nl> + } <nl> + <nl> + <nl> + <nl> + ocr - > performOCR ( & pipeline_data ) ; <nl> + ocr - > postProcessor - > analyze ( plateResult . region , topN ) ; <nl> + const vector < PPResult > ppResults = ocr - > postProcessor - > getResults ( ) ; <nl> + <nl> + <nl> + int bestPlateIndex = 0 ; <nl> + <nl> + for ( uint pp = 0 ; pp < ppResults . size ( ) ; pp + + ) <nl> + { <nl> + if ( pp > = topN ) <nl> + break ; <nl> <nl> + / / Set our " best plate " match to either the first entry , or the first entry with a postprocessor template match <nl> + if ( bestPlateIndex = = 0 & & ppResults [ pp ] . matchesTemplate ) <nl> + bestPlateIndex = pp ; <nl> <nl> - PlateDispatcher dispatcher ( response . plateRegions , & img , <nl> - config , stateIdentifier , ocr , <nl> - topN , detectRegion , defaultRegion ) ; <nl> + if ( ppResults [ pp ] . letters . size ( ) > = config - > postProcessMinCharacters & & <nl> + ppResults [ pp ] . letters . size ( ) < = config - > postProcessMaxCharacters ) <nl> + { <nl> + AlprPlate aplate ; <nl> + aplate . characters = ppResults [ pp ] . letters ; <nl> + aplate . overall_confidence = ppResults [ pp ] . totalscore ; <nl> + aplate . matches_template = ppResults [ pp ] . matchesTemplate ; <nl> + plateResult . topNPlates . push_back ( aplate ) ; <nl> + } <nl> + } <nl> + plateResult . result_count = plateResult . topNPlates . size ( ) ; <nl> + <nl> + if ( plateResult . topNPlates . size ( ) > 0 ) <nl> + plateResult . bestPlate = plateResult . topNPlates [ bestPlateIndex ] ; <nl> + <nl> + timespec plateEndTime ; <nl> + getTime ( & plateEndTime ) ; <nl> + plateResult . processing_time_ms = diffclock ( platestarttime , plateEndTime ) ; <nl> + <nl> + if ( plateResult . result_count > 0 ) <nl> + { <nl> + plateDetected = true ; <nl> + response . results . push_back ( plateResult ) ; <nl> + } <nl> + } <nl> <nl> - / / Spawn n threads to process all of the candidate regions and recognize <nl> - list < tthread : : thread * > threads ; <nl> - for ( uint i = 0 ; i < numThreads ; i + + ) <nl> - { <nl> - tthread : : thread * t = new tthread : : thread ( plateAnalysisThread , ( void * ) & dispatcher ) ; <nl> - threads . push_back ( t ) ; <nl> - } <nl> + if ( ! plateDetected ) <nl> + { <nl> + / / Not a valid plate <nl> + / / Check if this plate has any children , if so , send them back up for processing <nl> + for ( uint childidx = 0 ; childidx < plateRegion . children . size ( ) ; childidx + + ) <nl> + { <nl> + plateQueue . push ( plateRegion . children [ childidx ] ) ; <nl> + } <nl> + } <nl> <nl> - / / Wait for all threads to finish <nl> - for ( list < tthread : : thread * > : : iterator i = threads . begin ( ) ; i ! = threads . end ( ) ; + + i ) <nl> - { <nl> - tthread : : thread * t = * i ; <nl> - t - > join ( ) ; <nl> - delete t ; <nl> + <nl> + <nl> + <nl> } <nl> <nl> + <nl> if ( config - > debugTiming ) <nl> { <nl> timespec endTime ; <nl> AlprFullDetails AlprImpl : : recognizeFullDetails ( cv : : Mat img , std : : vector < cv : : Rect <nl> rectangle ( img , response . plateRegions [ i ] . rect , Scalar ( 0 , 0 , 255 ) , 2 ) ; <nl> } <nl> <nl> - for ( uint i = 0 ; i < dispatcher . getRecognitionResults ( ) . size ( ) ; i + + ) <nl> + for ( uint i = 0 ; i < response . results . size ( ) ; i + + ) <nl> { <nl> for ( int z = 0 ; z < 4 ; z + + ) <nl> { <nl> - AlprCoordinate * coords = dispatcher . getRecognitionResults ( ) [ i ] . plate_points ; <nl> + AlprCoordinate * coords = response . results [ i ] . plate_points ; <nl> Point p1 ( coords [ z ] . x , coords [ z ] . y ) ; <nl> Point p2 ( coords [ ( z + 1 ) % 4 ] . x , coords [ ( z + 1 ) % 4 ] . y ) ; <nl> line ( img , p1 , p2 , Scalar ( 255 , 0 , 255 ) , 2 ) ; <nl> AlprFullDetails AlprImpl : : recognizeFullDetails ( cv : : Mat img , std : : vector < cv : : Rect <nl> } <nl> <nl> <nl> - response . results = dispatcher . getRecognitionResults ( ) ; <nl> - <nl> if ( config - > debugPauseOnFrame ) <nl> { <nl> / / Pause indefinitely until they press a key <nl> std : : vector < AlprResult > AlprImpl : : recognize ( cv : : Mat img , std : : vector < cv : : Rect > r <nl> AlprFullDetails fullDetails = recognizeFullDetails ( img , regionsOfInterest ) ; <nl> return fullDetails . results ; <nl> } <nl> - void plateAnalysisThread ( void * arg ) <nl> - { <nl> - PlateDispatcher * dispatcher = ( PlateDispatcher * ) arg ; <nl> - <nl> - if ( dispatcher - > config - > debugGeneral ) <nl> - cout < < " Thread : " < < tthread : : this_thread : : get_id ( ) < < " Initialized " < < endl ; <nl> - <nl> - int loop_count = 0 ; <nl> - while ( true ) <nl> - { <nl> - PlateRegion plateRegion ; <nl> - if ( dispatcher - > nextPlate ( & plateRegion ) = = false ) <nl> - break ; <nl> - <nl> - if ( dispatcher - > config - > debugGeneral ) <nl> - cout < < " Thread : " < < tthread : : this_thread : : get_id ( ) < < " loop " < < + + loop_count < < endl ; <nl> - <nl> - PipelineData pipeline_data ( dispatcher - > getImageCopy ( ) , plateRegion . rect , dispatcher - > config ) ; <nl> - <nl> - timespec platestarttime ; <nl> - getTime ( & platestarttime ) ; <nl> - <nl> - LicensePlateCandidate lp ( & pipeline_data ) ; <nl> - <nl> - lp . recognize ( ) ; <nl> - <nl> - <nl> - if ( pipeline_data . plate_area_confidence < = 10 ) <nl> - { <nl> - / / Not a valid plate <nl> - / / Check if this plate has any children , if so , send them back up to the dispatcher for processing <nl> - for ( uint childidx = 0 ; childidx < plateRegion . children . size ( ) ; childidx + + ) <nl> - { <nl> - dispatcher - > appendPlate ( plateRegion . children [ childidx ] ) ; <nl> - } <nl> - } <nl> - else <nl> - { <nl> - AlprResult plateResult ; <nl> - plateResult . region = dispatcher - > defaultRegion ; <nl> - plateResult . regionConfidence = 0 ; <nl> - <nl> - for ( int pointidx = 0 ; pointidx < 4 ; pointidx + + ) <nl> - { <nl> - plateResult . plate_points [ pointidx ] . x = ( int ) pipeline_data . plate_corners [ pointidx ] . x ; <nl> - plateResult . plate_points [ pointidx ] . y = ( int ) pipeline_data . plate_corners [ pointidx ] . y ; <nl> - } <nl> - <nl> - if ( dispatcher - > detectRegion ) <nl> - { <nl> - char statecode [ 4 ] ; <nl> - plateResult . regionConfidence = dispatcher - > stateIdentifier - > recognize ( & pipeline_data ) ; <nl> - if ( plateResult . regionConfidence > 0 ) <nl> - { <nl> - plateResult . region = statecode ; <nl> - } <nl> - } <nl> - <nl> - <nl> - / / Tesseract OCR does not appear to be threadsafe <nl> - dispatcher - > ocrMutex . lock ( ) ; <nl> - dispatcher - > ocr - > performOCR ( & pipeline_data ) ; <nl> - dispatcher - > ocr - > postProcessor - > analyze ( plateResult . region , dispatcher - > topN ) ; <nl> - const vector < PPResult > ppResults = dispatcher - > ocr - > postProcessor - > getResults ( ) ; <nl> - dispatcher - > ocrMutex . unlock ( ) ; <nl> - <nl> - int bestPlateIndex = 0 ; <nl> - <nl> - for ( uint pp = 0 ; pp < ppResults . size ( ) ; pp + + ) <nl> - { <nl> - if ( pp > = dispatcher - > topN ) <nl> - break ; <nl> - <nl> - / / Set our " best plate " match to either the first entry , or the first entry with a postprocessor template match <nl> - if ( bestPlateIndex = = 0 & & ppResults [ pp ] . matchesTemplate ) <nl> - bestPlateIndex = pp ; <nl> - <nl> - if ( ppResults [ pp ] . letters . size ( ) > = dispatcher - > config - > postProcessMinCharacters & & <nl> - ppResults [ pp ] . letters . size ( ) < = dispatcher - > config - > postProcessMaxCharacters ) <nl> - { <nl> - AlprPlate aplate ; <nl> - aplate . characters = ppResults [ pp ] . letters ; <nl> - aplate . overall_confidence = ppResults [ pp ] . totalscore ; <nl> - aplate . matches_template = ppResults [ pp ] . matchesTemplate ; <nl> - plateResult . topNPlates . push_back ( aplate ) ; <nl> - } <nl> - } <nl> - plateResult . result_count = plateResult . topNPlates . size ( ) ; <nl> - <nl> - if ( plateResult . topNPlates . size ( ) > 0 ) <nl> - plateResult . bestPlate = plateResult . topNPlates [ bestPlateIndex ] ; <nl> - <nl> - timespec plateEndTime ; <nl> - getTime ( & plateEndTime ) ; <nl> - plateResult . processing_time_ms = diffclock ( platestarttime , plateEndTime ) ; <nl> - <nl> - if ( plateResult . result_count > 0 ) <nl> - { <nl> - / / Synchronized section <nl> - dispatcher - > addResult ( plateResult ) ; <nl> - <nl> - } <nl> - <nl> - } <nl> - <nl> - <nl> - <nl> - if ( dispatcher - > config - > debugTiming ) <nl> - { <nl> - timespec plateEndTime ; <nl> - getTime ( & plateEndTime ) ; <nl> - cout < < " Thread : " < < tthread : : this_thread : : get_id ( ) < < " Finished loop " < < loop_count < < " in " < < diffclock ( platestarttime , plateEndTime ) < < " ms . " < < endl ; <nl> - } <nl> - <nl> - <nl> - } <nl> <nl> - if ( dispatcher - > config - > debugGeneral ) <nl> - cout < < " Thread : " < < tthread : : this_thread : : get_id ( ) < < " Complete " < < endl ; <nl> - } <nl> <nl> std : : vector < cv : : Rect > AlprImpl : : convertRects ( std : : vector < AlprRegionOfInterest > regionsOfInterest ) <nl> { <nl> mmm a / src / openalpr / alpr_impl . h <nl> ppp b / src / openalpr / alpr_impl . h <nl> <nl> <nl> # include < list > <nl> # include < sstream > <nl> + # include < vector > <nl> + # include < queue > <nl> <nl> # include " alpr . h " <nl> # include " config . h " <nl> <nl> <nl> # include < opencv2 / core / core . hpp > <nl> <nl> - <nl> - # include " support / tinythread . h " <nl> # include " support / platform . h " <nl> <nl> # define DEFAULT_TOPN 25 <nl> class AlprImpl <nl> cJSON * createJsonObj ( const AlprResult * result ) ; <nl> } ; <nl> <nl> - class PlateDispatcher <nl> - { <nl> - public : <nl> - PlateDispatcher ( std : : vector < PlateRegion > plateRegions , cv : : Mat * image , <nl> - Config * config , <nl> - StateIdentifier * stateIdentifier , <nl> - OCR * ocr , <nl> - int topN , bool detectRegion , std : : string defaultRegion ) <nl> - { <nl> - this - > plateRegions = plateRegions ; <nl> - this - > frame = image ; <nl> - <nl> - this - > config = config ; <nl> - this - > stateIdentifier = stateIdentifier ; <nl> - this - > ocr = ocr ; <nl> - this - > topN = topN ; <nl> - this - > detectRegion = detectRegion ; <nl> - this - > defaultRegion = defaultRegion ; <nl> - } <nl> - <nl> - cv : : Mat getImageCopy ( ) <nl> - { <nl> - tthread : : lock_guard < tthread : : mutex > guard ( mMutex ) ; <nl> - <nl> - cv : : Mat img ( this - > frame - > size ( ) , this - > frame - > type ( ) ) ; <nl> - this - > frame - > copyTo ( img ) ; <nl> - <nl> - return img ; <nl> - } <nl> <nl> - <nl> - bool nextPlate ( PlateRegion * plateRegion ) <nl> - { <nl> - tthread : : lock_guard < tthread : : mutex > guard ( mMutex ) ; <nl> - <nl> - if ( plateRegions . size ( ) = = 0 ) <nl> - return false ; <nl> - <nl> - * plateRegion = plateRegions [ plateRegions . size ( ) - 1 ] ; <nl> - plateRegions . pop_back ( ) ; <nl> - <nl> - return true ; <nl> - } <nl> - <nl> - void appendPlate ( PlateRegion plate ) <nl> - { <nl> - tthread : : lock_guard < tthread : : mutex > guard ( mMutex ) ; <nl> - <nl> - plateRegions . push_back ( plate ) ; <nl> - } <nl> - <nl> - void addResult ( AlprResult recognitionResult ) <nl> - { <nl> - tthread : : lock_guard < tthread : : mutex > guard ( mMutex ) ; <nl> - recognitionResults . push_back ( recognitionResult ) ; <nl> - } <nl> - <nl> - std : : vector < AlprResult > getRecognitionResults ( ) <nl> - { <nl> - return recognitionResults ; <nl> - } <nl> - <nl> - StateIdentifier * stateIdentifier ; <nl> - OCR * ocr ; <nl> - Config * config ; <nl> - <nl> - uint topN ; <nl> - bool detectRegion ; <nl> - std : : string defaultRegion ; <nl> - <nl> - tthread : : mutex ocrMutex ; <nl> - <nl> - private : <nl> - <nl> - tthread : : mutex mMutex ; <nl> - <nl> - cv : : Mat * frame ; <nl> - std : : vector < PlateRegion > plateRegions ; <nl> - std : : vector < AlprResult > recognitionResults ; <nl> - <nl> - } ; <nl> <nl> # endif / / OPENALPR_ALPRIMPL_H <nl> \ No newline at end of file <nl> mmm a / src / openalpr / config . cpp <nl> ppp b / src / openalpr / config . cpp <nl> void Config : : loadValues ( string country ) <nl> <nl> runtimeBaseDir = getString ( " common " , " runtime_dir " , " / usr / share / openalpr / runtime_data " ) ; <nl> <nl> - multithreading_cores = getInt ( " common " , " multithreading_cores " , 1 ) ; <nl> - <nl> detection_iteration_increase = getFloat ( " common " , " detection_iteration_increase " , 1 . 1 ) ; <nl> detectionStrictness = getInt ( " common " , " detection_strictness " , 3 ) ; <nl> maxPlateWidthPercent = getFloat ( " common " , " max_plate_width_percent " , 100 ) ; <nl> mmm a / src / openalpr / config . h <nl> ppp b / src / openalpr / config . h <nl> class Config <nl> <nl> std : : string country ; <nl> <nl> - int multithreading_cores ; <nl> - <nl> float detection_iteration_increase ; <nl> int detectionStrictness ; <nl> float maxPlateWidthPercent ; <nl> | Removed ( non - working ) multithreading implementation . Going to reimplement it differently . | openalpr/openalpr | 01b00b04502a2a5a54e463b92cf63d176e0a59a4 | 2014-08-31T15:31:58Z |
mmm a / s / d_state . cpp <nl> ppp b / s / d_state . cpp <nl> namespace mongo { <nl> BSONObj d = cursor - > next ( ) ; <nl> <nl> if ( min . isEmpty ( ) ) { <nl> - min = d [ " min " ] . Obj ( ) ; <nl> - max = d [ " max " ] . Obj ( ) ; <nl> + min = d [ " min " ] . Obj ( ) . getOwned ( ) ; <nl> + max = d [ " max " ] . Obj ( ) . getOwned ( ) ; <nl> continue ; <nl> } <nl> <nl> if ( max = = d [ " min " ] . Obj ( ) ) { <nl> - max = d [ " max " ] . Obj ( ) ; <nl> + max = d [ " max " ] . Obj ( ) . getOwned ( ) ; <nl> continue ; <nl> } <nl> <nl> p - > gotRange ( min . getOwned ( ) , max . getOwned ( ) ) ; <nl> - min = d [ " min " ] . Obj ( ) ; <nl> - max = d [ " max " ] . Obj ( ) ; <nl> + min = d [ " min " ] . Obj ( ) . getOwned ( ) ; <nl> + max = d [ " max " ] . Obj ( ) . getOwned ( ) ; <nl> } <nl> assert ( ! min . isEmpty ( ) ) ; <nl> p - > gotRange ( min . getOwned ( ) , max . getOwned ( ) ) ; <nl> | getOwned ( ) on all cursor objects | mongodb/mongo | 18132e81cb12c2b5b90bd556a4f16e233a74e0c9 | 2010-07-27T16:48:11Z |
mmm a / plugins / state_history_plugin / state_history_plugin . cpp <nl> ppp b / plugins / state_history_plugin / state_history_plugin . cpp <nl> struct state_history_plugin_impl : std : : enable_shared_from_this < state_history_pl <nl> socket_stream - > next_layer ( ) . set_option ( boost : : asio : : ip : : tcp : : no_delay ( true ) ) ; <nl> socket_stream - > next_layer ( ) . set_option ( boost : : asio : : socket_base : : send_buffer_size ( 1024 * 1024 ) ) ; <nl> socket_stream - > next_layer ( ) . set_option ( boost : : asio : : socket_base : : receive_buffer_size ( 1024 * 1024 ) ) ; <nl> - socket_stream - > async_accept ( [ self = shared_from_this ( ) , this ] ( boost : : system : : error_code ec ) { <nl> - callback ( ec , " async_accept " , [ & ] { <nl> - start_read ( ) ; <nl> - send ( state_history_plugin_abi ) ; <nl> + socket_stream - > async_accept ( [ self = shared_from_this ( ) ] ( boost : : system : : error_code ec ) { <nl> + self - > callback ( ec , " async_accept " , [ self ] { <nl> + self - > start_read ( ) ; <nl> + self - > send ( state_history_plugin_abi ) ; <nl> } ) ; <nl> } ) ; <nl> } <nl> struct state_history_plugin_impl : std : : enable_shared_from_this < state_history_pl <nl> void start_read ( ) { <nl> auto in_buffer = std : : make_shared < boost : : beast : : flat_buffer > ( ) ; <nl> socket_stream - > async_read ( <nl> - * in_buffer , [ self = shared_from_this ( ) , this , in_buffer ] ( boost : : system : : error_code ec , size_t ) { <nl> - callback ( ec , " async_read " , [ & ] { <nl> + * in_buffer , [ self = shared_from_this ( ) , in_buffer ] ( boost : : system : : error_code ec , size_t ) { <nl> + self - > callback ( ec , " async_read " , [ self , in_buffer ] { <nl> auto d = boost : : asio : : buffer_cast < char const * > ( boost : : beast : : buffers_front ( in_buffer - > data ( ) ) ) ; <nl> auto s = boost : : asio : : buffer_size ( in_buffer - > data ( ) ) ; <nl> fc : : datastream < const char * > ds ( d , s ) ; <nl> state_request req ; <nl> fc : : raw : : unpack ( ds , req ) ; <nl> - req . visit ( * this ) ; <nl> - start_read ( ) ; <nl> + req . visit ( * self ) ; <nl> + self - > start_read ( ) ; <nl> } ) ; <nl> } ) ; <nl> } <nl> struct state_history_plugin_impl : std : : enable_shared_from_this < state_history_pl <nl> sent_abi = true ; <nl> socket_stream - > async_write ( / / <nl> boost : : asio : : buffer ( send_queue [ 0 ] ) , <nl> - [ self = shared_from_this ( ) , this ] ( boost : : system : : error_code ec , size_t ) { <nl> - callback ( ec , " async_write " , [ & ] { <nl> - send_queue . erase ( send_queue . begin ( ) ) ; <nl> - sending = false ; <nl> - send ( ) ; <nl> + [ self = shared_from_this ( ) ] ( boost : : system : : error_code ec , size_t ) { <nl> + self - > callback ( ec , " async_write " , [ self ] { <nl> + self - > send_queue . erase ( self - > send_queue . begin ( ) ) ; <nl> + self - > sending = false ; <nl> + self - > send ( ) ; <nl> } ) ; <nl> } ) ; <nl> } <nl> struct state_history_plugin_impl : std : : enable_shared_from_this < state_history_pl <nl> <nl> template < typename F > <nl> void callback ( boost : : system : : error_code ec , const char * what , F f ) { <nl> - if ( plugin - > stopping ) <nl> - return ; <nl> - if ( ec ) <nl> - return on_fail ( ec , what ) ; <nl> - catch_and_close ( f ) ; <nl> + app ( ) . post ( priority : : medium , [ = ] ( ) { <nl> + if ( plugin - > stopping ) <nl> + return ; <nl> + if ( ec ) <nl> + return on_fail ( ec , what ) ; <nl> + catch_and_close ( f ) ; <nl> + } ) ; <nl> } <nl> <nl> void on_fail ( boost : : system : : error_code ec , const char * what ) { <nl> | Merge pull request from EOSIO / ship - priority - 1 . 8 | EOSIO/eos | 3d9b6510b5437b9290d0226b24dbe244e9de65e5 | 2019-11-04T22:28:02Z |
mmm a / tools / system - analyzer / stats - panel . mjs <nl> ppp b / tools / system - analyzer / stats - panel . mjs <nl> defineCustomElement ( ' stats - panel ' , ( templateText ) = > <nl> return this . timeline_ ; <nl> } <nl> <nl> - set timeline ( value ) { <nl> - this . timeline_ = value ; <nl> - } <nl> - <nl> - get timeline ( ) { <nl> - return this . timeline_ ; <nl> - } <nl> - <nl> update ( ) { <nl> this . removeAllChildren ( this . stats ) ; <nl> this . updateGeneralStats ( ) ; <nl> | [ tools ] [ system - analyzer ] Delete Stats Panel duplicated getter / setter | v8/v8 | 86a19a69bb18d69c2481cb95e915aa7267c6039c | 2020-07-16T13:58:15Z |
mmm a / docs / 03_keosd / 15_plugins / wallet_api_plugin / index . md <nl> ppp b / docs / 03_keosd / 15_plugins / wallet_api_plugin / index . md <nl> <nl> The ` wallet_api_plugin ` exposes functionality from the [ ` wallet_plugin ` ] ( . . / wallet_plugin / index . md ) to the RPC API interface managed by the [ ` http_plugin ` ] ( . . / http_plugin / index . md ) . <nl> <nl> [ [ caution | Caution ] ] <nl> - | This plugin exposes wallets and so running this plugin on a publicly accessible node is not recommended . As of 1 . 2 . 0 , ` nodeos ` will no longer allow the ` wallet_api_plugin ` . <nl> + | This plugin exposes wallets . Therefore , running this plugin on a publicly accessible node is not recommended . As of 1 . 2 . 0 , ` nodeos ` will no longer allow the ` wallet_api_plugin ` . <nl> <nl> # # Usage <nl> <nl> mmm a / docs / 03_keosd / 15_plugins / wallet_plugin / index . md <nl> ppp b / docs / 03_keosd / 15_plugins / wallet_plugin / index . md <nl> <nl> The ` wallet_plugin ` adds access to wallet functionality from a node . <nl> <nl> [ [ caution | Caution ] ] <nl> - | This plugin is not designed to be loaded as a plugin on a publicly accessible node without further security measures . This is also particularly true when loading the ` wallet_api_plugin ` , which should not be loaded on a publicly accessible node under any conditions . <nl> + | This plugin is not designed to be loaded as a plugin on a publicly accessible node without further security measures . This is particularly true when loading the ` wallet_api_plugin ` , which should not be loaded on a publicly accessible node under any circumstances . <nl> <nl> # # Usage <nl> <nl> | minor edits on keosd wallet plugins | EOSIO/eos | a509151a903825b5a5c4eebc11854f5a19e58469 | 2019-12-09T17:28:39Z |
mmm a / modules / map / pnc_map / pnc_map . cc <nl> ppp b / modules / map / pnc_map / pnc_map . cc <nl> bool PncMap : : PassageToSegments ( routing : : Passage passage , <nl> } <nl> segments - > emplace_back ( lane_ptr , lane . start_s ( ) , lane . end_s ( ) ) ; <nl> } <nl> - return true ; <nl> + return ! segments - > empty ( ) ; <nl> } <nl> <nl> bool RouteSegments : : IsOnSegment ( ) const { return is_on_segment_ ; } <nl> std : : vector < int > PncMap : : GetNeighborPassages ( const routing : : RoadSegment & road , <nl> return result ; <nl> } <nl> RouteSegments source_segments ; <nl> - DCHECK ( PassageToSegments ( source_passage , & source_segments ) ) <nl> - < < " failed to convert passage to segments " ; <nl> + if ( ! PassageToSegments ( source_passage , & source_segments ) ) { <nl> + AERROR < < " failed to convert passage to segments " ; <nl> + return result ; <nl> + } <nl> std : : unordered_set < std : : string > neighbor_lanes ; <nl> if ( source_passage . change_lane_type ( ) = = routing : : LEFT ) { <nl> for ( const auto & segment : source_segments ) { <nl> bool PncMap : : GetRouteSegments ( <nl> for ( const int index : drive_passages ) { <nl> const auto & passage = road . passage ( index ) ; <nl> RouteSegments segments ; <nl> - DCHECK ( PassageToSegments ( passage , & segments ) ) <nl> - < < " Failed to convert passage to lane segments . " ; <nl> + if ( ! PassageToSegments ( passage , & segments ) ) { <nl> + ADEBUG < < " Failed to convert passage to lane segments . " ; <nl> + continue ; <nl> + } <nl> double s = 0 . 0 ; <nl> double l = 0 . 0 ; <nl> auto nearest_point = point ; <nl> | pnc_map : remove DCHECK that did not execute code in opt build | ApolloAuto/apollo | 8f99c1bac12a30f9e4d61ae792b13e1b0808127e | 2017-10-25T22:37:35Z |
mmm a / tests / test_core . py <nl> ppp b / tests / test_core . py <nl> def test_double_i64_conversion ( self ) : <nl> self . do_run_from_file ( src , output ) <nl> <nl> def test_float32_precise ( self ) : <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> + <nl> Settings . PRECISE_F32 = 1 <nl> <nl> test_path = path_from_root ( ' tests ' , ' core ' , ' test_float32_precise ' ) <nl> def test_regex ( self ) : <nl> self . do_run_from_file ( src , output ) <nl> <nl> def test_longjmp ( self ) : <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> + <nl> test_path = path_from_root ( ' tests ' , ' core ' , ' test_longjmp ' ) <nl> src , output = ( test_path + s for s in ( ' . in ' , ' . out ' ) ) <nl> <nl> self . do_run_from_file ( src , output ) <nl> <nl> def test_longjmp2 ( self ) : <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> + <nl> test_path = path_from_root ( ' tests ' , ' core ' , ' test_longjmp2 ' ) <nl> src , output = ( test_path + s for s in ( ' . in ' , ' . out ' ) ) <nl> <nl> self . do_run_from_file ( src , output ) <nl> <nl> def test_longjmp3 ( self ) : <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> + <nl> test_path = path_from_root ( ' tests ' , ' core ' , ' test_longjmp3 ' ) <nl> src , output = ( test_path + s for s in ( ' . in ' , ' . out ' ) ) <nl> <nl> self . do_run_from_file ( src , output ) <nl> <nl> def test_longjmp4 ( self ) : <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> + <nl> test_path = path_from_root ( ' tests ' , ' core ' , ' test_longjmp4 ' ) <nl> src , output = ( test_path + s for s in ( ' . in ' , ' . out ' ) ) <nl> <nl> self . do_run_from_file ( src , output ) <nl> <nl> def test_longjmp_funcptr ( self ) : <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> + <nl> test_path = path_from_root ( ' tests ' , ' core ' , ' test_longjmp_funcptr ' ) <nl> src , output = ( test_path + s for s in ( ' . in ' , ' . out ' ) ) <nl> <nl> self . do_run_from_file ( src , output ) <nl> <nl> def test_longjmp_repeat ( self ) : <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> + <nl> Settings . MAX_SETJMPS = 1 <nl> <nl> test_path = path_from_root ( ' tests ' , ' core ' , ' test_longjmp_repeat ' ) <nl> def test_longjmp_repeat ( self ) : <nl> self . do_run_from_file ( src , output ) <nl> <nl> def test_longjmp_stacked ( self ) : <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> + <nl> test_path = path_from_root ( ' tests ' , ' core ' , ' test_longjmp_stacked ' ) <nl> src , output = ( test_path + s for s in ( ' . in ' , ' . out ' ) ) <nl> <nl> def test_longjmp_stacked ( self ) : <nl> <nl> <nl> def test_longjmp_exc ( self ) : <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> + <nl> test_path = path_from_root ( ' tests ' , ' core ' , ' test_longjmp_exc ' ) <nl> src , output = ( test_path + s for s in ( ' . in ' , ' . out ' ) ) <nl> <nl> self . do_run_from_file ( src , output ) <nl> <nl> def test_setjmp_many ( self ) : <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> + <nl> src = r ' ' ' <nl> # include < stdio . h > <nl> # include < setjmp . h > <nl> def test_setjmp_many ( self ) : <nl> def test_exceptions ( self ) : <nl> if Settings . QUANTUM_SIZE = = 1 : return self . skip ( " we don ' t support libcxx in q1 " ) <nl> if self . emcc_args is None : return self . skip ( ' need emcc to add in libcxx properly ' ) <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> <nl> Settings . EXCEPTION_DEBUG = 1 <nl> <nl> class MyException <nl> <nl> def test_exception_2 ( self ) : <nl> if self . emcc_args is None : return self . skip ( ' need emcc to add in libcxx properly ' ) <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> Settings . DISABLE_EXCEPTION_CATCHING = 0 <nl> <nl> test_path = path_from_root ( ' tests ' , ' core ' , ' test_exception_2 ' ) <nl> def test_emscripten_get_now ( self ) : <nl> <nl> def test_inlinejs ( self ) : <nl> if not self . is_le32 ( ) : return self . skip ( ' le32 needed for inline js ' ) <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> <nl> test_path = path_from_root ( ' tests ' , ' core ' , ' test_inlinejs ' ) <nl> src , output = ( test_path + s for s in ( ' . in ' , ' . out ' ) ) <nl> def test_inlinejs ( self ) : <nl> <nl> def test_inlinejs2 ( self ) : <nl> if not self . is_le32 ( ) : return self . skip ( ' le32 needed for inline js ' ) <nl> + if os . environ . get ( ' EMCC_FAST_COMPILER ' ) = = ' 1 ' : return self . skip ( ' todo in fastcomp ' ) <nl> <nl> test_path = path_from_root ( ' tests ' , ' core ' , ' test_inlinejs2 ' ) <nl> src , output = ( test_path + s for s in ( ' . in ' , ' . out ' ) ) <nl> | disable various tests in fastcomp | emscripten-core/emscripten | a41250b4e5c75fac33f96cd449f672360e4685bb | 2013-12-14T19:02:07Z |
mmm a / src / layer / arm / convolution_arm . cpp <nl> ppp b / src / layer / arm / convolution_arm . cpp <nl> <nl> # if __ARM_NEON <nl> # include < arm_neon . h > <nl> # include " neon_mathfun . h " <nl> + # if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> + # include " neon_mathfun_fp16s . h " <nl> + # endif <nl> # endif / / __ARM_NEON <nl> <nl> # include " neon_activation . h " <nl> mmm a / src / layer / arm / convolutiondepthwise_arm . cpp <nl> ppp b / src / layer / arm / convolutiondepthwise_arm . cpp <nl> <nl> # if __ARM_NEON <nl> # include < arm_neon . h > <nl> # include " neon_mathfun . h " <nl> + # if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> + # include " neon_mathfun_fp16s . h " <nl> + # endif <nl> # endif / / __ARM_NEON <nl> <nl> # include " neon_activation . h " <nl> mmm a / src / layer / arm / deconvolution_arm . cpp <nl> ppp b / src / layer / arm / deconvolution_arm . cpp <nl> <nl> # if __ARM_NEON <nl> # include < arm_neon . h > <nl> # include " neon_mathfun . h " <nl> + # if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> + # include " neon_mathfun_fp16s . h " <nl> + # endif <nl> # endif / / __ARM_NEON <nl> <nl> # include " neon_activation . h " <nl> mmm a / src / layer / arm / deconvolutiondepthwise_arm . cpp <nl> ppp b / src / layer / arm / deconvolutiondepthwise_arm . cpp <nl> <nl> # if __ARM_NEON <nl> # include < arm_neon . h > <nl> # include " neon_mathfun . h " <nl> + # if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> + # include " neon_mathfun_fp16s . h " <nl> + # endif <nl> # endif / / __ARM_NEON <nl> <nl> # include " neon_activation . h " <nl> mmm a / src / layer / arm / innerproduct_arm . cpp <nl> ppp b / src / layer / arm / innerproduct_arm . cpp <nl> <nl> # if __ARM_NEON <nl> # include < arm_neon . h > <nl> # include " neon_mathfun . h " <nl> + # if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> + # include " neon_mathfun_fp16s . h " <nl> + # endif <nl> # endif / / __ARM_NEON <nl> # include " cpu . h " <nl> # include " neon_activation . h " <nl> mmm a / src / layer / arm / lstm_arm . cpp <nl> ppp b / src / layer / arm / lstm_arm . cpp <nl> <nl> # include < math . h > <nl> <nl> # if __ARM_NEON <nl> + # include < arm_neon . h > <nl> # include " neon_mathfun . h " <nl> + # if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> + # include " neon_mathfun_fp16s . h " <nl> + # endif <nl> # include " neon_activation . h " <nl> # endif / / __ARM_NEON <nl> <nl> mmm a / src / layer / arm / neon_activation . h <nl> ppp b / src / layer / arm / neon_activation . h <nl> static inline float32x4_t activation_ps ( float32x4_t _v , int activation_type , con <nl> # if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> static inline __fp16 activation_ss ( __fp16 v , int activation_type , const ncnn : : Mat & activation_params ) <nl> { <nl> - float v32 = v ; <nl> - v32 = activation_ss ( v32 , activation_type , activation_params ) ; <nl> - return ( __fp16 ) v32 ; <nl> + if ( activation_type = = 1 ) <nl> + { <nl> + v = std : : max ( v , ( __fp16 ) 0 . f ) ; <nl> + } <nl> + else if ( activation_type = = 2 ) <nl> + { <nl> + __fp16 slope = ( __fp16 ) ( activation_params [ 0 ] ) ; <nl> + v = v > 0 . f ? v : v * slope ; <nl> + } <nl> + else if ( activation_type = = 3 ) <nl> + { <nl> + __fp16 min = ( __fp16 ) ( activation_params [ 0 ] ) ; <nl> + __fp16 max = ( __fp16 ) ( activation_params [ 1 ] ) ; <nl> + if ( v < min ) <nl> + v = min ; <nl> + if ( v > max ) <nl> + v = max ; <nl> + } <nl> + else if ( activation_type = = 4 ) <nl> + { <nl> + v = ( __fp16 ) 1 . f / ( ( __fp16 ) 1 . f + exp ( - v ) ) ; <nl> + } <nl> + else if ( activation_type = = 5 ) <nl> + { <nl> + v = v * tanh ( log ( exp ( v ) + ( __fp16 ) 1 . f ) ) ; <nl> + } <nl> + <nl> + return v ; <nl> } <nl> <nl> static inline float16x4_t activation_ps ( float16x4_t _v , int activation_type , const ncnn : : Mat & activation_params ) <nl> { <nl> - float32x4_t _v32 = vcvt_f32_f16 ( _v ) ; <nl> - _v32 = activation_ps ( _v32 , activation_type , activation_params ) ; <nl> - return vcvt_f16_f32 ( _v32 ) ; <nl> + if ( activation_type = = 1 ) <nl> + { <nl> + float16x4_t _zero = vdup_n_f16 ( 0 . f ) ; <nl> + _v = vmax_f16 ( _v , _zero ) ; <nl> + } <nl> + else if ( activation_type = = 2 ) <nl> + { <nl> + float16x4_t _zero = vdup_n_f16 ( 0 . f ) ; <nl> + float16x4_t _slope = vdup_n_f16 ( ( __fp16 ) activation_params [ 0 ] ) ; <nl> + uint16x4_t _lemask = vcle_f16 ( _v , _zero ) ; <nl> + float16x4_t _ps = vmul_f16 ( _v , _slope ) ; <nl> + _v = vbsl_f16 ( _lemask , _ps , _v ) ; <nl> + } <nl> + else if ( activation_type = = 3 ) <nl> + { <nl> + float16x4_t _min = vdup_n_f16 ( ( __fp16 ) activation_params [ 0 ] ) ; <nl> + float16x4_t _max = vdup_n_f16 ( ( __fp16 ) activation_params [ 1 ] ) ; <nl> + _v = vmax_f16 ( _v , _min ) ; <nl> + _v = vmin_f16 ( _v , _max ) ; <nl> + } <nl> + else if ( activation_type = = 4 ) <nl> + { <nl> + _v = sigmoid_ps ( _v ) ; <nl> + } <nl> + else if ( activation_type = = 5 ) <nl> + { <nl> + float32x4_t _v32 = vcvt_f32_f16 ( _v ) ; <nl> + _v32 = vmulq_f32 ( _v32 , tanh_ps ( log_ps ( vaddq_f32 ( exp_ps ( _v32 ) , vdupq_n_f32 ( 1 . f ) ) ) ) ) ; <nl> + _v = vcvt_f16_f32 ( _v32 ) ; <nl> + } <nl> + <nl> + return _v ; <nl> } <nl> <nl> static inline float16x8_t activation_ps ( float16x8_t _v , int activation_type , const ncnn : : Mat & activation_params ) <nl> { <nl> - float32x4_t _v32_low = vcvt_f32_f16 ( vget_low_f16 ( _v ) ) ; <nl> - float32x4_t _v32_high = vcvt_f32_f16 ( vget_high_f16 ( _v ) ) ; <nl> - _v32_low = activation_ps ( _v32_low , activation_type , activation_params ) ; <nl> - _v32_high = activation_ps ( _v32_high , activation_type , activation_params ) ; <nl> - return vcombine_f16 ( vcvt_f16_f32 ( _v32_low ) , vcvt_f16_f32 ( _v32_high ) ) ; <nl> + if ( activation_type = = 1 ) <nl> + { <nl> + float16x8_t _zero = vdupq_n_f16 ( 0 . f ) ; <nl> + _v = vmaxq_f16 ( _v , _zero ) ; <nl> + } <nl> + else if ( activation_type = = 2 ) <nl> + { <nl> + float16x8_t _zero = vdupq_n_f16 ( 0 . f ) ; <nl> + float16x8_t _slope = vdupq_n_f16 ( ( __fp16 ) activation_params [ 0 ] ) ; <nl> + uint16x8_t _lemask = vcleq_f16 ( _v , _zero ) ; <nl> + float16x8_t _ps = vmulq_f16 ( _v , _slope ) ; <nl> + _v = vbslq_f16 ( _lemask , _ps , _v ) ; <nl> + } <nl> + else if ( activation_type = = 3 ) <nl> + { <nl> + float16x8_t _min = vdupq_n_f16 ( ( __fp16 ) activation_params [ 0 ] ) ; <nl> + float16x8_t _max = vdupq_n_f16 ( ( __fp16 ) activation_params [ 1 ] ) ; <nl> + _v = vmaxq_f16 ( _v , _min ) ; <nl> + _v = vminq_f16 ( _v , _max ) ; <nl> + } <nl> + else if ( activation_type = = 4 ) <nl> + { <nl> + _v = sigmoid_ps ( _v ) ; <nl> + } <nl> + else if ( activation_type = = 5 ) <nl> + { <nl> + float32x4_t _v32_low = vcvt_f32_f16 ( vget_low_f16 ( _v ) ) ; <nl> + float32x4_t _v32_high = vcvt_f32_f16 ( vget_high_f16 ( _v ) ) ; <nl> + _v32_low = vmulq_f32 ( _v32_low , tanh_ps ( log_ps ( vaddq_f32 ( exp_ps ( _v32_low ) , vdupq_n_f32 ( 1 . f ) ) ) ) ) ; <nl> + _v32_high = vmulq_f32 ( _v32_high , tanh_ps ( log_ps ( vaddq_f32 ( exp_ps ( _v32_high ) , vdupq_n_f32 ( 1 . f ) ) ) ) ) ; <nl> + _v = vcombine_f16 ( vcvt_f16_f32 ( _v32_low ) , vcvt_f16_f32 ( _v32_high ) ) ; <nl> + } <nl> + <nl> + return _v ; <nl> } <nl> # endif / / __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> # endif / / __ARM_NEON <nl> new file mode 100644 <nl> index 0000000000 . . dfc72a849e <nl> mmm / dev / null <nl> ppp b / src / layer / arm / neon_mathfun_fp16s . h <nl> <nl> + / / Tencent is pleased to support the open source community by making ncnn available . <nl> + / / <nl> + / / Copyright ( C ) 2020 THL A29 Limited , a Tencent company . All rights reserved . <nl> + / / <nl> + / / Licensed under the BSD 3 - Clause License ( the " License " ) ; you may not use this file except <nl> + / / in compliance with the License . You may obtain a copy of the License at <nl> + / / <nl> + / / https : / / opensource . org / licenses / BSD - 3 - Clause <nl> + / / <nl> + / / Unless required by applicable law or agreed to in writing , software distributed <nl> + / / under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR <nl> + / / CONDITIONS OF ANY KIND , either express or implied . See the License for the <nl> + / / specific language governing permissions and limitations under the License . <nl> + <nl> + / * NEON implementation of sin , cos , exp and log <nl> + * <nl> + * Inspired by Intel Approximate Math library , and based on the <nl> + * corresponding algorithms of the cephes math library <nl> + * / <nl> + <nl> + / * Copyright ( C ) 2011 Julien Pommier <nl> + * <nl> + * This software is provided ' as - is ' , without any express or implied <nl> + * warranty . In no event will the authors be held liable for any damages <nl> + * arising from the use of this software . <nl> + * <nl> + * Permission is granted to anyone to use this software for any purpose , <nl> + * including commercial applications , and to alter it and redistribute it <nl> + * freely , subject to the following restrictions : <nl> + * <nl> + * 1 . The origin of this software must not be misrepresented ; you must not <nl> + * claim that you wrote the original software . If you use this software <nl> + * in a product , an acknowledgment in the product documentation would be <nl> + * appreciated but is not required . <nl> + * 2 . Altered source versions must be plainly marked as such , and must not be <nl> + * misrepresented as being the original software . <nl> + * 3 . This notice may not be removed or altered from any source distribution . <nl> + * <nl> + * ( this is the zlib license ) <nl> + * / <nl> + <nl> + # include < arm_neon . h > <nl> + <nl> + # define c_exp_hi_f16 10 . 7421875f <nl> + # define c_exp_lo_f16 - 10 . 7421875f <nl> + <nl> + # define c_cephes_LOG2EF 1 . 44269504088896341 <nl> + # define c_cephes_exp_C1 0 . 693359375 <nl> + # define c_cephes_exp_C2 - 2 . 12194440e - 4 <nl> + <nl> + # define c_cephes_exp_p0 1 . 9875691500E - 4 <nl> + # define c_cephes_exp_p1 1 . 3981999507E - 3 <nl> + # define c_cephes_exp_p2 8 . 3334519073E - 3 <nl> + # define c_cephes_exp_p3 4 . 1665795894E - 2 <nl> + # define c_cephes_exp_p4 1 . 6666665459E - 1 <nl> + # define c_cephes_exp_p5 5 . 0000001201E - 1 <nl> + <nl> + / * exp ( ) computed for 4 float at once * / <nl> + static inline float16x4_t exp_ps ( float16x4_t x ) <nl> + { <nl> + float16x4_t tmp , fx ; <nl> + <nl> + float16x4_t one = vdup_n_f16 ( 1 ) ; <nl> + x = vmin_f16 ( x , vdup_n_f16 ( c_exp_hi_f16 ) ) ; <nl> + x = vmax_f16 ( x , vdup_n_f16 ( c_exp_lo_f16 ) ) ; <nl> + <nl> + / * express exp ( x ) as exp ( g + n * log ( 2 ) ) * / <nl> + fx = vfma_f16 ( vdup_n_f16 ( 0 . 5f ) , x , vdup_n_f16 ( c_cephes_LOG2EF ) ) ; <nl> + <nl> + / * perform a floorf * / <nl> + tmp = vcvt_f16_s16 ( vcvt_s16_f16 ( fx ) ) ; <nl> + <nl> + / * if greater , substract 1 * / <nl> + uint16x4_t mask = vcgt_f16 ( tmp , fx ) ; <nl> + mask = vand_u16 ( mask , vreinterpret_u16_f16 ( one ) ) ; <nl> + <nl> + fx = vsub_f16 ( tmp , vreinterpret_f16_u16 ( mask ) ) ; <nl> + <nl> + tmp = vmul_f16 ( fx , vdup_n_f16 ( c_cephes_exp_C1 ) ) ; <nl> + float16x4_t z = vmul_f16 ( fx , vdup_n_f16 ( c_cephes_exp_C2 ) ) ; <nl> + x = vsub_f16 ( x , tmp ) ; <nl> + x = vsub_f16 ( x , z ) ; <nl> + <nl> + static const __fp16 cephes_exp_p [ 6 ] = { c_cephes_exp_p0 , c_cephes_exp_p1 , c_cephes_exp_p2 , c_cephes_exp_p3 , c_cephes_exp_p4 , c_cephes_exp_p5 } ; <nl> + float16x4_t y = vld1_dup_f16 ( cephes_exp_p + 0 ) ; <nl> + float16x4_t c1 = vld1_dup_f16 ( cephes_exp_p + 1 ) ; <nl> + float16x4_t c2 = vld1_dup_f16 ( cephes_exp_p + 2 ) ; <nl> + float16x4_t c3 = vld1_dup_f16 ( cephes_exp_p + 3 ) ; <nl> + float16x4_t c4 = vld1_dup_f16 ( cephes_exp_p + 4 ) ; <nl> + float16x4_t c5 = vld1_dup_f16 ( cephes_exp_p + 5 ) ; <nl> + <nl> + y = vmul_f16 ( y , x ) ; <nl> + z = vmul_f16 ( x , x ) ; <nl> + <nl> + y = vadd_f16 ( y , c1 ) ; <nl> + y = vmul_f16 ( y , x ) ; <nl> + y = vadd_f16 ( y , c2 ) ; <nl> + y = vmul_f16 ( y , x ) ; <nl> + y = vadd_f16 ( y , c3 ) ; <nl> + y = vmul_f16 ( y , x ) ; <nl> + y = vadd_f16 ( y , c4 ) ; <nl> + y = vmul_f16 ( y , x ) ; <nl> + y = vadd_f16 ( y , c5 ) ; <nl> + <nl> + y = vmul_f16 ( y , z ) ; <nl> + y = vadd_f16 ( y , x ) ; <nl> + y = vadd_f16 ( y , one ) ; <nl> + <nl> + / * build 2 ^ n * / <nl> + int16x4_t mm ; <nl> + mm = vcvt_s16_f16 ( fx ) ; <nl> + mm = vadd_s16 ( mm , vdup_n_s16 ( 0xf ) ) ; <nl> + mm = vshl_n_s16 ( mm , 10 ) ; <nl> + float16x4_t pow2n = vreinterpret_f16_s16 ( mm ) ; <nl> + <nl> + y = vmul_f16 ( y , pow2n ) ; <nl> + return y ; <nl> + } <nl> + <nl> + static inline float16x8_t exp_ps ( float16x8_t x ) <nl> + { <nl> + float16x8_t tmp , fx ; <nl> + <nl> + float16x8_t one = vdupq_n_f16 ( 1 ) ; <nl> + x = vminq_f16 ( x , vdupq_n_f16 ( c_exp_hi_f16 ) ) ; <nl> + x = vmaxq_f16 ( x , vdupq_n_f16 ( c_exp_lo_f16 ) ) ; <nl> + <nl> + / * express exp ( x ) as exp ( g + n * log ( 2 ) ) * / <nl> + fx = vfmaq_f16 ( vdupq_n_f16 ( 0 . 5f ) , x , vdupq_n_f16 ( c_cephes_LOG2EF ) ) ; <nl> + <nl> + / * perform a floorf * / <nl> + tmp = vcvtq_f16_s16 ( vcvtq_s16_f16 ( fx ) ) ; <nl> + <nl> + / * if greater , substract 1 * / <nl> + uint16x8_t mask = vcgtq_f16 ( tmp , fx ) ; <nl> + mask = vandq_u16 ( mask , vreinterpretq_u16_f16 ( one ) ) ; <nl> + <nl> + fx = vsubq_f16 ( tmp , vreinterpretq_f16_u16 ( mask ) ) ; <nl> + <nl> + tmp = vmulq_f16 ( fx , vdupq_n_f16 ( c_cephes_exp_C1 ) ) ; <nl> + float16x8_t z = vmulq_f16 ( fx , vdupq_n_f16 ( c_cephes_exp_C2 ) ) ; <nl> + x = vsubq_f16 ( x , tmp ) ; <nl> + x = vsubq_f16 ( x , z ) ; <nl> + <nl> + static const __fp16 cephes_exp_p [ 6 ] = { c_cephes_exp_p0 , c_cephes_exp_p1 , c_cephes_exp_p2 , c_cephes_exp_p3 , c_cephes_exp_p4 , c_cephes_exp_p5 } ; <nl> + float16x8_t y = vld1q_dup_f16 ( cephes_exp_p + 0 ) ; <nl> + float16x8_t c1 = vld1q_dup_f16 ( cephes_exp_p + 1 ) ; <nl> + float16x8_t c2 = vld1q_dup_f16 ( cephes_exp_p + 2 ) ; <nl> + float16x8_t c3 = vld1q_dup_f16 ( cephes_exp_p + 3 ) ; <nl> + float16x8_t c4 = vld1q_dup_f16 ( cephes_exp_p + 4 ) ; <nl> + float16x8_t c5 = vld1q_dup_f16 ( cephes_exp_p + 5 ) ; <nl> + <nl> + y = vmulq_f16 ( y , x ) ; <nl> + z = vmulq_f16 ( x , x ) ; <nl> + <nl> + y = vaddq_f16 ( y , c1 ) ; <nl> + y = vmulq_f16 ( y , x ) ; <nl> + y = vaddq_f16 ( y , c2 ) ; <nl> + y = vmulq_f16 ( y , x ) ; <nl> + y = vaddq_f16 ( y , c3 ) ; <nl> + y = vmulq_f16 ( y , x ) ; <nl> + y = vaddq_f16 ( y , c4 ) ; <nl> + y = vmulq_f16 ( y , x ) ; <nl> + y = vaddq_f16 ( y , c5 ) ; <nl> + <nl> + y = vmulq_f16 ( y , z ) ; <nl> + y = vaddq_f16 ( y , x ) ; <nl> + y = vaddq_f16 ( y , one ) ; <nl> + <nl> + / * build 2 ^ n * / <nl> + int16x8_t mm ; <nl> + mm = vcvtq_s16_f16 ( fx ) ; <nl> + mm = vaddq_s16 ( mm , vdupq_n_s16 ( 0xf ) ) ; <nl> + mm = vshlq_n_s16 ( mm , 10 ) ; <nl> + float16x8_t pow2n = vreinterpretq_f16_s16 ( mm ) ; <nl> + <nl> + y = vmulq_f16 ( y , pow2n ) ; <nl> + return y ; <nl> + } <nl> + <nl> + static inline float16x4_t sigmoid_ps ( float16x4_t _v ) <nl> + { <nl> + float16x4_t _one = vdup_n_f16 ( 1 . f ) ; <nl> + _v = vneg_f16 ( _v ) ; <nl> + _v = exp_ps ( _v ) ; <nl> + _v = vadd_f16 ( _v , _one ) ; <nl> + return vdiv_f16 ( _one , _v ) ; <nl> + } <nl> + <nl> + static inline float16x8_t sigmoid_ps ( float16x8_t _v ) <nl> + { <nl> + float16x8_t _one = vdupq_n_f16 ( 1 . f ) ; <nl> + _v = vnegq_f16 ( _v ) ; <nl> + _v = exp_ps ( _v ) ; <nl> + _v = vaddq_f16 ( _v , _one ) ; <nl> + return vdivq_f16 ( _one , _v ) ; <nl> + } <nl> mmm a / src / layer / arm / sigmoid_arm . cpp <nl> ppp b / src / layer / arm / sigmoid_arm . cpp <nl> <nl> # include " neon_mathfun . h " <nl> <nl> # include < arm_neon . h > <nl> + # if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> + # include " neon_mathfun_fp16s . h " <nl> + # endif <nl> # endif / / __ARM_NEON <nl> <nl> # include < math . h > <nl> int Sigmoid_arm : : forward_inplace ( Mat & bottom_top_blob , const Option & opt ) const <nl> <nl> # if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> if ( opt . use_fp16_storage & & elembits = = 16 ) <nl> - return forward_inplace_fp16s ( bottom_top_blob , opt ) ; <nl> + { <nl> + if ( opt . use_fp16_arithmetic ) <nl> + return forward_inplace_fp16sa ( bottom_top_blob , opt ) ; <nl> + else <nl> + return forward_inplace_fp16s ( bottom_top_blob , opt ) ; <nl> + } <nl> # endif <nl> <nl> if ( opt . use_bf16_storage & & elembits = = 16 ) <nl> int Sigmoid_arm : : forward_inplace_fp16s ( Mat & bottom_top_blob , const Option & opt ) <nl> <nl> return 0 ; <nl> } <nl> + <nl> + int Sigmoid_arm : : forward_inplace_fp16sa ( Mat & bottom_top_blob , const Option & opt ) const <nl> + { <nl> + int w = bottom_top_blob . w ; <nl> + int h = bottom_top_blob . h ; <nl> + int channels = bottom_top_blob . c ; <nl> + int size = w * h ; <nl> + int elempack = bottom_top_blob . elempack ; <nl> + <nl> + if ( elempack = = 8 ) <nl> + { <nl> + # pragma omp parallel for num_threads ( opt . num_threads ) <nl> + for ( int q = 0 ; q < channels ; q + + ) <nl> + { <nl> + __fp16 * ptr = bottom_top_blob . channel ( q ) ; <nl> + <nl> + for ( int i = 0 ; i < size ; i + + ) <nl> + { <nl> + float16x8_t _p = vld1q_f16 ( ptr ) ; <nl> + _p = sigmoid_ps ( _p ) ; <nl> + vst1q_f16 ( ptr , _p ) ; <nl> + <nl> + ptr + = 8 ; <nl> + } <nl> + } <nl> + <nl> + return 0 ; <nl> + } <nl> + <nl> + if ( elempack = = 4 ) <nl> + { <nl> + # pragma omp parallel for num_threads ( opt . num_threads ) <nl> + for ( int q = 0 ; q < channels ; q + + ) <nl> + { <nl> + __fp16 * ptr = bottom_top_blob . channel ( q ) ; <nl> + <nl> + for ( int i = 0 ; i < size ; i + + ) <nl> + { <nl> + float16x4_t _p = vld1_f16 ( ptr ) ; <nl> + _p = sigmoid_ps ( _p ) ; <nl> + vst1_f16 ( ptr , _p ) ; <nl> + <nl> + ptr + = 4 ; <nl> + } <nl> + } <nl> + <nl> + return 0 ; <nl> + } <nl> + <nl> + # pragma omp parallel for num_threads ( opt . num_threads ) <nl> + for ( int q = 0 ; q < channels ; q + + ) <nl> + { <nl> + __fp16 * ptr = bottom_top_blob . channel ( q ) ; <nl> + <nl> + int i = 0 ; <nl> + for ( ; i + 3 < size ; i + = 4 ) <nl> + { <nl> + float16x4_t _p = vld1_f16 ( ptr ) ; <nl> + _p = sigmoid_ps ( _p ) ; <nl> + vst1_f16 ( ptr , _p ) ; <nl> + <nl> + ptr + = 4 ; <nl> + } <nl> + for ( ; i < size ; i + + ) <nl> + { <nl> + __fp16 v = * ptr ; <nl> + v = 1 . f / ( 1 . f + exp ( - v ) ) ; <nl> + * ptr = v ; <nl> + ptr + + ; <nl> + } <nl> + } <nl> + <nl> + return 0 ; <nl> + } <nl> # endif / / __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> <nl> int Sigmoid_arm : : forward_inplace_bf16s ( Mat & bottom_top_blob , const Option & opt ) const <nl> mmm a / src / layer / arm / sigmoid_arm . h <nl> ppp b / src / layer / arm / sigmoid_arm . h <nl> class Sigmoid_arm : virtual public Sigmoid <nl> protected : <nl> # if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> int forward_inplace_fp16s ( Mat & bottom_top_blob , const Option & opt ) const ; <nl> + int forward_inplace_fp16sa ( Mat & bottom_top_blob , const Option & opt ) const ; <nl> # endif <nl> int forward_inplace_bf16s ( Mat & bottom_top_blob , const Option & opt ) const ; <nl> } ; <nl> mmm a / src / layer / arm / swish_arm . cpp <nl> ppp b / src / layer / arm / swish_arm . cpp <nl> <nl> # include " neon_mathfun . h " <nl> <nl> # include < arm_neon . h > <nl> + # if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> + # include " neon_mathfun_fp16s . h " <nl> + # endif <nl> # endif / / __ARM_NEON <nl> <nl> # include < math . h > <nl> int Swish_arm : : forward_inplace ( Mat & bottom_top_blob , const Option & opt ) const <nl> <nl> # if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> if ( opt . use_fp16_storage & & elembits = = 16 ) <nl> - return forward_inplace_fp16s ( bottom_top_blob , opt ) ; <nl> + { <nl> + if ( opt . use_fp16_arithmetic ) <nl> + return forward_inplace_fp16sa ( bottom_top_blob , opt ) ; <nl> + else <nl> + return forward_inplace_fp16s ( bottom_top_blob , opt ) ; <nl> + } <nl> # endif <nl> <nl> if ( opt . use_bf16_storage & & elembits = = 16 ) <nl> int Swish_arm : : forward_inplace_fp16s ( Mat & bottom_top_blob , const Option & opt ) co <nl> for ( int i = 0 ; i < size ; i + + ) <nl> { <nl> float32x4_t _p = vcvt_f32_f16 ( vld1_f16 ( ptr ) ) ; <nl> - _p = div_ps ( _p , vaddq_f32 ( _one , exp_ps ( vnegq_f32 ( _p ) ) ) ) ; <nl> + _p = vdivq_f32 ( _p , vaddq_f32 ( _one , exp_ps ( vnegq_f32 ( _p ) ) ) ) ; <nl> vst1_f16 ( ptr , vcvt_f16_f32 ( _p ) ) ; <nl> <nl> ptr + = 4 ; <nl> int Swish_arm : : forward_inplace_fp16s ( Mat & bottom_top_blob , const Option & opt ) co <nl> for ( ; i + 3 < size ; i + = 4 ) <nl> { <nl> float32x4_t _p = vcvt_f32_f16 ( vld1_f16 ( ptr ) ) ; <nl> - _p = div_ps ( _p , vaddq_f32 ( _one , exp_ps ( vnegq_f32 ( _p ) ) ) ) ; <nl> + _p = vdivq_f32 ( _p , vaddq_f32 ( _one , exp_ps ( vnegq_f32 ( _p ) ) ) ) ; <nl> vst1_f16 ( ptr , vcvt_f16_f32 ( _p ) ) ; <nl> <nl> ptr + = 4 ; <nl> int Swish_arm : : forward_inplace_fp16s ( Mat & bottom_top_blob , const Option & opt ) co <nl> <nl> return 0 ; <nl> } <nl> + <nl> + int Swish_arm : : forward_inplace_fp16sa ( Mat & bottom_top_blob , const Option & opt ) const <nl> + { <nl> + int w = bottom_top_blob . w ; <nl> + int h = bottom_top_blob . h ; <nl> + int channels = bottom_top_blob . c ; <nl> + int size = w * h ; <nl> + int elempack = bottom_top_blob . elempack ; <nl> + <nl> + if ( elempack = = 8 ) <nl> + { <nl> + # pragma omp parallel for num_threads ( opt . num_threads ) <nl> + for ( int q = 0 ; q < channels ; q + + ) <nl> + { <nl> + __fp16 * ptr = bottom_top_blob . channel ( q ) ; <nl> + <nl> + float16x8_t _one = vdupq_n_f16 ( 1 . f ) ; <nl> + for ( int i = 0 ; i < size ; i + + ) <nl> + { <nl> + float16x8_t _p = vld1q_f16 ( ptr ) ; <nl> + _p = vdivq_f16 ( _p , vaddq_f16 ( _one , exp_ps ( vnegq_f16 ( _p ) ) ) ) ; <nl> + vst1q_f16 ( ptr , _p ) ; <nl> + <nl> + ptr + = 8 ; <nl> + } <nl> + } <nl> + <nl> + return 0 ; <nl> + } <nl> + <nl> + if ( elempack = = 4 ) <nl> + { <nl> + # pragma omp parallel for num_threads ( opt . num_threads ) <nl> + for ( int q = 0 ; q < channels ; q + + ) <nl> + { <nl> + __fp16 * ptr = bottom_top_blob . channel ( q ) ; <nl> + <nl> + float16x4_t _one = vdup_n_f16 ( 1 . f ) ; <nl> + for ( int i = 0 ; i < size ; i + + ) <nl> + { <nl> + float16x4_t _p = vld1_f16 ( ptr ) ; <nl> + _p = vdiv_f16 ( _p , vadd_f16 ( _one , exp_ps ( vneg_f16 ( _p ) ) ) ) ; <nl> + vst1_f16 ( ptr , _p ) ; <nl> + <nl> + ptr + = 4 ; <nl> + } <nl> + } <nl> + <nl> + return 0 ; <nl> + } <nl> + <nl> + # pragma omp parallel for num_threads ( opt . num_threads ) <nl> + for ( int q = 0 ; q < channels ; q + + ) <nl> + { <nl> + __fp16 * ptr = bottom_top_blob . channel ( q ) ; <nl> + <nl> + float16x4_t _one = vdup_n_f16 ( 1 . f ) ; <nl> + int i = 0 ; <nl> + for ( ; i + 3 < size ; i + = 4 ) <nl> + { <nl> + float16x4_t _p = vld1_f16 ( ptr ) ; <nl> + _p = vdiv_f16 ( _p , vadd_f16 ( _one , exp_ps ( vneg_f16 ( _p ) ) ) ) ; <nl> + vst1_f16 ( ptr , _p ) ; <nl> + <nl> + ptr + = 4 ; <nl> + } <nl> + for ( ; i < size ; i + + ) <nl> + { <nl> + __fp16 v = * ptr ; <nl> + v = v / ( ( __fp16 ) 1 . f + exp ( - v ) ) ; <nl> + * ptr = v ; <nl> + ptr + + ; <nl> + } <nl> + } <nl> + <nl> + return 0 ; <nl> + } <nl> # endif / / __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> <nl> int Swish_arm : : forward_inplace_bf16s ( Mat & bottom_top_blob , const Option & opt ) const <nl> mmm a / src / layer / arm / swish_arm . h <nl> ppp b / src / layer / arm / swish_arm . h <nl> class Swish_arm : virtual public Swish <nl> protected : <nl> # if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC <nl> int forward_inplace_fp16s ( Mat & bottom_top_blob , const Option & opt ) const ; <nl> + int forward_inplace_fp16sa ( Mat & bottom_top_blob , const Option & opt ) const ; <nl> # endif <nl> int forward_inplace_bf16s ( Mat & bottom_top_blob , const Option & opt ) const ; <nl> } ; <nl> | exp arm fp16sa neon optimization | Tencent/ncnn | bf09af21be182b7a322b72bdb106223885e14340 | 2020-08-22T08:55:24Z |
mmm a / src / objects / transitions . cc <nl> ppp b / src / objects / transitions . cc <nl> void TransitionsAccessor : : Insert ( Handle < Name > name , Handle < Map > target , <nl> DisallowHeapAllocation no_gc ; <nl> TransitionArray array = transitions ( ) ; <nl> number_of_transitions = array . number_of_transitions ( ) ; <nl> - new_nof = number_of_transitions ; <nl> <nl> int index = is_special_transition <nl> ? array . SearchSpecial ( Symbol : : cast ( * name ) , & insertion_index ) <nl> void TransitionsAccessor : : Insert ( Handle < Name > name , Handle < Map > target , <nl> return ; <nl> } <nl> <nl> - + + new_nof ; <nl> + new_nof = number_of_transitions + 1 ; <nl> CHECK_LE ( new_nof , kMaxNumberOfTransitions ) ; <nl> - DCHECK ( insertion_index > = 0 & & insertion_index < = number_of_transitions ) ; <nl> + DCHECK_GE ( insertion_index , 0 ) ; <nl> + DCHECK_LE ( insertion_index , number_of_transitions ) ; <nl> <nl> / / If there is enough capacity , insert new entry into the existing array . <nl> if ( new_nof < = array . Capacity ( ) ) { <nl> array . SetNumberOfTransitions ( new_nof ) ; <nl> - for ( index = number_of_transitions ; index > insertion_index ; - - index ) { <nl> - array . SetKey ( index , array . GetKey ( index - 1 ) ) ; <nl> - array . SetRawTarget ( index , array . GetRawTarget ( index - 1 ) ) ; <nl> + for ( int i = number_of_transitions ; i > insertion_index ; - - i ) { <nl> + array . SetKey ( i , array . GetKey ( i - 1 ) ) ; <nl> + array . SetRawTarget ( i , array . GetRawTarget ( i - 1 ) ) ; <nl> } <nl> - array . SetKey ( index , * name ) ; <nl> - array . SetRawTarget ( index , HeapObjectReference : : Weak ( * target ) ) ; <nl> + array . SetKey ( insertion_index , * name ) ; <nl> + array . SetRawTarget ( insertion_index , HeapObjectReference : : Weak ( * target ) ) ; <nl> SLOW_DCHECK ( array . IsSortedNoDuplicates ( ) ) ; <nl> return ; <nl> } <nl> void TransitionsAccessor : : Insert ( Handle < Name > name , Handle < Map > target , <nl> DisallowHeapAllocation no_gc ; <nl> TransitionArray array = transitions ( ) ; <nl> if ( array . number_of_transitions ( ) ! = number_of_transitions ) { <nl> - DCHECK ( array . number_of_transitions ( ) < number_of_transitions ) ; <nl> - <nl> - number_of_transitions = array . number_of_transitions ( ) ; <nl> - new_nof = number_of_transitions ; <nl> + DCHECK_LT ( array . number_of_transitions ( ) , number_of_transitions ) ; <nl> <nl> - insertion_index = kNotFound ; <nl> int index = is_special_transition <nl> ? array . SearchSpecial ( Symbol : : cast ( * name ) , & insertion_index ) <nl> : array . Search ( details . kind ( ) , * name , details . attributes ( ) , <nl> & insertion_index ) ; <nl> - if ( index = = kNotFound ) { <nl> - + + new_nof ; <nl> - } else { <nl> - insertion_index = index ; <nl> - } <nl> - DCHECK ( insertion_index > = 0 & & insertion_index < = number_of_transitions ) ; <nl> + CHECK_EQ ( index , kNotFound ) ; <nl> + USE ( index ) ; <nl> + DCHECK_GE ( insertion_index , 0 ) ; <nl> + DCHECK_LE ( insertion_index , number_of_transitions ) ; <nl> <nl> + number_of_transitions = array . number_of_transitions ( ) ; <nl> + new_nof = number_of_transitions + 1 ; <nl> result - > SetNumberOfTransitions ( new_nof ) ; <nl> } <nl> <nl> | [ cleanup ] Clean kFullTransitionArray path in TransitionsAccessor : : Insert | v8/v8 | 0da6b2cbfedb7026c7c90ac6fc79b850b6b6482d | 2020-06-22T14:06:11Z |
mmm a / language / English / strings . xml <nl> ppp b / language / English / strings . xml <nl> <nl> < string id = " 16317 " > Temporal ( Half ) < / string > <nl> < string id = " 16318 " > Temporal / Spatial ( Half ) < / string > <nl> < string id = " 16319 " > DXVA < / string > <nl> + < string id = " 16320 " > DXVA Bob < / string > <nl> + < string id = " 16321 " > DXVA Best < / string > <nl> <nl> < string id = " 16400 " > Post - processing < / string > <nl> <nl> mmm a / xbmc / cores / VideoRenderers / RenderFlags . h <nl> ppp b / xbmc / cores / VideoRenderers / RenderFlags . h <nl> <nl> # define RENDER_FLAG_TOP 0x02 <nl> # define RENDER_FLAG_BOTH ( RENDER_FLAG_BOT | RENDER_FLAG_TOP ) <nl> # define RENDER_FLAG_FIELDMASK 0x03 <nl> + <nl> + # define RENDER_FLAG_FIELD0 0x80 <nl> + # define RENDER_FLAG_FIELD1 0x100 <nl> + <nl> # define RENDER_FLAG_LAST 0x40 <nl> <nl> # define RENDER_FLAG_NOOSD 0x04 / * don ' t draw any osd * / <nl> mmm a / xbmc / cores / VideoRenderers / RenderManager . cpp <nl> ppp b / xbmc / cores / VideoRenderers / RenderManager . cpp <nl> void CXBMCRenderManager : : FlipPage ( volatile bool & bStop , double timestamp / * = 0L <nl> { <nl> if ( m_presentfield = = FS_NONE ) <nl> m_presentmethod = VS_INTERLACEMETHOD_NONE ; <nl> - else if ( m_pRenderer - > Supports ( VS_INTERLACEMETHOD_RENDER_BOB ) ) <nl> + else if ( m_pRenderer - > Supports ( VS_INTERLACEMETHOD_RENDER_BOB ) | | m_pRenderer - > Supports ( VS_INTERLACEMETHOD_DXVA_ANY ) ) <nl> m_presentmethod = VS_INTERLACEMETHOD_RENDER_BOB ; <nl> else <nl> m_presentmethod = VS_INTERLACEMETHOD_NONE ; <nl> void CXBMCRenderManager : : Present ( ) <nl> CSharedLock lock ( m_sharedSection ) ; <nl> <nl> if ( m_presentmethod = = VS_INTERLACEMETHOD_RENDER_BOB <nl> - | | m_presentmethod = = VS_INTERLACEMETHOD_RENDER_BOB_INVERTED ) <nl> + | | m_presentmethod = = VS_INTERLACEMETHOD_RENDER_BOB_INVERTED <nl> + | | m_presentmethod = = VS_INTERLACEMETHOD_DXVA_BOB <nl> + | | m_presentmethod = = VS_INTERLACEMETHOD_DXVA_BEST ) <nl> PresentBob ( ) ; <nl> else if ( m_presentmethod = = VS_INTERLACEMETHOD_RENDER_WEAVE <nl> | | m_presentmethod = = VS_INTERLACEMETHOD_RENDER_WEAVE_INVERTED ) <nl> void CXBMCRenderManager : : PresentBob ( ) <nl> if ( m_presentstep = = PRESENT_FRAME ) <nl> { <nl> if ( m_presentfield = = FS_BOT ) <nl> - m_pRenderer - > RenderUpdate ( true , RENDER_FLAG_BOT , 255 ) ; <nl> + m_pRenderer - > RenderUpdate ( true , RENDER_FLAG_BOT | RENDER_FLAG_FIELD0 , 255 ) ; <nl> else <nl> - m_pRenderer - > RenderUpdate ( true , RENDER_FLAG_TOP , 255 ) ; <nl> + m_pRenderer - > RenderUpdate ( true , RENDER_FLAG_TOP | RENDER_FLAG_FIELD0 , 255 ) ; <nl> m_presentstep = PRESENT_FRAME2 ; <nl> g_application . NewFrame ( ) ; <nl> } <nl> else <nl> { <nl> if ( m_presentfield = = FS_TOP ) <nl> - m_pRenderer - > RenderUpdate ( true , RENDER_FLAG_BOT , 255 ) ; <nl> + m_pRenderer - > RenderUpdate ( true , RENDER_FLAG_BOT | RENDER_FLAG_FIELD1 , 255 ) ; <nl> else <nl> - m_pRenderer - > RenderUpdate ( true , RENDER_FLAG_TOP , 255 ) ; <nl> + m_pRenderer - > RenderUpdate ( true , RENDER_FLAG_TOP | RENDER_FLAG_FIELD1 , 255 ) ; <nl> m_presentstep = PRESENT_IDLE ; <nl> } <nl> } <nl> mmm a / xbmc / cores / VideoRenderers / WinRenderer . cpp <nl> ppp b / xbmc / cores / VideoRenderers / WinRenderer . cpp <nl> CWinRenderer : : CWinRenderer ( ) <nl> <nl> m_sw_scale_ctx = NULL ; <nl> m_dllSwScale = NULL ; <nl> + m_dxvaDecoding = false ; <nl> } <nl> <nl> CWinRenderer : : ~ CWinRenderer ( ) <nl> bool CWinRenderer : : Configure ( unsigned int width , unsigned int height , unsigned i <nl> m_bFilterInitialized = false ; <nl> } <nl> <nl> + if ( CONF_FLAGS_FORMAT_MASK ( flags ) = = CONF_FLAGS_FORMAT_DXVA ) <nl> + m_dxvaDecoding = true ; <nl> + else <nl> + m_dxvaDecoding = false ; <nl> + <nl> m_fps = fps ; <nl> m_flags = flags ; <nl> m_format = format ; <nl> void CWinRenderer : : RenderProcessor ( DWORD flags ) <nl> return ; <nl> } <nl> <nl> - m_processor . Render ( sourceRect , destRect , target , image - > id ) ; <nl> + m_processor . Render ( sourceRect , destRect , target , image - > id , flags ) ; <nl> <nl> target - > Release ( ) ; <nl> } <nl> bool CWinRenderer : : CreateYV12Texture ( int index ) <nl> <nl> bool CWinRenderer : : Supports ( EINTERLACEMETHOD method ) <nl> { <nl> + if ( method = = VS_INTERLACEMETHOD_NONE <nl> + | | method = = VS_INTERLACEMETHOD_AUTO ) <nl> + return true ; <nl> + <nl> if ( m_renderMethod = = RENDER_DXVA ) <nl> { <nl> - if ( method = = VS_INTERLACEMETHOD_NONE ) <nl> + if ( method = = VS_INTERLACEMETHOD_DXVA_ANY <nl> + | | method = = VS_INTERLACEMETHOD_DXVA_BOB <nl> + | | method = = VS_INTERLACEMETHOD_DXVA_BEST ) <nl> return true ; <nl> - return false ; <nl> } <nl> <nl> - if ( method = = VS_INTERLACEMETHOD_NONE <nl> - | | method = = VS_INTERLACEMETHOD_AUTO <nl> - | | method = = VS_INTERLACEMETHOD_DEINTERLACE <nl> - | | method = = VS_INTERLACEMETHOD_DEINTERLACE_HALF ) <nl> + if ( ! m_dxvaDecoding <nl> + & & ( method = = VS_INTERLACEMETHOD_DEINTERLACE <nl> + | | method = = VS_INTERLACEMETHOD_DEINTERLACE_HALF ) ) <nl> return true ; <nl> <nl> return false ; <nl> mmm a / xbmc / cores / VideoRenderers / WinRenderer . h <nl> ppp b / xbmc / cores / VideoRenderers / WinRenderer . h <nl> <nl> # include " RenderCapture . h " <nl> # include " settings / VideoSettings . h " <nl> # include " cores / dvdplayer / DVDCodecs / Video / DXVA . h " <nl> + # include " cores / VideoRenderers / RenderFlags . h " <nl> + <nl> / / # define MP_DIRECTRENDERING <nl> <nl> # ifdef MP_DIRECTRENDERING <nl> <nl> <nl> # define IMAGE_FLAG_INUSE ( IMAGE_FLAG_WRITING | IMAGE_FLAG_READING | IMAGE_FLAG_RESERVED ) <nl> <nl> - <nl> - # define RENDER_FLAG_BOT 0x01 <nl> - # define RENDER_FLAG_TOP 0x02 <nl> - # define RENDER_FLAG_BOTH ( RENDER_FLAG_BOT | RENDER_FLAG_TOP ) <nl> - # define RENDER_FLAG_FIELDMASK 0x03 <nl> - <nl> - # define RENDER_FLAG_NOOSD 0x04 / * don ' t draw any osd * / <nl> - <nl> - / * these two flags will be used if we need to render same image twice ( bob deinterlacing ) * / <nl> - # define RENDER_FLAG_NOLOCK 0x10 / * don ' t attempt to lock texture before rendering * / <nl> - # define RENDER_FLAG_NOUNLOCK 0x20 / * don ' t unlock texture after rendering * / <nl> - <nl> - / * this defines what color translation coefficients * / <nl> - # define CONF_FLAGS_YUVCOEF_MASK ( a ) ( ( a ) & 0x07 ) <nl> - # define CONF_FLAGS_YUVCOEF_BT709 0x01 <nl> - # define CONF_FLAGS_YUVCOEF_BT601 0x02 <nl> - # define CONF_FLAGS_YUVCOEF_240M 0x03 <nl> - # define CONF_FLAGS_YUVCOEF_EBU 0x04 <nl> - <nl> - # define CONF_FLAGS_YUV_FULLRANGE 0x08 <nl> - # define CONF_FLAGS_FULLSCREEN 0x10 <nl> - <nl> class CBaseTexture ; <nl> class CYUV2RGBShader ; <nl> class CConvolutionShader ; <nl> class CWinRenderer : public CBaseRenderer <nl> DWORD m_clearColour ; <nl> unsigned int m_flags ; <nl> unsigned int m_format ; <nl> + bool m_dxvaDecoding ; <nl> <nl> / / Width and height of the render target <nl> / / the separable HQ scalers need this info , but could the m_destRect be used instead ? <nl> mmm a / xbmc / cores / dvdplayer / DVDCodecs / Video / DXVA . cpp <nl> ppp b / xbmc / cores / dvdplayer / DVDCodecs / Video / DXVA . cpp <nl> static const dxva2_mode_t dxva2_modes [ ] = { <nl> { NULL , NULL , 0 } <nl> } ; <nl> <nl> + DEFINE_GUID ( DXVA2_VideoProcATIVectorAdaptiveDevice , 0x3C5323C1 , 0x6fb7 , 0x44f5 , 0x90 , 0x81 , 0x05 , 0x6b , 0xf2 , 0xee , 0x44 , 0x9d ) ; <nl> + DEFINE_GUID ( DXVA2_VideoProcATIMotionAdaptiveDevice , 0x552C0DAD , 0xccbc , 0x420b , 0x83 , 0xc8 , 0x74 , 0x94 , 0x3c , 0xf9 , 0xf1 , 0xa6 ) ; <nl> + DEFINE_GUID ( DXVA2_VideoProcATIAdaptiveDevice , 0x6E8329FF , 0xb642 , 0x418b , 0xbc , 0xf0 , 0xbc , 0xb6 , 0x59 , 0x1e , 0x25 , 0x5f ) ; <nl> + DEFINE_GUID ( DXVA2_VideoProcNVidiaAdaptiveDevice , 0x6CB69578 , 0x7617 , 0x4637 , 0x91 , 0xE5 , 0x1C , 0x02 , 0xDB , 0x81 , 0x02 , 0x85 ) ; <nl> + DEFINE_GUID ( DXVA2_VideoProcIntelEdgeDevice , 0xBF752EF6 , 0x8CC4 , 0x457A , 0xBE , 0x1B , 0x08 , 0xBD , 0x1C , 0xAE , 0xEE , 0x9F ) ; <nl> + DEFINE_GUID ( DXVA2_VideoProcNVidiaUnknownDevice , 0xF9F19DA5 , 0x3B09 , 0x4B2F , 0x9D , 0x89 , 0xC6 , 0x47 , 0x53 , 0xE3 , 0xEA , 0xAB ) ; <nl> + <nl> + typedef struct { <nl> + const char * name ; <nl> + const GUID * guid ; <nl> + } dxva2_device_t ; <nl> + <nl> + static const dxva2_device_t dxva2_devices [ ] = { <nl> + { " Progressive Device " , & DXVA2_VideoProcProgressiveDevice } , <nl> + { " Bob Device " , & DXVA2_VideoProcBobDevice } , <nl> + { " Vector Adaptative Device " , & DXVA2_VideoProcATIVectorAdaptiveDevice } , <nl> + { " Motion Adaptative Device " , & DXVA2_VideoProcATIMotionAdaptiveDevice } , <nl> + { " Adaptative Device " , & DXVA2_VideoProcATIAdaptiveDevice } , <nl> + { " Spatial - temporal device " , & DXVA2_VideoProcNVidiaAdaptiveDevice } , <nl> + { " Edge directed device " , & DXVA2_VideoProcIntelEdgeDevice } , <nl> + { " Unknown device ( nVidia ) " , & DXVA2_VideoProcNVidiaUnknownDevice } , <nl> + { NULL , NULL } <nl> + } ; <nl> + <nl> + typedef struct { <nl> + const char * name ; <nl> + unsigned flags ; <nl> + } dxva2_deinterlacetech_t ; <nl> + <nl> + static const dxva2_deinterlacetech_t dxva2_deinterlacetechs [ ] = { <nl> + { " Inverse Telecine " , DXVA2_DeinterlaceTech_InverseTelecine } , <nl> + { " Motion vector steered " , DXVA2_DeinterlaceTech_MotionVectorSteered } , <nl> + { " Pixel adaptive " , DXVA2_DeinterlaceTech_PixelAdaptive } , <nl> + { " Field adaptive " , DXVA2_DeinterlaceTech_FieldAdaptive } , <nl> + { " Edge filtering " , DXVA2_DeinterlaceTech_EdgeFiltering } , <nl> + { " Median filtering " , DXVA2_DeinterlaceTech_MedianFiltering } , <nl> + { " Bob vertical stretch 4 - tap " , DXVA2_DeinterlaceTech_BOBVerticalStretch4Tap } , <nl> + { " Bob vertical stretch " , DXVA2_DeinterlaceTech_BOBVerticalStretch } , <nl> + { " Bob line replicate " , DXVA2_DeinterlaceTech_BOBLineReplicate } , <nl> + { " Unknown " , DXVA2_DeinterlaceTech_Unknown } , <nl> + { NULL , 0 } <nl> + } ; <nl> + <nl> + <nl> / / Prefered targets must be first <nl> static const D3DFORMAT render_targets [ ] = { <nl> ( D3DFORMAT ) MAKEFOURCC ( ' N ' , ' V ' , ' 1 ' , ' 2 ' ) , <nl> static DWORD VP3DeviceID [ ] = { <nl> static CStdString GUIDToString ( const GUID & guid ) <nl> { <nl> CStdString buffer ; <nl> - buffer . Format ( " % 08X - % 04x - % 04x - % 02x % 02x - % 02x % 02x % 02x % 02x % 02x % 02x \ n " <nl> + buffer . Format ( " % 08X - % 04x - % 04x - % 02x % 02x - % 02x % 02x % 02x % 02x % 02x % 02x " <nl> , guid . Data1 , guid . Data2 , guid . Data3 <nl> , guid . Data4 [ 0 ] , guid . Data4 [ 1 ] <nl> , guid . Data4 [ 2 ] , guid . Data4 [ 3 ] , guid . Data4 [ 4 ] <nl> static CStdString GUIDToString ( const GUID & guid ) <nl> return buffer ; <nl> } <nl> <nl> - static const dxva2_mode_t * dxva2_find ( const GUID * guid ) <nl> + static const dxva2_mode_t * dxva2_find_mode ( const GUID * guid ) <nl> { <nl> for ( unsigned i = 0 ; dxva2_modes [ i ] . name ; i + + ) { <nl> if ( IsEqualGUID ( * dxva2_modes [ i ] . guid , * guid ) ) <nl> static const dxva2_mode_t * dxva2_find ( const GUID * guid ) <nl> return NULL ; <nl> } <nl> <nl> + static const dxva2_device_t * dxva2_find_device ( const GUID * guid ) <nl> + { <nl> + for ( unsigned i = 0 ; dxva2_devices [ i ] . name ; i + + ) { <nl> + if ( IsEqualGUID ( * dxva2_devices [ i ] . guid , * guid ) ) <nl> + return & dxva2_devices [ i ] ; <nl> + } <nl> + return NULL ; <nl> + } <nl> + <nl> + static const dxva2_deinterlacetech_t * dxva2_find_deinterlacetech ( unsigned flags ) <nl> + { <nl> + for ( unsigned i = 0 ; dxva2_deinterlacetechs [ i ] . name ; i + + ) { <nl> + if ( dxva2_deinterlacetechs [ i ] . flags = = flags ) <nl> + return & dxva2_deinterlacetechs [ i ] ; <nl> + } <nl> + return NULL ; <nl> + } <nl> <nl> # define SCOPE ( type , var ) boost : : shared_ptr < type > var # # _holder ( var , CoTaskMemFree ) ; <nl> <nl> bool CDecoder : : Open ( AVCodecContext * avctx , enum PixelFormat fmt , unsigned int su <nl> for ( unsigned i = 0 ; i < input_count ; i + + ) <nl> { <nl> const GUID * g = & input_list [ i ] ; <nl> - const dxva2_mode_t * mode = dxva2_find ( g ) ; <nl> + const dxva2_mode_t * mode = dxva2_find_mode ( g ) ; <nl> if ( mode ) <nl> CLog : : Log ( LOGDEBUG , " DXVA - supports ' % s ' " , mode - > name ) ; <nl> else <nl> CProcessor : : CProcessor ( ) <nl> m_surfaces = NULL ; <nl> m_context = NULL ; <nl> m_index = 0 ; <nl> + m_interlace_method = g_settings . m_currentVideoSettings . m_InterlaceMethod ; <nl> + m_last_field_rendered = 0 ; <nl> } <nl> <nl> CProcessor : : ~ CProcessor ( ) <nl> bool CProcessor : : UpdateSize ( const DXVA2_VideoDesc & dsc ) <nl> m_size = caps . NumBackwardRefSamples + caps . NumForwardRefSamples ; <nl> CLog : : Log ( LOGDEBUG , " DXVA - updated maximum samples count to % d " , m_size ) ; <nl> } <nl> + m_max_back_refs = std : : max ( caps . NumBackwardRefSamples , m_max_back_refs ) ; <nl> + m_max_fwd_refs = std : : max ( caps . NumForwardRefSamples , m_max_fwd_refs ) ; <nl> } <nl> <nl> return true ; <nl> bool CProcessor : : PreInit ( ) <nl> dsc . SampleHeight = 480 ; <nl> dsc . SampleFormat . SampleFormat = DXVA2_SampleFieldInterleavedOddFirst ; <nl> <nl> + m_max_back_refs = 0 ; <nl> + m_max_fwd_refs = 0 ; <nl> + <nl> for ( unsigned i = 0 ; render_targets [ i ] ! = D3DFMT_UNKNOWN ; i + + ) <nl> { <nl> dsc . Format = render_targets [ i ] ; <nl> bool CProcessor : : PreInit ( ) <nl> CLog : : Log ( LOGDEBUG , " DXVA - render target not supported by processor " ) ; <nl> } <nl> <nl> - m_size + = 3 ; / / 1 display + 2 safety frames <nl> + m_size = m_max_back_refs + 1 + m_max_fwd_refs + 2 ; / / refs + 1 display + 2 safety frames <nl> <nl> return true ; <nl> } <nl> bool CProcessor : : Open ( UINT width , UINT height , unsigned int flags , unsigned int <nl> <nl> dsc . SampleWidth = width ; <nl> dsc . SampleHeight = height ; <nl> - dsc . SampleFormat . SampleFormat = DXVA2_SampleProgressiveFrame ; <nl> dsc . SampleFormat . VideoLighting = DXVA2_VideoLighting_dim ; <nl> <nl> switch ( CONF_FLAGS_CHROMA_MASK ( flags ) ) <nl> bool CProcessor : : Open ( UINT width , UINT height , unsigned int flags , unsigned int <nl> return false ; <nl> } <nl> <nl> + if ( ! OpenProcessor ( ) ) <nl> + return false ; <nl> + <nl> + m_time = 0 ; <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + bool CProcessor : : SelectProcessor ( ) <nl> + { <nl> + if ( m_interlace_method ! = VS_INTERLACEMETHOD_AUTO <nl> + & & m_interlace_method ! = VS_INTERLACEMETHOD_DXVA_BOB <nl> + & & m_interlace_method ! = VS_INTERLACEMETHOD_DXVA_BEST ) <nl> + m_desc . SampleFormat . SampleFormat = DXVA2_SampleProgressiveFrame ; <nl> + else <nl> + m_desc . SampleFormat . SampleFormat = DXVA2_SampleFieldInterleavedEvenFirst ; <nl> + <nl> GUID * guid_list ; <nl> unsigned guid_count ; <nl> CHECK ( m_service - > GetVideoProcessorDeviceGuids ( & m_desc , & guid_count , & guid_list ) ) ; <nl> bool CProcessor : : Open ( UINT width , UINT height , unsigned int flags , unsigned int <nl> return false ; <nl> } <nl> <nl> - m_device = guid_list [ 0 ] ; <nl> for ( unsigned i = 0 ; i < guid_count ; i + + ) <nl> { <nl> - GUID * g = & guid_list [ i ] ; <nl> - CLog : : Log ( LOGDEBUG , " DXVA - processor found % s " , GUIDToString ( * g ) . c_str ( ) ) ; <nl> + const GUID * g = & guid_list [ i ] ; <nl> + const dxva2_device_t * device = dxva2_find_device ( g ) ; <nl> + <nl> + if ( device ) <nl> + { <nl> + CLog : : Log ( LOGDEBUG , " DXVA - processor found % s " , device - > name ) ; <nl> + } <nl> + else <nl> + { <nl> + CHECK ( m_service - > GetVideoProcessorCaps ( * g , & m_desc , D3DFMT_X8R8G8B8 , & m_caps ) ) ; <nl> + const dxva2_deinterlacetech_t * tech = dxva2_find_deinterlacetech ( m_caps . DeinterlaceTechnology ) ; <nl> + if ( tech ! = NULL ) <nl> + CLog : : Log ( LOGDEBUG , " DXVA - unknown processor % s found , deinterlace technology % s " , GUIDToString ( * g ) . c_str ( ) , tech - > name ) ; <nl> + else <nl> + CLog : : Log ( LOGDEBUG , " DXVA - unknown processor % s found , unknown technology " , GUIDToString ( * g ) . c_str ( ) ) ; <nl> + } <nl> + } <nl> <nl> - if ( IsEqualGUID ( * g , DXVA2_VideoProcProgressiveDevice ) ) <nl> - m_device = * g ; <nl> + m_device = guid_list [ 0 ] ; <nl> + if ( m_interlace_method ! = VS_INTERLACEMETHOD_DXVA_BEST & & m_interlace_method ! = VS_INTERLACEMETHOD_AUTO ) <nl> + { <nl> + if ( m_interlace_method ! = VS_INTERLACEMETHOD_DXVA_BOB ) <nl> + m_device = DXVA2_VideoProcProgressiveDevice ; <nl> + else <nl> + m_device = DXVA2_VideoProcBobDevice ; <nl> } <nl> <nl> - CLog : : Log ( LOGDEBUG , " DXVA - processor selected % s " , GUIDToString ( m_device ) . c_str ( ) ) ; <nl> + return true ; <nl> + } <nl> + <nl> + bool CProcessor : : OpenProcessor ( ) <nl> + { <nl> + if ( ! SelectProcessor ( ) ) <nl> + return false ; <nl> + <nl> + SAFE_RELEASE ( m_process ) ; <nl> + <nl> + const dxva2_device_t * device = dxva2_find_device ( & m_device ) ; <nl> + if ( device ) <nl> + CLog : : Log ( LOGDEBUG , " DXVA - processor selected % s " , device - > name ) ; <nl> + else <nl> + CLog : : Log ( LOGDEBUG , " DXVA - processor selected % s " , GUIDToString ( m_device ) . c_str ( ) ) ; <nl> <nl> D3DFORMAT rtFormat = D3DFMT_X8R8G8B8 ; <nl> CHECK ( m_service - > GetVideoProcessorCaps ( m_device , & m_desc , rtFormat , & m_caps ) ) <nl> bool CProcessor : : Open ( UINT width , UINT height , unsigned int flags , unsigned int <nl> CHECK ( m_service - > GetProcAmpRange ( m_device , & m_desc , rtFormat , DXVA2_ProcAmp_Hue , & m_hue ) ) ; <nl> CHECK ( m_service - > GetProcAmpRange ( m_device , & m_desc , rtFormat , DXVA2_ProcAmp_Saturation , & m_saturation ) ) ; <nl> <nl> - m_time = 0 ; <nl> - <nl> return true ; <nl> } <nl> <nl> REFERENCE_TIME CProcessor : : Add ( DVDVideoPicture * picture ) <nl> vs . sample . Start = m_time ; <nl> vs . sample . End = 0 ; <nl> vs . sample . SampleFormat = m_desc . SampleFormat ; <nl> + <nl> + if ( picture - > iFlags & DVP_FLAG_INTERLACED ) <nl> + { <nl> + if ( picture - > iFlags & DVP_FLAG_TOP_FIELD_FIRST ) <nl> + vs . sample . SampleFormat . SampleFormat = DXVA2_SampleFieldInterleavedEvenFirst ; <nl> + else <nl> + vs . sample . SampleFormat . SampleFormat = DXVA2_SampleFieldInterleavedOddFirst ; <nl> + } <nl> + else <nl> + { <nl> + vs . sample . SampleFormat . SampleFormat = DXVA2_SampleProgressiveFrame ; <nl> + } <nl> + <nl> vs . sample . PlanarAlpha = DXVA2_Fixed32OpaqueAlpha ( ) ; <nl> vs . sample . SampleData = 0 ; <nl> vs . sample . SrcSurface = surface ; <nl> <nl> + <nl> vs . context = context ; <nl> <nl> if ( ! m_sample . empty ( ) ) <nl> static DXVA2_Fixed32 ConvertRange ( const DXVA2_ValueRange & range , int value , int <nl> return range . DefaultValue ; <nl> } <nl> <nl> - bool CProcessor : : Render ( RECT src , RECT dst , IDirect3DSurface9 * target , REFERENCE_TIME time ) <nl> + bool CProcessor : : Render ( RECT src , RECT dst , IDirect3DSurface9 * target , REFERENCE_TIME time , DWORD flags ) <nl> { <nl> CSingleLock lock ( m_section ) ; <nl> <nl> - / / MinTime and MaxTime are the first and last samples to feed the processor . <nl> - / / MinTime is also the first sample to keep . <nl> - REFERENCE_TIME MinTime = time - m_caps . NumBackwardRefSamples * 2 ; <nl> - REFERENCE_TIME MaxTime = time + m_caps . NumForwardRefSamples * 2 ; <nl> + if ( m_interlace_method ! = g_settings . m_currentVideoSettings . m_InterlaceMethod | | ! m_process ) <nl> + { <nl> + m_interlace_method = g_settings . m_currentVideoSettings . m_InterlaceMethod ; <nl> + if ( ! OpenProcessor ( ) ) <nl> + return false ; <nl> + } <nl> + <nl> + <nl> + / / MinTime and MaxTime are the first and last samples to keep . Delete the rest . <nl> + REFERENCE_TIME MinTime = time - m_max_back_refs * 2 ; <nl> + REFERENCE_TIME MaxTime = time + m_max_fwd_refs * 2 ; <nl> <nl> SSamples : : iterator it = m_sample . begin ( ) ; <nl> while ( it ! = m_sample . end ( ) ) <nl> bool CProcessor : : Render ( RECT src , RECT dst , IDirect3DSurface9 * target , REFERENCE <nl> if ( m_sample . empty ( ) ) <nl> return false ; <nl> <nl> + / / MinTime and MaxTime are now the first and last samples to feed the processor . <nl> + MinTime = time - m_caps . NumBackwardRefSamples * 2 ; <nl> + MaxTime = time + m_caps . NumForwardRefSamples * 2 ; <nl> + <nl> D3DSURFACE_DESC desc ; <nl> CHECK ( target - > GetDesc ( & desc ) ) ; <nl> <nl> bool CProcessor : : Render ( RECT src , RECT dst , IDirect3DSurface9 * target , REFERENCE <nl> <nl> for ( it = m_sample . begin ( ) ; it ! = m_sample . end ( ) & & valid < count ; it + + ) <nl> { <nl> - if ( it - > sample . Start < = MaxTime ) <nl> + if ( it - > sample . Start > = MinTime & & it - > sample . Start < = MaxTime ) <nl> { <nl> DXVA2_VideoSample & vs = samp [ ( it - > sample . Start - MinTime ) / 2 ] ; <nl> vs = it - > sample ; <nl> bool CProcessor : : Render ( RECT src , RECT dst , IDirect3DSurface9 * target , REFERENCE <nl> vs . DstRect = dst ; <nl> if ( vs . End = = 0 ) <nl> vs . End = vs . Start + 2 ; <nl> + <nl> + if ( m_interlace_method = = VS_INTERLACEMETHOD_NONE ) <nl> + vs . SampleFormat . SampleFormat = DXVA2_SampleProgressiveFrame ; <nl> + else if ( ( m_interlace_method = = VS_INTERLACEMETHOD_DXVA_BOB | | m_interlace_method = = VS_INTERLACEMETHOD_DXVA_BEST ) & & vs . SampleFormat . SampleFormat = = DXVA2_SampleProgressiveFrame ) <nl> + vs . SampleFormat . SampleFormat = DXVA2_SampleFieldInterleavedEvenFirst ; <nl> + <nl> valid + + ; <nl> } <nl> } <nl> bool CProcessor : : Render ( RECT src , RECT dst , IDirect3DSurface9 * target , REFERENCE <nl> <nl> DXVA2_VideoProcessBltParams blt = { } ; <nl> blt . TargetFrame = time ; <nl> + if ( flags & RENDER_FLAG_FIELD1 | | ( flags & RENDER_FLAG_LAST & & m_last_field_rendered = = 1 ) ) <nl> + blt . TargetFrame + = 1 ; <nl> + if ( flags & ( RENDER_FLAG_FIELD0 | RENDER_FLAG_FIELD1 ) ) <nl> + m_last_field_rendered = ( flags & RENDER_FLAG_FIELD1 ) ! = 0 ; <nl> blt . TargetRect = dst ; <nl> blt . ConstrictionSize . cx = 0 ; <nl> blt . ConstrictionSize . cy = 0 ; <nl> mmm a / xbmc / cores / dvdplayer / DVDCodecs / Video / DXVA . h <nl> ppp b / xbmc / cores / dvdplayer / DVDCodecs / Video / DXVA . h <nl> <nl> # include < dxva2api . h > <nl> # include < deque > <nl> # include < vector > <nl> + # include " settings / VideoSettings . h " <nl> <nl> namespace DXVA { <nl> <nl> class CProcessor <nl> bool Open ( UINT width , UINT height , unsigned int flags , unsigned int format ) ; <nl> void Close ( ) ; <nl> REFERENCE_TIME Add ( DVDVideoPicture * picture ) ; <nl> - bool Render ( RECT src , RECT dst , IDirect3DSurface9 * target , const REFERENCE_TIME time ) ; <nl> + bool Render ( RECT src , RECT dst , IDirect3DSurface9 * target , const REFERENCE_TIME time , DWORD flags ) ; <nl> unsigned Size ( ) { if ( m_service ) return m_size ; return 0 ; } <nl> <nl> virtual void OnCreateDevice ( ) { } <nl> class CProcessor <nl> protected : <nl> bool UpdateSize ( const DXVA2_VideoDesc & dsc ) ; <nl> bool CreateSurfaces ( ) ; <nl> + bool OpenProcessor ( ) ; <nl> + bool SelectProcessor ( ) ; <nl> <nl> IDirectXVideoProcessorService * m_service ; <nl> IDirectXVideoProcessor * m_process ; <nl> class CProcessor <nl> DXVA2_ValueRange m_saturation ; <nl> REFERENCE_TIME m_time ; <nl> unsigned m_size ; <nl> - <nl> + unsigned m_max_back_refs ; <nl> + unsigned m_max_fwd_refs ; <nl> + EINTERLACEMETHOD m_interlace_method ; <nl> unsigned m_index ; <nl> + unsigned m_last_field_rendered ; <nl> <nl> struct SVideoSample <nl> { <nl> mmm a / xbmc / cores / dvdplayer / DVDPlayerVideo . cpp <nl> ppp b / xbmc / cores / dvdplayer / DVDPlayerVideo . cpp <nl> void CDVDPlayerVideo : : Process ( ) <nl> mFilters = CDVDVideoCodec : : FILTER_DEINTERLACE_ANY ; <nl> else if ( mInt = = VS_INTERLACEMETHOD_DEINTERLACE_HALF ) <nl> mFilters = CDVDVideoCodec : : FILTER_DEINTERLACE_ANY | CDVDVideoCodec : : FILTER_DEINTERLACE_HALFED ; <nl> - else if ( mInt = = VS_INTERLACEMETHOD_AUTO ) <nl> + else if ( mInt = = VS_INTERLACEMETHOD_AUTO & & ! g_renderManager . Supports ( VS_INTERLACEMETHOD_DXVA_ANY ) ) <nl> mFilters = CDVDVideoCodec : : FILTER_DEINTERLACE_ANY | CDVDVideoCodec : : FILTER_DEINTERLACE_FLAGGED ; <nl> <nl> mFilters = m_pVideoCodec - > SetFilters ( mFilters ) ; <nl> void CDVDPlayerVideo : : Process ( ) <nl> { <nl> if ( ( mInt = = VS_INTERLACEMETHOD_DEINTERLACE ) <nl> | | ( mInt = = VS_INTERLACEMETHOD_AUTO & & ( picture . iFlags & DVP_FLAG_INTERLACED ) <nl> - & & ! g_renderManager . Supports ( VS_INTERLACEMETHOD_RENDER_BOB ) ) ) <nl> + & & ! g_renderManager . Supports ( VS_INTERLACEMETHOD_RENDER_BOB ) <nl> + & & ! g_renderManager . Supports ( VS_INTERLACEMETHOD_DXVA_ANY ) ) ) <nl> { <nl> if ( ! sPostProcessType . empty ( ) ) <nl> sPostProcessType + = " , " ; <nl> mmm a / xbmc / settings / VideoSettings . h <nl> ppp b / xbmc / settings / VideoSettings . h <nl> enum EINTERLACEMETHOD <nl> VS_INTERLACEMETHOD_VDPAU_TEMPORAL_SPATIAL_HALF = 15 , <nl> <nl> VS_INTERLACEMETHOD_DEINTERLACE_HALF = 16 , <nl> + <nl> + VS_INTERLACEMETHOD_DXVA_BOB = 17 , <nl> + VS_INTERLACEMETHOD_DXVA_BEST = 18 , <nl> + VS_INTERLACEMETHOD_DXVA_ANY = 19 <nl> } ; <nl> <nl> enum ESCALINGMETHOD <nl> mmm a / xbmc / video / dialogs / GUIDialogVideoSettings . cpp <nl> ppp b / xbmc / video / dialogs / GUIDialogVideoSettings . cpp <nl> void CGUIDialogVideoSettings : : CreateSettings ( ) <nl> entries . push_back ( make_pair ( VS_INTERLACEMETHOD_VDPAU_TEMPORAL_SPATIAL_HALF , 16318 ) ) ; <nl> entries . push_back ( make_pair ( VS_INTERLACEMETHOD_VDPAU_TEMPORAL_HALF , 16317 ) ) ; <nl> entries . push_back ( make_pair ( VS_INTERLACEMETHOD_VDPAU_INVERSE_TELECINE , 16314 ) ) ; <nl> + entries . push_back ( make_pair ( VS_INTERLACEMETHOD_DXVA_BOB , 16320 ) ) ; <nl> + entries . push_back ( make_pair ( VS_INTERLACEMETHOD_DXVA_BEST , 16321 ) ) ; <nl> <nl> / * remove unsupported methods * / <nl> for ( vector < pair < int , int > > : : iterator it = entries . begin ( ) ; it ! = entries . end ( ) ; ) <nl> | Merge pull request from CrystalP / simple - deinterlacing | xbmc/xbmc | 6da111866524f405eb1dda8b9a6d86beb8210f27 | 2011-09-10T03:16:24Z |
mmm a / stdlib / public / core / UnavailableStringAPIs . swift . gyb <nl> ppp b / stdlib / public / core / UnavailableStringAPIs . swift . gyb <nl> extension String { <nl> $ { stringSubscriptComment } <nl> @ available ( <nl> * , unavailable , <nl> - message : " cannot subscript String with an Int , see the documentation comment for discussion " ) <nl> + message : " cannot subscript String with an Int , use a String . Index instead . " ) <nl> public subscript ( i : Int ) - > Character { <nl> Builtin . unreachable ( ) <nl> } <nl> $ { stringSubscriptComment } <nl> $ { stringSubscriptComment } <nl> @ available ( <nl> * , unavailable , <nl> - message : " cannot subscript String with an integer range , see the documentation comment for discussion " ) <nl> + message : " cannot subscript String with an integer range , use a String . Index range instead . " ) <nl> public subscript < R : RangeExpression > ( bounds : R ) - > String where R . Bound = = Int { <nl> Builtin . unreachable ( ) <nl> } <nl> mmm a / test / Constraints / diagnostics . swift <nl> ppp b / test / Constraints / diagnostics . swift <nl> func r23641896 ( ) { <nl> var g = " Hello World " <nl> g . replaceSubrange ( 0 . . . 2 , with : " ce " ) / / expected - error { { cannot convert value of type ' ClosedRange < Int > ' to expected argument type ' Range < String . Index > ' } } <nl> <nl> - _ = g [ 12 ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an Int , see the documentation comment for discussion } } <nl> + _ = g [ 12 ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an Int , use a String . Index instead . } } <nl> <nl> } <nl> <nl> mmm a / test / stdlib / StringDiagnostics . swift <nl> ppp b / test / stdlib / StringDiagnostics . swift <nl> import Foundation <nl> / / Common pitfall : trying to subscript a string with integers . <nl> func testIntSubscripting ( s : String , i : Int ) { <nl> / / FIXME swift - 3 - indexing - model : test new overloads of . . < , . . . <nl> - _ = s [ i ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an Int , see the documentation comment for discussion } } <nl> - _ = s [ 17 ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an Int , see the documentation comment for discussion } } <nl> - _ = s [ i . . . i ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , see the documentation comment for discussion } } <nl> - _ = s [ 17 . . < 20 ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , see the documentation comment for discussion } } <nl> - _ = s [ 17 . . . 20 ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , see the documentation comment for discussion } } <nl> + _ = s [ i ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an Int , use a String . Index instead . } } <nl> + _ = s [ 17 ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an Int , use a String . Index instead . } } <nl> + _ = s [ i . . . i ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , use a String . Index range instead . } } <nl> + _ = s [ 17 . . < 20 ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , use a String . Index range instead . } } <nl> + _ = s [ 17 . . . 20 ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , use a String . Index range instead . } } <nl> <nl> - _ = s [ Range ( i . . . i ) ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , see the documentation comment for discussion } } <nl> - _ = s [ Range ( 17 . . < 20 ) ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , see the documentation comment for discussion } } <nl> - _ = s [ Range ( 17 . . . 20 ) ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , see the documentation comment for discussion } } <nl> + _ = s [ Range ( i . . . i ) ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , use a String . Index range instead . } } <nl> + _ = s [ Range ( 17 . . < 20 ) ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , use a String . Index range instead . } } <nl> + _ = s [ Range ( 17 . . . 20 ) ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , use a String . Index range instead . } } <nl> <nl> - _ = s [ Range ( i . . . i ) ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , see the documentation comment for discussion } } <nl> - _ = s [ Range ( 17 . . < 20 ) ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , see the documentation comment for discussion } } <nl> - _ = s [ Range ( 17 . . . 20 ) ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , see the documentation comment for discussion } } <nl> + _ = s [ Range ( i . . . i ) ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , use a String . Index range instead . } } <nl> + _ = s [ Range ( 17 . . < 20 ) ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , use a String . Index range instead . } } <nl> + _ = s [ Range ( 17 . . . 20 ) ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , use a String . Index range instead . } } <nl> } <nl> <nl> func testNonAmbiguousStringComparisons ( ) { <nl> mmm a / test / stdlib / UnavailableStringAPIs . swift . gyb <nl> ppp b / test / stdlib / UnavailableStringAPIs . swift . gyb <nl> func test_StringSubscriptByInt ( <nl> r1 : Range < Int > , <nl> r2 : ClosedRange < Int > <nl> ) { <nl> - _ = x [ i ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an Int , see the documentation comment for discussion } } { { none } } <nl> - _ = x [ r1 ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , see the documentation comment for discussion } } { { none } } <nl> - _ = x [ r2 ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , see the documentation comment for discussion } } { { none } } <nl> + _ = x [ i ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an Int , use a String . Index instead . } } { { none } } <nl> + _ = x [ r1 ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , use a String . Index range instead . } } { { none } } <nl> + _ = x [ r2 ] / / expected - error { { ' subscript ( _ : ) ' is unavailable : cannot subscript String with an integer range , use a String . Index range instead . } } { { none } } <nl> } <nl> <nl> func test_UTF8View ( s : String . UTF8View , i : String . UTF8View . Index , d : Int ) { <nl> | Update the error message when subscripting String with Int . ( ) | apple/swift | ce28cdee93f923c854957a16c49a6506241ce05e | 2019-09-10T17:23:09Z |
mmm a / windows / xgboost . sln <nl> ppp b / windows / xgboost . sln <nl> <nl> <nl> - Microsoft Visual Studio Solution File , Format Version 11 . 00 <nl> - # Visual Studio 2010 <nl> + Microsoft Visual Studio Solution File , Format Version 12 . 00 <nl> + # Visual Studio Express 2013 for Windows Desktop <nl> + VisualStudioVersion = 12 . 0 . 30723 . 0 <nl> + MinimumVisualStudioVersion = 10 . 0 . 40219 . 1 <nl> Project ( " { 8BC9CEB8 - 8B4A - 11D0 - 8D11 - 00A0C91BC942 } " ) = " xgboost " , " xgboost \ xgboost . vcxproj " , " { 1D6A56A5 - 5557 - 4D20 - 9D50 - 3DE4C30BE00C } " <nl> EndProject <nl> + Project ( " { 8BC9CEB8 - 8B4A - 11D0 - 8D11 - 00A0C91BC942 } " ) = " xgboost_wrapper " , " xgboost_wrapper \ xgboost_wrapper . vcxproj " , " { 2E1AF937 - 28BB - 4832 - B916 - 309C9A0F6C4F } " <nl> + EndProject <nl> Global <nl> GlobalSection ( SolutionConfigurationPlatforms ) = preSolution <nl> Debug | Win32 = Debug | Win32 <nl> Global <nl> { 1D6A56A5 - 5557 - 4D20 - 9D50 - 3DE4C30BE00C } . Release | Win32 . Build . 0 = Release | Win32 <nl> { 1D6A56A5 - 5557 - 4D20 - 9D50 - 3DE4C30BE00C } . Release | x64 . ActiveCfg = Release | x64 <nl> { 1D6A56A5 - 5557 - 4D20 - 9D50 - 3DE4C30BE00C } . Release | x64 . Build . 0 = Release | x64 <nl> + { 2E1AF937 - 28BB - 4832 - B916 - 309C9A0F6C4F } . Debug | Win32 . ActiveCfg = Debug | Win32 <nl> + { 2E1AF937 - 28BB - 4832 - B916 - 309C9A0F6C4F } . Debug | Win32 . Build . 0 = Debug | Win32 <nl> + { 2E1AF937 - 28BB - 4832 - B916 - 309C9A0F6C4F } . Debug | x64 . ActiveCfg = Debug | x64 <nl> + { 2E1AF937 - 28BB - 4832 - B916 - 309C9A0F6C4F } . Debug | x64 . Build . 0 = Debug | x64 <nl> + { 2E1AF937 - 28BB - 4832 - B916 - 309C9A0F6C4F } . Release | Win32 . ActiveCfg = Release | Win32 <nl> + { 2E1AF937 - 28BB - 4832 - B916 - 309C9A0F6C4F } . Release | Win32 . Build . 0 = Release | Win32 <nl> + { 2E1AF937 - 28BB - 4832 - B916 - 309C9A0F6C4F } . Release | x64 . ActiveCfg = Release | x64 <nl> + { 2E1AF937 - 28BB - 4832 - B916 - 309C9A0F6C4F } . Release | x64 . Build . 0 = Release | x64 <nl> EndGlobalSection <nl> GlobalSection ( SolutionProperties ) = preSolution <nl> HideSolutionNode = FALSE <nl> mmm a / windows / xgboost / xgboost . vcxproj <nl> ppp b / windows / xgboost / xgboost . vcxproj <nl> <nl> < ? xml version = " 1 . 0 " encoding = " utf - 8 " ? > <nl> - < Project DefaultTargets = " Build " ToolsVersion = " 4 . 0 " xmlns = " http : / / schemas . microsoft . com / developer / msbuild / 2003 " > <nl> + < Project DefaultTargets = " Build " ToolsVersion = " 12 . 0 " xmlns = " http : / / schemas . microsoft . com / developer / msbuild / 2003 " > <nl> < ItemGroup Label = " ProjectConfigurations " > <nl> < ProjectConfiguration Include = " Debug | Win32 " > <nl> < Configuration > Debug < / Configuration > <nl> <nl> < ConfigurationType > Application < / ConfigurationType > <nl> < UseDebugLibraries > true < / UseDebugLibraries > <nl> < CharacterSet > MultiByte < / CharacterSet > <nl> + < PlatformToolset > v120 < / PlatformToolset > <nl> < / PropertyGroup > <nl> < PropertyGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug | x64 ' " Label = " Configuration " > <nl> < ConfigurationType > Application < / ConfigurationType > <nl> < UseDebugLibraries > true < / UseDebugLibraries > <nl> < CharacterSet > MultiByte < / CharacterSet > <nl> + < PlatformToolset > v120 < / PlatformToolset > <nl> < / PropertyGroup > <nl> < PropertyGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Release | Win32 ' " Label = " Configuration " > <nl> < ConfigurationType > Application < / ConfigurationType > <nl> < UseDebugLibraries > false < / UseDebugLibraries > <nl> < WholeProgramOptimization > true < / WholeProgramOptimization > <nl> < CharacterSet > MultiByte < / CharacterSet > <nl> + < PlatformToolset > v120 < / PlatformToolset > <nl> < / PropertyGroup > <nl> < PropertyGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Release | x64 ' " Label = " Configuration " > <nl> < ConfigurationType > Application < / ConfigurationType > <nl> < UseDebugLibraries > false < / UseDebugLibraries > <nl> < WholeProgramOptimization > true < / WholeProgramOptimization > <nl> < CharacterSet > MultiByte < / CharacterSet > <nl> + < PlatformToolset > v120 < / PlatformToolset > <nl> < / PropertyGroup > <nl> < Import Project = " $ ( VCTargetsPath ) \ Microsoft . Cpp . props " / > <nl> < ImportGroup Label = " ExtensionSettings " > <nl> new file mode 100644 <nl> index 0000000000 . . b167e8d7d1 <nl> mmm / dev / null <nl> ppp b / windows / xgboost / xgboost_wrapper / xgboost_wrapper . vcxproj <nl> <nl> + < ? xml version = " 1 . 0 " encoding = " utf - 8 " ? > <nl> + < Project DefaultTargets = " Build " ToolsVersion = " 12 . 0 " xmlns = " http : / / schemas . microsoft . com / developer / msbuild / 2003 " > <nl> + < ItemGroup Label = " ProjectConfigurations " > <nl> + < ProjectConfiguration Include = " Debug | Win32 " > <nl> + < Configuration > Debug < / Configuration > <nl> + < Platform > Win32 < / Platform > <nl> + < / ProjectConfiguration > <nl> + < ProjectConfiguration Include = " Debug | x64 " > <nl> + < Configuration > Debug < / Configuration > <nl> + < Platform > x64 < / Platform > <nl> + < / ProjectConfiguration > <nl> + < ProjectConfiguration Include = " Release | Win32 " > <nl> + < Configuration > Release < / Configuration > <nl> + < Platform > Win32 < / Platform > <nl> + < / ProjectConfiguration > <nl> + < ProjectConfiguration Include = " Release | x64 " > <nl> + < Configuration > Release < / Configuration > <nl> + < Platform > x64 < / Platform > <nl> + < / ProjectConfiguration > <nl> + < / ItemGroup > <nl> + < PropertyGroup Label = " Globals " > <nl> + < ProjectGuid > { 2E1AF937 - 28BB - 4832 - B916 - 309C9A0F6C4F } < / ProjectGuid > <nl> + < TargetFrameworkVersion > v4 . 5 < / TargetFrameworkVersion > <nl> + < Keyword > ManagedCProj < / Keyword > <nl> + < RootNamespace > xgboost_wrapper < / RootNamespace > <nl> + < / PropertyGroup > <nl> + < Import Project = " $ ( VCTargetsPath ) \ Microsoft . Cpp . Default . props " / > <nl> + < PropertyGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug | Win32 ' " Label = " Configuration " > <nl> + < ConfigurationType > DynamicLibrary < / ConfigurationType > <nl> + < UseDebugLibraries > true < / UseDebugLibraries > <nl> + < PlatformToolset > v120 < / PlatformToolset > <nl> + < CLRSupport > true < / CLRSupport > <nl> + < CharacterSet > Unicode < / CharacterSet > <nl> + < / PropertyGroup > <nl> + < PropertyGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug | x64 ' " Label = " Configuration " > <nl> + < ConfigurationType > DynamicLibrary < / ConfigurationType > <nl> + < UseDebugLibraries > true < / UseDebugLibraries > <nl> + < PlatformToolset > v120 < / PlatformToolset > <nl> + < CLRSupport > true < / CLRSupport > <nl> + < CharacterSet > Unicode < / CharacterSet > <nl> + < / PropertyGroup > <nl> + < PropertyGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Release | Win32 ' " Label = " Configuration " > <nl> + < ConfigurationType > DynamicLibrary < / ConfigurationType > <nl> + < UseDebugLibraries > false < / UseDebugLibraries > <nl> + < PlatformToolset > v120 < / PlatformToolset > <nl> + < CLRSupport > true < / CLRSupport > <nl> + < CharacterSet > Unicode < / CharacterSet > <nl> + < / PropertyGroup > <nl> + < PropertyGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Release | x64 ' " Label = " Configuration " > <nl> + < ConfigurationType > DynamicLibrary < / ConfigurationType > <nl> + < UseDebugLibraries > false < / UseDebugLibraries > <nl> + < PlatformToolset > v120 < / PlatformToolset > <nl> + < CLRSupport > true < / CLRSupport > <nl> + < CharacterSet > Unicode < / CharacterSet > <nl> + < / PropertyGroup > <nl> + < Import Project = " $ ( VCTargetsPath ) \ Microsoft . Cpp . props " / > <nl> + < ImportGroup Label = " ExtensionSettings " > <nl> + < / ImportGroup > <nl> + < ImportGroup Label = " PropertySheets " Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug | Win32 ' " > <nl> + < Import Project = " $ ( UserRootDir ) \ Microsoft . Cpp . $ ( Platform ) . user . props " Condition = " exists ( ' $ ( UserRootDir ) \ Microsoft . Cpp . $ ( Platform ) . user . props ' ) " Label = " LocalAppDataPlatform " / > <nl> + < / ImportGroup > <nl> + < ImportGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug | x64 ' " Label = " PropertySheets " > <nl> + < Import Project = " $ ( UserRootDir ) \ Microsoft . Cpp . $ ( Platform ) . user . props " Condition = " exists ( ' $ ( UserRootDir ) \ Microsoft . Cpp . $ ( Platform ) . user . props ' ) " Label = " LocalAppDataPlatform " / > <nl> + < / ImportGroup > <nl> + < ImportGroup Label = " PropertySheets " Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Release | Win32 ' " > <nl> + < Import Project = " $ ( UserRootDir ) \ Microsoft . Cpp . $ ( Platform ) . user . props " Condition = " exists ( ' $ ( UserRootDir ) \ Microsoft . Cpp . $ ( Platform ) . user . props ' ) " Label = " LocalAppDataPlatform " / > <nl> + < / ImportGroup > <nl> + < ImportGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Release | x64 ' " Label = " PropertySheets " > <nl> + < Import Project = " $ ( UserRootDir ) \ Microsoft . Cpp . $ ( Platform ) . user . props " Condition = " exists ( ' $ ( UserRootDir ) \ Microsoft . Cpp . $ ( Platform ) . user . props ' ) " Label = " LocalAppDataPlatform " / > <nl> + < / ImportGroup > <nl> + < PropertyGroup Label = " UserMacros " / > <nl> + < PropertyGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug | Win32 ' " > <nl> + < LinkIncremental > true < / LinkIncremental > <nl> + < / PropertyGroup > <nl> + < PropertyGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug | x64 ' " > <nl> + < LinkIncremental > true < / LinkIncremental > <nl> + < / PropertyGroup > <nl> + < PropertyGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Release | Win32 ' " > <nl> + < LinkIncremental > false < / LinkIncremental > <nl> + < / PropertyGroup > <nl> + < PropertyGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Release | x64 ' " > <nl> + < LinkIncremental > false < / LinkIncremental > <nl> + < / PropertyGroup > <nl> + < ItemDefinitionGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug | Win32 ' " > <nl> + < ClCompile > <nl> + < WarningLevel > Level3 < / WarningLevel > <nl> + < Optimization > Disabled < / Optimization > <nl> + < PreprocessorDefinitions > WIN32 ; _DEBUG ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> + < PrecompiledHeader > NotUsing < / PrecompiledHeader > <nl> + < / ClCompile > <nl> + < Link > <nl> + < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> + < AdditionalDependencies / > <nl> + < / Link > <nl> + < / ItemDefinitionGroup > <nl> + < ItemDefinitionGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug | x64 ' " > <nl> + < ClCompile > <nl> + < WarningLevel > Level3 < / WarningLevel > <nl> + < Optimization > Disabled < / Optimization > <nl> + < PreprocessorDefinitions > WIN32 ; _DEBUG ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> + < PrecompiledHeader > NotUsing < / PrecompiledHeader > <nl> + < OpenMPSupport > true < / OpenMPSupport > <nl> + < / ClCompile > <nl> + < Link > <nl> + < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> + < AdditionalDependencies > <nl> + < / AdditionalDependencies > <nl> + < / Link > <nl> + < / ItemDefinitionGroup > <nl> + < ItemDefinitionGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Release | Win32 ' " > <nl> + < ClCompile > <nl> + < WarningLevel > Level3 < / WarningLevel > <nl> + < PreprocessorDefinitions > WIN32 ; NDEBUG ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> + < PrecompiledHeader > Use < / PrecompiledHeader > <nl> + < / ClCompile > <nl> + < Link > <nl> + < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> + < AdditionalDependencies / > <nl> + < / Link > <nl> + < / ItemDefinitionGroup > <nl> + < ItemDefinitionGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Release | x64 ' " > <nl> + < ClCompile > <nl> + < WarningLevel > Level3 < / WarningLevel > <nl> + < PreprocessorDefinitions > WIN32 ; NDEBUG ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> + < PrecompiledHeader > NotUsing < / PrecompiledHeader > <nl> + < OpenMPSupport > true < / OpenMPSupport > <nl> + < / ClCompile > <nl> + < Link > <nl> + < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> + < AdditionalDependencies > <nl> + < / AdditionalDependencies > <nl> + < / Link > <nl> + < / ItemDefinitionGroup > <nl> + < ItemGroup > <nl> + < Reference Include = " System " / > <nl> + < Reference Include = " System . Data " / > <nl> + < Reference Include = " System . Xml " / > <nl> + < / ItemGroup > <nl> + < ItemGroup > <nl> + < ClInclude Include = " . . \ . . \ src \ io \ io . h " / > <nl> + < ClInclude Include = " . . \ . . \ src \ io \ simple_dmatrix - inl . hpp " / > <nl> + < ClInclude Include = " . . \ . . \ wrapper \ xgboost_wrapper . h " / > <nl> + < / ItemGroup > <nl> + < ItemGroup > <nl> + < ClCompile Include = " . . \ . . \ src \ io \ io . cpp " / > <nl> + < ClCompile Include = " . . \ . . \ wrapper \ xgboost_wrapper . cpp " / > <nl> + < / ItemGroup > <nl> + < ItemGroup > <nl> + < None Include = " . . \ . . \ wrapper \ xgboost . py " / > <nl> + < / ItemGroup > <nl> + < Import Project = " $ ( VCTargetsPath ) \ Microsoft . Cpp . targets " / > <nl> + < ImportGroup Label = " ExtensionTargets " > <nl> + < / ImportGroup > <nl> + < / Project > <nl> \ No newline at end of file <nl> mmm a / wrapper / xgboost . py <nl> ppp b / wrapper / xgboost . py <nl> <nl> import scipy . sparse as scp <nl> <nl> # set this line correctly <nl> - XGBOOST_PATH = os . path . dirname ( __file__ ) + ' / libxgboostwrapper . so ' <nl> + if os . name = = ' nt ' : <nl> + XGBOOST_PATH = os . path . dirname ( __file__ ) + ' / . . / windows / x64 / Release / xgboost_wrapper . dll ' <nl> + else : <nl> + XGBOOST_PATH = os . path . dirname ( __file__ ) + ' / . . / libxgboostwrapper . so ' <nl> <nl> # load in xgboost library <nl> xglib = ctypes . cdll . LoadLibrary ( XGBOOST_PATH ) <nl> def get_fscore ( self , fmap = ' ' ) : <nl> trees = self . get_dump ( fmap ) <nl> fmap = { } <nl> for tree in trees : <nl> - print tree <nl> + print ( tree ) <nl> for l in tree . split ( ' \ n ' ) : <nl> arr = l . split ( ' [ ' ) <nl> if len ( arr ) = = 1 : <nl> def train ( params , dtrain , num_boost_round = 10 , evals = [ ] , obj = None , feval = None <nl> for i in range ( num_boost_round ) : <nl> bst . update ( dtrain , i ) <nl> if len ( evals ) ! = 0 : <nl> - sys . stderr . write ( evaluate ( bst , evals , i , feval ) + ' \ n ' ) <nl> + sys . stderr . write ( evaluate ( bst , evals , i , feval ) . decode ( ) + ' \ n ' ) <nl> else : <nl> # try customized objective function <nl> for i in range ( num_boost_round ) : <nl> | Merge pull request from giuliohome / master | dmlc/xgboost | 2451ba0f1cb2e076c8c923eaaf5b3e652257712d | 2014-08-27T19:24:09Z |
new file mode 100644 <nl> index 0000000000 . . cdaa57cf60 <nl> mmm / dev / null <nl> ppp b / examples / async / write . php <nl> <nl> + < ? php <nl> + for ( $ i = 0 ; $ i < 10 ; $ i + + ) <nl> + { <nl> + swoole_async_write ( " data . txt " , str_repeat ( ' S ' , 8192 ) , $ i * 8192 , function ( $ file , $ writen ) { <nl> + echo " write [ $ writen ] \ n " ; <nl> + / / return true : write contine . return false : close the file . <nl> + return true ; <nl> + } ) ; <nl> + } <nl> | Added async_write example | swoole/swoole-src | 24e6414c788b923bc27bab2a88e964acdf5b5cd4 | 2014-04-01T11:50:39Z |
mmm a / test / functional / rpc_preciousblock . py <nl> ppp b / test / functional / rpc_preciousblock . py <nl> <nl> from test_framework . util import ( <nl> assert_equal , <nl> connect_nodes_bi , <nl> - sync_chain , <nl> sync_blocks , <nl> ) <nl> <nl> def run_test ( self ) : <nl> assert_equal ( self . nodes [ 0 ] . getbestblockhash ( ) , hashC ) <nl> self . log . info ( " Make Node1 prefer block C " ) <nl> self . nodes [ 1 ] . preciousblock ( hashC ) <nl> - sync_chain ( self . nodes [ 0 : 2 ] ) # wait because node 1 may not have downloaded hashC <nl> + sync_blocks ( self . nodes [ 0 : 2 ] ) # wait because node 1 may not have downloaded hashC <nl> assert_equal ( self . nodes [ 1 ] . getbestblockhash ( ) , hashC ) <nl> self . log . info ( " Make Node1 prefer block G again " ) <nl> self . nodes [ 1 ] . preciousblock ( hashG ) <nl> mmm a / test / functional / test_framework / util . py <nl> ppp b / test / functional / test_framework / util . py <nl> def sync_blocks ( rpc_connections , * , wait = 1 , timeout = 60 ) : <nl> one node already synced to the latest , stable tip , otherwise there ' s a <nl> chance it might return before all nodes are stably synced . <nl> " " " <nl> - # Use getblockcount ( ) instead of waitforblockheight ( ) to determine the <nl> - # initial max height because the two RPCs look at different internal global <nl> - # variables ( chainActive vs latestBlock ) and the former gets updated <nl> - # earlier . <nl> - maxheight = max ( x . getblockcount ( ) for x in rpc_connections ) <nl> - start_time = cur_time = time . time ( ) <nl> - while cur_time < = start_time + timeout : <nl> - tips = [ r . waitforblockheight ( maxheight , int ( wait * 1000 ) ) for r in rpc_connections ] <nl> - if all ( t [ " height " ] = = maxheight for t in tips ) : <nl> - if all ( t [ " hash " ] = = tips [ 0 ] [ " hash " ] for t in tips ) : <nl> - return <nl> - raise AssertionError ( " Block sync failed , mismatched block hashes : { } " . format ( <nl> - " " . join ( " \ n { ! r } " . format ( tip ) for tip in tips ) ) ) <nl> - cur_time = time . time ( ) <nl> - raise AssertionError ( " Block sync to height { } timed out : { } " . format ( <nl> - maxheight , " " . join ( " \ n { ! r } " . format ( tip ) for tip in tips ) ) ) <nl> - <nl> - def sync_chain ( rpc_connections , * , wait = 1 , timeout = 60 ) : <nl> - " " " <nl> - Wait until everybody has the same best block <nl> - " " " <nl> - while timeout > 0 : <nl> + stop_time = time . time ( ) + timeout <nl> + while time . time ( ) < = stop_time : <nl> best_hash = [ x . getbestblockhash ( ) for x in rpc_connections ] <nl> - if best_hash = = [ best_hash [ 0 ] ] * len ( best_hash ) : <nl> + if best_hash . count ( best_hash [ 0 ] ) = = len ( rpc_connections ) : <nl> return <nl> time . sleep ( wait ) <nl> - timeout - = wait <nl> - raise AssertionError ( " Chain sync failed : Best block hashes don ' t match " ) <nl> + raise AssertionError ( " Block sync timed out : { } " . format ( " " . join ( " \ n { ! r } " . format ( b ) for b in best_hash ) ) ) <nl> <nl> def sync_mempools ( rpc_connections , * , wait = 1 , timeout = 60 , flush_scheduler = True ) : <nl> " " " <nl> Wait until everybody has the same transactions in their memory <nl> pools <nl> " " " <nl> - while timeout > 0 : <nl> - pool = set ( rpc_connections [ 0 ] . getrawmempool ( ) ) <nl> - num_match = 1 <nl> - for i in range ( 1 , len ( rpc_connections ) ) : <nl> - if set ( rpc_connections [ i ] . getrawmempool ( ) ) = = pool : <nl> - num_match = num_match + 1 <nl> - if num_match = = len ( rpc_connections ) : <nl> + stop_time = time . time ( ) + timeout <nl> + while time . time ( ) < = stop_time : <nl> + pool = [ set ( r . getrawmempool ( ) ) for r in rpc_connections ] <nl> + if pool . count ( pool [ 0 ] ) = = len ( rpc_connections ) : <nl> if flush_scheduler : <nl> for r in rpc_connections : <nl> r . syncwithvalidationinterfacequeue ( ) <nl> return <nl> time . sleep ( wait ) <nl> - timeout - = wait <nl> - raise AssertionError ( " Mempool sync failed " ) <nl> + raise AssertionError ( " Mempool sync timed out : { } " . format ( " " . join ( " \ n { ! r } " . format ( m ) for m in pool ) ) ) <nl> <nl> # Transaction / Block functions <nl> # # # # # # # # # # # # # # # # # # # # # # # # # # # # # <nl> | Merge : [ qa ] util : Remove unused sync_chain | bitcoin/bitcoin | 0f0229d0c36310eea329716fbc81541c7c3a62b1 | 2018-03-13T16:45:48Z |
mmm a / scripts / metadata - generator . py <nl> ppp b / scripts / metadata - generator . py <nl> <nl> import pathlib <nl> import collections <nl> <nl> + <nl> + def first_layer_files ( directory ) : <nl> + p = pathlib . Path ( directory ) <nl> + files = [ ] <nl> + for file in p . iterdir ( ) : <nl> + if file . is_file ( ) : <nl> + files . append ( str ( file ) . split ( " / " ) [ - 1 ] ) <nl> + return files <nl> + <nl> + <nl> Path = collections . namedtuple ( " Entry " , ( " suffix " , " group " , " name " ) ) <nl> avoid_extensions = [ <nl> " " , <nl> <nl> ) <nl> ) <nl> <nl> - metadata = collections . defaultdict ( str ) <nl> + # metadata = collections . defaultdict ( str ) <nl> + metadata = dict ( ) <nl> for each in paths : <nl> x = each [ - 1 ] . replace ( " " , " _ " ) . rstrip ( ) <nl> metadata_path = " metadata / { } " . format ( x ) <nl> <nl> filename = pathlib . Path ( " { } / data . json " . format ( metadata_path ) ) <nl> filename . touch ( exist_ok = True ) <nl> metadata [ " location " ] = original_paths [ x ] + " / " + x <nl> + metadata [ " files " ] = first_layer_files ( metadata [ " location " ] ) <nl> json_dump = json . dumps ( metadata , indent = 2 ) <nl> filename . write_text ( json_dump ) <nl> | add files object to metadata which shows first layer files only | OpenGenus/cosmos | 066996dd7868021c462b2c67b2efcc7c528551c4 | 2019-05-14T16:25:34Z |
mmm a / Code / CryEngine / RenderDll / XRenderD3D9 / D3DSystem . cpp <nl> ppp b / Code / CryEngine / RenderDll / XRenderD3D9 / D3DSystem . cpp <nl> bool CD3D9Renderer : : SetWindow ( int width , int height ) <nl> <nl> if ( m_hCursor = = NULL & & gEnv - > pConsole - > GetCVar ( " r_MouseUseSystemCursor " ) - > GetIVal ( ) ! = 0 ) <nl> { <nl> - m_hCursor = CreateResourceFromTexture ( this , gEnv - > pConsole - > GetCVar ( " r_MouseCursorTexture " ) - > GetString ( ) , eResourceType_Cursor ) ; <nl> + const char * texture = gEnv - > pConsole - > GetCVar ( " r_MouseCursorTexture " ) - > GetString ( ) ; <nl> + if ( texture & & * texture ) <nl> + { <nl> + m_hCursor = CreateResourceFromTexture ( this , texture , eResourceType_Cursor ) ; <nl> + } <nl> + else <nl> + { <nl> + m_hCursor = : : LoadCursor ( NULL , IDC_ARROW ) ; <nl> + } <nl> } <nl> <nl> / / Moved from Game DLL <nl> | ! B ( CryRenderer ) Fixes when r_MouseUseSystemCursor is enabled and r_MouseCursorTexture is set to empty will correctly use default windows cursor instead of the Warning . | CRYTEK/CRYENGINE | 681859f09cd42c3d0087652b28f3310ca36c83b7 | 2018-03-05T15:42:10Z |
mmm a / db / db_test . cc <nl> ppp b / db / db_test . cc <nl> TEST ( DBTest , TailingIteratorPrefixSeek ) { <nl> ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> } <nl> <nl> + TEST ( DBTest , TailingIteratorIncomplete ) { <nl> + CreateAndReopenWithCF ( { " pikachu " } ) ; <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + read_options . read_tier = kBlockCacheTier ; <nl> + <nl> + std : : string key ( " key " ) ; <nl> + std : : string value ( " value " ) ; <nl> + <nl> + ASSERT_OK ( db_ - > Put ( WriteOptions ( ) , key , value ) ) ; <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options ) ) ; <nl> + iter - > SeekToFirst ( ) ; <nl> + / / we either see the entry or it ' s not in cache <nl> + ASSERT_TRUE ( iter - > Valid ( ) | | iter - > status ( ) . IsIncomplete ( ) ) ; <nl> + <nl> + ASSERT_OK ( db_ - > CompactRange ( nullptr , nullptr ) ) ; <nl> + iter - > SeekToFirst ( ) ; <nl> + / / should still be true after compaction <nl> + ASSERT_TRUE ( iter - > Valid ( ) | | iter - > status ( ) . IsIncomplete ( ) ) ; <nl> + } <nl> + <nl> TEST ( DBTest , BlockBasedTablePrefixIndexTest ) { <nl> / / create a DB with block prefix index <nl> BlockBasedTableOptions table_options ; <nl> mmm a / db / forward_iterator . cc <nl> ppp b / db / forward_iterator . cc <nl> class LevelIterator : public Iterator { <nl> return file_iter_ - > value ( ) ; <nl> } <nl> Status status ( ) const override { <nl> - return status_ ; <nl> + if ( ! status_ . ok ( ) ) { <nl> + return status_ ; <nl> + } else if ( file_iter_ & & ! file_iter_ - > status ( ) . ok ( ) ) { <nl> + return file_iter_ - > status ( ) ; <nl> + } <nl> + return Status : : OK ( ) ; <nl> } <nl> <nl> private : <nl> Status ForwardIterator : : status ( ) const { <nl> } else if ( ! mutable_iter_ - > status ( ) . ok ( ) ) { <nl> return mutable_iter_ - > status ( ) ; <nl> } <nl> + <nl> + for ( auto * it : imm_iters_ ) { <nl> + if ( it & & ! it - > status ( ) . ok ( ) ) { <nl> + return it - > status ( ) ; <nl> + } <nl> + } <nl> + for ( auto * it : l0_iters_ ) { <nl> + if ( it & & ! it - > status ( ) . ok ( ) ) { <nl> + return it - > status ( ) ; <nl> + } <nl> + } <nl> + for ( auto * it : level_iters_ ) { <nl> + if ( it & & ! it - > status ( ) . ok ( ) ) { <nl> + return it - > status ( ) ; <nl> + } <nl> + } <nl> + <nl> return Status : : OK ( ) ; <nl> } <nl> <nl> | ForwardIterator : : status ( ) checks all child iterators | facebook/rocksdb | 105c1e099b8ae61c785bc199fa75aba3fde60ee8 | 2014-07-10T19:43:12Z |
mmm a / include / swift / SIL / SILInstruction . h <nl> ppp b / include / swift / SIL / SILInstruction . h <nl> class SILInstruction : public ValueBase , public llvm : : ilist_node < SILInstruction > { <nl> / / / Return the array of opened archetypes operands for this instruction . <nl> MutableArrayRef < Operand > getOpenedArchetypeOperands ( ) ; <nl> <nl> + / / / Returns true if a given kind of instruciton may have opened archetype <nl> + / / / operands . <nl> + bool mayHaveOpenedArchetypeOperands ( ) const ; <nl> + <nl> unsigned getNumOperands ( ) const { return getAllOperands ( ) . size ( ) ; } <nl> <nl> unsigned getNumOpenedArchetypeOperands ( ) const { <nl> mmm a / lib / SIL / SILInstruction . cpp <nl> ppp b / lib / SIL / SILInstruction . cpp <nl> namespace { <nl> } <nl> <nl> bool visitMarkDependenceInst ( const MarkDependenceInst * RHS ) { <nl> + return true ; <nl> + } <nl> + <nl> + bool visitOpenExistentialRefInst ( const OpenExistentialRefInst * RHS ) { <nl> return true ; <nl> } <nl> <nl> namespace { <nl> return { } ; \ <nl> return I - > getOpenedArchetypeOperands ( ) ; \ <nl> } <nl> + # include " swift / SIL / SILNodes . def " <nl> + } ; <nl> + <nl> + class MayHaveOpenedArchetypeOperandsAccessor <nl> + : public SILVisitor < MayHaveOpenedArchetypeOperandsAccessor , <nl> + bool > { <nl> + public : <nl> + # define VALUE ( CLASS , PARENT ) \ <nl> + bool visit # # CLASS ( const CLASS * I ) { \ <nl> + llvm_unreachable ( " accessing non - instruction " # CLASS ) ; \ <nl> + } <nl> + # define INST ( CLASS , PARENT , MEMBEHAVIOR , RELEASINGBEHAVIOR ) \ <nl> + bool visit # # CLASS ( const CLASS * I ) { \ <nl> + return IMPLEMENTS_METHOD ( CLASS , SILInstruction , \ <nl> + getOpenedArchetypeOperands , \ <nl> + ArrayRef < Operand > ( ) const ) ; \ <nl> + } <nl> # include " swift / SIL / SILNodes . def " <nl> } ; <nl> } / / end anonymous namespace <nl> MutableArrayRef < Operand > SILInstruction : : getOpenedArchetypeOperands ( ) { <nl> return OpenedArchetypeOperandsMutableAccessor ( ) . visit ( this ) ; <nl> } <nl> <nl> + bool SILInstruction : : mayHaveOpenedArchetypeOperands ( ) const { <nl> + return MayHaveOpenedArchetypeOperandsAccessor ( ) . visit ( <nl> + const_cast < SILInstruction * > ( this ) ) ; <nl> + } <nl> + <nl> / / / getOperandNumber - Return which operand this is in the operand list of the <nl> / / / using instruction . <nl> unsigned Operand : : getOperandNumber ( ) const { <nl> mmm a / lib / SILOptimizer / Transforms / CSE . cpp <nl> ppp b / lib / SILOptimizer / Transforms / CSE . cpp <nl> class HashVisitor : public SILInstructionVisitor < HashVisitor , llvm : : hash_code > { <nl> Operands . begin ( ) , <nl> Operands . end ( ) ) ) ; <nl> } <nl> + <nl> hash_code visitMarkDependenceInst ( MarkDependenceInst * X ) { <nl> OperandValueArrayRef Operands ( X - > getAllOperands ( ) ) ; <nl> return llvm : : hash_combine ( <nl> X - > getKind ( ) , X - > getType ( ) , <nl> llvm : : hash_combine_range ( Operands . begin ( ) , Operands . end ( ) ) ) ; <nl> } <nl> + <nl> + hash_code visitOpenExistentialRefInst ( OpenExistentialRefInst * X ) { <nl> + auto ArchetypeTy = cast < ArchetypeType > ( X - > getType ( ) . getSwiftRValueType ( ) ) ; <nl> + auto ConformsTo = ArchetypeTy - > getConformsTo ( ) ; <nl> + return llvm : : hash_combine ( <nl> + X - > getKind ( ) , X - > getOperand ( ) , <nl> + llvm : : hash_combine_range ( ConformsTo . begin ( ) , ConformsTo . end ( ) ) ) ; <nl> + } <nl> } ; <nl> } / / end anonymous namespace <nl> <nl> bool llvm : : DenseMapInfo < SimpleValue > : : isEqual ( SimpleValue LHS , <nl> if ( LHS . isSentinel ( ) | | RHS . isSentinel ( ) ) <nl> return LHSI = = RHSI ; <nl> <nl> + if ( isa < OpenExistentialRefInst > ( LHSI ) & & isa < OpenExistentialRefInst > ( RHSI ) ) { <nl> + if ( LHSI - > getNumOperands ( ) ! = RHSI - > getNumOperands ( ) ) <nl> + return false ; <nl> + <nl> + / / Check operands . <nl> + for ( unsigned i = 0 , e = LHSI - > getNumOperands ( ) ; i ! = e ; + + i ) <nl> + if ( LHSI - > getOperand ( i ) ! = RHSI - > getOperand ( i ) ) <nl> + return false ; <nl> + <nl> + / / Consider the types of two open_existential_ref instructions to be equal , <nl> + / / if the sets of protocols they conform to are equal . <nl> + auto LHSArchetypeTy = <nl> + cast < ArchetypeType > ( LHSI - > getType ( ) . getSwiftRValueType ( ) ) ; <nl> + auto LHSConformsTo = LHSArchetypeTy - > getConformsTo ( ) ; <nl> + auto RHSArchetypeTy = <nl> + cast < ArchetypeType > ( RHSI - > getType ( ) . getSwiftRValueType ( ) ) ; <nl> + auto RHSConformsTo = RHSArchetypeTy - > getConformsTo ( ) ; <nl> + return LHSConformsTo = = RHSConformsTo ; <nl> + } <nl> return LHSI - > getKind ( ) = = RHSI - > getKind ( ) & & LHSI - > isIdenticalTo ( RHSI ) ; <nl> } <nl> <nl> bool llvm : : DenseMapInfo < SimpleValue > : : isEqual ( SimpleValue LHS , <nl> / / CSE Interface <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> <nl> - namespace { <nl> + namespace swift { <nl> <nl> / / / CSE - This pass does a simple depth - first walk over the dominator tree , <nl> / / / eliminating trivially redundant instructions and using simplifyInstruction <nl> class CSE { <nl> } ; <nl> <nl> bool processNode ( DominanceInfoNode * Node ) ; <nl> + bool processOpenExistentialRef ( SILInstruction * Inst , ValueBase * V , <nl> + SILBasicBlock : : iterator & I ) ; <nl> } ; <nl> } / / end anonymous namespace <nl> <nl> bool CSE : : processFunction ( SILFunction & Fm , DominanceInfo * DT ) { <nl> return Changed ; <nl> } <nl> <nl> + namespace { <nl> + / / A very simple cloner for cloning instructions inside <nl> + / / the same function . The only interesting thing it does <nl> + / / is remapping the archetypes when it is required . <nl> + class InstructionCloner : public SILCloner < InstructionCloner > { <nl> + friend class SILCloner < InstructionCloner > ; <nl> + friend class SILVisitor < InstructionCloner > ; <nl> + SILInstruction * Result = nullptr ; <nl> + public : <nl> + InstructionCloner ( SILFunction * F ) : SILCloner ( * F ) { } <nl> + <nl> + static SILInstruction * doIt ( SILInstruction * I ) { <nl> + InstructionCloner TC ( I - > getFunction ( ) ) ; <nl> + return TC . clone ( I ) ; <nl> + } <nl> + <nl> + SILInstruction * clone ( SILInstruction * I ) { <nl> + visit ( I ) ; <nl> + return Result ; <nl> + } <nl> + <nl> + void postProcess ( SILInstruction * Orig , SILInstruction * Cloned ) { <nl> + assert ( Orig - > getFunction ( ) = = & getBuilder ( ) . getFunction ( ) & & <nl> + " cloning between functions is not supported " ) ; <nl> + <nl> + Result = Cloned ; <nl> + SILCloner < InstructionCloner > : : postProcess ( Orig , Cloned ) ; <nl> + } <nl> + SILValue remapValue ( SILValue Value ) { <nl> + return Value ; <nl> + } <nl> + SILBasicBlock * remapBasicBlock ( SILBasicBlock * BB ) { return BB ; } <nl> + } ; <nl> + } <nl> + <nl> + / / / Handle CSE of open_existential_ref instructions . <nl> + / / / Returns true if uses of open_existential_ref can <nl> + / / / be replaced by a dominating instruction . <nl> + / / / \ Inst is the open_existential_ref instruction <nl> + / / / \ V is the dominating open_existential_ref instruction <nl> + / / / \ I is the iterator referring to the current instruction . <nl> + bool CSE : : processOpenExistentialRef ( SILInstruction * Inst , ValueBase * V , <nl> + SILBasicBlock : : iterator & I ) { <nl> + assert ( isa < OpenExistentialRefInst > ( Inst ) ) ; <nl> + llvm : : SmallSetVector < SILInstruction * , 16 > Candidates ; <nl> + / / Collect all candidates that may contain opened archetypes <nl> + / / that need to be replaced . <nl> + for ( auto Use : Inst - > getUses ( ) ) { <nl> + auto User = Use - > getUser ( ) ; <nl> + if ( User - > mayHaveOpenedArchetypeOperands ( ) ) { <nl> + if ( canHandle ( User ) ) { <nl> + auto It = AvailableValues - > begin ( User ) ; <nl> + if ( It ! = AvailableValues - > end ( ) ) { <nl> + return false ; <nl> + } <nl> + } <nl> + Candidates . insert ( User ) ; <nl> + } <nl> + } <nl> + / / Now process candidates . <nl> + auto OldOpenedArchetype = getOpenedArchetypeOf ( Inst ) ; <nl> + auto NewOpenedArchetype = getOpenedArchetypeOf ( dyn_cast < SILInstruction > ( V ) ) ; <nl> + / / TODO : Move it to CSE instance to avoid recreating it every time ? <nl> + SILOpenedArchetypesTracker OpenedArchetypesTracker ( * Inst - > getFunction ( ) ) ; <nl> + / / Register the new archetype to be used . <nl> + OpenedArchetypesTracker . registerOpenedArchetypes ( dyn_cast < SILInstruction > ( V ) ) ; <nl> + / / Use a cloner . It makes copying the instruction and remaping of <nl> + / / opened archetypes trivial . <nl> + InstructionCloner Cloner ( I - > getFunction ( ) ) ; <nl> + Cloner . registerOpenedExistentialRemapping ( <nl> + OldOpenedArchetype - > castTo < ArchetypeType > ( ) , NewOpenedArchetype ) ; <nl> + auto & Builder = Cloner . getBuilder ( ) ; <nl> + Builder . setOpenedArchetypesTracker ( & OpenedArchetypesTracker ) ; <nl> + <nl> + / / Now clone each candidate and replace the opened archetype <nl> + / / by a dominating one . <nl> + for ( auto Candidate : Candidates ) { <nl> + Builder . getOpenedArchetypes ( ) . addOpenedArchetypeOperands ( <nl> + Candidate - > getOpenedArchetypeOperands ( ) ) ; <nl> + Builder . setInsertionPoint ( Candidate ) ; <nl> + auto NewI = Cloner . clone ( Candidate ) ; <nl> + Candidate - > replaceAllUsesWith ( NewI ) ; <nl> + if ( I = = Candidate - > getIterator ( ) ) <nl> + I = NewI - > getIterator ( ) ; <nl> + eraseFromParentWithDebugInsts ( Candidate , I ) ; <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> bool CSE : : processNode ( DominanceInfoNode * Node ) { <nl> SILBasicBlock * BB = Node - > getBlock ( ) ; <nl> bool Changed = false ; <nl> bool CSE : : processNode ( DominanceInfoNode * Node ) { <nl> / / instruction has an available value . If so , use it . <nl> if ( ValueBase * V = AvailableValues - > lookup ( Inst ) ) { <nl> DEBUG ( llvm : : dbgs ( ) < < " SILCSE CSE : " < < * Inst < < " to : " < < * V < < ' \ n ' ) ; <nl> - Inst - > replaceAllUsesWith ( V ) ; <nl> - Inst - > eraseFromParent ( ) ; <nl> - Changed = true ; <nl> - + + NumCSE ; <nl> - continue ; <nl> + / / Instructions producing a new opened archetype need a special handling , <nl> + / / because replacing these intructions may require a replacement <nl> + / / of the opened archetype type operands in some of the uses . <nl> + if ( ! isa < OpenExistentialRefInst > ( Inst ) | | <nl> + processOpenExistentialRef ( Inst , V , I ) ) { <nl> + Inst - > replaceAllUsesWith ( V ) ; <nl> + Inst - > eraseFromParent ( ) ; <nl> + Changed = true ; <nl> + + + NumCSE ; <nl> + continue ; <nl> + } <nl> } <nl> <nl> / / Otherwise , just remember that this value is available . <nl> bool CSE : : canHandle ( SILInstruction * Inst ) { <nl> case ValueKind : : ThinFunctionToPointerInst : <nl> case ValueKind : : PointerToThinFunctionInst : <nl> case ValueKind : : MarkDependenceInst : <nl> + case ValueKind : : OpenExistentialRefInst : <nl> return true ; <nl> default : <nl> return false ; <nl> mmm a / lib / Serialization / SerializeSIL . cpp <nl> ppp b / lib / Serialization / SerializeSIL . cpp <nl> <nl> # include " Serialization . h " <nl> # include " swift / Strings . h " <nl> # include " swift / AST / Module . h " <nl> + # include " swift / SIL / CFG . h " <nl> # include " swift / SIL / SILArgument . h " <nl> # include " swift / SIL / SILModule . h " <nl> # include " swift / SIL / SILUndef . h " <nl> # include " swift / SILOptimizer / Utils / Generics . h " <nl> <nl> # include " llvm / ADT / MapVector . h " <nl> + # include " llvm / ADT / PostOrderIterator . h " <nl> # include " llvm / ADT / SmallString . h " <nl> # include " llvm / ADT / SmallVector . h " <nl> # include " llvm / ADT / StringExtras . h " <nl> void SILSerializer : : writeSILFunction ( const SILFunction & F , bool DeclOnly ) { <nl> / / Assign a value ID to each SILInstruction that has value and to each basic <nl> / / block argument . <nl> unsigned ValueID = 0 ; <nl> - for ( const SILBasicBlock & BB : F ) { <nl> + llvm : : ReversePostOrderTraversal < SILFunction * > RPOT ( <nl> + const_cast < SILFunction * > ( & F ) ) ; <nl> + for ( auto Iter = RPOT . begin ( ) , E = RPOT . end ( ) ; Iter ! = E ; + + Iter ) { <nl> + auto & BB = * * Iter ; <nl> BasicBlockMap . insert ( std : : make_pair ( & BB , BasicID + + ) ) ; <nl> <nl> for ( auto I = BB . bbarg_begin ( ) , E = BB . bbarg_end ( ) ; I ! = E ; + + I ) <nl> void SILSerializer : : writeSILFunction ( const SILFunction & F , bool DeclOnly ) { <nl> ValueIDs [ & SI ] = + + ValueID ; <nl> } <nl> <nl> - for ( const SILBasicBlock & BB : F ) <nl> - writeSILBasicBlock ( BB ) ; <nl> + / / Write SIL basic blocks in the RPOT order <nl> + / / to make sure that instructions defining open archetypes <nl> + / / are serialized before instructions using those opened <nl> + / / archetypes . <nl> + unsigned SerializedBBNum = 0 ; <nl> + for ( auto Iter = RPOT . begin ( ) , E = RPOT . end ( ) ; Iter ! = E ; + + Iter ) { <nl> + auto * BB = * Iter ; <nl> + writeSILBasicBlock ( * BB ) ; <nl> + SerializedBBNum + + ; <nl> + } <nl> + assert ( BasicID = = SerializedBBNum & & " Wrong number of BBs was serialized " ) ; <nl> } <nl> <nl> void SILSerializer : : writeSILBasicBlock ( const SILBasicBlock & BB ) { <nl> mmm a / test / ClangModules / serialization - sil . swift <nl> ppp b / test / ClangModules / serialization - sil . swift <nl> public func testPartialApply ( _ obj : Test ) { <nl> / / CHECK - LABEL : @ _TF4Test16testPartialApplyFPSo4Test_T_ : $ @ convention ( thin ) ( @ owned Test ) - > ( ) { <nl> if let curried1 = obj . normalObject { <nl> / / CHECK : dynamic_method_br [ [ CURRIED1_OBJ : % . + ] ] : $ @ opened ( [ [ CURRIED1_EXISTENTIAL : . + ] ] ) Test , # Test . normalObject ! 1 . foreign , [ [ CURRIED1_TRUE : [ ^ , ] + ] ] , [ [ CURRIED1_FALSE : [ ^ , ] + ] ] <nl> + / / CHECK : [ [ CURRIED1_FALSE ] ] : <nl> / / CHECK : [ [ CURRIED1_TRUE ] ] ( [ [ CURRIED1_METHOD : % . + ] ] : $ @ convention ( objc_method ) ( @ opened ( [ [ CURRIED1_EXISTENTIAL ] ] ) Test ) - > @ autoreleased AnyObject ) : <nl> / / CHECK : [ [ CURRIED1_PARTIAL : % . + ] ] = partial_apply [ [ CURRIED1_METHOD ] ] ( [ [ CURRIED1_OBJ ] ] ) : $ @ convention ( objc_method ) ( @ opened ( [ [ CURRIED1_EXISTENTIAL ] ] ) Test ) - > @ autoreleased AnyObject <nl> / / CHECK : [ [ CURRIED1_THUNK : % . + ] ] = function_ref @ _TTRXFo__oPs9AnyObject__XFo_iT__iPS___ : $ @ convention ( thin ) ( @ in ( ) , @ owned @ callee_owned ( ) - > @ owned AnyObject ) - > @ out AnyObject <nl> / / CHECK : = partial_apply [ [ CURRIED1_THUNK ] ] ( [ [ CURRIED1_PARTIAL ] ] ) : $ @ convention ( thin ) ( @ in ( ) , @ owned @ callee_owned ( ) - > @ owned AnyObject ) - > @ out AnyObject <nl> - / / CHECK : [ [ CURRIED1_FALSE ] ] : <nl> curried1 ( ) <nl> } <nl> if let curried2 = obj . innerPointer { <nl> / / CHECK : dynamic_method_br [ [ CURRIED2_OBJ : % . + ] ] : $ @ opened ( [ [ CURRIED2_EXISTENTIAL : . + ] ] ) Test , # Test . innerPointer ! 1 . foreign , [ [ CURRIED2_TRUE : [ ^ , ] + ] ] , [ [ CURRIED2_FALSE : [ ^ , ] + ] ] <nl> + / / CHECK : [ [ CURRIED2_FALSE ] ] : <nl> / / CHECK : [ [ CURRIED2_TRUE ] ] ( [ [ CURRIED2_METHOD : % . + ] ] : $ @ convention ( objc_method ) ( @ opened ( [ [ CURRIED2_EXISTENTIAL ] ] ) Test ) - > @ unowned_inner_pointer UnsafeMutablePointer < ( ) > ) : <nl> / / CHECK : [ [ CURRIED2_PARTIAL : % . + ] ] = partial_apply [ [ CURRIED2_METHOD ] ] ( [ [ CURRIED2_OBJ ] ] ) : $ @ convention ( objc_method ) ( @ opened ( [ [ CURRIED2_EXISTENTIAL ] ] ) Test ) - > @ unowned_inner_pointer UnsafeMutablePointer < ( ) > <nl> / / CHECK : [ [ CURRIED2_THUNK : % . + ] ] = function_ref @ _TTRXFo__dGSpT___XFo_iT__iGSpT___ : $ @ convention ( thin ) ( @ in ( ) , @ owned @ callee_owned ( ) - > UnsafeMutablePointer < ( ) > ) - > @ out UnsafeMutablePointer < ( ) > <nl> / / CHECK : = partial_apply [ [ CURRIED2_THUNK ] ] ( [ [ CURRIED2_PARTIAL ] ] ) : $ @ convention ( thin ) ( @ in ( ) , @ owned @ callee_owned ( ) - > UnsafeMutablePointer < ( ) > ) - > @ out UnsafeMutablePointer < ( ) > <nl> - / / CHECK : [ [ CURRIED2_FALSE ] ] : <nl> curried2 ( ) <nl> } <nl> if let prop1 = obj . normalObjectProp { <nl> / / CHECK : dynamic_method_br [ [ PROP1_OBJ : % . + ] ] : $ @ opened ( [ [ PROP1_EXISTENTIAL : . + ] ] ) Test , # Test . normalObjectProp ! getter . 1 . foreign , [ [ PROP1_TRUE : [ ^ , ] + ] ] , [ [ PROP1_FALSE : [ ^ , ] + ] ] <nl> + / / CHECK : [ [ PROP1_FALSE ] ] : <nl> / / CHECK : [ [ PROP1_TRUE ] ] ( [ [ PROP1_METHOD : % . + ] ] : $ @ convention ( objc_method ) ( @ opened ( [ [ PROP1_EXISTENTIAL ] ] ) Test ) - > @ autoreleased AnyObject ) : <nl> / / CHECK : [ [ PROP1_PARTIAL : % . + ] ] = partial_apply [ [ PROP1_METHOD ] ] ( [ [ PROP1_OBJ ] ] ) : $ @ convention ( objc_method ) ( @ opened ( [ [ PROP1_EXISTENTIAL ] ] ) Test ) - > @ autoreleased AnyObject <nl> / / CHECK : = apply [ [ PROP1_PARTIAL ] ] ( ) : $ @ callee_owned ( ) - > @ owned AnyObject <nl> - / / CHECK : [ [ PROP1_FALSE ] ] : <nl> _ = prop1 <nl> } <nl> if let prop2 = obj . innerPointerProp { <nl> / / CHECK : dynamic_method_br [ [ PROP2_OBJ : % . + ] ] : $ @ opened ( [ [ PROP2_EXISTENTIAL : . + ] ] ) Test , # Test . innerPointerProp ! getter . 1 . foreign , [ [ PROP2_TRUE : [ ^ , ] + ] ] , [ [ PROP2_FALSE : [ ^ , ] + ] ] <nl> + / / CHECK : [ [ PROP2_FALSE ] ] : <nl> / / CHECK : [ [ PROP2_TRUE ] ] ( [ [ PROP2_METHOD : % . + ] ] : $ @ convention ( objc_method ) ( @ opened ( [ [ PROP2_EXISTENTIAL ] ] ) Test ) - > @ unowned_inner_pointer UnsafeMutablePointer < ( ) > ) : <nl> / / CHECK : [ [ PROP2_PARTIAL : % . + ] ] = partial_apply [ [ PROP2_METHOD ] ] ( [ [ PROP2_OBJ ] ] ) : $ @ convention ( objc_method ) ( @ opened ( [ [ PROP2_EXISTENTIAL ] ] ) Test ) - > @ unowned_inner_pointer UnsafeMutablePointer < ( ) > <nl> / / CHECK : = apply [ [ PROP2_PARTIAL ] ] ( ) : $ @ callee_owned ( ) - > UnsafeMutablePointer < ( ) > <nl> - / / CHECK : [ [ PROP2_FALSE ] ] : <nl> _ = prop2 <nl> } <nl> } / / CHECK : { { ^ } $ } } <nl> mmm a / test / SILOptimizer / cse . sil <nl> ppp b / test / SILOptimizer / cse . sil <nl> bb0 ( % 0 : $ * Builtin . Int64 , % 1 : $ Builtin . NativeObject ) : <nl> % 6 = tuple ( % 4 : $ Builtin . Int64 , % 5 : $ Builtin . Int64 ) <nl> return % 6 : $ ( Builtin . Int64 , Builtin . Int64 ) <nl> } <nl> + <nl> + protocol Proto : class { <nl> + func doThis ( ) <nl> + func doThat ( ) <nl> + } <nl> + <nl> + / / Check that all open_existential_ref instructions are CSEd <nl> + / / CHECK - LABEL : sil @ cse_open_existential : $ @ convention ( thin ) ( @ guaranteed Proto , Bool ) - > ( ) <nl> + / / CHECK : bb0 <nl> + / / CHECK : % [ [ OPENED_EXISTENTIAL : [ 0 - 9 ] + ] ] = open_existential_ref % { { [ 0 - 9 ] + } } : $ Proto to $ @ opened ( " 1B68354A - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto <nl> + / / CHECK : % [ [ WM1 : [ 0 - 9 ] + ] ] = witness_method $ @ opened ( " 1B68354A - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto , # Proto . doThis ! 1 <nl> + / / CHECK : apply % [ [ WM1 ] ] { { . * } } ( % [ [ OPENED_EXISTENTIAL ] ] ) <nl> + / / CHECK : cond_br <nl> + / / CHECK : bb1 : <nl> + / / CHECK - NEXT : % [ [ WM2 : [ 0 - 9 ] + ] ] = witness_method $ @ opened ( " 1B68354A - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto , # Proto . doThat ! 1 <nl> + / / CHECK - NEXT : apply % [ [ WM2 ] ] { { . * } } ( % [ [ OPENED_EXISTENTIAL ] ] ) <nl> + / / CHECK - NEXT : br <nl> + / / CHECK : bb2 : <nl> + / / CHECK - NEXT : apply % [ [ WM1 ] ] { { . * } } ( % [ [ OPENED_EXISTENTIAL ] ] ) <nl> + / / CHECK - NEXT : br <nl> + / / CHECK : bb3 : <nl> + / / CHECK - NEXT : tuple <nl> + / / CHECK - NEXT : return <nl> + sil @ cse_open_existential : $ @ convention ( thin ) ( @ guaranteed Proto , Bool ) - > ( ) { <nl> + bb0 ( % 0 : $ Proto , % 1 : $ Bool ) : <nl> + % 4 = open_existential_ref % 0 : $ Proto to $ @ opened ( " 1B68354A - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto <nl> + % 5 = witness_method $ @ opened ( " 1B68354A - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto , # Proto . doThis ! 1 , % 4 : $ @ opened ( " 1B68354A - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto : $ @ convention ( witness_method ) < τ_0_0 where τ_0_0 : Proto > ( @ guaranteed τ_0_0 ) - > ( ) <nl> + % 6 = apply % 5 < @ opened ( " 1B68354A - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto > ( % 4 ) : $ @ convention ( witness_method ) < τ_0_0 where τ_0_0 : Proto > ( @ guaranteed τ_0_0 ) - > ( ) <nl> + % 7 = struct_extract % 1 : $ Bool , # Bool . _value <nl> + cond_br % 7 , bb1 , bb2 <nl> + <nl> + bb1 : <nl> + % 9 = open_existential_ref % 0 : $ Proto to $ @ opened ( " 1B685052 - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto <nl> + % 10 = witness_method $ @ opened ( " 1B685052 - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto , # Proto . doThat ! 1 , % 9 : $ @ opened ( " 1B685052 - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto : $ @ convention ( witness_method ) < τ_0_0 where τ_0_0 : Proto > ( @ guaranteed τ_0_0 ) - > ( ) <nl> + % 11 = apply % 10 < @ opened ( " 1B685052 - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto > ( % 9 ) : $ @ convention ( witness_method ) < τ_0_0 where τ_0_0 : Proto > ( @ guaranteed τ_0_0 ) - > ( ) <nl> + br bb3 <nl> + <nl> + bb2 : / / Preds : bb0 <nl> + % 13 = open_existential_ref % 0 : $ Proto to $ @ opened ( " 1B6851A6 - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto <nl> + % 14 = witness_method $ @ opened ( " 1B6851A6 - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto , # Proto . doThis ! 1 , % 13 : $ @ opened ( " 1B6851A6 - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto : $ @ convention ( witness_method ) < τ_0_0 where τ_0_0 : Proto > ( @ guaranteed τ_0_0 ) - > ( ) <nl> + % 15 = apply % 14 < @ opened ( " 1B6851A6 - 4796 - 11E6 - B7DF - B8E856428C60 " ) Proto > ( % 13 ) : $ @ convention ( witness_method ) < τ_0_0 where τ_0_0 : Proto > ( @ guaranteed τ_0_0 ) - > ( ) <nl> + br bb3 <nl> + <nl> + bb3 : <nl> + % 17 = tuple ( ) <nl> + return % 17 : $ ( ) <nl> + } <nl> + <nl> mmm a / test / Serialization / Inputs / def_basic . sil <nl> ppp b / test / Serialization / Inputs / def_basic . sil <nl> bb1 : <nl> / / CHECK - LABEL : sil public_external [ fragile ] @ test2 : $ @ convention ( thin ) ( Int ) - > ( ) <nl> sil [ fragile ] @ test2 : $ @ convention ( thin ) ( Int ) - > ( ) { <nl> / / CHECK : bb1 : <nl> - / / CHECK : return % 5 : $ ( ) <nl> + / / CHECK : % [ [ VAL : [ 0 - 9 ] + ] ] = tuple ( ) <nl> + / / CHECK : br bb2 <nl> / / CHECK : bb2 : <nl> - / / CHECK : % 5 = tuple ( ) <nl> - / / CHECK : br bb1 <nl> + / / CHECK : return % [ [ VAL ] ] : $ ( ) <nl> bb0 ( % 0 : $ Int ) : <nl> br bb2 <nl> bb1 : <nl> bb3 ( % 6 : $ Builtin . Word ) : <nl> sil [ fragile ] @ test_cond_branch_basic_block_args : $ @ convention ( thin ) ( Int , Builtin . Int1 ) - > Int { <nl> bb0 ( % 0 : $ Int , % 1 : $ Builtin . Int1 ) : <nl> cond_br % 1 , bb1 ( % 0 : $ Int ) , bb2 ( % 0 : $ Int ) <nl> - / / CHECK : cond_br % 1 , bb1 ( % 0 : $ Int ) , bb2 ( % 0 : $ Int ) <nl> + / / CHECK : cond_br % 1 , bb2 ( % 0 : $ Int ) , bb1 ( % 0 : $ Int ) <nl> bb1 ( % 3 : $ Int ) : <nl> br bb3 ( % 3 : $ Int ) <nl> bb2 ( % 2 : $ Int ) : <nl> bb1 : <nl> bb2 : <nl> % 7 = function_ref @ _TF6switch1aFT_T_ : $ @ convention ( thin ) ( ) - > ( ) <nl> % 8 = apply % 7 ( ) : $ @ convention ( thin ) ( ) - > ( ) <nl> - br bb5 / / CHECK : br <nl> + br bb5 <nl> <nl> bb3 ( % 10 : $ Int ) : <nl> / / CHECK : unchecked_enum_data { { % . * } } : $ MaybePair , # MaybePair . Left ! enumelt . 1 <nl> % x = unchecked_enum_data % 3 : $ MaybePair , # MaybePair . Left ! enumelt . 1 <nl> br bb4 ( % x : $ Int ) <nl> + / / CHECK : br <nl> <nl> bb4 ( % y : $ Int ) : <nl> % 12 = function_ref @ _TF6switch1bFT_T_ : $ @ convention ( thin ) ( ) - > ( ) <nl> bb3 : <nl> / / CHECK - LABEL : sil public_external [ fragile ] @ test_switch_value : $ @ convention ( thin ) ( Builtin . Word ) - > ( ) <nl> sil [ fragile ] @ test_switch_value : $ @ convention ( thin ) ( Builtin . Word ) - > ( ) { <nl> bb0 ( % 0 : $ Builtin . Word ) : <nl> - / / CHECK : switch_value % { { . * } } : $ Builtin . Word , case % 1 : bb1 , case % 2 : bb2 <nl> + / / CHECK : switch_value % { { . * } } : $ Builtin . Word , case % 1 : bb2 , case % 2 : bb1 <nl> % 1 = integer_literal $ Builtin . Word , 1 <nl> % 2 = integer_literal $ Builtin . Word , 2 <nl> switch_value % 0 : $ Builtin . Word , case % 1 : bb1 , case % 2 : bb2 <nl> sil [ fragile ] @ block_invoke : $ @ convention ( c ) ( @ inout_aliasable @ block_storage I <nl> / / CHECK - LABEL : sil public_external [ fragile ] @ test_try_apply : $ @ convention ( thin ) ( @ convention ( thin ) ( ) - > @ error Error ) - > @ error Error { <nl> sil [ fragile ] @ test_try_apply : $ @ convention ( thin ) ( @ convention ( thin ) ( ) - > @ error Error ) - > @ error Error { <nl> bb0 ( % 0 : $ @ convention ( thin ) ( ) - > @ error Error ) : <nl> - / / CHECK : try_apply % 0 ( ) : $ @ convention ( thin ) ( ) - > @ error Error , normal bb1 , error bb2 <nl> + / / CHECK : try_apply % 0 ( ) : $ @ convention ( thin ) ( ) - > @ error Error , normal bb2 , error bb1 <nl> try_apply % 0 ( ) : $ @ convention ( thin ) ( ) - > @ error Error , normal bb1 , error bb2 <nl> <nl> bb1 ( % 1 : $ ( ) ) : <nl> mmm a / test / Serialization / transparent . swift <nl> ppp b / test / Serialization / transparent . swift <nl> func wrap_br ( ) { <nl> / / SIL : bb0 ( % 0 : $ MaybePair ) : <nl> / / SIL : retain_value % 0 : $ MaybePair <nl> / / SIL : switch_enum % 0 : $ MaybePair , case # MaybePair . Neither ! enumelt : bb [ [ CASE1 : [ 0 - 9 ] + ] ] , case # MaybePair . Left ! enumelt . 1 : bb [ [ CASE2 : [ 0 - 9 ] + ] ] , case # MaybePair . Right ! enumelt . 1 : bb [ [ CASE3 : [ 0 - 9 ] + ] ] , case # MaybePair . Both ! enumelt . 1 : bb [ [ CASE4 : [ 0 - 9 ] + ] ] <nl> - / / SIL : bb [ [ CASE1 ] ] : <nl> - / / SIL : bb [ [ CASE2 ] ] ( % { { . * } } : $ Int32 ) : <nl> - / / SIL : bb [ [ CASE3 ] ] ( % { { . * } } : $ String ) : <nl> / / SIL : bb [ [ CASE4 ] ] ( % { { . * } } : $ ( Int32 , String ) ) : <nl> + / / SIL : bb [ [ CASE3 ] ] ( % { { . * } } : $ String ) : <nl> + / / SIL : bb [ [ CASE2 ] ] ( % { { . * } } : $ Int32 ) : <nl> + / / SIL : bb [ [ CASE1 ] ] : <nl> func test_switch ( u : MaybePair ) { <nl> do_switch ( u : u ) <nl> } <nl> | Merge pull request from swiftix / cse - of - open - existentials | apple/swift | 865b23a06208829ca8fd2a21ab0ef2678e9f2a3f | 2016-07-14T15:22:48Z |
mmm a / src / runtime / runtime - typedarray . cc <nl> ppp b / src / runtime / runtime - typedarray . cc <nl> namespace { <nl> return true ; \ <nl> } else if ( x > y ) { \ <nl> return false ; \ <nl> - } else if ( x = = 0 & & x = = y ) { \ <nl> - return std : : signbit ( static_cast < double > ( x ) ) ? true : false ; \ <nl> - } else if ( std : : isnan ( static_cast < double > ( x ) ) ) { \ <nl> - return false ; \ <nl> + } else { \ <nl> + double _x = x , _y = y ; \ <nl> + if ( x = = 0 & & x = = y ) { \ <nl> + / * - 0 . 0 is less than + 0 . 0 * / \ <nl> + return std : : signbit ( _x ) & & ! std : : signbit ( _y ) ; \ <nl> + } else if ( ! std : : isnan ( _x ) & & std : : isnan ( _y ) ) { \ <nl> + / * number is less than NaN * / \ <nl> + return true ; \ <nl> + } \ <nl> } \ <nl> - return true ; \ <nl> + return false ; \ <nl> } <nl> <nl> TYPED_ARRAYS ( TYPED_ARRAY_SORT_COMPAREFN ) <nl> RUNTIME_FUNCTION ( Runtime_TypedArraySortFast ) { <nl> ASSIGN_RETURN_FAILURE_ON_EXCEPTION ( <nl> isolate , array , JSTypedArray : : Validate ( isolate , target_obj , method ) ) ; <nl> <nl> - / / This line can be remove when JSTypedArray : : Validate throws <nl> + / / This line can be removed when JSTypedArray : : Validate throws <nl> / / if array . [ [ ViewedArrayBuffer ] ] is neutered ( v8 : 4648 ) <nl> if ( V8_UNLIKELY ( array - > WasNeutered ( ) ) ) return * array ; <nl> <nl> new file mode 100644 <nl> index 00000000000 . . b31a8760468 <nl> mmm / dev / null <nl> ppp b / test / mjsunit / regress / regress - 696251 . js <nl> <nl> + / / Copyright 2017 the V8 project authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + var a = new Uint8Array ( 1000 ) ; <nl> + a . fill ( 255 ) ; <nl> + a . sort ( ) ; <nl> | [ typedarrays ] Fix Out of Bound Access in TypedArraySortFast | v8/v8 | cd3a76d56f544c5c90cd262d2576b7bb1ef04c13 | 2017-02-27T11:41:25Z |
mmm a / ios / sdk / WeexSDK / Sources / Component / WXScrollerComponent . mm <nl> ppp b / ios / sdk / WeexSDK / Sources / Component / WXScrollerComponent . mm <nl> - ( void ) adjustForRTL <nl> <nl> / / this is scroll rtl solution . <nl> / / scroll layout not use direction , use self tranform <nl> - if ( self . view & & _flexCssNode & & _flexCssNode - > getLayoutDirectionFromPathNode ( ) = = WeexCore : : kDirectionRTL <nl> - ) { <nl> + if ( self . view & & [ self isDirectionRTL ] ) { <nl> if ( _transform ) { <nl> self . view . layer . transform = CATransform3DConcat ( self . view . layer . transform , CATransform3DScale ( CATransform3DIdentity , - 1 , 1 , 1 ) ) ; <nl> } else { <nl> | [ ios ] fixed layout . cpp crash in scrollercomponent | apache/incubator-weex | 0e80f83cbc442be7b1f159f419176a9f9748dda1 | 2019-01-10T06:30:29Z |
mmm a / test / common_methods_invocations . py <nl> ppp b / test / common_methods_invocations . py <nl> def gather_variable ( shape , index_dim , max_indices , duplicate = False ) : <nl> <nl> <nl> def bernoulli_scalar ( ) : <nl> - return torch . tensor ( 0 , dtype = torch . uint8 ) . bernoulli_ ( ) <nl> + return torch . tensor ( 0 , dtype = torch . bool ) . bernoulli_ ( ) <nl> <nl> <nl> def mask_not_all_zeros ( shape ) : <nl> def method_tests ( ) : <nl> ( ' masked_select ' , ( M , ) , ( mask_not_all_zeros ( ( M , M ) ) , ) , ' broadcast_lhs ' ) , <nl> ( ' masked_select ' , ( M , 1 , M ) , ( mask_not_all_zeros ( ( M , M ) ) , ) , <nl> ' broadcast_all ' ) , <nl> - ( ' masked_select ' , ( ) , ( torch . tensor ( 1 , dtype = torch . uint8 ) , ) , ' scalar ' ) , <nl> - ( ' masked_select ' , ( M , M ) , ( torch . tensor ( 1 , dtype = torch . uint8 ) , ) , ' scalar_broadcast_rhs ' ) , <nl> + ( ' masked_select ' , ( ) , ( torch . tensor ( 1 , dtype = torch . bool ) , ) , ' scalar ' ) , <nl> + ( ' masked_select ' , ( M , M ) , ( torch . tensor ( 1 , dtype = torch . bool ) , ) , ' scalar_broadcast_rhs ' ) , <nl> ( ' masked_select ' , ( ) , ( mask_not_all_zeros ( ( M , M ) ) , ) , ' scalar_broadcast_lhs ' ) , <nl> - ( ' masked_fill ' , ( M , M ) , ( torch . ByteTensor ( M , M ) . bernoulli_ ( ) , 10 ) ) , <nl> - ( ' masked_fill ' , ( M , M ) , ( torch . ByteTensor ( M , M ) . bernoulli_ ( ) , ( ) ) , ' tensor ' ) , <nl> - ( ' masked_fill ' , ( M , ) , ( torch . ByteTensor ( M , M ) . bernoulli_ ( ) , 10 ) , ' broadcast_lhs ' ) , <nl> - ( ' masked_fill ' , ( M , M ) , ( torch . ByteTensor ( M , ) . bernoulli_ ( ) , 10 ) , ' broadcast_rhs ' ) , <nl> - ( ' masked_fill ' , ( ) , ( torch . tensor ( 0 , dtype = torch . uint8 ) . bernoulli_ ( ) , 10 ) , ' scalar ' ) , <nl> - ( ' masked_fill ' , ( ) , ( torch . tensor ( 0 , dtype = torch . uint8 ) . bernoulli_ ( ) , ( ) ) , <nl> + ( ' masked_fill ' , ( M , M ) , ( torch . BoolTensor ( M , M ) . bernoulli_ ( ) , 10 ) ) , <nl> + ( ' masked_fill ' , ( M , M ) , ( torch . BoolTensor ( M , M ) . bernoulli_ ( ) , ( ) ) , ' tensor ' ) , <nl> + ( ' masked_fill ' , ( M , ) , ( torch . BoolTensor ( M , M ) . bernoulli_ ( ) , 10 ) , ' broadcast_lhs ' ) , <nl> + ( ' masked_fill ' , ( M , M ) , ( torch . BoolTensor ( M , ) . bernoulli_ ( ) , 10 ) , ' broadcast_rhs ' ) , <nl> + ( ' masked_fill ' , ( ) , ( torch . tensor ( 0 , dtype = torch . bool ) . bernoulli_ ( ) , 10 ) , ' scalar ' ) , <nl> + ( ' masked_fill ' , ( ) , ( torch . tensor ( 0 , dtype = torch . bool ) . bernoulli_ ( ) , ( ) ) , <nl> ' scalar_variable ' ) , <nl> - ( ' masked_fill ' , ( M , M ) , ( torch . tensor ( 0 , dtype = torch . uint8 ) . bernoulli_ ( ) , 10 ) , <nl> + ( ' masked_fill ' , ( M , M ) , ( torch . tensor ( 0 , dtype = torch . bool ) . bernoulli_ ( ) , 10 ) , <nl> ' scalar_broadcast_rhs ' ) , <nl> - ( ' masked_scatter ' , ( M , M ) , ( torch . ByteTensor ( M , M ) . bernoulli_ ( ) , ( M , M ) ) ) , <nl> - ( ' masked_scatter ' , ( M , ) , ( torch . ByteTensor ( M , M ) . bernoulli_ ( ) , ( M , M ) ) , <nl> + ( ' masked_scatter ' , ( M , M ) , ( torch . BoolTensor ( M , M ) . bernoulli_ ( ) , ( M , M ) ) ) , <nl> + ( ' masked_scatter ' , ( M , ) , ( torch . BoolTensor ( M , M ) . bernoulli_ ( ) , ( M , M ) ) , <nl> ' broadcast_lhs ' ) , <nl> - ( ' masked_scatter ' , ( M , M ) , ( torch . ByteTensor ( M , ) . bernoulli_ ( ) , ( M , M ) ) , <nl> + ( ' masked_scatter ' , ( M , M ) , ( torch . BoolTensor ( M , ) . bernoulli_ ( ) , ( M , M ) ) , <nl> ' broadcast_rhs ' ) , <nl> ( ' masked_scatter ' , ( M , M ) , ( bernoulli_scalar ( ) , ( M , M ) ) , ' scalar ' ) , <nl> ( ' masked_scatter ' , ( M , M ) , ( bernoulli_scalar ( ) , ( M , M ) ) , <nl> mmm a / test / test_autograd . py <nl> ppp b / test / test_autograd . py <nl> def check_index ( x , y , idx ) : <nl> check_index ( x , y , ( 1 , slice ( 2 , None ) ) ) <nl> check_index ( x , y , ( slice ( None , None ) , slice ( 2 , None ) ) ) <nl> check_index ( x , y , torch . LongTensor ( [ 0 , 2 ] ) ) <nl> - check_index ( x , y , torch . rand ( 4 , 4 ) . bernoulli ( ) . byte ( ) ) <nl> + check_index ( x , y , torch . rand ( 4 , 4 ) . bernoulli ( ) . bool ( ) ) <nl> check_index ( x , y , ( Ellipsis , slice ( 2 , None ) ) ) <nl> check_index ( x , y , ( [ 0 ] , [ 0 ] ) ) <nl> check_index ( x , y , ( [ 1 , 2 , 3 ] , [ 0 ] ) ) <nl> def test_setitem ( self ) : <nl> 3 ] ) , requires_grad = False ) , [ 2 , 4 ] , slice ( None ) ] ) <nl> <nl> def test_setitem_mask ( self ) : <nl> - mask = torch . ByteTensor ( 5 , 5 ) . bernoulli_ ( ) <nl> + mask = torch . BoolTensor ( 5 , 5 ) . bernoulli_ ( ) <nl> self . _test_setitem ( ( 5 , 5 ) , Variable ( mask ) ) <nl> self . _test_setitem ( ( 5 , ) , Variable ( mask [ 0 ] ) ) <nl> self . _test_setitem ( ( 1 , ) , Variable ( mask [ 0 , 0 : 1 ] ) ) <nl> mmm a / test / test_jit . py <nl> ppp b / test / test_jit . py <nl> def addmm ( mat , mat1 , mat2 , alpha , beta ) : <nl> <nl> def test_index_put ( self ) : <nl> ten = torch . zeros ( 3 , 3 ) <nl> - mask = torch . Tensor ( [ [ True , True , True ] , <nl> + mask = torch . tensor ( [ [ True , True , True ] , <nl> [ True , False , False ] , <nl> - [ True , True , False ] ] ) . byte ( ) <nl> + [ True , True , False ] ] ) <nl> <nl> def test_fn ( ten , mask ) : <nl> ten [ mask ] = torch . ones ( 6 ) <nl> | Fixed masking warnings in tests ( ) | pytorch/pytorch | 1ea1d7f0958816009346dc20f6740c65f66298ed | 2019-08-29T19:13:52Z |
mmm a / docs / root / configuration / http / http_conn_man / headers . rst <nl> ppp b / docs / root / configuration / http / http_conn_man / headers . rst <nl> Supported variable names are : <nl> key : " x - request - start " <nl> value : " % START_TIME ( % s . % 3f ) % " <nl> append : true <nl> + <nl> + % RESPONSE_FLAGS % <nl> + Additional details about the response or connection , if any . Possible values and their meanings <nl> + are listed in the access log formatter : ref : ` documentation < config_access_log_format_response_flags > ` . <nl> + <nl> + % RESPONSE_CODE_DETAILS % <nl> + Response code details provides additional information about the HTTP response code , such as <nl> + who set it ( the upstream or envoy ) and why . <nl> \ No newline at end of file <nl> mmm a / docs / root / version_history / current . rst <nl> ppp b / docs / root / version_history / current . rst <nl> New Features <nl> * request_id : added to : ref : ` always_set_request_id_in_response setting < envoy_v3_api_field_extensions . filters . network . http_connection_manager . v3 . HttpConnectionManager . always_set_request_id_in_response > ` <nl> to set : ref : ` x - request - id < config_http_conn_man_headers_x - request - id > ` header in response even if <nl> tracing is not forced . <nl> + * router : add support for RESPONSE_FLAGS and RESPONSE_CODE_DETAILS : ref : ` header formatters <nl> + < config_http_conn_man_headers_custom_request_headers > ` . <nl> * router : more fine grained internal redirect configs are added to the : ref ` internal_redirect_policy <nl> < envoy_api_field_router . RouterAction . internal_redirect_policy > ` field . <nl> * runtime : add new gauge : ref : ` deprecated_feature_seen_since_process_start < runtime_stats > ` that gets reset across hot restarts . <nl> mmm a / source / common / router / header_formatter . cc <nl> ppp b / source / common / router / header_formatter . cc <nl> StreamInfoHeaderFormatter : : StreamInfoHeaderFormatter ( absl : : string_view field_nam <nl> } else if ( field_name = = " HOSTNAME " ) { <nl> std : : string hostname = Envoy : : AccessLog : : AccessLogFormatUtils : : getHostname ( ) ; <nl> field_extractor_ = [ hostname ] ( const StreamInfo : : StreamInfo & ) { return hostname ; } ; <nl> + } else if ( field_name = = " RESPONSE_FLAGS " ) { <nl> + field_extractor_ = [ ] ( const StreamInfo : : StreamInfo & stream_info ) { <nl> + return StreamInfo : : ResponseFlagUtils : : toShortString ( stream_info ) ; <nl> + } ; <nl> + } else if ( field_name = = " RESPONSE_CODE_DETAILS " ) { <nl> + field_extractor_ = [ ] ( const StreamInfo : : StreamInfo & stream_info ) - > std : : string { <nl> + if ( stream_info . responseCodeDetails ( ) . has_value ( ) ) { <nl> + return stream_info . responseCodeDetails ( ) . value ( ) ; <nl> + } <nl> + return " " ; <nl> + } ; <nl> } else { <nl> throw EnvoyException ( fmt : : format ( " field ' { } ' not supported as custom header " , field_name ) ) ; <nl> } <nl> mmm a / test / common / router / header_formatter_test . cc <nl> ppp b / test / common / router / header_formatter_test . cc <nl> TEST ( HeaderParserTest , TestParseInternal ) { <nl> { " % PER_REQUEST_STATE ( testing ) % " , { " test_value " } , { } } , <nl> { " % REQ ( x - request - id ) % " , { " 123 " } , { } } , <nl> { " % START_TIME % " , { " 2018 - 04 - 03T23 : 06 : 09 . 123Z " } , { } } , <nl> + { " % RESPONSE_FLAGS % " , { " LR " } , { } } , <nl> + { " % RESPONSE_CODE_DETAILS % " , { " via_upstream " } , { } } , <nl> <nl> / / Unescaped % <nl> { " % " , { } , { " Invalid header configuration . Un - escaped % at position 0 " } } , <nl> TEST ( HeaderParserTest , TestParseInternal ) { <nl> ON_CALL ( stream_info , filterState ( ) ) . WillByDefault ( ReturnRef ( filter_state ) ) ; <nl> ON_CALL ( Const ( stream_info ) , filterState ( ) ) . WillByDefault ( ReturnRef ( * filter_state ) ) ; <nl> <nl> + ON_CALL ( stream_info , hasResponseFlag ( StreamInfo : : ResponseFlag : : LocalReset ) ) <nl> + . WillByDefault ( Return ( true ) ) ; <nl> + <nl> + absl : : optional < std : : string > rc_details { " via_upstream " } ; <nl> + ON_CALL ( stream_info , responseCodeDetails ( ) ) . WillByDefault ( ReturnRef ( rc_details ) ) ; <nl> + <nl> for ( const auto & test_case : test_cases ) { <nl> Protobuf : : RepeatedPtrField < envoy : : config : : core : : v3 : : HeaderValueOption > to_add ; <nl> envoy : : config : : core : : v3 : : HeaderValueOption * header = to_add . Add ( ) ; <nl> | router : add two header formatter operators ( ) | envoyproxy/envoy | 72b930b3a148abbb2f5efa1e6ad04d7ea210830c | 2020-05-20T20:52:29Z |
mmm a / platform / windows / detect . py <nl> ppp b / platform / windows / detect . py <nl> def configure ( env ) : <nl> <nl> if ( env [ " openmp " ] ) : <nl> env . Append ( CPPFLAGS = [ ' - fopenmp ' ] ) <nl> - env . Append ( LIBS = [ ' gomp ' ] ) <nl> + env . Append ( LINKFLAGS = [ ' - fopenmp ' ] ) <nl> <nl> # # Compile flags <nl> <nl> mmm a / thirdparty / thekla_atlas / nvcore / Debug . cpp <nl> ppp b / thirdparty / thekla_atlas / nvcore / Debug . cpp <nl> namespace <nl> # pragma warning ( disable : 4748 ) <nl> static NV_NOINLINE int backtrace ( void * trace [ ] , int maxcount ) { <nl> CONTEXT ctx = { 0 } ; <nl> + / / - - GODOT start - - <nl> # if NV_CPU_X86 & & ! NV_CPU_X86_64 <nl> ctx . ContextFlags = CONTEXT_CONTROL ; <nl> + # if NV_CC_MSVC <nl> _asm { <nl> call x <nl> x : pop eax <nl> namespace <nl> mov ctx . Ebp , ebp <nl> mov ctx . Esp , esp <nl> } <nl> + # else <nl> + register long unsigned int ebp asm ( " ebp " ) ; <nl> + ctx . Eip = ( DWORD ) __builtin_return_address ( 0 ) ; <nl> + ctx . Ebp = ebp ; <nl> + ctx . Esp = ( DWORD ) __builtin_frame_address ( 0 ) ; <nl> + # endif <nl> + / / - - GODOT end - - <nl> # else <nl> RtlCaptureContext ( & ctx ) ; / / Not implemented correctly in x86 . <nl> # endif <nl> | Merge pull request from hpvb / fix - thekla - ming - 32bit - build | godotengine/godot | 747d1c96a493883a70d2e3b0178f6dde36aff48a | 2017-12-15T22:32:33Z |
mmm a / project / VS2010Express / XBMC . vcxproj <nl> ppp b / project / VS2010Express / XBMC . vcxproj <nl> <nl> < ExcludedFromBuild Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug Testsuite | Win32 ' " > true < / ExcludedFromBuild > <nl> < / ClCompile > <nl> < ClCompile Include = " . . \ . . \ xbmc \ platform \ win32 \ MessagePrinter . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ main \ win32 \ WinMain . cpp " > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ platform \ win32 \ WinMain . cpp " > <nl> < ExcludedFromBuild Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug Testsuite | Win32 ' " > true < / ExcludedFromBuild > <nl> < / ClCompile > <nl> < ClCompile Include = " . . \ . . \ xbmc \ MediaSource . cpp " / > <nl> mmm a / project / VS2010Express / XBMC . vcxproj . filters <nl> ppp b / project / VS2010Express / XBMC . vcxproj . filters <nl> <nl> < ClCompile Include = " . . \ . . \ xbmc \ main \ main . cpp " > <nl> < Filter > main < / Filter > <nl> < / ClCompile > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ main \ win32 \ WinMain . cpp " > <nl> - < Filter > main \ win32 < / Filter > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ platform \ win32 \ WinMain . cpp " > <nl> + < Filter > platform \ win32 < / Filter > <nl> < / ClCompile > <nl> < ClCompile Include = " . . \ . . \ xbmc \ platform \ win32 \ MessagePrinter . cpp " > <nl> < Filter > platform \ win32 < / Filter > <nl> similarity index 100 % <nl> rename from xbmc / main / win32 / WinMain . cpp <nl> rename to xbmc / platform / win32 / WinMain . cpp <nl> | [ codeshuffle ] - moved winmain to platform | xbmc/xbmc | c46df9a8bc4571ebf2cb98a5ab39fc271073fc69 | 2015-12-12T10:49:41Z |
mmm a / include_dirs . js <nl> ppp b / include_dirs . js <nl> <nl> - console . log ( require ( ' path ' ) . relative ( ' . ' , __dirname ) ) ; <nl> - <nl> + var path = require ( ' path ' ) ; <nl> + console . log ( path . join ( path . relative ( ' . ' , __dirname ) , ' include ' ) ) ; <nl> | include folder added | Tencent/rapidjson | f8df63778310a7ba52a2f4c0e70d512808a02911 | 2016-05-09T15:45:18Z |
mmm a / Documentation / Books / Users / General - Graphs / Management . mdpp <nl> ppp b / Documentation / Books / Users / General - Graphs / Management . mdpp <nl> alternative call : <nl> <nl> ! SUBSECTION List available graphs <nl> <nl> - @ startDocuBlock JSF_general_graph_list_call <nl> - ` general - graph . _list ( ) ` * List all graphs . * <nl> - < br / > <nl> - < br / > <nl> - <nl> - @ startDocuBlock JSF_general_graph_list_info <nl> - <nl> - < br / > <nl> - @ EXAMPLES <nl> - < br / > <nl> - <nl> - @ startDocuBlock JSF_general_graph_list_examples <nl> + @ startDocuBlock JSF_general_graph_list <nl> <nl> ! SUBSECTION Load a graph <nl> <nl> mmm a / js / common / modules / org / arangodb / general - graph . js <nl> ppp b / js / common / modules / org / arangodb / general - graph . js <nl> AQLGenerator . prototype . _edges = function ( edgeExample , options ) { <nl> / / / This will include * inbound * as well as * outbound * edges . <nl> / / / The resulting set of edges can be filtered by defining one or more * examples * . <nl> / / / <nl> + / / / * Parameter * <nl> + / / / <nl> / / / * * examples * : See [ Definition of examples ] ( # definition_of_examples ) <nl> / / / <nl> / / / * Examples * <nl> AQLGenerator . prototype . edges = function ( example ) { <nl> / / / in the step before . <nl> / / / The resulting set of edges can be filtered by defining one or more * examples * . <nl> / / / <nl> + / / / * Parameter * <nl> + / / / <nl> / / / * * examples * : See [ Definition of examples ] ( # definition_of_examples ) <nl> / / / <nl> / / / * Examples * <nl> AQLGenerator . prototype . outEdges = function ( example ) { <nl> / / / in the step before . <nl> / / / The resulting set of edges can be filtered by defining one or more * examples * . <nl> / / / <nl> + / / / * Parameter * <nl> + / / / <nl> / / / * * examples * : See [ Definition of examples ] ( # definition_of_examples ) <nl> / / / <nl> / / / * Examples * <nl> AQLGenerator . prototype . _vertices = function ( example , options ) { <nl> / / / @ startDocuBlock JSF_general_graph_fluent_aql_vertices <nl> / / / ` graph_query . vertices ( examples ) ` <nl> / / / * Select all vertices connected to the edges selected before . * <nl> - / / / <nl> / / / <nl> / / / Creates an AQL statement to select all vertices for each of the edges selected <nl> / / / in the step before . <nl> / / / This includes all vertices contained in * _from * as well as * _to * attribute of the edges . <nl> / / / The resulting set of vertices can be filtered by defining one or more * examples * . <nl> / / / <nl> + / / / * Parameter * <nl> + / / / <nl> / / / * * examples * : See [ Definition of examples ] ( # definition_of_examples ) <nl> / / / <nl> / / / * Examples * <nl> AQLGenerator . prototype . vertices = function ( example ) { <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ startDocuBlock JSF_general_graph_fluent_aql_fromVertices <nl> - / / / ` graph_query . vertices ( examples ) ` <nl> - / / / * Select all vertices where the edges selected before start . * <nl> + / / / ` graph_query . fromVertices ( examples ) ` <nl> + / / / * Select all source vertices of the edges selected before . * <nl> / / / <nl> / / / <nl> / / / Creates an AQL statement to select the set of vertices where the edges selected <nl> AQLGenerator . prototype . vertices = function ( example ) { <nl> / / / This includes all vertices contained in * _from * attribute of the edges . <nl> / / / The resulting set of vertices can be filtered by defining one or more * examples * . <nl> / / / <nl> + / / / * Parameter * <nl> + / / / <nl> / / / * * examples * : See [ Definition of examples ] ( # definition_of_examples ) <nl> / / / <nl> / / / * Examples * <nl> AQLGenerator . prototype . fromVertices = function ( example ) { <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ startDocuBlock JSF_general_graph_fluent_aql_toVertices <nl> - / / / ` graph_query . vertices ( examples ) ` <nl> + / / / ` graph_query . toVertices ( examples ) ` <nl> / / / * Select all vertices targeted by the edges selected before . * <nl> / / / <nl> / / / <nl> AQLGenerator . prototype . fromVertices = function ( example ) { <nl> / / / This includes all vertices contained in * _to * attribute of the edges . <nl> / / / The resulting set of vertices can be filtered by defining one or more * examples * . <nl> / / / <nl> + / / / * Parameter * <nl> + / / / <nl> / / / * * examples * : See [ Definition of examples ] ( # definition_of_examples ) <nl> / / / <nl> / / / * Examples * <nl> AQLGenerator . prototype . restrict = function ( restrictions ) { <nl> / / / This can be used to further specfiy the expected result of the query . <nl> / / / The result set is reduced to the set of elements that matches the given * examples * . <nl> / / / <nl> + / / / * Parameter * <nl> + / / / <nl> / / / * * examples * : See [ Definition of examples ] ( # definition_of_examples ) <nl> / / / <nl> / / / * Examples * <nl> AQLGenerator . prototype . count = function ( ) { <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ startDocuBlock JSF_general_graph_fluent_aql_hasNext <nl> - / / / ` graph_query . neighbors ( examples ) ` <nl> + / / / ` graph_query . hasNext ( ) ` <nl> / / / * Checks if the query has further results . * <nl> / / / <nl> / / / The generated statement maintains a cursor for you . <nl> var _directedRelation = function ( <nl> / / / @ startDocuBlock JSF_general_graph_list <nl> / / / ` general_graph . _list ( ) ` <nl> / / / * List all graphs . * <nl> - / / <nl> + / / / <nl> / / / Lists all graph names stored in this database . <nl> / / / <nl> / / / * Examples * <nl> | Fixed an error for list of graphs in the graph module | arangodb/arangodb | b468d336c80bb1b477f81b66ccb3436c13ffdf9b | 2014-06-20T15:45:37Z |
mmm a / project / VS2010Express / update_git_rev . bat <nl> ppp b / project / VS2010Express / update_git_rev . bat <nl> IF EXIST % REV_FILE % ( <nl> del % REV_FILE % <nl> ) <nl> <nl> - rem Use tgit . exe of TortoiseGit if available <nl> - SET GITEXE = " tgit . exe " <nl> - % GITEXE % - - version > NUL 2 > & 1 <nl> - if errorlevel 1 goto : notgit <nl> - GOTO : extract <nl> - <nl> - : notgit <nl> - <nl> - rem Fallback on msysgit , which must have been added manually to the path . <nl> - SET GITEXE = " git . exe " <nl> - % GITEXE % - - help > NUL 2 > & 1 <nl> - if errorlevel 1 goto : nogit <nl> - GOTO : extract <nl> - <nl> - : nogit <nl> - <nl> - rem Failure - no git tool to extract information . <nl> - SET GIT_REV = Unknown <nl> - GOTO : extracted <nl> - <nl> - : extract <nl> - <nl> - set oldCurrentDir = % CD % <nl> - cd . . \ . . <nl> - FOR / F " tokens = 1 delims = " % % A IN ( ' % GITEXE % rev - parse - - short HEAD ' ) DO SET GIT_REV = % % A <nl> - cd % oldCurrentDir % <nl> - <nl> - : extracted <nl> + CALL . . \ Win32BuildSetup \ extract_git_rev . bat <nl> <nl> copy " % TEMPLATE % " " % REV_FILE % " <nl> <nl> mmm a / project / Win32BuildSetup / BuildSetup . bat <nl> ppp b / project / Win32BuildSetup / BuildSetup . bat <nl> IF % comp % = = vs2008 ( <nl> ECHO Generating installer includes . . . <nl> call genNsisIncludes . bat <nl> ECHO mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm <nl> - FOR / F " Tokens = 2 * Delims = ] " % % R IN ( ' FIND / v / n " & _ & _ & _ & " " . . \ . . \ . svn \ entries " ^ | FIND " [ 11 ] " ' ) DO SET XBMC_REV = % % R <nl> - SET XBMC_SETUPFILE = XBMCSetup - Rev % XBMC_REV % - % target % . exe <nl> + CALL extract_git_rev . bat <nl> + SET GIT_REV = # % GIT_REV % <nl> + SET XBMC_SETUPFILE = XBMCSetup - Rev % GIT_REV % - % target % . exe <nl> ECHO Creating installer % XBMC_SETUPFILE % . . . <nl> IF EXIST % XBMC_SETUPFILE % del % XBMC_SETUPFILE % > NUL <nl> rem get path to makensis . exe from registry , first try tab delim <nl> IF % comp % = = vs2008 ( <nl> ) <nl> <nl> SET NSISExe = % NSISExePath % \ makensis . exe <nl> - " % NSISExe % " / V1 / X " SetCompressor / FINAL lzma " / Dxbmc_root = " % CD % \ BUILD_WIN32 " / Dxbmc_revision = " % XBMC_REV % " / Dxbmc_target = " % target % " " XBMC for Windows . nsi " <nl> + " % NSISExe % " / V1 / X " SetCompressor / FINAL lzma " / Dxbmc_root = " % CD % \ BUILD_WIN32 " / Dxbmc_revision = " % GIT_REV % " / Dxbmc_target = " % target % " " XBMC for Windows . nsi " <nl> IF NOT EXIST " % XBMC_SETUPFILE % " ( <nl> set DIETEXT = Failed to create % XBMC_SETUPFILE % . <nl> goto DIE <nl> new file mode 100644 <nl> index 000000000000 . . dfd3c08e017a <nl> mmm / dev / null <nl> ppp b / project / Win32BuildSetup / extract_git_rev . bat <nl> <nl> + @ ECHO OFF <nl> + <nl> + REM Batch file output : % GIT_REV % variable , containing the git revision <nl> + <nl> + REM Use tgit . exe of TortoiseGit if available <nl> + SET GITEXE = " tgit . exe " <nl> + % GITEXE % - - version > NUL 2 > & 1 <nl> + IF errorlevel 1 GOTO : notgit <nl> + GOTO : extract <nl> + <nl> + : notgit <nl> + <nl> + REM Fallback on msysgit - must be in the path <nl> + SET GITEXE = " git . exe " <nl> + % GITEXE % - - help > NUL 2 > & 1 <nl> + IF errorlevel 1 GOTO : nogit <nl> + GOTO : extract <nl> + <nl> + : nogit <nl> + <nl> + REM Failure - no git tool to extract information . <nl> + SET GIT_REV = Unknown <nl> + GOTO : done <nl> + <nl> + : extract <nl> + <nl> + SET oldCurrentDir = % CD % <nl> + CD . . \ . . <nl> + FOR / F " tokens = 1 delims = " % % A IN ( ' % GITEXE % rev - parse - - short HEAD ' ) DO SET GIT_REV = % % A <nl> + CD % oldCurrentDir % <nl> + <nl> + : done <nl> + <nl> + SET GITEXE = <nl> old mode 100755 <nl> new mode 100644 <nl> old mode 100755 <nl> new mode 100644 <nl> old mode 100755 <nl> new mode 100644 <nl> old mode 100755 <nl> new mode 100644 <nl> old mode 100755 <nl> new mode 100644 <nl> old mode 100755 <nl> new mode 100644 <nl> old mode 100755 <nl> new mode 100644 <nl> old mode 100755 <nl> new mode 100644 <nl> old mode 100755 <nl> new mode 100644 <nl> old mode 100755 <nl> new mode 100644 <nl> old mode 100755 <nl> new mode 100644 <nl> mmm a / xbmc / GUIWindowVideoFiles . cpp <nl> ppp b / xbmc / GUIWindowVideoFiles . cpp <nl> void CGUIWindowVideoFiles : : GetContextButtons ( int itemNumber , CContextButtons & bu <nl> if ( ! item - > IsDVD ( ) & & item - > m_strPath ! = " add " & & <nl> ( g_settings . GetCurrentProfile ( ) . canWriteDatabases ( ) | | g_passwordManager . bMasterUser ) ) <nl> { <nl> - CGUIDialogVideoScan * pScanDlg = ( CGUIDialogVideoScan * ) g_windowManager . GetWindow ( WINDOW_DIALOG_VIDEO_SCAN ) ; <nl> - if ( ! pScanDlg | | ( pScanDlg & & ! pScanDlg - > IsScanning ( ) ) ) <nl> - if ( ! item - > IsLiveTV ( ) & & ! item - > IsPlugin ( ) & & ! item - > IsAddonsPath ( ) ) <nl> - buttons . Add ( CONTEXT_BUTTON_SET_CONTENT , 20333 ) ; <nl> CVideoDatabase database ; <nl> database . Open ( ) ; <nl> ADDON : : ScraperPtr info = database . GetScraperForPath ( item - > m_strPath ) ; <nl> <nl> + CGUIDialogVideoScan * pScanDlg = ( CGUIDialogVideoScan * ) g_windowManager . GetWindow ( WINDOW_DIALOG_VIDEO_SCAN ) ; <nl> + if ( ! pScanDlg | | ( pScanDlg & & ! pScanDlg - > IsScanning ( ) ) ) <nl> + { <nl> + if ( ! item - > IsLiveTV ( ) & & ! item - > IsPlugin ( ) & & ! item - > IsAddonsPath ( ) ) <nl> + { <nl> + if ( info & & info - > Content ( ) ! = CONTENT_NONE ) <nl> + buttons . Add ( CONTEXT_BUTTON_SET_CONTENT , 20442 ) ; <nl> + else <nl> + buttons . Add ( CONTEXT_BUTTON_SET_CONTENT , 20333 ) ; <nl> + } <nl> + } <nl> + <nl> if ( info & & ( ! pScanDlg | | ( pScanDlg & & ! pScanDlg - > IsScanning ( ) ) ) ) <nl> buttons . Add ( CONTEXT_BUTTON_SCAN , 13349 ) ; <nl> } <nl> void CGUIWindowVideoFiles : : GetContextButtons ( int itemNumber , CContextButtons & bu <nl> if ( item - > m_bIsFolder ) <nl> { <nl> if ( ! pScanDlg | | ( pScanDlg & & ! pScanDlg - > IsScanning ( ) ) ) <nl> + { <nl> if ( ! item - > IsPlayList ( ) & & ! item - > IsLiveTV ( ) & & ! item - > IsPlugin ( ) & & ! item - > IsAddonsPath ( ) ) <nl> - buttons . Add ( CONTEXT_BUTTON_SET_CONTENT , 20333 ) ; <nl> + { <nl> + if ( info & & info - > Content ( ) ! = CONTENT_NONE ) <nl> + buttons . Add ( CONTEXT_BUTTON_SET_CONTENT , 20442 ) ; <nl> + else <nl> + buttons . Add ( CONTEXT_BUTTON_SET_CONTENT , 20333 ) ; <nl> + } <nl> + } <nl> if ( ! info ) <nl> { / / scraper not set - allow movie information or set content <nl> CStdString strPath ( item - > m_strPath ) ; <nl> mmm a / xbmc / Util . cpp <nl> ppp b / xbmc / Util . cpp <nl> void CUtil : : ScanForExternalSubtitles ( const CStdString & strMovie , std : : vector < CSt <nl> } <nl> g_directoryCache . ClearDirectory ( strLookInPaths [ step ] ) ; <nl> } <nl> - } <nl> + } <nl> + <nl> + iSize = vecSubtitles . size ( ) ; <nl> + for ( int i = 0 ; i < iSize ; i + + ) <nl> + { <nl> + if ( CUtil : : GetExtension ( vecSubtitles [ i ] ) . Equals ( " . smi " ) ) <nl> + { <nl> + / / Cache multi - language sami subtitle <nl> + CDVDSubtitleStream * pStream = new CDVDSubtitleStream ( ) ; <nl> + if ( pStream - > Open ( vecSubtitles [ i ] ) ) <nl> + { <nl> + CDVDSubtitleTagSami TagConv ; <nl> + TagConv . LoadHead ( pStream ) ; <nl> + if ( TagConv . m_Langclass . size ( ) > = 2 ) <nl> + { <nl> + for ( unsigned int k = 0 ; k < TagConv . m_Langclass . size ( ) ; k + + ) <nl> + { <nl> + strDest . Format ( " special : / / temp / subtitle . % s . % d . smi " , TagConv . m_Langclass [ k ] . Name , i ) ; <nl> + if ( CFile : : Cache ( vecSubtitles [ i ] , strDest ) ) <nl> + { <nl> + CLog : : Log ( LOGINFO , " cached subtitle % s - > % s \ n " , vecSubtitles [ i ] . c_str ( ) , strDest . c_str ( ) ) ; <nl> + vecSubtitles . push_back ( strDest ) ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + delete pStream ; <nl> + } <nl> + } <nl> CLog : : Log ( LOGDEBUG , " % s : END ( total time : % i ms ) " , __FUNCTION__ , ( int ) ( CTimeUtils : : GetTimeMS ( ) - startTimer ) ) ; <nl> } <nl> <nl> mmm a / xbmc / VideoInfoTag . cpp <nl> ppp b / xbmc / VideoInfoTag . cpp <nl> void CVideoInfoTag : : Serialize ( CVariant & value ) <nl> value [ " file " ] = m_strFile ; <nl> value [ " path " ] = m_strPath ; <nl> value [ " imdbnumber " ] = m_strIMDBNumber ; <nl> + value [ " mpaa " ] = m_strMPAARating ; <nl> value [ " filenameandpath " ] = m_strFileNameAndPath ; <nl> value [ " originaltitle " ] = m_strOriginalTitle ; <nl> value [ " episodeguide " ] = m_strEpisodeGuide ; <nl> mmm a / xbmc / cores / dvdplayer / DVDCodecs / Overlay / DVDOverlayCodecSSA . cpp <nl> ppp b / xbmc / cores / dvdplayer / DVDCodecs / Overlay / DVDOverlayCodecSSA . cpp <nl> int CDVDOverlayCodecSSA : : Decode ( BYTE * data , int size , double pts , double duratio <nl> if ( m_pOverlay ) <nl> SAFE_RELEASE ( m_pOverlay ) ; <nl> <nl> - if ( strncmp ( ( const char * ) data , " Dialogue : " , 7 ) = = 0 ) <nl> + if ( strncmp ( ( const char * ) data , " Dialogue : " , 9 ) = = 0 ) <nl> { <nl> int sh , sm , ss , sc , eh , em , es , ec ; <nl> size_t pos ; <nl> mmm a / xbmc / visualizations / WaveForm / Waveform . vcxproj <nl> ppp b / xbmc / visualizations / WaveForm / Waveform . vcxproj <nl> <nl> < DebugInformationFormat > ProgramDatabase < / DebugInformationFormat > <nl> < / ClCompile > <nl> < Link > <nl> - < AdditionalDependencies > opengl32 . lib ; winmm . lib ; ws2_32 . lib ; glu32 . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> + < AdditionalDependencies > opengl32 . lib ; glu32 . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> < OutputFile > $ ( OutDir ) $ ( TargetName ) $ ( TargetExt ) < / OutputFile > <nl> < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> < SubSystem > Windows < / SubSystem > <nl> <nl> < DebugInformationFormat > EditAndContinue < / DebugInformationFormat > <nl> < / ClCompile > <nl> < Link > <nl> - < AdditionalDependencies > opengl32 . lib ; glu32 . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> + < AdditionalDependencies > <nl> + < / AdditionalDependencies > <nl> < OutputFile > $ ( OutDir ) $ ( TargetName ) $ ( TargetExt ) < / OutputFile > <nl> < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> < ProgramDatabaseFile > $ ( OutDir ) Waveform . pdb < / ProgramDatabaseFile > <nl> <nl> < DebugInformationFormat > ProgramDatabase < / DebugInformationFormat > <nl> < / ClCompile > <nl> < Link > <nl> - < AdditionalDependencies > opengl32 . lib ; winmm . lib ; ws2_32 . lib ; glu32 . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> + < AdditionalDependencies > <nl> + < / AdditionalDependencies > <nl> < OutputFile > $ ( OutDir ) $ ( TargetName ) $ ( TargetExt ) < / OutputFile > <nl> < GenerateDebugInformation > true < / GenerateDebugInformation > <nl> < SubSystem > Windows < / SubSystem > <nl> mmm a / xbmc / win32 / WIN32Util . cpp <nl> ppp b / xbmc / win32 / WIN32Util . cpp <nl> CWIN32Util : : ~ CWIN32Util ( void ) <nl> { <nl> } <nl> <nl> - <nl> - const CStdString CWIN32Util : : GetNextFreeDriveLetter ( ) <nl> - { <nl> - for ( int iDrive = ' a ' ; iDrive < = ' z ' ; iDrive + + ) <nl> - { <nl> - CStdString strDrive ; <nl> - strDrive . Format ( " % c : " , iDrive ) ; <nl> - int iType = GetDriveType ( strDrive ) ; <nl> - if ( iType = = DRIVE_NO_ROOT_DIR & & iDrive ! = ' a ' & & iDrive ! = ' b ' ) <nl> - return strDrive ; <nl> - } <nl> - return StringUtils : : EmptyString ; <nl> - } <nl> - <nl> - CStdString CWIN32Util : : MountShare ( const CStdString & smbPath , const CStdString & strUser , const CStdString & strPass , DWORD * dwError ) <nl> - { <nl> - NETRESOURCE nr ; <nl> - memset ( & nr , 0 , sizeof ( nr ) ) ; <nl> - CStdString strRemote = smbPath ; <nl> - CStdString strDrive = CWIN32Util : : GetNextFreeDriveLetter ( ) ; <nl> - <nl> - if ( strDrive = = StringUtils : : EmptyString ) <nl> - return StringUtils : : EmptyString ; <nl> - <nl> - strRemote . Replace ( ' / ' , ' \ \ ' ) ; <nl> - <nl> - nr . lpRemoteName = ( LPTSTR ) ( LPCTSTR ) strRemote . c_str ( ) ; <nl> - nr . lpLocalName = ( LPTSTR ) ( LPCTSTR ) strDrive . c_str ( ) ; <nl> - nr . dwType = RESOURCETYPE_DISK ; <nl> - <nl> - DWORD dwRes = WNetAddConnection2 ( & nr , ( LPCTSTR ) strPass . c_str ( ) , ( LPCTSTR ) strUser . c_str ( ) , NULL ) ; <nl> - <nl> - if ( dwError ! = NULL ) <nl> - * dwError = dwRes ; <nl> - <nl> - if ( dwRes ! = NO_ERROR ) <nl> - { <nl> - CLog : : Log ( LOGERROR , " Can ' t mount % s to % s . Error code % d " , strRemote . c_str ( ) , strDrive . c_str ( ) , dwRes ) ; <nl> - return StringUtils : : EmptyString ; <nl> - } <nl> - <nl> - return strDrive ; <nl> - } <nl> - <nl> - DWORD CWIN32Util : : UmountShare ( const CStdString & strPath ) <nl> - { <nl> - return WNetCancelConnection2 ( ( LPCTSTR ) strPath . c_str ( ) , NULL , true ) ; <nl> - } <nl> - <nl> - CStdString CWIN32Util : : MountShare ( const CStdString & strPath , DWORD * dwError ) <nl> - { <nl> - CURL url ( strPath ) ; <nl> - CStdString strPassword = url . GetPassWord ( ) ; <nl> - CStdString strUserName = url . GetUserName ( ) ; <nl> - CStdString strPathToShare = " \ \ \ \ " + url . GetHostName ( ) + " \ \ " + url . GetShareName ( ) ; <nl> - if ( ! url . GetUserName ( ) . IsEmpty ( ) ) <nl> - return CWIN32Util : : MountShare ( strPathToShare , strUserName , strPassword , dwError ) ; <nl> - else <nl> - return CWIN32Util : : MountShare ( strPathToShare , " " , " " , dwError ) ; <nl> - } <nl> - <nl> CStdString CWIN32Util : : URLEncode ( const CURL & url ) <nl> { <nl> / * due to smb wanting encoded urls we have to build it manually * / <nl> mmm a / xbmc / win32 / WIN32Util . h <nl> ppp b / xbmc / win32 / WIN32Util . h <nl> class CWIN32Util <nl> CWIN32Util ( void ) ; <nl> virtual ~ CWIN32Util ( void ) ; <nl> <nl> - static const CStdString GetNextFreeDriveLetter ( ) ; <nl> - static CStdString MountShare ( const CStdString & smbPath , const CStdString & strUser , const CStdString & strPass , DWORD * dwError = NULL ) ; <nl> - static CStdString MountShare ( const CStdString & strPath , DWORD * dwError = NULL ) ; <nl> - static DWORD UmountShare ( const CStdString & strPath ) ; <nl> static CStdString URLEncode ( const CURL & url ) ; <nl> static CStdString GetLocalPath ( const CStdString & strPath ) ; <nl> static char FirstDriveFromMask ( ULONG unitmask ) ; <nl> | Merge remote branch ' upstream / master ' | xbmc/xbmc | 0be24733539c14f5f3df97cb8dfb15f2cf86dadc | 2011-01-16T22:15:36Z |
new file mode 100644 <nl> index 000000000000 . . 5d4cdabf8d1e <nl> mmm / dev / null <nl> ppp b / doc / files . txt <nl> <nl> + Used in 0 . 8 . 0 : <nl> + * wallet . dat : personal wallet ( BDB ) with keys and transactions <nl> + * peers . dat : peer IP address database ( custom format ) ; since 0 . 7 . 0 <nl> + * blocks / blk000 ? ? . dat : block data ( custom , 128 MiB per file ) ; since 0 . 8 . 0 <nl> + * blocks / rev000 ? ? . dat ; block undo data ( custom ) ; since 0 . 8 . 0 ( format changed since pre - 0 . 8 ) <nl> + * blocks / index / * ; block index ( LevelDB ) ; since 0 . 8 . 0 <nl> + * chainstate / * ; block chain state database ( LevelDB ) ; since 0 . 8 . 0 <nl> + * database / * : BDB database environment ; only used for wallet since 0 . 8 . 0 <nl> + <nl> + Only used in pre - 0 . 8 . 0 : <nl> + * blktree / * ; block chain index ( LevelDB ) ; since pre - 0 . 8 , replaced by blocks / index / * in 0 . 8 . 0 <nl> + * coins / * ; unspent transaction output database ( LevelDB ) ; since pre - 0 . 8 , replaced by chainstate / * in 0 . 8 . 0 <nl> + <nl> + Only used before 0 . 8 . 0 : <nl> + * blkindex . dat : block chain index database ( BDB ) ; replaced by { chainstate / * , blocks / index / * , blocks / rev000 ? ? . dat } in 0 . 8 . 0 <nl> + * blk000 ? . dat : block data ( custom , 2 GiB per file ) ; replaced by blocks / blk000 ? ? . dat in 0 . 8 . 0 <nl> + <nl> + Only used before 0 . 7 . 0 : <nl> + * addr . dat : peer IP address database ( BDB ) ; replaced by peers . dat in 0 . 7 . 0 <nl> | Merge pull request from sipa / files | bitcoin/bitcoin | cb2e1bdaa902197ba0f04aebd00420a4680548e0 | 2013-01-30T20:38:11Z |
mmm a / src / citra_qt / configuration / configure_graphics . ui <nl> ppp b / src / citra_qt / configuration / configure_graphics . ui <nl> <nl> < widget class = " QComboBox " name = " layout_combobox " > <nl> < item > <nl> < property name = " text " > <nl> - < string notr = " true " > Default < / string > <nl> + < string > Default < / string > <nl> < / property > <nl> < / item > <nl> < item > <nl> < property name = " text " > <nl> - < string notr = " true " > Single Screen < / string > <nl> + < string > Single Screen < / string > <nl> < / property > <nl> < / item > <nl> < item > <nl> < property name = " text " > <nl> - < string notr = " true " > Large Screen < / string > <nl> + < string > Large Screen < / string > <nl> + < / property > <nl> + < / item > <nl> + < item > <nl> + < property name = " text " > <nl> + < string > Side by Side < / string > <nl> < / property > <nl> < / item > <nl> < / widget > <nl> mmm a / src / core / frontend / emu_window . cpp <nl> ppp b / src / core / frontend / emu_window . cpp <nl> void EmuWindow : : UpdateCurrentFramebufferLayout ( unsigned width , unsigned height ) <nl> case Settings : : LayoutOption : : LargeScreen : <nl> layout = Layout : : LargeFrameLayout ( width , height , Settings : : values . swap_screen ) ; <nl> break ; <nl> + case Settings : : LayoutOption : : SideScreen : <nl> + layout = Layout : : SideFrameLayout ( width , height , Settings : : values . swap_screen ) ; <nl> + break ; <nl> case Settings : : LayoutOption : : Default : <nl> default : <nl> layout = Layout : : DefaultFrameLayout ( width , height , Settings : : values . swap_screen ) ; <nl> mmm a / src / core / frontend / framebuffer_layout . cpp <nl> ppp b / src / core / frontend / framebuffer_layout . cpp <nl> FramebufferLayout LargeFrameLayout ( unsigned width , unsigned height , bool swapped <nl> return res ; <nl> } <nl> <nl> + FramebufferLayout SideFrameLayout ( unsigned width , unsigned height , bool swapped ) { <nl> + ASSERT ( width > 0 ) ; <nl> + ASSERT ( height > 0 ) ; <nl> + <nl> + FramebufferLayout res { width , height , true , true , { } , { } } ; <nl> + / / Aspect ratio of both screens side by side <nl> + const float emulation_aspect_ratio = static_cast < float > ( Core : : kScreenTopHeight ) / <nl> + ( Core : : kScreenTopWidth + Core : : kScreenBottomWidth ) ; <nl> + float window_aspect_ratio = static_cast < float > ( height ) / width ; <nl> + MathUtil : : Rectangle < unsigned > screen_window_area { 0 , 0 , width , height } ; <nl> + / / Find largest Rectangle that can fit in the window size with the given aspect ratio <nl> + MathUtil : : Rectangle < unsigned > screen_rect = <nl> + maxRectangle ( screen_window_area , emulation_aspect_ratio ) ; <nl> + / / Find sizes of top and bottom screen <nl> + MathUtil : : Rectangle < unsigned > top_screen = maxRectangle ( screen_rect , TOP_SCREEN_ASPECT_RATIO ) ; <nl> + MathUtil : : Rectangle < unsigned > bot_screen = maxRectangle ( screen_rect , BOT_SCREEN_ASPECT_RATIO ) ; <nl> + <nl> + if ( window_aspect_ratio < emulation_aspect_ratio ) { <nl> + / / Apply borders to the left and right sides of the window . <nl> + u32 shift_horizontal = ( screen_window_area . GetWidth ( ) - screen_rect . GetWidth ( ) ) / 2 ; <nl> + top_screen = top_screen . TranslateX ( shift_horizontal ) ; <nl> + bot_screen = bot_screen . TranslateX ( shift_horizontal ) ; <nl> + } else { <nl> + / / Window is narrower than the emulation content = > apply borders to the top and bottom <nl> + u32 shift_vertical = ( screen_window_area . GetHeight ( ) - screen_rect . GetHeight ( ) ) / 2 ; <nl> + top_screen = top_screen . TranslateY ( shift_vertical ) ; <nl> + bot_screen = bot_screen . TranslateY ( shift_vertical ) ; <nl> + } <nl> + / / Move the top screen to the right if we are swapped . <nl> + res . top_screen = swapped ? top_screen . TranslateX ( bot_screen . GetWidth ( ) ) : top_screen ; <nl> + res . bottom_screen = swapped ? bot_screen : bot_screen . TranslateX ( top_screen . GetWidth ( ) ) ; <nl> + return res ; <nl> + } <nl> + <nl> FramebufferLayout CustomFrameLayout ( unsigned width , unsigned height ) { <nl> ASSERT ( width > 0 ) ; <nl> ASSERT ( height > 0 ) ; <nl> FramebufferLayout CustomFrameLayout ( unsigned width , unsigned height ) { <nl> res . bottom_screen = bot_screen ; <nl> return res ; <nl> } <nl> - } <nl> + } / / namespace Layout <nl> mmm a / src / core / frontend / framebuffer_layout . h <nl> ppp b / src / core / frontend / framebuffer_layout . h <nl> FramebufferLayout SingleFrameLayout ( unsigned width , unsigned height , bool is_swa <nl> * / <nl> FramebufferLayout LargeFrameLayout ( unsigned width , unsigned height , bool is_swapped ) ; <nl> <nl> + / * * <nl> + * Factory method for constructing a Frame with the Top screen and bottom <nl> + * screen side by side <nl> + * This is useful for devices with small screens , like the GPDWin <nl> + * @ param width Window framebuffer width in pixels <nl> + * @ param height Window framebuffer height in pixels <nl> + * @ param is_swapped if true , the bottom screen will be the left display <nl> + * @ return Newly created FramebufferLayout object with default screen regions initialized <nl> + * / <nl> + FramebufferLayout SideFrameLayout ( unsigned width , unsigned height , bool is_swapped ) ; <nl> + <nl> / * * <nl> * Factory method for constructing a custom FramebufferLayout <nl> * @ param width Window framebuffer width in pixels <nl> mmm a / src / core / settings . cpp <nl> ppp b / src / core / settings . cpp <nl> void Apply ( ) { <nl> Service : : IR : : ReloadInputDevices ( ) ; <nl> } <nl> <nl> - } / / namespace <nl> + } / / namespace Settings <nl> mmm a / src / core / settings . h <nl> ppp b / src / core / settings . h <nl> enum class LayoutOption { <nl> Default , <nl> SingleScreen , <nl> LargeScreen , <nl> + SideScreen , <nl> } ; <nl> <nl> namespace NativeButton { <nl> enum Values { <nl> static const std : : array < const char * , NumAnalogs > mapping = { { <nl> " circle_pad " , " c_stick " , <nl> } } ; <nl> - } / / namespace NumAnalog <nl> + } / / namespace NativeAnalog <nl> <nl> struct Values { <nl> / / CheckNew3DS <nl> struct Values { <nl> static constexpr int REGION_VALUE_AUTO_SELECT = - 1 ; <nl> <nl> void Apply ( ) ; <nl> - } <nl> + } / / namespace Settings <nl> | SidebySide Layout ( ) | yuzu-emu/yuzu | 3cdf854e44e7ff088fa0cbdcfa2bcc6e41822b2c | 2017-08-25T21:53:07Z |
mmm a / Unity / AirLibWrapper / AirsimWrapper / Source / WorldSimApi . cpp <nl> ppp b / Unity / AirLibWrapper / AirsimWrapper / Source / WorldSimApi . cpp <nl> bool WorldSimApi : : isPaused ( ) const <nl> return simmode_ - > isPaused ( ) ; <nl> } <nl> <nl> - void WorldSimApi : : resetImplementation ( ) <nl> + void WorldSimApi : : reset ( ) <nl> { <nl> simmode_ - > reset ( ) ; <nl> } <nl> mmm a / Unity / AirLibWrapper / AirsimWrapper / Source / WorldSimApi . h <nl> ppp b / Unity / AirLibWrapper / AirsimWrapper / Source / WorldSimApi . h <nl> class WorldSimApi : public msr : : airlib : : WorldSimApiBase <nl> WorldSimApi ( SimModeBase * simmode , std : : string vehicle_name ) ; <nl> virtual ~ WorldSimApi ( ) ; <nl> virtual bool isPaused ( ) const override ; <nl> - virtual void resetImplementation ( ) override ; <nl> + virtual void reset ( ) override ; <nl> virtual void pause ( bool is_paused ) override ; <nl> virtual void continueForTime ( double seconds ) override ; <nl> virtual void setTimeOfDay ( bool is_enabled , const std : : string & start_datetime , bool is_start_datetime_dst , <nl> | Merge pull request from rajat2004 / fix - unity - build | microsoft/AirSim | ecc084a003d679ad2429dcac536de3fee90fc411 | 2019-09-20T16:48:56Z |
mmm a / util / env_posix . cc <nl> ppp b / util / env_posix . cc <nl> static int MaxMmaps ( ) { <nl> if ( mmap_limit > = 0 ) { <nl> return mmap_limit ; <nl> } <nl> - / / Up to 1000 mmaps for 64 - bit binaries ; none for smaller pointer sizes . <nl> - mmap_limit = sizeof ( void * ) > = 8 ? 1000 : 0 ; <nl> + / / Up to 4096 mmaps for 64 - bit binaries ; none for smaller pointer sizes . <nl> + mmap_limit = sizeof ( void * ) > = 8 ? 4096 : 0 ; <nl> return mmap_limit ; <nl> } <nl> <nl> | Squashed ' src / leveldb / ' changes from 64052c76c5 . . 524b7e36a8 | bitcoin/bitcoin | ec749b1bcdf2483b642fb51d635800e272c68ba6 | 2018-08-09T15:30:12Z |
mmm a / xbmc / peripherals / devices / PeripheralCecAdapter . cpp <nl> ppp b / xbmc / peripherals / devices / PeripheralCecAdapter . cpp <nl> <nl> * http : / / www . gnu . org / copyleft / gpl . html <nl> * <nl> * / <nl> + # include " system . h " <nl> <nl> + # ifdef HAVE_LIBCEC <nl> # include " PeripheralCecAdapter . h " <nl> # include " dialogs / GUIDialogOK . h " <nl> # include " input / XBIRRemote . h " <nl> <nl> # include " peripherals / bus / PeripheralBus . h " <nl> # include " utils / log . h " <nl> <nl> + # include < libcec / CECExports . h > <nl> + <nl> using namespace PERIPHERALS ; <nl> using namespace ANNOUNCEMENT ; <nl> using namespace CEC ; <nl> bool CPeripheralCecAdapter : : TranslateComPort ( CStdString & strLocation ) <nl> <nl> return false ; <nl> } <nl> + # endif <nl> mmm a / xbmc / peripherals / devices / PeripheralCecAdapter . h <nl> ppp b / xbmc / peripherals / devices / PeripheralCecAdapter . h <nl> <nl> # include " interfaces / AnnouncementManager . h " <nl> # include " threads / Thread . h " <nl> # include " threads / CriticalSection . h " <nl> - # include < libcec / CECExports . h > <nl> # include < queue > <nl> <nl> namespace PERIPHERALS <nl> namespace PERIPHERALS <nl> unsigned int iButtonReleased ; <nl> } CecButtonPress ; <nl> <nl> + class CEC : : ICECDevice ; <nl> + <nl> class CPeripheralCecAdapter : public CPeripheralHID , public ANNOUNCEMENT : : IAnnouncer , private CThread <nl> { <nl> public : <nl> | changed , forward declare class and move the system include to cpp file , add compile guards | xbmc/xbmc | e16a2d0f12cd8e983631c71bf3f7ce62df8a0596 | 2011-09-30T04:33:27Z |
mmm a / modules / mono / glue / cs_files / Basis . cs <nl> ppp b / modules / mono / glue / cs_files / Basis . cs <nl> public Basis ( Vector3 euler ) <nl> <nl> c = Mathf . Cos ( euler . x ) ; <nl> s = Mathf . Sin ( euler . x ) ; <nl> - var xmat = new Basis ( ( real_t ) 1 . 0 , ( real_t ) 0 . 0 , ( real_t ) 0 . 0 , ( real_t ) 0 . 0 , c , - s , ( real_t ) 0 . 0 , s , c ) ; <nl> + var xmat = new Basis ( 1 , 0 , 0 , 0 , c , - s , 0 , s , c ) ; <nl> <nl> c = Mathf . Cos ( euler . y ) ; <nl> s = Mathf . Sin ( euler . y ) ; <nl> - var ymat = new Basis ( c , ( real_t ) 0 . 0 , s , ( real_t ) 0 . 0 , ( real_t ) 1 . 0 , ( real_t ) 0 . 0 , - s , ( real_t ) 0 . 0 , c ) ; <nl> + var ymat = new Basis ( c , 0 , s , 0 , 1 , 0 , - s , 0 , c ) ; <nl> <nl> c = Mathf . Cos ( euler . z ) ; <nl> s = Mathf . Sin ( euler . z ) ; <nl> - var zmat = new Basis ( c , - s , ( real_t ) 0 . 0 , s , c , ( real_t ) 0 . 0 , ( real_t ) 0 . 0 , ( real_t ) 0 . 0 , ( real_t ) 1 . 0 ) ; <nl> + var zmat = new Basis ( c , - s , 0 , s , c , 0 , 0 , 0 , 1 ) ; <nl> <nl> this = ymat * xmat * zmat ; <nl> } <nl> mmm a / modules / mono / glue / cs_files / VERSION . txt <nl> ppp b / modules / mono / glue / cs_files / VERSION . txt <nl> @ @ - 1 + 1 @ @ <nl> - 2 <nl> + 3 <nl> mmm a / modules / mono / glue / cs_files / Vector2 . cs <nl> ppp b / modules / mono / glue / cs_files / Vector2 . cs <nl> internal void Normalize ( ) <nl> } <nl> } <nl> <nl> - private real_t Cross ( Vector2 b ) <nl> + public real_t Cross ( Vector2 b ) <nl> { <nl> return x * b . y - y * b . x ; <nl> } <nl> public void Set ( Vector2 v ) <nl> x = v . x ; <nl> y = v . y ; <nl> } <nl> + <nl> + public Vector2 Slerp ( Vector2 b , real_t t ) <nl> + { <nl> + real_t theta = AngleTo ( b ) ; <nl> + return Rotated ( theta * t ) ; <nl> + } <nl> <nl> public Vector2 Slide ( Vector2 n ) <nl> { <nl> mmm a / modules / mono / glue / cs_files / Vector3 . cs <nl> ppp b / modules / mono / glue / cs_files / Vector3 . cs <nl> public void Set ( Vector3 v ) <nl> z = v . z ; <nl> } <nl> <nl> + public Vector3 Slerp ( Vector3 b , real_t t ) <nl> + { <nl> + real_t theta = AngleTo ( b ) ; <nl> + return Rotated ( Cross ( b ) , theta * t ) ; <nl> + } <nl> + <nl> public Vector3 Slide ( Vector3 n ) <nl> { <nl> return this - n * Dot ( n ) ; <nl> | mono : add Slerp method to vector classes , expose Cross method for Vector2 , and fix unnecessary casts in Basis | godotengine/godot | b335274bcd6df9ad7e4ba381574fd1607f2b3437 | 2018-05-22T00:27:49Z |
mmm a / arangod / RocksDBEngine / RocksDBPrimaryIndex . cpp <nl> ppp b / arangod / RocksDBEngine / RocksDBPrimaryIndex . cpp <nl> RocksDBAnyIndexIterator : : RocksDBAnyIndexIterator ( <nl> <nl> _iterator . reset ( rtrx - > GetIterator ( options ) ) ; <nl> _total = collection - > numberDocuments ( trx ) ; <nl> + uint64_t off = RandomGenerator : : interval ( _total - 1 ) ; <nl> + uint64_t goal = off ; <nl> if ( _total > 0 ) { <nl> - uint64_t off = RandomGenerator : : interval ( _total ) ; <nl> - if ( off < _total / 2 ) { <nl> + if ( off < = _total / 2 ) { <nl> _iterator - > Seek ( _bounds . start ( ) ) ; <nl> - while ( _iterator - > Valid ( ) & & - - off > 0 ) { <nl> + while ( _iterator - > Valid ( ) & & off - - > 0 ) { <nl> _iterator - > Next ( ) ; <nl> } <nl> } else { <nl> - off / = 2 ; <nl> + off = _total - ( off + 1 ) ; <nl> _iterator - > SeekForPrev ( _bounds . end ( ) ) ; <nl> - while ( _iterator - > Valid ( ) & & - - off > 0 ) { <nl> + while ( _iterator - > Valid ( ) & & off - - > 0 ) { <nl> _iterator - > Prev ( ) ; <nl> } <nl> } <nl> if ( ! _iterator - > Valid ( ) ) { <nl> + LOG_TOPIC ( ERR , Logger : : FIXME ) < < " invalid iterator ! ! ! offset " < < goal ; <nl> _iterator - > Seek ( _bounds . start ( ) ) ; <nl> } <nl> } <nl> bool RocksDBAnyIndexIterator : : outOfRange ( ) const { <nl> <nl> RocksDBPrimaryIndex : : RocksDBPrimaryIndex ( <nl> arangodb : : LogicalCollection * collection , VPackSlice const & info ) <nl> - : RocksDBIndex ( 0 , <nl> - collection , <nl> + : RocksDBIndex ( 0 , collection , <nl> std : : vector < std : : vector < arangodb : : basics : : AttributeName > > ( <nl> { { arangodb : : basics : : AttributeName ( <nl> StaticStrings : : KeyString , false ) } } ) , <nl> - true , false , basics : : VelocyPackHelper : : stringUInt64 ( info , " objectId " ) ) { <nl> + true , false , <nl> + basics : : VelocyPackHelper : : stringUInt64 ( info , " objectId " ) ) { <nl> _useCache = true ; <nl> createCache ( ) ; <nl> } <nl> | Fixed any iterator . | arangodb/arangodb | aa24d452fe4a1de40a2d5d15bbba8fc5a3d3b698 | 2017-04-06T18:23:15Z |
mmm a / tensorflow / compiler / xla / client / compile_only_client . cc <nl> ppp b / tensorflow / compiler / xla / client / compile_only_client . cc <nl> namespace xla { <nl> StatusOr < std : : vector < std : : unique_ptr < AotCompilationResult > > > <nl> CompileOnlyClient : : CompileAheadOfTime ( <nl> const tensorflow : : gtl : : ArraySlice < AotXlaComputationInstance > computations , <nl> - const AotCompilationOptions & options ) { <nl> + const AotCompilationOptions & options , <nl> + std : : unique_ptr < AotCompilationMetadata > * metadata ) { <nl> std : : vector < CompileOnlyService : : AotXlaComputationInstance > service_instances ; <nl> service_instances . reserve ( computations . size ( ) ) ; <nl> for ( const AotXlaComputationInstance & instance : computations ) { <nl> CompileOnlyClient : : CompileAheadOfTime ( <nl> service_instance . argument_layouts = instance . argument_layouts ; <nl> service_instance . result_layout = instance . result_layout ; <nl> } <nl> - return compiler_service_ - > CompileAheadOfTime ( service_instances , options ) ; <nl> + return compiler_service_ - > CompileAheadOfTime ( service_instances , options , <nl> + metadata ) ; <nl> } <nl> <nl> int64 CompileOnlyClient : : PointerSizeForTriple ( tensorflow : : StringPiece triple ) { <nl> mmm a / tensorflow / compiler / xla / client / compile_only_client . h <nl> ppp b / tensorflow / compiler / xla / client / compile_only_client . h <nl> class CompileOnlyClient : public Client { <nl> const Shape * result_layout ; <nl> } ; <nl> <nl> - / / Compiles a list of xla computations for ahead - of - time execution . This is <nl> - / / intended for use in static compilation . The | options | parameter describes <nl> - / / the target for which the compiler should emit code . <nl> + / / Compiles a list of xla computations for ahead - of - time execution . <nl> + / / This is intended for use in static compilation . The | options | <nl> + / / parameter describes the target for which the compiler should emit <nl> + / / code . | metadata | , if provided , is populated during compilation . <nl> StatusOr < std : : vector < std : : unique_ptr < AotCompilationResult > > > <nl> CompileAheadOfTime ( <nl> const tensorflow : : gtl : : ArraySlice < AotXlaComputationInstance > computations , <nl> - const AotCompilationOptions & options ) ; <nl> + const AotCompilationOptions & options , <nl> + std : : unique_ptr < AotCompilationMetadata > * metadata = nullptr ) ; <nl> <nl> / / Returns the size of a pointer in bytes for a given triple . <nl> static int64 PointerSizeForTriple ( tensorflow : : StringPiece triple ) ; <nl> mmm a / tensorflow / compiler / xla / service / compile_only_service . cc <nl> ppp b / tensorflow / compiler / xla / service / compile_only_service . cc <nl> CompileOnlyService : : CompileOnlyService ( const ServiceOptions & options , <nl> StatusOr < std : : vector < std : : unique_ptr < AotCompilationResult > > > <nl> CompileOnlyService : : CompileAheadOfTime ( <nl> const tensorflow : : gtl : : ArraySlice < AotXlaComputationInstance > computations , <nl> - const AotCompilationOptions & options ) { <nl> + const AotCompilationOptions & options , <nl> + std : : unique_ptr < AotCompilationMetadata > * metadata ) { <nl> std : : vector < std : : unique_ptr < HloModule > > hlo_modules ; <nl> for ( const AotXlaComputationInstance & instance : computations ) { <nl> TF_RET_CHECK ( instance . computation . has_program_shape ( ) ) ; <nl> CompileOnlyService : : CompileAheadOfTime ( <nl> hlo_modules . push_back ( std : : move ( hlo_module ) ) ; <nl> } <nl> <nl> - return compiler_ - > CompileAheadOfTime ( std : : move ( hlo_modules ) , options ) ; <nl> + return compiler_ - > CompileAheadOfTime ( std : : move ( hlo_modules ) , options , <nl> + metadata ) ; <nl> } <nl> <nl> } / / namespace xla <nl> mmm a / tensorflow / compiler / xla / service / compile_only_service . h <nl> ppp b / tensorflow / compiler / xla / service / compile_only_service . h <nl> class CompileOnlyService : public Service { <nl> const tensorflow : : gtl : : ArraySlice < AotXlaComputationInstance > computations , <nl> const AotCompilationOptions & options ) ; <nl> <nl> + StatusOr < std : : vector < std : : unique_ptr < AotCompilationResult > > > <nl> + CompileAheadOfTime ( <nl> + const tensorflow : : gtl : : ArraySlice < AotXlaComputationInstance > computations , <nl> + const AotCompilationOptions & options , <nl> + std : : unique_ptr < AotCompilationMetadata > * metadata ) ; <nl> + <nl> Status GetDeviceHandles ( const GetDeviceHandlesRequest * arg , <nl> GetDeviceHandlesResponse * result ) override { <nl> return Unimplemented ( " CompileOnlyService does not support devices . " ) ; <nl> mmm a / tensorflow / compiler / xla / service / compiler . cc <nl> ppp b / tensorflow / compiler / xla / service / compiler . cc <nl> Compiler : : ComputeBackendConfigs ( const HloInstruction & hlo , <nl> return { } ; <nl> } <nl> <nl> + / / Define a default version where metadata is not used . <nl> + StatusOr < std : : vector < std : : unique_ptr < AotCompilationResult > > > <nl> + Compiler : : CompileAheadOfTime ( <nl> + std : : vector < std : : unique_ptr < HloModule > > modules , <nl> + const AotCompilationOptions & options , <nl> + std : : unique_ptr < AotCompilationMetadata > * metadata ) { <nl> + if ( metadata ! = nullptr ) { <nl> + return Unimplemented ( <nl> + " Populating AotCompilationMetadata is not implemented on this " <nl> + " compiler . " ) ; <nl> + } <nl> + return CompileAheadOfTime ( std : : move ( modules ) , options ) ; <nl> + } <nl> + <nl> / * static * / std : : map < se : : Platform : : Id , Compiler : : CompilerFactory > * <nl> Compiler : : GetPlatformCompilerFactories ( ) { <nl> static auto * r = new std : : map < se : : Platform : : Id , CompilerFactory > ; <nl> mmm a / tensorflow / compiler / xla / service / compiler . h <nl> ppp b / tensorflow / compiler / xla / service / compiler . h <nl> class AotCompilationOptions { <nl> DebugOptions debug_options_ ; <nl> } ; <nl> <nl> + / / Abstract superclass describing metadata produced during ahead - of - time <nl> + / / compilation . <nl> + class AotCompilationMetadata { <nl> + public : <nl> + AotCompilationMetadata ( const AotCompilationMetadata & ) = delete ; <nl> + AotCompilationMetadata & operator = ( AotCompilationMetadata const & ) = delete ; <nl> + <nl> + virtual ~ AotCompilationMetadata ( ) = default ; <nl> + <nl> + protected : <nl> + AotCompilationMetadata ( ) = default ; <nl> + } ; <nl> + <nl> / / Abstract compiler interface that is subclassed for compilation on a <nl> / / particular platform . <nl> / / <nl> class Compiler { <nl> CompileAheadOfTime ( std : : vector < std : : unique_ptr < HloModule > > modules , <nl> const AotCompilationOptions & options ) = 0 ; <nl> <nl> + / / Similar to CompileAheadOfTime above but AotCompilationMetadata <nl> + / / has an argument that can be populated during compilation . <nl> + virtual StatusOr < std : : vector < std : : unique_ptr < AotCompilationResult > > > <nl> + CompileAheadOfTime ( std : : vector < std : : unique_ptr < HloModule > > modules , <nl> + const AotCompilationOptions & options , <nl> + std : : unique_ptr < AotCompilationMetadata > * metadata ) ; <nl> + <nl> / / / / / <nl> / / The Compiler class also serves as a point to register compiler objects <nl> / / for the various platforms . <nl> | Add AotCompilationMetadata field to variant of CompileAheadOfTime . | tensorflow/tensorflow | 65cefda2f9a62f29af51b3effa0725c180244576 | 2018-06-13T17:03:26Z |
mmm a / Code / CryEngine / CryCommon / CryCore / ToolsHelpers / ResourceCompilerHelper . h <nl> ppp b / Code / CryEngine / CryCommon / CryCore / ToolsHelpers / ResourceCompilerHelper . h <nl> enum ERcExitCode <nl> eRcExitCode_Crash = 101 , <nl> eRcExitCode_UserFixing = 200 , <nl> eRcExitCode_Pending = 666 , <nl> + eRcExitCode_Skipped = 667 , <nl> } ; <nl> <nl> / / ! Listener for synchronous resource - compilation . <nl> mmm a / Code / CryEngine / CryCommon / CryString / CryPath . h <nl> ppp b / Code / CryEngine / CryCommon / CryString / CryPath . h <nl> inline string GetProjectFolder ( ) <nl> } <nl> checkedForCmdLineProjectArg = true ; <nl> } <nl> - return cmdLineProjectPath ; <nl> + return PathUtil : : ToUnixPath ( cmdLineProjectPath ) ; <nl> } <nl> <nl> inline string GetLocalizationFolder ( ) <nl> inline string MakeGamePath ( const char * szPath ) <nl> { <nl> return MakeGamePath ( string ( szPath ) ) ; <nl> } <nl> + <nl> + / / ! Make a project correct path out of any input path . <nl> + template < typename TString > <nl> + typename std : : enable_if < detail : : IsValidStringType < TString > : : value , TString > : : type <nl> + inline / * TString * / MakeProjectPath ( const TString & path ) <nl> + { <nl> + const auto fullpath = ToUnixPath ( path ) ; <nl> + const auto rootDataFolder = ToUnixPath ( AddSlash ( PathUtil : : GetProjectFolder ( ) ) ) ; <nl> + if ( fullpath . length ( ) > rootDataFolder . length ( ) & & strnicmp ( fullpath . c_str ( ) , rootDataFolder . c_str ( ) , rootDataFolder . length ( ) ) = = 0 ) <nl> + { <nl> + return fullpath . substr ( rootDataFolder . length ( ) , fullpath . length ( ) - rootDataFolder . length ( ) ) ; <nl> + } <nl> + return fullpath ; <nl> + } <nl> + <nl> + inline string MakeProjectPath ( const char * szPath ) <nl> + { <nl> + return MakeProjectPath ( string ( szPath ) ) ; <nl> + } <nl> } <nl> # endif <nl> mmm a / Code / CryEngine / RenderDll / Common / Textures / TextureCompiler . cpp <nl> ppp b / Code / CryEngine / RenderDll / Common / Textures / TextureCompiler . cpp <nl> <nl> <nl> DECLARE_JOB ( " AsyncResourceCompiler " , TAsyncResourceCompilerJob , CTextureCompiler : : ConsumeQueuedResourceCompiler ) ; <nl> <nl> + namespace Private_TextureCompiler <nl> + { <nl> + <nl> + void AddResourceCachePrefix ( char path [ ] ) <nl> + { <nl> + const ICVar * pCacheFolderVar = gEnv - > pConsole - > GetCVar ( " sys_resource_cache_folder " ) ; <nl> + const auto cacheFolder = pCacheFolderVar - > GetString ( ) ; <nl> + const auto cacheFolderLen = strlen ( cacheFolder ) ; <nl> + memmove ( path + cacheFolderLen + 1 , path , strlen ( path ) + 1 ) ; <nl> + memcpy ( path , cacheFolder , cacheFolderLen ) ; <nl> + path [ cacheFolderLen ] = ' / ' ; <nl> + for ( int i = 0 ; i < cacheFolderLen ; + + i ) <nl> + { <nl> + if ( path [ i ] = = ' \ \ ' ) <nl> + { <nl> + path [ i ] = ' / ' ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + bool IsAlias ( const char * szFilename ) <nl> + { <nl> + return * szFilename = = ' % ' ; <nl> + } <nl> + <nl> + } <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> CTextureCompiler : : CTextureCompiler ( ) <nl> { <nl> void CTextureCompiler : : NotifyCompilationQueueDepleted ( ) <nl> <nl> void CTextureCompiler : : NotifyCompilationFinished ( TProcItem * item ) <nl> { <nl> + NotifyCompilationFinished ( item - > src . c_str ( ) , item - > dst . c_str ( ) , item - > returnval ) ; <nl> + } <nl> + <nl> + void CTextureCompiler : : NotifyCompilationFinished ( const char * szSourceFile , const char * szDestFile , ERcExitCode eReturnCode ) <nl> + { <nl> + const auto & source = PathUtil : : MakeProjectPath ( szSourceFile ) ; <nl> + const auto & dest = PathUtil : : MakeProjectPath ( szDestFile ) ; <nl> CryAutoReadLock < CryRWLock > lock ( m_rwLockNotify ) ; <nl> for ( IAsyncTextureCompileListener * notify : m_sNotifyList ) <nl> { <nl> - notify - > OnCompilationFinished ( item - > src . c_str ( ) , item - > dst . c_str ( ) , item - > returnval ) ; <nl> + notify - > OnCompilationFinished ( source . c_str ( ) , dest . c_str ( ) , eReturnCode ) ; <nl> } ; <nl> } <nl> <nl> void CTextureCompiler : : NotifyCompilationQueueTriggered ( int pending ) <nl> } ; <nl> } <nl> <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> CTextureCompiler : : EResult CTextureCompiler : : ProcessTextureIfNeeded ( <nl> - const char * originalFilename , <nl> + const char * szOriginalFilename , <nl> char * processedFilename , <nl> size_t processedFilenameSizeInBytes , <nl> bool immediate ) <nl> { <nl> - / / allocates 1k upto 4k on the stack <nl> + using namespace Private_TextureCompiler ; <nl> + / / allocates 1k up to 4k on the stack <nl> char sSrcFile [ MAX_PATH ] ; <nl> char sDestFile [ MAX_PATH ] ; <nl> <nl> char sFullSrcFilename [ MAX_PATH ] ; <nl> char sFullDestFilename [ MAX_PATH ] ; <nl> <nl> - GetOutputFilename ( originalFilename , sDestFile , sizeof ( sDestFile ) ) ; <nl> + GetOutputFilename ( szOriginalFilename , sDestFile , sizeof ( sDestFile ) ) ; <nl> + <nl> + if ( ! IsAlias ( szOriginalFilename ) ) <nl> + { <nl> + Private_TextureCompiler : : AddResourceCachePrefix ( sDestFile ) ; <nl> + } <nl> <nl> / / Adjust filename so that it is global . <nl> gEnv - > pCryPak - > AdjustFileName ( sDestFile , sFullDestFilename , 0 ) ; <nl> CTextureCompiler : : EResult CTextureCompiler : : ProcessTextureIfNeeded ( <nl> <nl> for ( uint32 dwIndex = 0 ; ; + + dwIndex ) / / check for all input files <nl> { <nl> - GetInputFilename ( originalFilename , dwIndex , sSrcFile , sizeof ( sSrcFile ) ) ; <nl> + GetInputFilename ( szOriginalFilename , dwIndex , sSrcFile , sizeof ( sSrcFile ) ) ; <nl> <nl> if ( sSrcFile [ 0 ] = = 0 ) <nl> { <nl> CTextureCompiler : : EResult CTextureCompiler : : ProcessTextureIfNeeded ( <nl> sourceFile . Close ( ) ; <nl> } <nl> <nl> + bool isSkipped = false ; <nl> / / is there no destination file ? <nl> if ( sourceFile . GetHandle ( ) ! = nullptr & & destinationFile . GetHandle ( ) = = nullptr ) <nl> { <nl> bInvokeResourceCompiler = true ; <nl> } <nl> - <nl> / / if both files exist , is the source file newer ? <nl> - if ( sourceFile . GetHandle ( ) ! = nullptr & & destinationFile . GetHandle ( ) ! = nullptr & & ! IsFileReadOnly ( sFullDestFilename ) ) <nl> + else if ( sourceFile . GetHandle ( ) ! = nullptr & & destinationFile . GetHandle ( ) ! = nullptr & & ! IsFileReadOnly ( sFullDestFilename ) ) <nl> { <nl> ICryPak : : FileTime timeSrc = gEnv - > pCryPak - > GetModificationTime ( sourceFile . GetHandle ( ) ) ; <nl> ICryPak : : FileTime timeDest = gEnv - > pCryPak - > GetModificationTime ( destinationFile . GetHandle ( ) ) ; <nl> CTextureCompiler : : EResult CTextureCompiler : : ProcessTextureIfNeeded ( <nl> { <nl> bInvokeResourceCompiler = ( timeDest ! = timeSrc ) ; <nl> } <nl> + isSkipped = ! bInvokeResourceCompiler ; <nl> } <nl> <nl> destinationFile . Close ( ) ; <nl> CTextureCompiler : : EResult CTextureCompiler : : ProcessTextureIfNeeded ( <nl> <nl> if ( ! processed ) <nl> { <nl> - cry_strcpy ( processedFilename , processedFilenameSizeInBytes , originalFilename ) ; <nl> + cry_strcpy ( processedFilename , processedFilenameSizeInBytes , szOriginalFilename ) ; <nl> <nl> / / rc failed <nl> return EResult : : Failed ; <nl> } <nl> } <nl> + else if ( isSkipped & & ! IsAlias ( szOriginalFilename ) ) <nl> + { <nl> + NotifyCompilationFinished ( sFullSrcFilename , sFullDestFilename , eRcExitCode_Skipped ) ; <nl> + } <nl> <nl> break ; <nl> } <nl> mmm a / Code / CryEngine / RenderDll / Common / Textures / TextureCompiler . h <nl> ppp b / Code / CryEngine / RenderDll / Common / Textures / TextureCompiler . h <nl> class CTextureCompiler : public CResourceCompilerHelper , NoCopy <nl> bool AddToWatchList ( const char * szDstFile , const char * szSrcFile ) ; <nl> void NotifyCompilationQueueTriggered ( int pending ) ; <nl> void NotifyCompilationStarted ( TProcItem * item , int pending ) ; <nl> + void NotifyCompilationFinished ( const char * szSourceFile , const char * szDestFile , ERcExitCode eReturnCode ) ; <nl> void NotifyCompilationFinished ( TProcItem * item ) ; <nl> void NotifyCompilationQueueDepleted ( ) ; <nl> void GetNextItem ( TProcItem * & item , int & pending ) ; <nl> mmm a / Code / Sandbox / EditorQt / AssetSystem / TextureAssetType . h <nl> ppp b / Code / Sandbox / EditorQt / AssetSystem / TextureAssetType . h <nl> class CTextureType : public CAssetType <nl> virtual bool IsImported ( ) const override { return true ; } <nl> virtual bool CanBeCopied ( ) const { return true ; } <nl> virtual bool CanBeEdited ( ) const override { return true ; } <nl> + virtual bool HasDerivedFiles ( ) const { return true ; } <nl> virtual bool HasThumbnail ( ) const override { return true ; } <nl> virtual QColor GetThumbnailColor ( ) const override { return QColor ( 79 , 187 , 185 ) ; } <nl> virtual std : : vector < CItemModelAttribute * > GetDetails ( ) const override ; <nl> mmm a / Code / Sandbox / EditorQt / LevelEditor / LevelAssetType . cpp <nl> ppp b / Code / Sandbox / EditorQt / LevelEditor / LevelAssetType . cpp <nl> CAssetEditor * CLevelType : : Edit ( CAsset * pAsset ) const <nl> return nullptr ; <nl> } <nl> <nl> - std : : vector < string > CLevelType : : GetAssetFiles ( const CAsset & asset , bool includeSourceFile , bool makeAbsolute , bool includeThumbnail ) const <nl> + std : : vector < string > CLevelType : : GetAssetFiles ( const CAsset & asset , bool includeSourceFile , bool makeAbsolute , bool includeThumbnail , bool includeDerived ) const <nl> { <nl> - std : : vector < string > files = CAssetType : : GetAssetFiles ( asset , includeSourceFile , makeAbsolute , includeThumbnail ) ; <nl> + std : : vector < string > files = CAssetType : : GetAssetFiles ( asset , includeSourceFile , makeAbsolute , includeThumbnail , includeDerived ) ; <nl> <nl> if ( makeAbsolute ) <nl> { <nl> mmm a / Code / Sandbox / EditorQt / LevelEditor / LevelAssetType . h <nl> ppp b / Code / Sandbox / EditorQt / LevelEditor / LevelAssetType . h <nl> class CLevelType : public CAssetType <nl> virtual bool RenameAsset ( CAsset * pAsset , const char * szNewName ) const override { return false ; } <nl> virtual bool MoveAsset ( CAsset * pAsset , const char * szNewPath , bool bMoveSourcefile ) const override { return false ; } <nl> virtual CAssetEditor * Edit ( CAsset * pAsset ) const override ; <nl> - virtual std : : vector < string > GetAssetFiles ( const CAsset & asset , bool includeSourceFile , bool makeAbsolute , bool includeThumbnail = true ) const override ; <nl> + virtual std : : vector < string > GetAssetFiles ( const CAsset & asset , bool includeSourceFile , bool makeAbsolute , bool includeThumbnail = true , bool includeDerived = false ) const override ; <nl> virtual bool OnValidateAssetPath ( const char * szFilepath , / * out * / string & reasonToReject ) const override ; <nl> <nl> static const char * GetFileExtensionStatic ( ) { return " level " ; } <nl> mmm a / Code / Sandbox / Plugins / EditorCommon / AssetSystem / AssetGenerator . cpp <nl> ppp b / Code / Sandbox / Plugins / EditorCommon / AssetSystem / AssetGenerator . cpp <nl> class CBatchProcess : public CProgressNotification <nl> <nl> static AssetManagerHelpers : : CAssetGenerator * s_pInstance = nullptr ; <nl> <nl> + bool IsGameFolderPath ( const char * szSource ) <nl> + { <nl> + const string gameFolder = PathUtil : : GetGameFolder ( ) ; <nl> + return strnicmp ( szSource , gameFolder . c_str ( ) , gameFolder . size ( ) ) = = 0 & & <nl> + strlen ( szSource ) > gameFolder . size ( ) & & szSource [ gameFolder . size ( ) ] = = ' / ' ; <nl> + } <nl> + <nl> } <nl> <nl> namespace AssetManagerHelpers <nl> CAssetGenerator : : CAssetGenerator ( ) <nl> m_rcSettings . AppendFormat ( " % s , % s ; " , pType - > GetFileExtension ( ) , pType - > GetTypeName ( ) ) ; <nl> GetIEditor ( ) - > GetFileMonitor ( ) - > RegisterListener ( this , " " , pType - > GetFileExtension ( ) ) ; <nl> } <nl> - m_rcSettings . Append ( " \ " " ) ; <nl> <nl> / / TODO : There are . wav . cryasset and . ogg . cryasset for the CSoundType . Remove the following scoped lines when this is fixed . <nl> { <nl> CAssetGenerator : : CAssetGenerator ( ) <nl> GetIEditor ( ) - > GetFileMonitor ( ) - > RegisterListener ( this , " " , " ogg " ) ; <nl> } <nl> <nl> + m_rcSettings . Append ( " \ " " ) ; <nl> + <nl> m_rcSettings . shrink_to_fit ( ) ; <nl> } <nl> <nl> - void CAssetGenerator : : GenerateCryasset ( const string & filePath ) <nl> + void CAssetGenerator : : GenerateCryasset ( const string & filePath , const string & destFolder / * = " " * / ) <nl> { <nl> using namespace Private_AssetGenerator ; <nl> <nl> void CAssetGenerator : : GenerateCryasset ( const string & filePath ) <nl> } <nl> static_cast < CBatchProcess * > ( m_pProgress . get ( ) ) - > PushItem ( ) ; <nl> <nl> - ThreadingUtils : : AsyncQueue ( [ filePath , this ] ( ) <nl> + ThreadingUtils : : AsyncQueue ( [ filePath , destFolder , this ] ( ) <nl> { <nl> RCLogger rcLogger ; <nl> <nl> void CAssetGenerator : : GenerateCryasset ( const string & filePath ) <nl> { <nl> / / TODO : Move the implementation to a virtual function of CAssetType . Thus , each asset would override the default implementation . <nl> <nl> + string extendedSettings ; <nl> + if ( ! destFolder . empty ( ) ) <nl> + { <nl> + extendedSettings = m_rcSettings + " / targetroot = \ " " + destFolder + " \ " " ; <nl> + } <nl> + const string & currentSettings = destFolder . empty ( ) ? m_rcSettings : extendedSettings ; <nl> + <nl> CResourceCompilerHelper : : CallResourceCompiler ( <nl> filePath . c_str ( ) , <nl> - m_rcSettings . c_str ( ) , <nl> + currentSettings . c_str ( ) , <nl> & rcLogger , <nl> false , / / may show window ? <nl> CResourceCompilerHelper : : eRcExePath_editor , <nl> void CAssetGenerator : : OnCompilationStarted ( const char * szSource , const char * szT <nl> <nl> void CAssetGenerator : : OnCompilationFinished ( const char * szSource , const char * szTarget , ERcExitCode eReturnCode ) <nl> { <nl> + using namespace Private_AssetGenerator ; <nl> + if ( ! IsGameFolderPath ( szSource ) ) <nl> + { <nl> + return ; <nl> + } <nl> + <nl> + auto const absRoot = PathUtil : : GetCurrentProjectDirectoryAbsolute ( ) ; <nl> + auto const destFolder = PathUtil : : Make ( absRoot , PathUtil : : GetDirectory ( PathUtil : : ToUnixPath ( szSource ) ) ) ; <nl> + auto const targetFile = PathUtil : : Make ( absRoot , PathUtil : : ToUnixPath ( szTarget ) ) ; <nl> + GenerateCryasset ( targetFile , destFolder ) ; <nl> } <nl> <nl> void CAssetGenerator : : OnCompilationQueueTriggered ( int nPending ) <nl> mmm a / Code / Sandbox / Plugins / EditorCommon / AssetSystem / AssetGenerator . h <nl> ppp b / Code / Sandbox / Plugins / EditorCommon / AssetSystem / AssetGenerator . h <nl> class CAssetGenerator : public IFileChangeListener , public IAsyncTextureCompileL <nl> virtual void OnCompilationQueueTriggered ( int nPending ) override ; <nl> virtual void OnCompilationQueueDepleted ( ) override ; <nl> <nl> - void GenerateCryasset ( const string & filePath ) ; <nl> + void GenerateCryasset ( const string & filePath , const string & destFolder = " " ) ; <nl> <nl> / / ! Generates / repair * . cryasset files for the current project . <nl> static bool GenerateCryassets ( ) ; <nl> mmm a / Code / Sandbox / Plugins / EditorCommon / AssetSystem / AssetManager . cpp <nl> ppp b / Code / Sandbox / Plugins / EditorCommon / AssetSystem / AssetManager . cpp <nl> void CAssetManager : : DeleteAssetsOnlyFromData ( std : : vector < CAsset * > assets ) <nl> signalAfterAssetsRemoved ( ) ; <nl> } <nl> <nl> - void CAssetManager : : MoveAssets ( const std : : vector < CAsset * > & assets , const char * szDestinationFolder ) const <nl> + void CAssetManager : : MoveAssets ( const std : : vector < CAsset * > & assets , const char * szDestinationFolder ) <nl> { <nl> + using namespace Private_AssetManager ; <nl> for ( CAsset * pAsset : assets ) <nl> { <nl> if ( ! pAsset ) <nl> void CAssetManager : : MoveAssets ( const std : : vector < CAsset * > & assets , const char * s <nl> <nl> / / Make a new copy of the source file if it is shared between several assets , move it to the new location otherwise . <nl> const bool bMoveSourceFile = ! HasSharedSourceFile ( * pAsset ) ; <nl> + DeleteAssetFilesFromMap ( m_fileToAssetMap , pAsset ) ; <nl> pAsset - > GetType ( ) - > MoveAsset ( pAsset , szDestinationFolder , bMoveSourceFile ) ; <nl> + AddAssetFilesToMap ( m_fileToAssetMap , pAsset ) ; <nl> + m_orderedByGUID = false ; <nl> } <nl> } <nl> <nl> mmm a / Code / Sandbox / Plugins / EditorCommon / AssetSystem / AssetManager . h <nl> ppp b / Code / Sandbox / Plugins / EditorCommon / AssetSystem / AssetManager . h <nl> class EDITOR_COMMON_API CAssetManager <nl> / / ! Moves existing assets to the specified folder , including all assets files . <nl> / / ! \ param assets A collection of assets to be moved . <nl> / / ! \ param szDestinationFolder The destination folder . The path must be relative to the assets root directory . <nl> - void MoveAssets ( const std : : vector < CAsset * > & assets , const char * szDestinationFolder ) const ; <nl> + void MoveAssets ( const std : : vector < CAsset * > & assets , const char * szDestinationFolder ) ; <nl> <nl> / / ! Renames an existing asset . <nl> / / ! \ param pAsset The asset to be renamed . <nl> mmm a / Code / Sandbox / Plugins / EditorCommon / AssetSystem / AssetType . cpp <nl> ppp b / Code / Sandbox / Plugins / EditorCommon / AssetSystem / AssetType . cpp <nl> static bool TryReplaceFilename ( const string & oldNamePrefix , const string & newNam <nl> } <nl> <nl> / / Rename asset file . Expects paths relative to the assets root directory . <nl> - static bool RenameAssetFile ( const string & oldFilename , const string & newFilename ) <nl> + static bool RenameAssetFile ( const string & oldFilename , const string & newFilename , string rootFolder = " " ) <nl> { <nl> - const string oldFilepath = PathUtil : : Make ( PathUtil : : GetGameProjectAssetsPath ( ) , oldFilename ) ; <nl> - const string newFilepath = PathUtil : : Make ( PathUtil : : GetGameProjectAssetsPath ( ) , newFilename ) ; <nl> + if ( rootFolder . empty ( ) ) <nl> + { <nl> + rootFolder = PathUtil : : GetGameProjectAssetsPath ( ) ; <nl> + } <nl> + const string oldFilepath = PathUtil : : Make ( rootFolder , oldFilename ) ; <nl> + const string newFilepath = PathUtil : : Make ( rootFolder , newFilename ) ; <nl> <nl> if ( ! QFileInfo ( QtUtil : : ToQString ( oldFilepath ) ) . exists ( ) ) <nl> { <nl> static bool RenameAssetFile ( const string & oldFilename , const string & newFilename <nl> } <nl> <nl> / / Copy asset file . Expects paths relative to the assets root directory . <nl> - static bool CopyAssetFile ( const string & oldFilename , const string & newFilename ) <nl> + static bool CopyAssetFile ( const string & oldFilename , const string & newFilename , const string & destRoot = " " ) <nl> { <nl> if ( oldFilename . empty ( ) | | newFilename . empty ( ) | | oldFilename . CompareNoCase ( newFilename ) = = 0 ) <nl> { <nl> return true ; <nl> } <nl> <nl> - const string newFilepath = PathUtil : : ToUnixPath ( PathUtil : : Make ( PathUtil : : GetGameProjectAssetsPath ( ) , newFilename ) ) ; <nl> + const string newFilepath = PathUtil : : ToUnixPath ( PathUtil : : Make ( <nl> + destRoot . empty ( ) ? PathUtil : : GetGameProjectAssetsPath ( ) : destRoot , newFilename ) ) ; <nl> if ( FileUtils : : Pak : : CopyFileAllowOverwrite ( oldFilename . c_str ( ) , newFilepath . c_str ( ) ) ) <nl> { <nl> return true ; <nl> std : : vector < CAsset * > CAssetType : : Import ( const string & sourceFilePath , const stri <nl> return pAssetImporter - > Import ( { GetTypeName ( ) } , ctx ) ; <nl> } <nl> <nl> - std : : vector < string > CAssetType : : GetAssetFiles ( const CAsset & asset , bool includeSourceFile , bool makeAbsolute / * = false * / , bool includeThumbnail / * = true * / ) const <nl> + std : : vector < string > CAssetType : : GetAssetFiles ( const CAsset & asset , bool includeSourceFile , bool makeAbsolute / * = false * / <nl> + , bool includeThumbnail / * = true * / , bool includeDerived / * = false * / ) const <nl> { <nl> + const bool includeDataFiles = ! HasDerivedFiles ( ) | | includeDerived ; <nl> std : : vector < string > files ; <nl> - files . reserve ( asset . GetFilesCount ( ) + 3 ) ; <nl> - for ( size_t i = 0 , N = asset . GetFilesCount ( ) ; i < N ; + + i ) <nl> - { <nl> - files . emplace_back ( asset . GetFile ( i ) ) ; <nl> - } <nl> + files . reserve ( 3 + ( includeDataFiles ? 0 : asset . GetFilesCount ( ) ) ) ; <nl> files . emplace_back ( asset . GetMetadataFile ( ) ) ; <nl> if ( includeThumbnail & & HasThumbnail ( ) ) <nl> { <nl> std : : vector < string > CAssetType : : GetAssetFiles ( const CAsset & asset , bool includeS <nl> <nl> if ( makeAbsolute ) <nl> { <nl> - const string assetsPath ( PathUtil : : GetGameProjectAssetsPath ( ) ) ; <nl> + const string assetsPath = PathUtil : : GetGameProjectAssetsPath ( ) ; <nl> for ( string & filename : files ) <nl> { <nl> filename = PathUtil : : Make ( assetsPath , filename ) ; <nl> } <nl> } <nl> <nl> + if ( includeDataFiles ) <nl> + { <nl> + for ( size_t i = 0 , N = asset . GetFilesCount ( ) ; i < N ; + + i ) <nl> + { <nl> + if ( makeAbsolute ) <nl> + { <nl> + files . emplace_back ( PathUtil : : Make ( HasDerivedFiles ( ) ? <nl> + PathUtil : : GetEditorCachePath ( ) : PathUtil : : GetGameProjectAssetsPath ( ) , asset . GetFile ( i ) ) ) ; <nl> + } <nl> + else <nl> + { <nl> + files . emplace_back ( asset . GetFile ( i ) ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> return files ; <nl> } <nl> <nl> bool CAssetType : : OnCopy ( INewAsset & asset , CAsset & assetToCopy ) const <nl> if ( Private_AssetType : : TryReplaceFilename ( assetToCopy . GetName ( ) , asset . GetName ( ) , file , newFile ) ) <nl> { <nl> newFile = PathUtil : : AdjustCasing ( PathUtil : : Make ( destinationFolder , PathUtil : : GetFile ( newFile ) ) ) ; <nl> - Private_AssetType : : CopyAssetFile ( file , newFile ) ; <nl> + Private_AssetType : : CopyAssetFile ( file , newFile , <nl> + assetToCopy . GetType ( ) - > HasDerivedFiles ( ) ? PathUtil : : GetEditorCachePath ( ) : " " ) ; <nl> file = newFile ; <nl> } <nl> } <nl> bool CAssetType : : RenameAsset ( CAsset * pAsset , const char * szNewName ) const <nl> string newFile ; <nl> if ( Private_AssetType : : TryReplaceFilename ( oldName , newName , file , newFile ) ) <nl> { <nl> - if ( Private_AssetType : : RenameAssetFile ( file , newFile ) ) <nl> + if ( Private_AssetType : : RenameAssetFile ( file , newFile , <nl> + pAsset - > GetType ( ) - > HasDerivedFiles ( ) ? PathUtil : : GetEditorCachePath ( ) : " " ) ) <nl> { <nl> file = newFile ; <nl> } <nl> bool CAssetType : : MoveAsset ( CAsset * pAsset , const char * szDestinationFolder , bool <nl> <nl> bool bReadOnly = false ; <nl> { <nl> - std : : vector < string > filepaths ( GetAssetFiles ( * pAsset , bMoveSourcefile , true ) ) ; <nl> + std : : vector < string > filepaths ( GetAssetFiles ( * pAsset , bMoveSourcefile , true , true , true ) ) ; <nl> for ( string & path : filepaths ) <nl> { <nl> QFileInfo fileInfo ( QtUtil : : ToQString ( path ) ) ; <nl> bool CAssetType : : MoveAsset ( CAsset * pAsset , const char * szDestinationFolder , bool <nl> for ( string & file : files ) <nl> { <nl> string newFile = PathUtil : : Make ( szDestinationFolder , PathUtil : : GetFile ( file ) ) ; <nl> - if ( Private_AssetType : : RenameAssetFile ( file , newFile ) ) <nl> + if ( Private_AssetType : : RenameAssetFile ( file , newFile , <nl> + pAsset - > GetType ( ) - > HasDerivedFiles ( ) ? PathUtil : : GetEditorCachePath ( ) : " " ) ) <nl> { <nl> file = newFile ; <nl> } <nl> mmm a / Code / Sandbox / Plugins / EditorCommon / AssetSystem / AssetType . h <nl> ppp b / Code / Sandbox / Plugins / EditorCommon / AssetSystem / AssetType . h <nl> class EDITOR_COMMON_API CAssetType : public IClassDesc <nl> virtual std : : vector < CItemModelAttribute * > GetDetails ( ) const { return std : : vector < CItemModelAttribute * > ( ) ; } <nl> virtual QVariant GetDetailValue ( const CAsset * pAsset , const CItemModelAttribute * pDetail ) const { return QVariant ( ) ; } <nl> <nl> + / / ! Returns true if the asset ' s data files are derived and therefore are located in the cache folder ( like * . dds ) . <nl> + virtual bool HasDerivedFiles ( ) const { return false ; } <nl> + <nl> / / ! Returns true if the asset may have a thumbnail <nl> virtual bool HasThumbnail ( ) const { return false ; } <nl> <nl> class EDITOR_COMMON_API CAssetType : public IClassDesc <nl> / / Returns a collection of paths to all files belonging to the asset . <nl> / / The collection includes the asset metadata , thumbnail and data files . As an option , the collection can also include the asset source file . <nl> / / ! \ param asset An instance of asset to be examined . <nl> - / / ! \ param includeSourceFile If true , the collection will include the asset source file , if any . <nl> + / / ! \ param includeSourceFile If true , the collection will include the asset ' s source file , if any . <nl> / / ! \ param makeAbsolute By default the paths are relative to the assets root directory . <nl> - virtual std : : vector < string > GetAssetFiles ( const CAsset & asset , bool includeSourceFile , bool makeAbsolute = false , bool includeThumbnail = true ) const ; <nl> + / / ! \ param includeThumbnail If true , the collection will include the asset ' s thumbnail file , if any . <nl> + / / ! \ param includeDerived If true , the collection will include the asset ' s derived files , if any . <nl> + virtual std : : vector < string > GetAssetFiles ( const CAsset & asset , bool includeSourceFile , bool makeAbsolute = false , bool includeThumbnail = true , bool includeDerived = false ) const ; <nl> <nl> / / ! Returns the color code of the thumbnail . <nl> virtual QColor GetThumbnailColor ( ) const { return QColor ( Qt : : green ) ; } <nl> mmm a / Code / Sandbox / Plugins / EditorCommon / AssetSystem / Browser / AssetFoldersModel . cpp <nl> ppp b / Code / Sandbox / Plugins / EditorCommon / AssetSystem / Browser / AssetFoldersModel . cpp <nl> bool CanMove ( const std : : vector < CAsset * > & assets , const string & folder ) <nl> <nl> void OnMove ( const std : : vector < CAsset * > & assets , const QString & destinationFolder ) <nl> { <nl> - const CAssetManager * const pAssetManager = CAssetManager : : GetInstance ( ) ; <nl> + CAssetManager * const pAssetManager = CAssetManager : : GetInstance ( ) ; <nl> <nl> const QString question = QObject : : tr ( " There is a possibility of undetected dependencies which can be violated after performing the operation . \ n " <nl> " \ n " <nl> mmm a / Code / Sandbox / Plugins / EditorCommon / PathUtils . cpp <nl> ppp b / Code / Sandbox / Plugins / EditorCommon / PathUtils . cpp <nl> string GetGameProjectAssetsRelativePath ( ) <nl> return gEnv - > pSystem - > GetIProjectManager ( ) - > GetCurrentAssetDirectoryRelative ( ) ; <nl> } <nl> <nl> + string GetEditorCachePath ( ) <nl> + { <nl> + return Make ( GetProjectFolder ( ) , GetEditorCacheRelativePath ( ) ) ; <nl> + } <nl> + <nl> + string GetEditorCacheRelativePath ( ) <nl> + { <nl> + const ICVar * pCacheFolderVar = gEnv - > pConsole - > GetCVar ( " sys_resource_cache_folder " ) ; <nl> + return ToUnixPath ( pCacheFolderVar - > GetString ( ) ) ; <nl> + } <nl> + <nl> + string GetCurrentProjectDirectoryAbsolute ( ) <nl> + { <nl> + return gEnv - > pSystem - > GetIProjectManager ( ) - > GetCurrentProjectDirectoryAbsolute ( ) ; <nl> + } <nl> + <nl> string GetCurrentPlatformFolder ( ) <nl> { <nl> # ifdef CRY_PLATFORM_WINDOWS <nl> mmm a / Code / Sandbox / Plugins / EditorCommon / PathUtils . h <nl> ppp b / Code / Sandbox / Plugins / EditorCommon / PathUtils . h <nl> EDITOR_COMMON_API string GetGameProjectAssetsPath ( ) ; <nl> / / ! For example , for " path A : / ProjectDir / Assets " return value would be " Assets " <nl> EDITOR_COMMON_API string GetGameProjectAssetsRelativePath ( ) ; <nl> <nl> + / / ! Returns absolute path to the editor ' s resource cache folder of active project . <nl> + / / ! Path uses unix - style delimiters and contains no trailing delimiter . <nl> + / / ! Example : A : / ProjectDir / Editor / ResourceCache <nl> + EDITOR_COMMON_API string GetEditorCachePath ( ) ; <nl> + <nl> + / / ! Returns relative path to game the editor ' s resource cache folder of active project . <nl> + / / ! Path uses unix - style delimiters and contains no trailing delimiter . <nl> + / / ! Example : Editor / ResourceCache <nl> + EDITOR_COMMON_API string GetEditorCacheRelativePath ( ) ; <nl> + <nl> + / / ! Gets the absolute path to the root of the project directory , where the . cryproject resides . <nl> + / / ! \ return Path without trailing separator . <nl> + EDITOR_COMMON_API string GetCurrentProjectDirectoryAbsolute ( ) ; <nl> + <nl> / / ! Converts any path to a game path ( relative to assets folder ) <nl> / / ! Strips project root path and game directory from ' path ' . <nl> / / ! A : / p4 / GameSDK / Objects / bird . cgf - > Objects / bird . cgf <nl> mmm a / Code / Sandbox / Plugins / MeshImporter / AssetImporterImage . cpp <nl> ppp b / Code / Sandbox / Plugins / MeshImporter / AssetImporterImage . cpp <nl> <nl> <nl> # include " StdAfx . h " <nl> # include " AssetImporterImage . h " <nl> - # include " SandboxPlugin . h " <nl> # include " TextureHelpers . h " <nl> # include " ImporterUtil . h " <nl> - # include " RcCaller . h " <nl> <nl> # include < AssetSystem / AssetImportContext . h > <nl> # include < PathUtils . h > <nl> std : : vector < CAsset * > CAssetImporterImage : : ImportAssets ( const std : : vector < string > <nl> const string absOutputSourceFilePath = PathUtil : : Make ( PathUtil : : GetGameProjectAssetsPath ( ) , ctx . GetOutputSourceFilePath ( ) ) ; <nl> if ( ! fileImporter . Import ( ctx . GetInputFilePath ( ) , absOutputSourceFilePath ) ) <nl> { <nl> - return { } ; <nl> + return { } ; <nl> } <nl> <nl> / / If the source file is a TIF , we make it writable , as we might call the RC and store settings <nl> std : : vector < CAsset * > CAssetImporterImage : : ImportAssets ( const std : : vector < string > <nl> MakeFileWritable ( absOutputSourceFilePath ) ; <nl> } <nl> <nl> - const string tifFilePath = TextureHelpers : : CreateCryTif ( absOutputSourceFilePath ) ; <nl> - if ( ! tifFilePath ) <nl> - { <nl> - return { } ; <nl> - } <nl> + TextureHelpers : : CreateCryTif ( absOutputSourceFilePath ) ; <nl> <nl> - / / Create DDS . <nl> - CRcCaller rcCaller ; <nl> - rcCaller . SetAdditionalOptions ( CRcCaller : : OptionOverwriteFilename ( ctx . GetAssetName ( ) ) ) ; <nl> - if ( ! rcCaller . Call ( tifFilePath ) ) <nl> - { <nl> - return { } ; <nl> - } <nl> - <nl> - CAsset * const pTextureAsset = ctx . LoadAsset ( ctx . GetOutputFilePath ( " dds . cryasset " ) ) ; <nl> - if ( pTextureAsset ) <nl> - { <nl> - return { pTextureAsset } ; <nl> - } <nl> - else <nl> - { <nl> - return { } ; <nl> - } <nl> + / / there is no need to call RC here for tif file and then to load the asset from cryasset file since <nl> + / / file monitor will detect the changes and trigger it anyway . <nl> + return { } ; <nl> } <nl> mmm a / Code / Tools / RC / ResourceCompilerPC / Metadata / MetadataCompiler . cpp <nl> ppp b / Code / Tools / RC / ResourceCompilerPC / Metadata / MetadataCompiler . cpp <nl> bool CMetadataCompiler : : Process ( ) <nl> files = FindDdsAssetFiles ( filename ) ; <nl> <nl> / / try to resolve source file <nl> - const string tifFilename = PathUtil : : ReplaceExtension ( filename . c_str ( ) , " tif " ) ; <nl> + string tifFilename = PathUtil : : ReplaceExtension ( filename . c_str ( ) , " tif " ) ; <nl> if ( FileUtil : : FileExists ( tifFilename ) ) <nl> { <nl> sourceFilename = tifFilename ; <nl> } <nl> + else <nl> + { <nl> + / / try to resolve source file in output folder <nl> + tifFilename = PathUtil : : Make ( m_CC . GetOutputFolder ( ) , <nl> + PathUtil : : ReplaceExtension ( PathUtil : : GetFile ( filename ) , " tif " ) ) ; <nl> + if ( FileUtil : : FileExists ( tifFilename ) ) <nl> + { <nl> + sourceFilename = tifFilename ; <nl> + } <nl> + } <nl> + <nl> } <nl> else if ( ! stricmp ( szExt , " cgf " ) | | ! stricmp ( szExt , " cga " ) | | ! stricmp ( szExt , " skin " ) ) <nl> { <nl> | ! F ( Sandbox ) ( DEV - 7474 ) Provide a way of distinguishing between file dependencies and derived files | CRYTEK/CRYENGINE | f52931b5dbd58cdf8f2eea175dd16d5697aef36b | 2019-03-13T07:45:15Z |
new file mode 100755 <nl> index 0000000000 . . 6e72b85a98 <nl> mmm / dev / null <nl> ppp b / regression_build_test . sh <nl> <nl> + # ! / bin / bash - e <nl> + make clean <nl> + make db_bench - j12 <nl> + <nl> + function send_to_ods { <nl> + key = " $ 1 " <nl> + value = " $ 2 " <nl> + curl - s " https : / / www . intern . facebook . com / intern / agent / ods_set . php ? entity = rocksdb_build & key = $ key & value = $ value " <nl> + } <nl> + <nl> + NUM = 100000000 <nl> + <nl> + DATA_DIR = " $ 1 " <nl> + if [ - z " $ DATA_DIR " ] <nl> + then <nl> + DATA_DIR = " / data / users / abhishekk / test_ldb " <nl> + fi <nl> + STAT_FILE = " / tmp / leveldb_test_stats " <nl> + <nl> + . / db_bench - - benchmarks = fillseq - - db = " $ DATA_DIR " - - use_existing_db = 0 - - bloom_bits = 10 - - num = $ NUM - - writes = $ NUM - - cache_size = 6442450944 - - cache_numshardbits = 6 - - open_files = 55000 - - statistics = 1 - - histogram = 1 - - disable_data_sync = 1 - - disable_wal = 1 - - sync = 0 > " $ STAT_FILE . fillseq " <nl> + <nl> + . / db_bench - - benchmarks = overwrite - - db = $ DATA_DIR - - use_existing_db = 1 - - bloom_bits = 10 - - num = $ NUM - - writes = $ ( ( NUM / 2 ) ) - - cache_size = 6442450944 - - cache_numshardbits = 6 - - open_files = 55000 - - statistics = 1 - - histogram = 1 - - disable_data_sync = 1 - - disable_wal = 1 - - sync = 0 - - threads = 8 > " $ STAT_FILE . overwrite " <nl> + <nl> + . / db_bench - - benchmarks = readrandom - - db = $ DATA_DIR - - use_existing_db = 1 - - bloom_bits = 10 - - num = $ NUM - - reads = $ ( ( NUM / 100 ) ) - - cache_size = 6442450944 - - cache_numshardbits = 6 - - open_files = 55000 - - statistics = 1 - - histogram = 1 - - disable_data_sync = 1 - - disable_wal = 1 - - sync = 0 - - threads = 128 > " $ STAT_FILE . readrandom " <nl> + <nl> + OVERWRITE_OPS = $ ( grep overwrite " $ STAT_FILE . overwrite " | cut - d " / " - f2 | cut - d " " - f2 ) <nl> + FILLSEQ_OPS = $ ( grep fillseq a . out | cut - d " / " - f2 | cut - d " " - f2 ) <nl> + READRANDOM_OPS = $ ( grep readrandom a . out | cut - d " / " - f2 | cut - d " " - f2 ) <nl> + send_to_ods rocksdb . build . overwrite . qps $ OVERWRITE_OPS <nl> + send_to_ods rocksdb . build . fillseq . qps $ FILLSEQ_OPS <nl> + send_to_ods rocksdb . build . readrandom . qps $ READRANDOM_OPS <nl> | Bash script to run db_bench with options and send data to ods . | facebook/rocksdb | 917377c1fcec5833bbd67795bd5e08ca471a15c5 | 2013-01-15T20:18:01Z |
mmm a / tensorflow / compiler / jit / extract_outside_compilation_pass . cc <nl> ppp b / tensorflow / compiler / jit / extract_outside_compilation_pass . cc <nl> limitations under the License . <nl> # include " tensorflow / compiler / tf2xla / tf2xla_util . h " <nl> # include " tensorflow / compiler / xla / status_macros . h " <nl> # include " tensorflow / core / common_runtime / function . h " <nl> - # include " tensorflow / core / common_runtime / lower_functional_ops . h " <nl> # include " tensorflow / core / framework / function . h " <nl> # include " tensorflow / core / framework / graph_to_functiondef . h " <nl> # include " tensorflow / core / framework / node_def_builder . h " <nl> Status BuildHostGraphForFuncCallNode ( <nl> call_builder . Attr ( kXlaHasHostTransferAttrName , true ) ; <nl> call_builder . Attr ( xla_cluster_attr_name , xla_cluster_name ) ; <nl> call_builder . Attr ( outside_compilation_attr_name , call_builder . node_name ( ) ) ; <nl> - / / Make sure control outputs of this function call node will be respected when <nl> - / / this node is lowered . <nl> - call_builder . Attr ( LowerFunctionalOpsPass : : kLowerAsMultiDeviceFunctionAttr , <nl> - true ) ; <nl> NodeDef call_def ; <nl> TF_RETURN_IF_ERROR ( call_builder . Finalize ( & call_def ) ) ; <nl> Status s ; <nl> mmm a / tensorflow / compiler / tf2xla / functionalize_cond . cc <nl> ppp b / tensorflow / compiler / tf2xla / functionalize_cond . cc <nl> Status Conditional : : BuildIfNode ( Graph * graph , <nl> <nl> builder . Attr ( " Tcond " , DT_BOOL ) ; <nl> string outside_compilation ; <nl> - if ( GetNodeAttr ( predicate_ . node - > def ( ) , kXlaOutsideCompilationAttrName , <nl> + if ( GetNodeAttr ( ( * switches_ . begin ( ) ) - > def ( ) , kXlaOutsideCompilationAttrName , <nl> & outside_compilation ) <nl> . ok ( ) ) { <nl> builder . Attr ( kXlaOutsideCompilationAttrName , outside_compilation ) ; <nl> | For outside compilation nodes that are in outside compilation blocks , lower them as V1 function . | tensorflow/tensorflow | 8cc20b9cd0a2348f1290410b3182ca2011ad240e | 2019-08-01T20:55:09Z |
mmm a / doc / developer - notes . md <nl> ppp b / doc / developer - notes . md <nl> code . <nl> <nl> - * * Miscellaneous * * <nl> - ` + + i ` is preferred over ` i + + ` . <nl> + - ` static_assert ` is preferred over ` assert ` where possible . Generally ; compile - time checking is preferred over run - time checking . <nl> <nl> Block style example : <nl> ` ` ` c + + <nl> mmm a / src / arith_uint256 . h <nl> ppp b / src / arith_uint256 . h <nl> class base_uint <nl> <nl> uint64_t GetLow64 ( ) const <nl> { <nl> - assert ( WIDTH > = 2 ) ; <nl> + static_assert ( WIDTH > = 2 , " Assertion WIDTH > = 2 failed ( WIDTH = BITS / 32 ) . BITS is a template parameter . " ) ; <nl> return pn [ 0 ] | ( uint64_t ) pn [ 1 ] < < 32 ; <nl> } <nl> } ; <nl> | Prefer compile - time checking over run - time checking | bitcoin/bitcoin | d1e6f91f85ba81394297ba72271226ece7047303 | 2017-08-16T22:42:32Z |
mmm a / android / samples / sample - gltf - viewer / src / main / AndroidManifest . xml <nl> ppp b / android / samples / sample - gltf - viewer / src / main / AndroidManifest . xml <nl> <nl> android : roundIcon = " @ mipmap / ic_launcher_round " <nl> android : supportsRtl = " true " <nl> android : theme = " @ style / AppTheme " > <nl> - < activity android : name = " com . google . android . filament . gltf . MainActivity " android : screenOrientation = " portrait " > <nl> + < activity android : name = " com . google . android . filament . gltf . MainActivity " <nl> + android : screenOrientation = " fullSensor " <nl> + android : configChanges = " orientation | screenSize | screenLayout | keyboardHidden " > <nl> < intent - filter > <nl> < action android : name = " android . intent . action . MAIN " / > <nl> <nl> | sample - gltf - viewer now supports landscape orientation . | google/filament | 45e6e6eb184e6b3fa5bca88455625327734e1b7f | 2020-02-07T23:20:41Z |
mmm a / Marlin / Marlin . h <nl> ppp b / Marlin / Marlin . h <nl> FORCE_INLINE void serial_echopair_P ( const char * s_P , void * v ) { serial_echopair_ <nl> <nl> / / Things to write to serial from Program memory . Saves 400 to 2k of RAM . <nl> FORCE_INLINE void serialprintPGM ( const char * str ) { <nl> - char ch ; <nl> - while ( ( ch = pgm_read_byte ( str ) ) ) { <nl> - MYSERIAL . write ( ch ) ; <nl> - str + + ; <nl> - } <nl> + while ( char ch = pgm_read_byte ( str + + ) ) MYSERIAL . write ( ch ) ; <nl> } <nl> <nl> void idle ( <nl> void enqueue_and_echo_command_now ( const char * cmd ) ; / / enqueue now , only return <nl> void enqueue_and_echo_commands_P ( const char * cmd ) ; / / put one or many ASCII commands at the end of the current buffer , read from flash <nl> void clear_command_queue ( ) ; <nl> <nl> - void clamp_to_software_endstops ( float target [ 3 ] ) ; <nl> - <nl> extern millis_t previous_cmd_ms ; <nl> inline void refresh_cmd_timeout ( ) { previous_cmd_ms = millis ( ) ; } <nl> <nl> extern bool volumetric_enabled ; <nl> extern int flow_percentage [ EXTRUDERS ] ; / / Extrusion factor for each extruder <nl> extern float filament_size [ EXTRUDERS ] ; / / cross - sectional area of filament ( in millimeters ) , typically around 1 . 75 or 2 . 85 , 0 disables the volumetric calculations for the extruder . <nl> extern float volumetric_multiplier [ EXTRUDERS ] ; / / reciprocal of cross - sectional area of filament ( in square millimeters ) , stored this way to reduce computational burden in planner <nl> - extern bool axis_known_position [ 3 ] ; / / axis [ n ] . is_known <nl> - extern bool axis_homed [ 3 ] ; / / axis [ n ] . is_homed <nl> + extern bool axis_known_position [ XYZ ] ; / / axis [ n ] . is_known <nl> + extern bool axis_homed [ XYZ ] ; / / axis [ n ] . is_homed <nl> extern volatile bool wait_for_heatup ; <nl> <nl> extern float current_position [ NUM_AXIS ] ; <nl> - extern float position_shift [ 3 ] ; <nl> - extern float home_offset [ 3 ] ; <nl> - extern float sw_endstop_min [ 3 ] ; <nl> - extern float sw_endstop_max [ 3 ] ; <nl> + extern float position_shift [ XYZ ] ; <nl> + extern float home_offset [ XYZ ] ; <nl> + <nl> + / / Software Endstops <nl> + void update_software_endstops ( AxisEnum axis ) ; <nl> + # if ENABLED ( min_software_endstops ) | | ENABLED ( max_software_endstops ) <nl> + extern bool soft_endstops_enabled ; <nl> + void clamp_to_software_endstops ( float target [ XYZ ] ) ; <nl> + # else <nl> + # define soft_endstops_enabled false <nl> + # define clamp_to_software_endstops ( x ) NOOP <nl> + # endif <nl> + extern float soft_endstop_min [ XYZ ] ; <nl> + extern float soft_endstop_max [ XYZ ] ; <nl> <nl> # define LOGICAL_POSITION ( POS , AXIS ) ( POS + home_offset [ AXIS ] + position_shift [ AXIS ] ) <nl> # define RAW_POSITION ( POS , AXIS ) ( POS - home_offset [ AXIS ] - position_shift [ AXIS ] ) <nl> float code_value_temp_abs ( ) ; <nl> float code_value_temp_diff ( ) ; <nl> <nl> # if ENABLED ( DELTA ) <nl> - extern float delta [ 3 ] ; <nl> - extern float endstop_adj [ 3 ] ; / / axis [ n ] . endstop_adj <nl> + extern float delta [ ABC ] ; <nl> + extern float endstop_adj [ ABC ] ; / / axis [ n ] . endstop_adj <nl> extern float delta_radius ; <nl> extern float delta_diagonal_rod ; <nl> extern float delta_segments_per_second ; <nl> extern float delta_diagonal_rod_trim_tower_1 ; <nl> extern float delta_diagonal_rod_trim_tower_2 ; <nl> extern float delta_diagonal_rod_trim_tower_3 ; <nl> - void inverse_kinematics ( const float cartesian [ 3 ] ) ; <nl> + void inverse_kinematics ( const float cartesian [ XYZ ] ) ; <nl> void recalc_delta_settings ( float radius , float diagonal_rod ) ; <nl> # if ENABLED ( AUTO_BED_LEVELING_FEATURE ) <nl> extern int delta_grid_spacing [ 2 ] ; <nl> - void adjust_delta ( float cartesian [ 3 ] ) ; <nl> + void adjust_delta ( float cartesian [ XYZ ] ) ; <nl> # endif <nl> # elif ENABLED ( SCARA ) <nl> - extern float delta [ 3 ] ; <nl> - extern float axis_scaling [ 3 ] ; / / Build size scaling <nl> - void inverse_kinematics ( const float cartesian [ 3 ] ) ; <nl> - void forward_kinematics_SCARA ( float f_scara [ 3 ] ) ; <nl> + extern float delta [ ABC ] ; <nl> + extern float axis_scaling [ ABC ] ; / / Build size scaling <nl> + void inverse_kinematics ( const float cartesian [ XYZ ] ) ; <nl> + void forward_kinematics_SCARA ( float f_scara [ ABC ] ) ; <nl> # endif <nl> <nl> # if ENABLED ( Z_DUAL_ENDSTOPS ) <nl> extern uint8_t active_extruder ; <nl> extern float mixing_factor [ MIXING_STEPPERS ] ; <nl> # endif <nl> <nl> - void update_software_endstops ( AxisEnum axis ) ; <nl> void calculate_volumetric_multipliers ( ) ; <nl> <nl> / / Buzzer <nl> mmm a / Marlin / Marlin_main . cpp <nl> ppp b / Marlin / Marlin_main . cpp <nl> <nl> * M208 - Set Recover ( unretract ) Additional ( ! ) Length : S < length > and Feedrate : F < units / min > <nl> * M209 - Turn Automatic Retract Detection on / off : S < bool > ( For slicers that don ' t support G10 / 11 ) . <nl> Every normal extrude - only move will be classified as retract depending on the direction . <nl> + * M211 - Enable , Disable , and / or Report software endstops : [ S < bool > ] <nl> * M218 - Set a tool offset : T < index > X < offset > Y < offset > <nl> * M220 - Set Feedrate Percentage : S < percent > ( " FR " on your LCD ) <nl> * M221 - Set Flow Percentage : S < percent > <nl> uint8_t marlin_debug_flags = DEBUG_NONE ; <nl> <nl> float current_position [ NUM_AXIS ] = { 0 . 0 } ; <nl> static float destination [ NUM_AXIS ] = { 0 . 0 } ; <nl> - bool axis_known_position [ 3 ] = { false } ; <nl> - bool axis_homed [ 3 ] = { false } ; <nl> + bool axis_known_position [ XYZ ] = { false } ; <nl> + bool axis_homed [ XYZ ] = { false } ; <nl> <nl> static long gcode_N , gcode_LastN , Stopped_gcode_LastN = 0 ; <nl> <nl> float filament_size [ EXTRUDERS ] = ARRAY_BY_EXTRUDERS1 ( DEFAULT_NOMINAL_FILAMENT_DI <nl> float volumetric_multiplier [ EXTRUDERS ] = ARRAY_BY_EXTRUDERS1 ( 1 . 0 ) ; <nl> <nl> / / The distance that XYZ has been offset by G92 . Reset by G28 . <nl> - float position_shift [ 3 ] = { 0 } ; <nl> + float position_shift [ XYZ ] = { 0 } ; <nl> <nl> / / This offset is added to the configured home position . <nl> / / Set by M206 , M428 , or menu item . Saved to EEPROM . <nl> - float home_offset [ 3 ] = { 0 } ; <nl> + float home_offset [ XYZ ] = { 0 } ; <nl> <nl> - / / Software Endstops . Default to configured limits . <nl> - float sw_endstop_min [ 3 ] = { X_MIN_POS , Y_MIN_POS , Z_MIN_POS } ; <nl> - float sw_endstop_max [ 3 ] = { X_MAX_POS , Y_MAX_POS , Z_MAX_POS } ; <nl> + / / Software Endstops are based on the configured limits . <nl> + # if ENABLED ( min_software_endstops ) | | ENABLED ( max_software_endstops ) <nl> + bool soft_endstops_enabled = true ; <nl> + # endif <nl> + float soft_endstop_min [ XYZ ] = { X_MIN_POS , Y_MIN_POS , Z_MIN_POS } , <nl> + soft_endstop_max [ XYZ ] = { X_MAX_POS , Y_MAX_POS , Z_MAX_POS } ; <nl> <nl> # if FAN_COUNT > 0 <nl> int fanSpeeds [ FAN_COUNT ] = { 0 } ; <nl> static uint8_t target_extruder ; <nl> # define TOWER_2 Y_AXIS <nl> # define TOWER_3 Z_AXIS <nl> <nl> - float delta [ 3 ] ; <nl> - float cartesian_position [ 3 ] = { 0 } ; <nl> + float delta [ ABC ] ; <nl> + float cartesian_position [ XYZ ] = { 0 } ; <nl> # define SIN_60 0 . 8660254037844386 <nl> # define COS_60 0 . 5 <nl> - float endstop_adj [ 3 ] = { 0 } ; <nl> + float endstop_adj [ ABC ] = { 0 } ; <nl> / / these are the default values , can be overriden with M665 <nl> float delta_radius = DELTA_RADIUS ; <nl> float delta_tower1_x = - SIN_60 * ( delta_radius + DELTA_RADIUS_TRIM_TOWER_1 ) ; / / front left tower <nl> static uint8_t target_extruder ; <nl> <nl> # if ENABLED ( SCARA ) <nl> float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND ; <nl> - float delta [ 3 ] ; <nl> - float axis_scaling [ 3 ] = { 1 , 1 , 1 } ; / / Build size scaling , default to 1 <nl> + float delta [ ABC ] ; <nl> + float axis_scaling [ ABC ] = { 1 , 1 , 1 } ; / / Build size scaling , default to 1 <nl> # endif <nl> <nl> # if ENABLED ( FILAMENT_WIDTH_SENSOR ) <nl> DEFINE_PGM_READ_ANY ( float , float ) ; <nl> DEFINE_PGM_READ_ANY ( signed char , byte ) ; <nl> <nl> # define XYZ_CONSTS_FROM_CONFIG ( type , array , CONFIG ) \ <nl> - static const PROGMEM type array # # _P [ 3 ] = \ <nl> + static const PROGMEM type array # # _P [ XYZ ] = \ <nl> { X_ # # CONFIG , Y_ # # CONFIG , Z_ # # CONFIG } ; \ <nl> static inline type array ( int axis ) \ <nl> { return pgm_read_any ( & array # # _P [ axis ] ) ; } <nl> void update_software_endstops ( AxisEnum axis ) { <nl> if ( axis = = X_AXIS ) { <nl> float dual_max_x = max ( hotend_offset [ X_AXIS ] [ 1 ] , X2_MAX_POS ) ; <nl> if ( active_extruder ! = 0 ) { <nl> - sw_endstop_min [ X_AXIS ] = X2_MIN_POS + offs ; <nl> - sw_endstop_max [ X_AXIS ] = dual_max_x + offs ; <nl> + soft_endstop_min [ X_AXIS ] = X2_MIN_POS + offs ; <nl> + soft_endstop_max [ X_AXIS ] = dual_max_x + offs ; <nl> return ; <nl> } <nl> else if ( dual_x_carriage_mode = = DXC_DUPLICATION_MODE ) { <nl> - sw_endstop_min [ X_AXIS ] = base_min_pos ( X_AXIS ) + offs ; <nl> - sw_endstop_max [ X_AXIS ] = min ( base_max_pos ( X_AXIS ) , dual_max_x - duplicate_extruder_x_offset ) + offs ; <nl> + soft_endstop_min [ X_AXIS ] = base_min_pos ( X_AXIS ) + offs ; <nl> + soft_endstop_max [ X_AXIS ] = min ( base_max_pos ( X_AXIS ) , dual_max_x - duplicate_extruder_x_offset ) + offs ; <nl> return ; <nl> } <nl> } <nl> else <nl> # endif <nl> { <nl> - sw_endstop_min [ axis ] = base_min_pos ( axis ) + offs ; <nl> - sw_endstop_max [ axis ] = base_max_pos ( axis ) + offs ; <nl> + soft_endstop_min [ axis ] = base_min_pos ( axis ) + offs ; <nl> + soft_endstop_max [ axis ] = base_max_pos ( axis ) + offs ; <nl> } <nl> <nl> # if ENABLED ( DEBUG_LEVELING_FEATURE ) <nl> void update_software_endstops ( AxisEnum axis ) { <nl> SERIAL_ECHOPAIR ( " For " , axis_codes [ axis ] ) ; <nl> SERIAL_ECHOPAIR ( " axis : \ n home_offset = " , home_offset [ axis ] ) ; <nl> SERIAL_ECHOPAIR ( " \ n position_shift = " , position_shift [ axis ] ) ; <nl> - SERIAL_ECHOPAIR ( " \ n sw_endstop_min = " , sw_endstop_min [ axis ] ) ; <nl> - SERIAL_ECHOPAIR ( " \ n sw_endstop_max = " , sw_endstop_max [ axis ] ) ; <nl> + SERIAL_ECHOPAIR ( " \ n soft_endstop_min = " , soft_endstop_min [ axis ] ) ; <nl> + SERIAL_ECHOPAIR ( " \ n soft_endstop_max = " , soft_endstop_max [ axis ] ) ; <nl> SERIAL_EOL ; <nl> } <nl> # endif <nl> <nl> # if ENABLED ( DELTA ) <nl> - if ( axis = = Z_AXIS ) { <nl> - delta_clip_start_height = sw_endstop_max [ axis ] - delta_safe_distance_from_top ( ) ; <nl> - } <nl> + if ( axis = = Z_AXIS ) <nl> + delta_clip_start_height = soft_endstop_max [ axis ] - delta_safe_distance_from_top ( ) ; <nl> # endif <nl> <nl> } <nl> static void set_axis_is_at_home ( AxisEnum axis ) { <nl> <nl> if ( axis = = X_AXIS | | axis = = Y_AXIS ) { <nl> <nl> - float homeposition [ 3 ] ; <nl> + float homeposition [ XYZ ] ; <nl> LOOP_XYZ ( i ) homeposition [ i ] = LOGICAL_POSITION ( base_home_pos ( i ) , i ) ; <nl> <nl> / / SERIAL_ECHOPGM ( " homeposition [ x ] = " ) ; SERIAL_ECHO ( homeposition [ 0 ] ) ; <nl> static void set_axis_is_at_home ( AxisEnum axis ) { <nl> * SCARA home positions are based on configuration since the actual <nl> * limits are determined by the inverse kinematic transform . <nl> * / <nl> - sw_endstop_min [ axis ] = base_min_pos ( axis ) ; / / + ( delta [ axis ] - base_home_pos ( axis ) ) ; <nl> - sw_endstop_max [ axis ] = base_max_pos ( axis ) ; / / + ( delta [ axis ] - base_home_pos ( axis ) ) ; <nl> + soft_endstop_min [ axis ] = base_min_pos ( axis ) ; / / + ( delta [ axis ] - base_home_pos ( axis ) ) ; <nl> + soft_endstop_max [ axis ] = base_max_pos ( axis ) ; / / + ( delta [ axis ] - base_home_pos ( axis ) ) ; <nl> } <nl> else <nl> # endif <nl> inline void gcode_G28 ( ) { <nl> switch ( state ) { <nl> case MeshReport : <nl> if ( mbl . has_mesh ( ) ) { <nl> - SERIAL_PROTOCOLPAIR ( " State : " , mbl . active ( ) ? " On " : " Off " ) ; <nl> + SERIAL_PROTOCOLPAIR ( " State : " , mbl . active ( ) ? MSG_ON : MSG_OFF ) ; <nl> SERIAL_PROTOCOLLNPGM ( " \ nNum X , Y : " STRINGIFY ( MESH_NUM_X_POINTS ) " , " STRINGIFY ( MESH_NUM_Y_POINTS ) ) ; <nl> SERIAL_PROTOCOLLNPGM ( " Z search height : " STRINGIFY ( MESH_HOME_SEARCH_Z ) ) ; <nl> SERIAL_PROTOCOLPGM ( " Z offset : " ) ; SERIAL_PROTOCOL_F ( mbl . z_offset , 5 ) ; <nl> inline void gcode_M206 ( ) { <nl> * / <nl> inline void gcode_M209 ( ) { <nl> if ( code_seen ( ' S ' ) ) { <nl> - int t = code_value_int ( ) ; <nl> - switch ( t ) { <nl> - case 0 : <nl> - autoretract_enabled = false ; <nl> - break ; <nl> - case 1 : <nl> - autoretract_enabled = true ; <nl> - break ; <nl> - default : <nl> - unknown_command_error ( ) ; <nl> - return ; <nl> - } <nl> + autoretract_enabled = code_value_bool ( ) ; <nl> for ( int i = 0 ; i < EXTRUDERS ; i + + ) retracted [ i ] = false ; <nl> } <nl> } <nl> <nl> # endif / / FWRETRACT <nl> <nl> + / * * <nl> + * M211 : Enable , Disable , and / or Report software endstops <nl> + * <nl> + * Usage : M211 S1 to enable , M211 S0 to disable , M211 alone for report <nl> + * / <nl> + inline void gcode_M211 ( ) { <nl> + SERIAL_ECHO_START ; <nl> + # if ENABLED ( min_software_endstops ) | | ENABLED ( max_software_endstops ) <nl> + if ( code_seen ( ' S ' ) ) soft_endstops_enabled = code_value_bool ( ) ; <nl> + # endif <nl> + # if ENABLED ( min_software_endstops ) | | ENABLED ( max_software_endstops ) <nl> + SERIAL_ECHOPGM ( MSG_SOFT_ENDSTOPS " : " ) ; <nl> + serialprintPGM ( soft_endstops_enabled ? PSTR ( MSG_ON ) : PSTR ( MSG_OFF ) ) ; <nl> + # else <nl> + SERIAL_ECHOPGM ( MSG_SOFT_ENDSTOPS " : " MSG_OFF ) ; <nl> + # endif <nl> + SERIAL_ECHOPGM ( " " MSG_SOFT_MIN " : " ) ; <nl> + SERIAL_ECHOPAIR ( MSG_X , soft_endstop_min [ X_AXIS ] ) ; <nl> + SERIAL_ECHOPAIR ( " " MSG_Y , soft_endstop_min [ Y_AXIS ] ) ; <nl> + SERIAL_ECHOPAIR ( " " MSG_Z , soft_endstop_min [ Z_AXIS ] ) ; <nl> + SERIAL_ECHOPGM ( " " MSG_SOFT_MAX " : " ) ; <nl> + SERIAL_ECHOPAIR ( MSG_X , soft_endstop_max [ X_AXIS ] ) ; <nl> + SERIAL_ECHOPAIR ( " " MSG_Y , soft_endstop_max [ Y_AXIS ] ) ; <nl> + SERIAL_ECHOPAIR ( " " MSG_Z , soft_endstop_max [ Z_AXIS ] ) ; <nl> + SERIAL_EOL ; <nl> + } <nl> + <nl> # if HOTENDS > 1 <nl> <nl> / * * <nl> inline void gcode_M428 ( ) { <nl> bool err = false ; <nl> LOOP_XYZ ( i ) { <nl> if ( axis_homed [ i ] ) { <nl> - float base = ( current_position [ i ] > ( sw_endstop_min [ i ] + sw_endstop_max [ i ] ) * 0 . 5 ) ? base_home_pos ( i ) : 0 , <nl> + float base = ( current_position [ i ] > ( soft_endstop_min [ i ] + soft_endstop_max [ i ] ) * 0 . 5 ) ? base_home_pos ( i ) : 0 , <nl> diff = current_position [ i ] - LOGICAL_POSITION ( base , i ) ; <nl> if ( diff > - 20 & & diff < 20 ) { <nl> set_home_offset ( ( AxisEnum ) i , home_offset [ i ] - diff ) ; <nl> inline void gcode_M503 ( ) { <nl> stepper . synchronize ( ) ; <nl> extruder_duplication_enabled = code_seen ( ' S ' ) & & code_value_int ( ) = = 2 ; <nl> SERIAL_ECHO_START ; <nl> - SERIAL_ECHOPAIR ( MSG_DUPLICATION_MODE , extruder_duplication_enabled ? MSG_ON : MSG_OFF ) ; <nl> - SERIAL_EOL ; <nl> + SERIAL_ECHOLNPAIR ( MSG_DUPLICATION_MODE , extruder_duplication_enabled ? MSG_ON : MSG_OFF ) ; <nl> } <nl> <nl> # endif / / M605 <nl> void process_next_command ( ) { <nl> break ; <nl> # endif / / FWRETRACT <nl> <nl> + case 211 : / / M211 - Enable , Disable , and / or Report software endstops <nl> + gcode_M211 ( ) ; <nl> + break ; <nl> + <nl> # if HOTENDS > 1 <nl> case 218 : / / M218 - Set a tool offset : T < index > X < offset > Y < offset > <nl> gcode_M218 ( ) ; <nl> void ok_to_send ( ) { <nl> SERIAL_EOL ; <nl> } <nl> <nl> - void clamp_to_software_endstops ( float target [ 3 ] ) { <nl> - if ( min_software_endstops ) { <nl> - NOLESS ( target [ X_AXIS ] , sw_endstop_min [ X_AXIS ] ) ; <nl> - NOLESS ( target [ Y_AXIS ] , sw_endstop_min [ Y_AXIS ] ) ; <nl> - NOLESS ( target [ Z_AXIS ] , sw_endstop_min [ Z_AXIS ] ) ; <nl> - } <nl> - if ( max_software_endstops ) { <nl> - NOMORE ( target [ X_AXIS ] , sw_endstop_max [ X_AXIS ] ) ; <nl> - NOMORE ( target [ Y_AXIS ] , sw_endstop_max [ Y_AXIS ] ) ; <nl> - NOMORE ( target [ Z_AXIS ] , sw_endstop_max [ Z_AXIS ] ) ; <nl> + # if ENABLED ( min_software_endstops ) | | ENABLED ( max_software_endstops ) <nl> + <nl> + void clamp_to_software_endstops ( float target [ XYZ ] ) { <nl> + # if ENABLED ( min_software_endstops ) <nl> + NOLESS ( target [ X_AXIS ] , soft_endstop_min [ X_AXIS ] ) ; <nl> + NOLESS ( target [ Y_AXIS ] , soft_endstop_min [ Y_AXIS ] ) ; <nl> + NOLESS ( target [ Z_AXIS ] , soft_endstop_min [ Z_AXIS ] ) ; <nl> + # endif <nl> + # if ENABLED ( max_software_endstops ) <nl> + NOMORE ( target [ X_AXIS ] , soft_endstop_max [ X_AXIS ] ) ; <nl> + NOMORE ( target [ Y_AXIS ] , soft_endstop_max [ Y_AXIS ] ) ; <nl> + NOMORE ( target [ Z_AXIS ] , soft_endstop_max [ Z_AXIS ] ) ; <nl> + # endif <nl> } <nl> - } <nl> + <nl> + # endif <nl> <nl> # if ENABLED ( DELTA ) <nl> <nl> void clamp_to_software_endstops ( float target [ 3 ] ) { <nl> delta_diagonal_rod_2_tower_3 = sq ( diagonal_rod + delta_diagonal_rod_trim_tower_3 ) ; <nl> } <nl> <nl> - void inverse_kinematics ( const float in_cartesian [ 3 ] ) { <nl> + void inverse_kinematics ( const float in_cartesian [ XYZ ] ) { <nl> <nl> - const float cartesian [ 3 ] = { <nl> + const float cartesian [ XYZ ] = { <nl> RAW_X_POSITION ( in_cartesian [ X_AXIS ] ) , <nl> RAW_Y_POSITION ( in_cartesian [ Y_AXIS ] ) , <nl> RAW_Z_POSITION ( in_cartesian [ Z_AXIS ] ) <nl> void clamp_to_software_endstops ( float target [ 3 ] ) { <nl> } <nl> <nl> float delta_safe_distance_from_top ( ) { <nl> - float cartesian [ 3 ] = { <nl> + float cartesian [ XYZ ] = { <nl> LOGICAL_X_POSITION ( 0 ) , <nl> LOGICAL_Y_POSITION ( 0 ) , <nl> LOGICAL_Z_POSITION ( 0 ) <nl> void clamp_to_software_endstops ( float target [ 3 ] ) { <nl> cartesian_position [ Z_AXIS ] = z1 + ex [ 2 ] * Xnew + ey [ 2 ] * Ynew - ez [ 2 ] * Znew ; <nl> } ; <nl> <nl> - void forward_kinematics_DELTA ( float point [ 3 ] ) { <nl> - forward_kinematics_DELTA ( point [ X_AXIS ] , point [ Y_AXIS ] , point [ Z_AXIS ] ) ; <nl> + void forward_kinematics_DELTA ( float point [ ABC ] ) { <nl> + forward_kinematics_DELTA ( point [ A_AXIS ] , point [ B_AXIS ] , point [ C_AXIS ] ) ; <nl> } <nl> <nl> void set_cartesian_from_steppers ( ) { <nl> - forward_kinematics_DELTA ( stepper . get_axis_position_mm ( X_AXIS ) , <nl> - stepper . get_axis_position_mm ( Y_AXIS ) , <nl> - stepper . get_axis_position_mm ( Z_AXIS ) ) ; <nl> + forward_kinematics_DELTA ( stepper . get_axis_position_mm ( A_AXIS ) , <nl> + stepper . get_axis_position_mm ( B_AXIS ) , <nl> + stepper . get_axis_position_mm ( C_AXIS ) ) ; <nl> } <nl> <nl> # if ENABLED ( AUTO_BED_LEVELING_FEATURE ) <nl> <nl> / / Adjust print surface height by linear interpolation over the bed_level array . <nl> - void adjust_delta ( float cartesian [ 3 ] ) { <nl> + void adjust_delta ( float cartesian [ XYZ ] ) { <nl> if ( delta_grid_spacing [ X_AXIS ] = = 0 | | delta_grid_spacing [ Y_AXIS ] = = 0 ) return ; / / G29 not done ! <nl> <nl> int half = ( AUTO_BED_LEVELING_GRID_POINTS - 1 ) / 2 ; <nl> void prepare_move_to_destination ( ) { <nl> <nl> # if ENABLED ( SCARA ) <nl> <nl> - void forward_kinematics_SCARA ( float f_scara [ 3 ] ) { <nl> - / / Perform forward kinematics , and place results in delta [ 3 ] <nl> + void forward_kinematics_SCARA ( float f_scara [ ABC ] ) { <nl> + / / Perform forward kinematics , and place results in delta [ ] <nl> / / The maths and first version has been done by QHARLEY . Integrated into masterbranch 06 / 2014 and slightly restructured by Joachim Cerny in June 2014 <nl> <nl> float x_sin , x_cos , y_sin , y_cos ; <nl> void prepare_move_to_destination ( ) { <nl> / / SERIAL_ECHOPGM ( " delta [ Y_AXIS ] = " ) ; SERIAL_ECHOLN ( delta [ Y_AXIS ] ) ; <nl> } <nl> <nl> - void inverse_kinematics ( const float cartesian [ 3 ] ) { <nl> + void inverse_kinematics ( const float cartesian [ XYZ ] ) { <nl> / / Inverse kinematics . <nl> - / / Perform SCARA IK and place results in delta [ 3 ] . <nl> + / / Perform SCARA IK and place results in delta [ ] . <nl> / / The maths and first version were done by QHARLEY . <nl> / / Integrated , tweaked by Joachim Cerny in June 2014 . <nl> <nl> mmm a / Marlin / language . h <nl> ppp b / Marlin / language . h <nl> <nl> # define MSG_ENDSTOP_OPEN " open " <nl> # define MSG_HOTEND_OFFSET " Hotend offsets : " <nl> # define MSG_DUPLICATION_MODE " Duplication mode : " <nl> + # define MSG_SOFT_ENDSTOPS " Soft endstops " <nl> + # define MSG_SOFT_MIN " Min " <nl> + # define MSG_SOFT_MAX " Max " <nl> <nl> # define MSG_SD_CANT_OPEN_SUBDIR " Cannot open subdir " <nl> # define MSG_SD_INIT_FAIL " SD init fail " <nl> mmm a / Marlin / macros . h <nl> ppp b / Marlin / macros . h <nl> <nl> # define MACROS_H <nl> <nl> # define NUM_AXIS 4 <nl> + # define XYZE 4 <nl> + # define ABC 3 <nl> + # define XYZ 3 <nl> <nl> # define FORCE_INLINE __attribute__ ( ( always_inline ) ) inline <nl> <nl> mmm a / Marlin / planner . cpp <nl> ppp b / Marlin / planner . cpp <nl> void Planner : : check_axes_activity ( ) { <nl> float junction_deviation = 0 . 1 ; <nl> <nl> / / Compute path unit vector <nl> - double unit_vec [ 3 ] ; <nl> + double unit_vec [ XYZ ] ; <nl> <nl> unit_vec [ X_AXIS ] = delta_mm [ X_AXIS ] * inverse_millimeters ; <nl> unit_vec [ Y_AXIS ] = delta_mm [ Y_AXIS ] * inverse_millimeters ; <nl> mmm a / Marlin / stepper . cpp <nl> ppp b / Marlin / stepper . cpp <nl> unsigned short Stepper : : acc_step_rate ; / / needed for deceleration start point <nl> uint8_t Stepper : : step_loops , Stepper : : step_loops_nominal ; <nl> unsigned short Stepper : : OCR1A_nominal ; <nl> <nl> - volatile long Stepper : : endstops_trigsteps [ 3 ] ; <nl> + volatile long Stepper : : endstops_trigsteps [ XYZ ] ; <nl> <nl> # if ENABLED ( X_DUAL_STEPPER_DRIVERS ) <nl> # define X_APPLY_DIR ( v , Q ) do { X_DIR_WRITE ( v ) ; X2_DIR_WRITE ( ( v ) ! = INVERT_X2_VS_X_DIR ) ; } while ( 0 ) <nl> mmm a / Marlin / stepper . h <nl> ppp b / Marlin / stepper . h <nl> class Stepper { <nl> static uint8_t step_loops , step_loops_nominal ; <nl> static unsigned short OCR1A_nominal ; <nl> <nl> - static volatile long endstops_trigsteps [ 3 ] ; <nl> + static volatile long endstops_trigsteps [ XYZ ] ; <nl> static volatile long endstops_stepsTotal , endstops_stepsDone ; <nl> <nl> # if HAS_MOTOR_CURRENT_PWM <nl> mmm a / Marlin / temperature . cpp <nl> ppp b / Marlin / temperature . cpp <nl> unsigned char Temperature : : soft_pwm_bed ; <nl> # endif <nl> <nl> # if ENABLED ( BABYSTEPPING ) <nl> - volatile int Temperature : : babystepsTodo [ 3 ] = { 0 } ; <nl> + volatile int Temperature : : babystepsTodo [ XYZ ] = { 0 } ; <nl> # endif <nl> <nl> # if ENABLED ( THERMAL_PROTECTION_HOTENDS ) & & WATCH_TEMP_PERIOD > 0 <nl> mmm a / Marlin / ultralcd . cpp <nl> ppp b / Marlin / ultralcd . cpp <nl> void kill_screen ( const char * lcd_msg ) { <nl> * <nl> * / <nl> <nl> - static void _lcd_move_xyz ( const char * name , AxisEnum axis , float min , float max ) { <nl> + static void _lcd_move_xyz ( const char * name , AxisEnum axis ) { <nl> if ( LCD_CLICKED ) { lcd_goto_previous_menu ( true ) ; return ; } <nl> ENCODER_DIRECTION_NORMAL ( ) ; <nl> if ( encoderPosition ) { <nl> refresh_cmd_timeout ( ) ; <nl> + <nl> + / / Limit to software endstops , if enabled <nl> + float min = ( soft_endstops_enabled & & min_software_endstops ) ? soft_endstop_min [ axis ] : current_position [ axis ] - 1000 , <nl> + max = ( soft_endstops_enabled & & max_software_endstops ) ? soft_endstop_max [ axis ] : current_position [ axis ] + 1000 ; <nl> + <nl> + / / Get the new position <nl> current_position [ axis ] + = float ( ( int32_t ) encoderPosition ) * move_menu_scale ; <nl> - if ( min_software_endstops ) NOLESS ( current_position [ axis ] , min ) ; <nl> - if ( max_software_endstops ) NOMORE ( current_position [ axis ] , max ) ; <nl> - encoderPosition = 0 ; <nl> + <nl> + / / Delta limits XY based on the current offset from center <nl> + / / This assumes the center is 0 , 0 <nl> + # if ENABLED ( DELTA ) <nl> + if ( axis ! = Z_AXIS ) { <nl> + max = sqrt ( sq ( DELTA_PRINTABLE_RADIUS ) - sq ( current_position [ Y_AXIS - axis ] ) ) ; <nl> + min = - max ; <nl> + } <nl> + # endif <nl> + <nl> + / / Limit only when trying to move towards the limit <nl> + if ( ( int32_t ) encoderPosition < 0 ) NOLESS ( current_position [ axis ] , min ) ; <nl> + if ( ( int32_t ) encoderPosition > 0 ) NOMORE ( current_position [ axis ] , max ) ; <nl> + <nl> manual_move_to_current ( axis ) ; <nl> + <nl> + encoderPosition = 0 ; <nl> lcdDrawUpdate = LCDVIEW_REDRAW_NOW ; <nl> } <nl> if ( lcdDrawUpdate ) lcd_implementation_drawedit ( name , ftostr41sign ( current_position [ axis ] ) ) ; <nl> } <nl> - # if ENABLED ( DELTA ) <nl> - static float delta_clip_radius_2 = ( DELTA_PRINTABLE_RADIUS ) * ( DELTA_PRINTABLE_RADIUS ) ; <nl> - static int delta_clip ( float a ) { return sqrt ( delta_clip_radius_2 - sq ( a ) ) ; } <nl> - static void lcd_move_x ( ) { int clip = delta_clip ( current_position [ Y_AXIS ] ) ; _lcd_move_xyz ( PSTR ( MSG_MOVE_X ) , X_AXIS , max ( sw_endstop_min [ X_AXIS ] , - clip ) , min ( sw_endstop_max [ X_AXIS ] , clip ) ) ; } <nl> - static void lcd_move_y ( ) { int clip = delta_clip ( current_position [ X_AXIS ] ) ; _lcd_move_xyz ( PSTR ( MSG_MOVE_Y ) , Y_AXIS , max ( sw_endstop_min [ Y_AXIS ] , - clip ) , min ( sw_endstop_max [ Y_AXIS ] , clip ) ) ; } <nl> - # else <nl> - static void lcd_move_x ( ) { _lcd_move_xyz ( PSTR ( MSG_MOVE_X ) , X_AXIS , sw_endstop_min [ X_AXIS ] , sw_endstop_max [ X_AXIS ] ) ; } <nl> - static void lcd_move_y ( ) { _lcd_move_xyz ( PSTR ( MSG_MOVE_Y ) , Y_AXIS , sw_endstop_min [ Y_AXIS ] , sw_endstop_max [ Y_AXIS ] ) ; } <nl> - # endif <nl> - static void lcd_move_z ( ) { _lcd_move_xyz ( PSTR ( MSG_MOVE_Z ) , Z_AXIS , sw_endstop_min [ Z_AXIS ] , sw_endstop_max [ Z_AXIS ] ) ; } <nl> + static void lcd_move_x ( ) { _lcd_move_xyz ( PSTR ( MSG_MOVE_X ) , X_AXIS ) ; } <nl> + static void lcd_move_y ( ) { _lcd_move_xyz ( PSTR ( MSG_MOVE_Y ) , Y_AXIS ) ; } <nl> + static void lcd_move_z ( ) { _lcd_move_xyz ( PSTR ( MSG_MOVE_Z ) , Z_AXIS ) ; } <nl> static void _lcd_move_e ( <nl> # if E_MANUAL > 1 <nl> int8_t eindex = - 1 <nl> | Merge pull request from thinkyhead / rc_M211_sw_endstop_switch | MarlinFirmware/Marlin | 27b80b1dd174a0c1062c67d3a5a3d9b29473942f | 2016-08-21T11:44:00Z |
mmm a / Documentation / CNTK - TechReport / lyx / CNTKBook_CNTK_Programmer_Chapter . lyx <nl> ppp b / Documentation / CNTK - TechReport / lyx / CNTKBook_CNTK_Programmer_Chapter . lyx <nl> void DoCommand ( const ConfigParameters & config ) <nl> <nl> \ begin_layout Plain Layout <nl> <nl> - / / get the configuration parameters that match the command <nl> + / / get the configuration parameters that match the command <nl> \ end_layout <nl> <nl> \ begin_layout Plain Layout <nl> unctionValues ( ) . GetNumCols ( ) ) ; <nl> <nl> \ begin_layout Plain Layout <nl> <nl> - / / left Node must be a scalar <nl> + / / left Node must be a scalar <nl> \ end_layout <nl> <nl> \ begin_layout Plain Layout <nl> virtual void BackpropTo ( const size_t inputIndex ) <nl> <nl> \ begin_layout Plain Layout <nl> <nl> - / / left Node must be a scalar <nl> + / / left Node must be a scalar <nl> \ end_layout <nl> <nl> \ begin_layout Plain Layout <nl> <nl> - if ( inputIndex = = 0 ) / / left derivative <nl> + if ( inputIndex = = 0 ) / / left derivative <nl> \ end_layout <nl> <nl> \ begin_layout Plain Layout <nl> Seq ) <nl> <nl> \ begin_layout Plain Layout <nl> <nl> - / / left Node must be a scalar <nl> + / / left Node must be a scalar <nl> \ end_layout <nl> <nl> \ begin_layout Plain Layout <nl> <nl> - if ( inputIndex = = 0 ) / / left derivative <nl> + if ( inputIndex = = 0 ) / / left derivative <nl> \ end_layout <nl> <nl> \ begin_layout Plain Layout <nl> ComputationNodePtr CreateComputationNode ( const std : : wstring nodeType , const <nl> <nl> \ begin_layout Plain Layout <nl> <nl> - / / other node types <nl> + / / other node types <nl> \ end_layout <nl> <nl> \ begin_layout Plain Layout <nl> ComputationNode < ElemType > * CreateNodeFromFile ( const std : : wstring nodeType , <nl> <nl> \ begin_layout Plain Layout <nl> <nl> - / / other node types <nl> + / / other node types <nl> \ end_layout <nl> <nl> \ begin_layout Plain Layout <nl> ComputationNode < ElemType > * CreateNodeFromFile ( const std : : wstring nodeType , <nl> <nl> \ begin_layout Plain Layout <nl> <nl> - / / other node types <nl> + / / other node types <nl> \ end_layout <nl> <nl> \ begin_layout Plain Layout <nl> bool CheckFunction ( std : : string & p_nodeType , bool * allowUndeterminedVariable ) <nl> <nl> \ begin_layout Plain Layout <nl> <nl> - / / other node types <nl> + / / other node types <nl> \ end_layout <nl> <nl> \ begin_layout Plain Layout <nl> bool CheckFunction ( std : : string & p_nodeType , bool * allowUndeterminedVariable ) <nl> <nl> \ begin_layout Plain Layout <nl> <nl> - / / other node types and codes <nl> + / / other node types and codes <nl> \ end_layout <nl> <nl> \ begin_layout Plain Layout <nl> while ( trainSetDataReader - > GetMinibatch ( inputMatrices ) ) <nl> <nl> \ begin_layout Plain Layout <nl> <nl> - / / update the time stamp of the input nodes for re - evaluation <nl> + / / update the time stamp of the input nodes for re - evaluation <nl> \ end_layout <nl> <nl> \ begin_layout Plain Layout <nl> mmm a / Source / ActionsLib / EvalActions . cpp <nl> ppp b / Source / ActionsLib / EvalActions . cpp <nl> static void DoEvalBase ( const ConfigParameters & config , IDataReader < ElemType > & re <nl> template < typename ElemType > <nl> void DoEval ( const ConfigParameters & config ) <nl> { <nl> - / / test <nl> + / / test <nl> ConfigParameters readerConfig ( config ( L " reader " ) ) ; <nl> readerConfig . Insert ( " traceLevel " , config ( L " traceLevel " , " 0 " ) ) ; <nl> <nl> template void DoEval < float > ( const ConfigParameters & config ) ; <nl> template < typename ElemType > <nl> void DoCrossValidate ( const ConfigParameters & config ) <nl> { <nl> - / / test <nl> + / / test <nl> ConfigParameters readerConfig ( config ( L " reader " ) ) ; <nl> readerConfig . Insert ( " traceLevel " , config ( L " traceLevel " , " 0 " ) ) ; <nl> <nl> void DoCrossValidate ( const ConfigParameters & config ) <nl> : : Sleep ( 1000 * sleepSecondsBetweenRuns ) ; <nl> } <nl> <nl> - / / find best model <nl> + / / find best model <nl> if ( cvErrorResults . size ( ) = = 0 ) <nl> { <nl> LogicError ( " No model is evaluated . " ) ; <nl> void DoWriteOutput ( const ConfigParameters & config ) <nl> { <nl> ConfigParameters readerConfig ( config ( L " reader " ) ) ; <nl> readerConfig . Insert ( " traceLevel " , config ( L " traceLevel " , " 0 " ) ) ; <nl> - readerConfig . Insert ( " randomize " , " None " ) ; / / we don ' t want randomization when output results <nl> + readerConfig . Insert ( " randomize " , " None " ) ; / / we don ' t want randomization when output results <nl> <nl> DataReader < ElemType > testDataReader ( readerConfig ) ; <nl> <nl> void DoWriteOutput ( const ConfigParameters & config ) <nl> wstring outputPath = config ( L " outputPath " ) ; / / crashes if no default given ? <nl> writer . WriteOutput ( testDataReader , mbSize [ 0 ] , outputPath , outputNodeNamesVector , epochSize ) ; <nl> } <nl> - / / writer . WriteOutput ( testDataReader , mbSize [ 0 ] , testDataWriter , outputNodeNamesVector , epochSize ) ; <nl> + / / writer . WriteOutput ( testDataReader , mbSize [ 0 ] , testDataWriter , outputNodeNamesVector , epochSize ) ; <nl> } <nl> <nl> template void DoWriteOutput < float > ( const ConfigParameters & config ) ; <nl> mmm a / Source / ActionsLib / OtherActions . cpp <nl> ppp b / Source / ActionsLib / OtherActions . cpp <nl> void DoWriteWordAndClassInfo ( const ConfigParameters & config ) <nl> Matrix < ElemType > wrd2cls ( deviceId ) ; <nl> Matrix < ElemType > cls2idx ( deviceId ) ; <nl> <nl> - / / FILE * fp = fopen ( inputFile . c_str ( ) , " rt " ) ; <nl> + / / FILE * fp = fopen ( inputFile . c_str ( ) , " rt " ) ; <nl> ifstream fp ( inputFile . c_str ( ) ) ; <nl> if ( ! fp ) <nl> { <nl> void DoWriteWordAndClassInfo ( const ConfigParameters & config ) <nl> string token ; <nl> while ( getline ( fp , str ) ) <nl> { <nl> - str . erase ( 0 , str . find_first_not_of ( ' ' ) ) ; / / prefixing spaces <nl> - str . erase ( str . find_last_not_of ( ' ' ) + 1 ) ; / / surfixing spaces <nl> + str . erase ( 0 , str . find_first_not_of ( ' ' ) ) ; / / prefixing spaces <nl> + str . erase ( str . find_last_not_of ( ' ' ) + 1 ) ; / / surfixing spaces <nl> int sposition = str . find ( " < / s > " ) ; <nl> int eposition = str . find ( " < / s > " ) ; <nl> if ( sposition = = str . npos ) <nl> void DoTopologyPlot ( const ConfigParameters & config ) <nl> / / e . g . " d : \ Tools \ graphviz \ bin \ dot . exe - Tpng - x < IN > - o < OUT > " <nl> / / where < IN > and < OUT > are two special placeholders <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / Sec . 1 option check <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> if ( outdot . empty ( ) ) <nl> { <nl> outdot = modelPath + L " . dot " ; <nl> mmm a / Source / CNTK / CNTK . cpp <nl> ppp b / Source / CNTK / CNTK . cpp <nl> void DumpNodeInfo ( const ConfigParameters & config ) <nl> wstring outputFile = config ( L " outputFile " , defOutFilePath ) ; <nl> bool printValues = config ( L " printValues " , true ) ; <nl> <nl> - ComputationNetwork net ( - 1 ) ; / / always use CPU <nl> + ComputationNetwork net ( - 1 ) ; / / always use CPU <nl> net . Load < ElemType > ( modelPath ) ; <nl> net . DumpNodeInfoToFile ( nodeName , printValues , outputFile , nodeNameRegexStr ) ; <nl> } <nl> void DoCommands ( const ConfigParameters & config ) <nl> size_t fullTotalMaxEpochs = 0 ; <nl> for ( int i = 0 ; i < command . size ( ) ; i + + ) <nl> { <nl> - / / get the configuration parameters that match the command <nl> + / / get the configuration parameters that match the command <nl> ConfigParameters commandParams ( config ( command [ i ] ) ) ; <nl> ConfigArray action = commandParams ( " action " , " train " ) ; <nl> <nl> void DoCommands ( const ConfigParameters & config ) <nl> / / execute the commands <nl> for ( int i = 0 ; i < command . size ( ) ; i + + ) <nl> { <nl> - / / get the configuration parameters that match the command <nl> + / / get the configuration parameters that match the command <nl> ConfigParameters commandParams ( config ( command [ i ] ) ) ; <nl> ConfigArray action = commandParams ( " action " , " train " ) ; <nl> <nl> int wmainWithBS ( int argc , wchar_t * argv [ ] ) / / called from wmain which is a wrapp <nl> PrintBuiltInfo ( ) ; <nl> <nl> / / execute the actions <nl> - / / std : : string type = config ( L " precision " , " float " ) ; <nl> + / / std : : string type = config ( L " precision " , " float " ) ; <nl> int numCPUThreads = config ( L " numCPUThreads " , 0 ) ; <nl> numCPUThreads = CPUMatrix < float / * any will do * / > : : SetNumThreads ( numCPUThreads ) ; <nl> if ( numCPUThreads > 0 ) <nl> int wmainOldCNTKConfig ( int argc , wchar_t * argv [ ] ) / / called from wmain which is <nl> PrintBuiltInfo ( ) ; / / this one goes to log file <nl> std : : string timestamp = TimeDateStamp ( ) ; <nl> <nl> - / / dump config info <nl> + / / dump config info <nl> fprintf ( stderr , " running on % s at % s \ n " , GetHostName ( ) . c_str ( ) , timestamp . c_str ( ) ) ; <nl> fprintf ( stderr , " command line : \ n " ) ; <nl> for ( int i = 0 ; i < argc ; i + + ) <nl> int wmainOldCNTKConfig ( int argc , wchar_t * argv [ ] ) / / called from wmain which is <nl> fprintf ( stderr , " % s " , command [ i ] . c_str ( ) ) ; <nl> } <nl> <nl> - / / run commands <nl> + / / run commands <nl> std : : string type = config ( L " precision " , " float " ) ; <nl> / / accept old precision key for backward compatibility <nl> if ( config . Exists ( " type " ) ) <nl> mmm a / Source / CNTK / ModelEditLanguage . h <nl> ppp b / Source / CNTK / ModelEditLanguage . h <nl> class MELScript : public ConfigParser <nl> wstring name = msra : : strfun : : utf16 ( search ) ; <nl> vector < ComputationNodeBasePtr > nodes = netNdlIn - > cn - > GetNodesFromName ( name ) ; <nl> <nl> - if ( ! nodes . size ( ) ) / / found <nl> + if ( ! nodes . size ( ) ) / / found <nl> RuntimeError ( " GenerateNames : Node name does not exist % ls . " , name . c_str ( ) ) ; <nl> <nl> size_t firstStartOut , firstCountOut , secondStartOut , secondCountOut ; <nl> class MELScript : public ConfigParser <nl> found - > second . Clear ( ) ; <nl> } <nl> <nl> - m_mapNameToNetNdl [ modelName ] = NetNdl < ElemType > ( cn ) ; / / newly loaded model will be the new default if none has been set yet <nl> + m_mapNameToNetNdl [ modelName ] = NetNdl < ElemType > ( cn ) ; / / newly loaded model will be the new default if none has been set yet <nl> if ( m_netNdlDefault = = nullptr ) <nl> { <nl> m_netNdlDefault = & m_mapNameToNetNdl [ modelName ] ; <nl> class MELScript : public ConfigParser <nl> } <nl> wstring GetOptionalModelFormat ( const ConfigParamList & params , const size_t numFixedParams ) <nl> { <nl> - wstring modelFormat = L " cntk " ; / / default <nl> + wstring modelFormat = L " cntk " ; / / default <nl> for ( size_t paramNumber = params . size ( ) ; paramNumber > numFixedParams ; paramNumber - - ) <nl> { <nl> / / process optional parameter if it exists <nl> class MELScript : public ConfigParser <nl> <nl> CopyNodeFlags GetOptionalCopyNodeFlags ( const ConfigParamList & params , const size_t numFixedParams ) <nl> { <nl> - CopyNodeFlags copyFlags = CopyNodeFlags : : copyNodeAll ; / / by default copy both values and link structure <nl> + CopyNodeFlags copyFlags = CopyNodeFlags : : copyNodeAll ; / / by default copy both values and link structure <nl> <nl> for ( size_t paramNumber = params . size ( ) ; paramNumber > numFixedParams ; paramNumber - - ) <nl> { <nl> class MELScript : public ConfigParser <nl> RuntimeError ( " NDL Command cannot be executed until default model is established , cannot set ' % s ' without a default mode \ n Try calling SetDefaultModel ( model ) before any NDL statement are embedded \ n " , key . c_str ( ) ) ; <nl> HandleNDLInline ( stringParse , tokenStart , tokenEnd ) ; <nl> } <nl> - else / / createModel , loadModel , or loadNDL <nl> + else / / createModel , loadModel , or loadNDL <nl> { <nl> / / model1 = [ . . . ] - Embedded NDL script <nl> if ( 0 = = foundBrace ) <nl> mmm a / Source / CNTK / NDLNetworkBuilder . h <nl> ppp b / Source / CNTK / NDLNetworkBuilder . h <nl> class NDLBuilder <nl> <nl> virtual ComputationNetworkPtr BuildNetworkFromDescription ( ComputationNetwork * = nullptr ) <nl> { <nl> - if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> + if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> LoadNetworkFromConfig ( m_networkConfig ) ; <nl> else <nl> m_net - > ResetEvalTimeStamps ( ) ; <nl> mmm a / Source / CNTK / NDLUtil . h <nl> ppp b / Source / CNTK / NDLUtil . h <nl> class NDLUtil <nl> { <nl> NDLNode < ElemType > * nodeArray = script - > FindSymbol ( symbolName ) ; <nl> bool valid = m_net - > FeatureNodes ( ) . size ( ) > 0 ; / / see if it ' s already valid <nl> - if ( ! valid & & nodeArray ) / / otherwise , see if we found a symbol <nl> + if ( ! valid & & nodeArray ) / / otherwise , see if we found a symbol <nl> { <nl> NDLType outputType = nodeArray - > GetType ( ) ; <nl> / / accept either an array of nodes , or a single node <nl> class NDLUtil <nl> CheckOutputNodes ( script , " FeatureNodes " , m_net - > FeatureNodes ( ) ) ; <nl> CheckOutputNodes ( script , " LabelNodes " , m_net - > LabelNodes ( ) ) ; <nl> CheckOutputNodes ( script , " CriterionNodes " , m_net - > FinalCriterionNodes ( ) ) ; <nl> - CheckOutputNodes ( script , " CriteriaNodes " , m_net - > FinalCriterionNodes ( ) ) ; / / legacy <nl> + CheckOutputNodes ( script , " CriteriaNodes " , m_net - > FinalCriterionNodes ( ) ) ; / / legacy <nl> CheckOutputNodes ( script , " EvalNodes " , m_net - > EvaluationNodes ( ) ) ; <nl> CheckOutputNodes ( script , " OutputNodes " , m_net - > OutputNodes ( ) ) ; <nl> } <nl> mmm a / Source / CNTK / NetworkDescriptionLanguage . cpp <nl> ppp b / Source / CNTK / NetworkDescriptionLanguage . cpp <nl> NDLNode < ElemType > : : NDLNode ( const NDLNode < ElemType > & copyMe ) <nl> m_name = copyMe . m_name ; / / value on the left of the equals <nl> m_value = copyMe . m_value ; / / value on the right of the equals ( CN node name , or value ) <nl> m_parent = copyMe . m_parent ; / / parent script <nl> - m_type = copyMe . m_type ; / / type of node <nl> + m_type = copyMe . m_type ; / / type of node <nl> m_paramString = copyMe . m_paramString ; / / parameter of a function / array <nl> m_paramMacro = copyMe . m_paramMacro ; / / parameter of a macro ( the variables used in the macro definition ) <nl> / / don ' t copy over the parameters , they will be reparsed after the copy <nl> - / / m_parameters = copyMe . m_parameters ; / / copy over the parameters straight <nl> + / / m_parameters = copyMe . m_parameters ; / / copy over the parameters straight <nl> <nl> m_eval = nullptr ; / / pointer to an arbitrary eval structure <nl> / / script for macro calls , need to expand the macro for each call <nl> mmm a / Source / CNTK / NetworkDescriptionLanguage . h <nl> ppp b / Source / CNTK / NetworkDescriptionLanguage . h <nl> class NDLNode <nl> std : : string m_name ; / / value on the left of the equals <nl> ConfigValue m_value ; / / value on the right of the equals ( CN node name , or value ) <nl> NDLScript < ElemType > * m_parent ; / / parent script <nl> - NDLType m_type ; / / type of node <nl> + NDLType m_type ; / / type of node <nl> ConfigArray m_paramString ; / / parameter of a function / array <nl> ConfigArray m_paramMacro ; / / parameter of a macro ( the variables used in the macro definition ) <nl> vector < NDLNode * > m_parameters ; / / parameters as nodes / array elements <nl> class NDLNode <nl> / / copy constructor , creates a new disconnected copy of this node for macro expansion <nl> NDLNode ( const NDLNode & copyMe ) ; <nl> <nl> - NDLNode & operator = ( NDLNode & / * copyMe * / ) / / this is just a place holder implementation which is not functioning but prevent callers to use it . <nl> + NDLNode & operator = ( NDLNode & / * copyMe * / ) / / this is just a place holder implementation which is not functioning but prevent callers to use it . <nl> { <nl> LogicError ( " ' NDLNode & operator = ( NDLNode & copyMe ) ' should never be called . " ) ; <nl> } <nl> class NDLNode <nl> m_script - > AddSymbol ( paramName , nodeParam ) ; <nl> continue ; <nl> } <nl> - / / else assign the value below <nl> + / / else assign the value below <nl> } <nl> <nl> / / assign the parameter symbols in the script we will call with the values passed to the call <nl> class NDLScript : public ConfigParser <nl> std : : map < std : : string , NDLNode < ElemType > * , nocase_compare > m_symbols ; / / symbol table <nl> NDLNode < ElemType > * m_macroNode ; / / set when interpretting a macro definition <nl> bool m_noDefinitions ; / / no definitions can be made in this script , interpret all macro / function names as calls <nl> - static NDLScript < ElemType > s_global ; / / ( " global " ) ; / / global script for storing macros and global nodes <nl> + static NDLScript < ElemType > s_global ; / / ( " global " ) ; / / global script for storing macros and global nodes <nl> std : : vector < NDLNode < ElemType > * > m_children ; / / child nodes . Note that m_script nodes may not be children of this object , they include macro nodes <nl> ComputationNetworkPtr m_cn ; / / computation network to use for backup symbol lookup . Used for MEL where NDL and network nodes are mixed <nl> bool m_definingMacro ; / / currently defining a macro , flag to determine if we are defining or interpretting a macro call <nl> class NDLScript : public ConfigParser <nl> / / returns - node this symbol references <nl> NDLNode < ElemType > * FindSymbol ( const std : : string & symbol , bool searchForDotNames = true ) <nl> { <nl> - auto found = m_symbols . find ( symbol ) ; / / search symbol directly first <nl> + auto found = m_symbols . find ( symbol ) ; / / search symbol directly first <nl> if ( found ! = m_symbols . end ( ) ) <nl> return found - > second ; <nl> <nl> class NDLScript : public ConfigParser <nl> AddSymbol ( key , ndlNode ) ; <nl> <nl> ndlNode - > SetName ( key ) ; <nl> - if ( newNode ) / / only need to add nodes that are new ( not renames ) <nl> + if ( newNode ) / / only need to add nodes that are new ( not renames ) <nl> { <nl> m_script . push_back ( ndlNode ) ; <nl> } <nl> mmm a / Source / CNTK / SimpleNetworkBuilder . cpp <nl> ppp b / Source / CNTK / SimpleNetworkBuilder . cpp <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildSimpleDNN ( ) <nl> { <nl> <nl> ComputationNetworkBuilder < ElemType > builder ( * m_net ) ; <nl> - if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> + if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> { <nl> unsigned long randomSeed = 1 ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildSimpleDNN ( ) <nl> prior = builder . Mean ( label , L " Prior " ) ; <nl> input = builder . Log ( prior , L " LogOfPrior " ) ; <nl> <nl> - / / following two lines are needed only if true probability is needed <nl> - / / output = builder . Softmax ( output ) ; <nl> - / / output = builder . Log ( output ) ; <nl> + / / following two lines are needed only if true probability is needed <nl> + / / output = builder . Softmax ( output ) ; <nl> + / / output = builder . Log ( output ) ; <nl> <nl> scaledLogLikelihood = builder . Minus ( output , input , L " ScaledLogLikelihood " ) ; <nl> m_net - > OutputNodes ( ) . push_back ( scaledLogLikelihood ) ; <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildSimpleDNN ( ) <nl> m_net - > OutputNodes ( ) . push_back ( output ) ; <nl> } <nl> <nl> - / / add softmax layer ( if prob is needed or KL reg adaptation is needed ) <nl> + / / add softmax layer ( if prob is needed or KL reg adaptation is needed ) <nl> output = builder . Softmax ( output , L " PosteriorProb " ) ; <nl> - / / m_net - > OutputNodes ( ) . push_back ( output ) ; <nl> + / / m_net - > OutputNodes ( ) . push_back ( output ) ; <nl> } <nl> <nl> return m_net ; <nl> template < class ElemType > <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildSimpleRNN ( ) <nl> { <nl> ComputationNetworkBuilder < ElemType > builder ( * m_net ) ; <nl> - if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> + if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> { <nl> unsigned long randomSeed = 1 ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildSimpleRNN ( ) <nl> int recur_idx = 0 ; <nl> if ( numHiddenLayers > 0 ) <nl> { <nl> - / / TODO : to figure out sparse matrix size <nl> + / / TODO : to figure out sparse matrix size <nl> u = builder . CreateLearnableParameter ( L " U0 " , m_layerSizes [ 1 ] , m_layerSizes [ 0 ] ) ; <nl> m_net - > InitLearnableParameters ( u , m_uniformInit , randomSeed + + , m_initValueScale ) ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildSimpleRNN ( ) <nl> else <nl> { <nl> output = SimpleNetworkBuilder < ElemType > : : ApplyNonlinearFunction ( builder . Plus ( builder . Times ( u , input ) , b ) , 0 ) ; <nl> - / / output = builder . Times ( u , input ) ; <nl> + / / output = builder . Times ( u , input ) ; <nl> } <nl> <nl> if ( m_addDropoutNodes ) <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildSimpleRNN ( ) <nl> <nl> for ( int i = 1 ; i < numHiddenLayers ; i + + ) <nl> { <nl> - / / TODO : to figure out sparse matrix size <nl> + / / TODO : to figure out sparse matrix size <nl> u = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " U % d " , i ) , m_layerSizes [ i + 1 ] , m_layerSizes [ i ] ) ; <nl> m_net - > InitLearnableParameters ( u , m_uniformInit , randomSeed + + , m_initValueScale ) ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildClassEntropyNetwork ( ) <nl> { <nl> ComputationNetworkBuilder < ElemType > builder ( * m_net ) ; <nl> <nl> - if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> + if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> { <nl> unsigned long randomSeed = 1 ; <nl> <nl> template < class ElemType > <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildConditionalLSTMNetworkFromDescription ( ) <nl> { <nl> ComputationNetworkBuilder < ElemType > builder ( * m_net ) ; <nl> - if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> + if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> { <nl> unsigned long randomSeed = 1 ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildConditionalLSTMNetwor <nl> <nl> m_net - > OutputNodes ( ) . push_back ( output ) ; <nl> <nl> - / / add softmax layer ( if prob is needed or KL reg adaptation is needed ) <nl> + / / add softmax layer ( if prob is needed or KL reg adaptation is needed ) <nl> output = builder . Softmax ( output , L " PosteriorProb " ) ; <nl> } <nl> <nl> template < class ElemType > <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildLogBilinearNetworkFromDescription ( ) <nl> { <nl> ComputationNetworkBuilder < ElemType > builder ( * m_net ) ; <nl> - if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> + if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> { <nl> unsigned long randomSeed = 1 ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildLogBilinearNetworkFro <nl> input = output ; <nl> } <nl> <nl> - / / used for lookuptable node unittest , will delete <nl> + / / used for lookuptable node unittest , will delete <nl> if ( m_lookupTableOrder > 0 ) <nl> { <nl> e = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " E % d " , 0 ) , m_layerSizes [ 1 ] , m_layerSizes [ 0 ] / m_lookupTableOrder ) ; <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildLogBilinearNetworkFro <nl> builder . PastValue ( NULL , m_defaultHiddenActivity , m_layerSizes [ 0 ] , ik , msra : : strfun : : wstrprintf ( L " pastValue % d " , ik ) ) ; <nl> pastValueXI - > SetParameterUpdateRequired ( false ) ; <nl> pastValueXI - > AttachInputs ( input ) ; <nl> - / / TODO : to figure out sparse matrix size <nl> + / / TODO : to figure out sparse matrix size <nl> Wxi = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " DD % d " , ik ) , m_layerSizes [ 0 ] , m_layerSizes [ 0 ] ) ; <nl> m_net - > InitLearnableParameters ( Wxi , m_uniformInit , randomSeed + + , m_initValueScale ) ; <nl> <nl> template < class ElemType > <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildNeuralProbNetworkFromDescription ( ) <nl> { <nl> ComputationNetworkBuilder < ElemType > builder ( * m_net ) ; <nl> - if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> + if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> { <nl> unsigned long randomSeed = 1 ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildNeuralProbNetworkFrom <nl> <nl> if ( m_recurrentLayers . size ( ) > 0 & & m_recurrentLayers [ recur_idx ] = = 1 ) <nl> { <nl> - / / TODO : to figure out sparse matrix size <nl> + / / TODO : to figure out sparse matrix size <nl> Wxi2 = builder . CreateLearnableParameter ( L " WXI2 " , m_layerSizes [ 1 ] , m_layerSizes [ 0 ] ) ; <nl> m_net - > InitLearnableParameters ( Wxi2 , m_uniformInit , randomSeed + + , m_initValueScale ) ; <nl> - / / TODO : to figure out sparse matrix size <nl> + / / TODO : to figure out sparse matrix size <nl> Wxi3 = builder . CreateLearnableParameter ( L " WXI3 " , m_layerSizes [ 1 ] , m_layerSizes [ 0 ] ) ; <nl> m_net - > InitLearnableParameters ( Wxi3 , m_uniformInit , randomSeed + + , m_initValueScale ) ; <nl> - / / TODO : to figure out sparse matrix size <nl> + / / TODO : to figure out sparse matrix size <nl> Wxi4 = builder . CreateLearnableParameter ( L " WXI4 " , m_layerSizes [ 1 ] , m_layerSizes [ 0 ] ) ; <nl> m_net - > InitLearnableParameters ( Wxi4 , m_uniformInit , randomSeed + + , m_initValueScale ) ; <nl> - / / TODO : to figure out sparse matrix size <nl> + / / TODO : to figure out sparse matrix size <nl> Wxi1 = builder . CreateLearnableParameter ( L " WXI1 " , m_layerSizes [ 1 ] , m_layerSizes [ 0 ] ) ; <nl> m_net - > InitLearnableParameters ( Wxi1 , m_uniformInit , randomSeed + + , m_initValueScale ) ; <nl> - / / TODO : to figure out sparse matrix size <nl> + / / TODO : to figure out sparse matrix size <nl> Wxi = builder . CreateLearnableParameter ( L " WXI " , m_layerSizes [ 1 ] , m_layerSizes [ 0 ] ) ; <nl> m_net - > InitLearnableParameters ( Wxi , m_uniformInit , randomSeed + + , m_initValueScale ) ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildNeuralProbNetworkFrom <nl> } <nl> } <nl> <nl> - / / TODO : to figure out sparse matrix size <nl> + / / TODO : to figure out sparse matrix size <nl> w = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " W % d " , numHiddenLayers ) , m_layerSizes [ numHiddenLayers + 1 ] , m_layerSizes [ numHiddenLayers ] ) ; <nl> m_net - > InitLearnableParameters ( w , m_uniformInit , randomSeed + + , m_initValueScale ) ; <nl> / / b = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " B % d " , numHiddenLayers ) , m_layerSizes [ numHiddenLayers + 1 ] , 1 ) ; <nl> shared_ptr < ComputationNode < ElemType > > / * ComputationNodePtr * / SimpleNetworkBuilde <nl> bc = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " bc % d " , iLayer ) , outputDim , 1 ) ; <nl> bi = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " bi % d " , iLayer ) , outputDim , 1 ) ; <nl> bf = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " bf % d " , iLayer ) , outputDim , 1 ) ; <nl> - / / if ( m_forgetGateInitVal > 0 ) <nl> + / / if ( m_forgetGateInitVal > 0 ) <nl> bf - > Value ( ) . SetValue ( m_forgetGateInitVal ) ; <nl> - / / if ( m_inputGateInitVal > 0 ) <nl> + / / if ( m_inputGateInitVal > 0 ) <nl> bi - > Value ( ) . SetValue ( m_inputGateInitVal ) ; <nl> - / / if ( m_outputGateInitVal > 0 ) <nl> + / / if ( m_outputGateInitVal > 0 ) <nl> bo - > Value ( ) . SetValue ( m_outputGateInitVal ) ; <nl> <nl> Whi = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " WHI % d " , iLayer ) , outputDim , outputDim ) ; <nl> shared_ptr < ComputationNode < ElemType > > / * ComputationNodePtr * / SimpleNetworkBuilde <nl> <nl> if ( m_constInputGateValue ) <nl> { <nl> - / / it = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " CONSTIT % d " , iLayer ) , outputDim ) ; <nl> - / / it - > SetParameterUpdateRequired ( false ) ; <nl> - / / it - > Value ( ) . SetValue ( m_constInputGateValue ) ; <nl> + / / it = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " CONSTIT % d " , iLayer ) , outputDim ) ; <nl> + / / it - > SetParameterUpdateRequired ( false ) ; <nl> + / / it - > Value ( ) . SetValue ( m_constInputGateValue ) ; <nl> it = nullptr ; <nl> } <nl> else <nl> template < class ElemType > <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildSeqTrnLSTMNetworkFromDescription ( ) <nl> { <nl> ComputationNetworkBuilder < ElemType > builder ( * m_net ) ; <nl> - if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> + if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> { <nl> ULONG randomSeed = 1 ; <nl> <nl> template < class ElemType > <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildCLASSLSTMNetworkFromDescription ( ) <nl> { <nl> ComputationNetworkBuilder < ElemType > builder ( * m_net ) ; <nl> - if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> + if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> { <nl> unsigned long randomSeed = 1 ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildCLASSLSTMNetworkFromD <nl> <nl> m_net - > OutputNodes ( ) . push_back ( output ) ; <nl> <nl> - / / add softmax layer ( if prob is needed or KL reg adaptation is needed ) <nl> + / / add softmax layer ( if prob is needed or KL reg adaptation is needed ) <nl> output = builder . Softmax ( output , L " PosteriorProb " ) ; <nl> } <nl> <nl> template < class ElemType > <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildLSTMNetworkFromDescription ( ) <nl> { <nl> ComputationNetworkBuilder < ElemType > builder ( * m_net ) ; <nl> - if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> + if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> { <nl> ULONG randomSeed = 1 ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildLSTMNetworkFromDescri <nl> if ( numHiddenLayers > 0 ) <nl> { <nl> <nl> - / / output = ( ComputationNodePtr ) BuildLSTMNodeComponent ( randomSeed , 0 , m_layerSizes [ offset ] * ( offset ? m_lookupTableOrder : 1 ) , m_layerSizes [ offset + 1 ] , input ) ; <nl> + / / output = ( ComputationNodePtr ) BuildLSTMNodeComponent ( randomSeed , 0 , m_layerSizes [ offset ] * ( offset ? m_lookupTableOrder : 1 ) , m_layerSizes [ offset + 1 ] , input ) ; <nl> output = ( ComputationNodePtr ) BuildLSTMComponent ( randomSeed , 0 , m_layerSizes [ offset ] * ( offset ? m_lookupTableOrder : 1 ) , m_layerSizes [ offset + 1 ] , input ) ; <nl> / / previously used function . now uses LSTMNode which is correct and fast <nl> input = output ; <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildLSTMNetworkFromDescri <nl> if ( m_recurrentLayers . size ( ) > 0 & & m_recurrentLayers [ recur_idx ] = = i ) <nl> { <nl> <nl> - / / output = ( ComputationNodePtr ) BuildLSTMNodeComponent ( randomSeed , i , m_layerSizes [ i ] , m_layerSizes [ i + 1 ] , input ) ; <nl> + / / output = ( ComputationNodePtr ) BuildLSTMNodeComponent ( randomSeed , i , m_layerSizes [ i ] , m_layerSizes [ i + 1 ] , input ) ; <nl> output = ( ComputationNodePtr ) BuildLSTMComponent ( randomSeed , i , m_layerSizes [ i ] , m_layerSizes [ i + 1 ] , input ) ; <nl> / / previously used function , now uses LSTMnode , which is fast and correct <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildLSTMNetworkFromDescri <nl> else <nl> m_net - > OutputNodes ( ) . push_back ( output ) ; <nl> <nl> - / / add softmax layer ( if prob is needed or KL reg adaptation is needed ) <nl> + / / add softmax layer ( if prob is needed or KL reg adaptation is needed ) <nl> output = builder . Softmax ( output , L " PosteriorProb " ) ; <nl> } <nl> <nl> shared_ptr < ComputationNode < ElemType > > / * ComputationNodePtr * / SimpleNetworkBuilde <nl> bc = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " bc % d " , iLayer ) , outputDim , 1 ) ; <nl> bi = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " bi % d " , iLayer ) , outputDim , 1 ) ; <nl> bf = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " bf % d " , iLayer ) , outputDim , 1 ) ; <nl> - / / if ( m_forgetGateInitVal > 0 ) <nl> + / / if ( m_forgetGateInitVal > 0 ) <nl> bf - > Value ( ) . SetValue ( m_forgetGateInitVal ) ; <nl> - / / if ( m_inputGateInitVal > 0 ) <nl> + / / if ( m_inputGateInitVal > 0 ) <nl> bi - > Value ( ) . SetValue ( m_inputGateInitVal ) ; <nl> - / / if ( m_outputGateInitVal > 0 ) <nl> + / / if ( m_outputGateInitVal > 0 ) <nl> bo - > Value ( ) . SetValue ( m_outputGateInitVal ) ; <nl> <nl> Whi = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " WHI % d " , iLayer ) , outputDim , outputDim ) ; <nl> shared_ptr < ComputationNode < ElemType > > / * ComputationNodePtr * / SimpleNetworkBuilde <nl> <nl> if ( m_constInputGateValue ) <nl> { <nl> - / / it = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " CONSTIT % d " , iLayer ) , outputDim ) ; <nl> - / / it - > SetParameterUpdateRequired ( false ) ; <nl> - / / it - > Value ( ) . SetValue ( m_constInputGateValue ) ; <nl> + / / it = builder . CreateLearnableParameter ( msra : : strfun : : wstrprintf ( L " CONSTIT % d " , iLayer ) , outputDim ) ; <nl> + / / it - > SetParameterUpdateRequired ( false ) ; <nl> + / / it - > Value ( ) . SetValue ( m_constInputGateValue ) ; <nl> it = nullptr ; <nl> } <nl> else <nl> template < class ElemType > <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildNCELSTMNetworkFromDescription ( ) <nl> { <nl> ComputationNetworkBuilder < ElemType > builder ( * m_net ) ; <nl> - if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> + if ( m_net - > GetTotalNumberOfNodes ( ) < 1 ) / / not built yet <nl> { <nl> unsigned long randomSeed = 1 ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildNCELSTMNetworkFromDes <nl> <nl> bias = builder . CreateLearnableParameter ( L " BiasVector " , 1 , m_layerSizes [ m_layerSizes . size ( ) - 1 ] ) ; <nl> bias - > Value ( ) . SetValue ( ( ElemType ) - std : : log ( m_layerSizes [ m_layerSizes . size ( ) - 1 ] ) ) ; <nl> - / / m_net - > InitLearnableParameters ( bias , m_uniformInit , randomSeed + + , std : : log ( m_layerSizes [ m_layerSizes . size ( ) - 1 ] ) * m_initValueScale ) ; <nl> - / / clslogpostprob = builder . Times ( clsweight , input , L " ClassPostProb " ) ; <nl> + / / m_net - > InitLearnableParameters ( bias , m_uniformInit , randomSeed + + , std : : log ( m_layerSizes [ m_layerSizes . size ( ) - 1 ] ) * m_initValueScale ) ; <nl> + / / clslogpostprob = builder . Times ( clsweight , input , L " ClassPostProb " ) ; <nl> <nl> output = AddTrainAndEvalCriterionNodes ( input , label , w , L " TrainNodeNCEBasedCrossEntropy " , L " EvalNodeNCEBasedCrossEntrpy " , bias ) ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildNetworkFromDbnFile ( co <nl> assert ( globalMean . GetNumCols ( ) = = 1 ) ; <nl> assert ( globalStdDev . GetNumCols ( ) = = 1 ) ; <nl> <nl> - / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> + / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> int curDevId = globalStdDev . GetDeviceId ( ) ; <nl> globalStdDev . TransferFromDeviceToDevice ( curDevId , CPUDEVICE , true , false , false ) ; <nl> for ( int i = 0 ; i < globalStdDev . GetNumRows ( ) ; i + + ) <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildNetworkFromDbnFile ( co <nl> if ( ! CheckDbnTag ( fstream , " BNET " ) ) <nl> RuntimeError ( " Error reading DBN file - did not find expected tag BNET \ n " ) ; <nl> <nl> - for ( i = 0 ; i < numLayers ; i + + ) / / 0th index is for input layer , <nl> + for ( i = 0 ; i < numLayers ; i + + ) / / 0th index is for input layer , <nl> { <nl> fstream > > layerType ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildNetworkFromDbnFile ( co <nl> Matrix < ElemType > contextMean ( contextDim , 1 , m_deviceId ) ; <nl> Matrix < ElemType > contextStdDev ( contextDim , 1 , m_deviceId ) ; <nl> <nl> - / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> + / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> contextMean . TransferFromDeviceToDevice ( m_deviceId , CPUDEVICE , true , false , false ) ; <nl> contextStdDev . TransferFromDeviceToDevice ( m_deviceId , CPUDEVICE , true , false , false ) ; <nl> for ( size_t j = 0 ; j < frameDim ; j + + ) <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildNetworkFromDbnFile ( co <nl> <nl> if ( ! CheckDbnTag ( fstream , " ENET " ) ) <nl> RuntimeError ( " Error reading DBN file - did not find expected tag ENET \ n " ) ; <nl> - / / size_t outputLayerSize = m_layerSizes [ m_layerSizes . size ( ) - 1 ] ; <nl> + / / size_t outputLayerSize = m_layerSizes [ m_layerSizes . size ( ) - 1 ] ; <nl> <nl> label = builder . CreateInputNode ( L " labels " , m_outputLayerSize ) ; <nl> <nl> ComputationNetworkPtr SimpleNetworkBuilder < ElemType > : : BuildNetworkFromDbnFile ( co <nl> { <nl> input = builder . Log ( prior , L " LogOfPrior " ) ; <nl> <nl> - / / following two lines is needed only if true probability is needed <nl> - / / output = builder . Softmax ( output ) ; <nl> - / / output = builder . Log ( output ) ; <nl> + / / following two lines is needed only if true probability is needed <nl> + / / output = builder . Softmax ( output ) ; <nl> + / / output = builder . Log ( output ) ; <nl> <nl> scaledLogLikelihood = builder . CreateComputationNode ( OperationNameOf ( MinusNode ) , L " ScaledLogLikelihood " ) ; <nl> scaledLogLikelihood - > AttachInputs ( output , input ) ; <nl> shared_ptr < ComputationNode < ElemType > > SimpleNetworkBuilder < ElemType > : : ApplyNonli <nl> output = builder . Tanh ( input , nodeName ) ; <nl> else if ( nonLinearFunction = = L " None " | | nonLinearFunction = = L " none " | | nonLinearFunction = = L " " ) <nl> { <nl> - output = input ; / / linear layer <nl> + output = input ; / / linear layer <nl> if ( nodeName ! = L " " ) <nl> m_net - > RenameNode ( output , nodeName ) ; <nl> } <nl> shared_ptr < ComputationNode < ElemType > > SimpleNetworkBuilder < ElemType > : : AddTrainAn <nl> break ; <nl> case TrainingCriterion : : NCECrossEntropyWithSoftmax : <nl> output = builder . NoiseContrastiveEstimation ( label , input , matrix , clspostprob , ( trainNodeName = = L " " ) ? L " NoiseContrastiveEstimationNode " : trainNodeName ) ; <nl> - / / output = builder . NoiseContrastiveEstimation ( label , input , matrix , clspostprob , ( trainNodeName = = L " " ) ? L " NoiseContrastiveEstimationNode " : trainNodeName ) ; <nl> + / / output = builder . NoiseContrastiveEstimation ( label , input , matrix , clspostprob , ( trainNodeName = = L " " ) ? L " NoiseContrastiveEstimationNode " : trainNodeName ) ; <nl> break ; <nl> default : <nl> LogicError ( " Unsupported training criterion . " ) ; <nl> shared_ptr < ComputationNode < ElemType > > SimpleNetworkBuilder < ElemType > : : AddTrainAn <nl> case EvalCriterion : : CrossEntropyWithSoftmax : <nl> if ( matrix ! = nullptr & & tinput = = input ) <nl> tinput = builder . Times ( matrix , input ) ; <nl> - / / output = builder . CrossEntropyWithSoftmax ( label , tinput , ( evalNodeName = = L " " ) ? L " EvalCrossEntropyWithSoftmax " : evalNodeName ) ; <nl> + / / output = builder . CrossEntropyWithSoftmax ( label , tinput , ( evalNodeName = = L " " ) ? L " EvalCrossEntropyWithSoftmax " : evalNodeName ) ; <nl> output = builder . CrossEntropyWithSoftmax ( label , tinput , ( evalNodeName = = L " " ) ? L " CrossEntropyWithSoftmax " : evalNodeName ) ; <nl> break ; <nl> case EvalCriterion : : ClassCrossEntropyWithSoftmax : <nl> - / / output = builder . ClassCrossEntropyWithSoftmax ( label , input , matrix , clspostprob , ( evalNodeName = = L " " ) ? L " EvalClassCrossEntropyWithSoftmax " : evalNodeName ) ; <nl> + / / output = builder . ClassCrossEntropyWithSoftmax ( label , input , matrix , clspostprob , ( evalNodeName = = L " " ) ? L " EvalClassCrossEntropyWithSoftmax " : evalNodeName ) ; <nl> output = builder . ClassCrossEntropyWithSoftmax ( label , input , matrix , clspostprob , ( evalNodeName = = L " " ) ? L " ClassCrossEntropyWithSoftmax " : evalNodeName ) ; <nl> break ; <nl> case EvalCriterion : : NCECrossEntropyWithSoftmax : <nl> shared_ptr < ComputationNode < ElemType > > SimpleNetworkBuilder < ElemType > : : AddTrainAn <nl> case EvalCriterion : : SquareError : <nl> if ( matrix ! = nullptr & & tinput = = input ) <nl> tinput = builder . Times ( matrix , input ) ; <nl> - / / output = builder . SquareError ( label , tinput , ( evalNodeName = = L " " ) ? L " EvalSquareError " : evalNodeName ) ; <nl> + / / output = builder . SquareError ( label , tinput , ( evalNodeName = = L " " ) ? L " EvalSquareError " : evalNodeName ) ; <nl> output = builder . SquareError ( label , tinput , ( evalNodeName = = L " " ) ? L " SquareError " : evalNodeName ) ; <nl> break ; <nl> case EvalCriterion : : Logistic : <nl> if ( matrix ! = nullptr & & tinput = = input ) <nl> tinput = builder . Times ( matrix , input ) ; <nl> - / / output = builder . SquareError ( label , tinput , ( evalNodeName = = L " " ) ? L " EvalSquareError " : evalNodeName ) ; <nl> + / / output = builder . SquareError ( label , tinput , ( evalNodeName = = L " " ) ? L " EvalSquareError " : evalNodeName ) ; <nl> output = builder . Logistic ( label , tinput , ( evalNodeName = = L " " ) ? L " Logistic " : evalNodeName ) ; <nl> break ; <nl> case EvalCriterion : : ErrorPrediction : <nl> mmm a / Source / CNTK / SimpleNetworkBuilder . h <nl> ppp b / Source / CNTK / SimpleNetworkBuilder . h <nl> class SimpleNetworkBuilder <nl> typedef shared_ptr < ComputationNode < ElemType > > ComputationNodePtr ; <nl> <nl> private : <nl> - SimpleNetworkBuilder ( ) / / disable default constructor from being called <nl> + SimpleNetworkBuilder ( ) / / disable default constructor from being called <nl> { <nl> } <nl> <nl> class SimpleNetworkBuilder <nl> m_cls2index = config ( " cls2index " , " " ) ; <nl> m_vocabSize = ( int ) config ( " vocabSize " , " - 1 " ) ; <nl> m_nbrCls = ( int ) config ( " nbrClass " , " - 1 " ) ; <nl> - nce_noises = ( int ) config ( " noise_number " , " - 1 " ) ; / / nce noise <nl> + nce_noises = ( int ) config ( " noise_number " , " - 1 " ) ; / / nce noise <nl> <nl> Init ( layers , trainingCriterion , evalCriterion , outputLayerSize , <nl> nonlinearFunctions , addDropoutNodes , <nl> class SimpleNetworkBuilder <nl> <nl> ComputationNetworkPtr BuildNCELSTMNetworkFromDescription ( ) ; <nl> <nl> - / / layer is 0 based <nl> + / / layer is 0 based <nl> ComputationNodePtr ApplyNonlinearFunction ( ComputationNodePtr input , const size_t layer , const std : : wstring nodeName = L " " ) ; <nl> ComputationNodePtr AddTrainAndEvalCriterionNodes ( ComputationNodePtr input , ComputationNodePtr label , ComputationNodePtr matrix = nullptr , const std : : wstring trainNodeName = L " " , const std : : wstring evalNodeName = L " " , ComputationNodePtr clspostprob = nullptr , ComputationNodePtr trans = nullptr ) ; <nl> <nl> class SimpleNetworkBuilder <nl> std : : string name ; <nl> if ( ! CheckDbnTag ( fstream , " BMAT " ) ) <nl> RuntimeError ( " Error reading DBN file - did not find expected tag BMAT \ n " ) ; <nl> - / / fstream . GetMarker ( FileMarker : : fileMarkerBeginSection , " BMAT " ) ; <nl> + / / fstream . GetMarker ( FileMarker : : fileMarkerBeginSection , " BMAT " ) ; <nl> fstream > > name > > numRows > > numCols ; <nl> if ( name ! = expectedName ) <nl> { <nl> class SimpleNetworkBuilder <nl> Matrix < ElemType > mat ( numRows , numCols , m_deviceId ) ; <nl> <nl> / / dbn operates on row vectors not column vectors . x * W + b , so need to read in as W ' <nl> - / / ElemType * d_array = new ElemType [ numRows * numCols ] ; <nl> + / / ElemType * d_array = new ElemType [ numRows * numCols ] ; <nl> float tmp ; <nl> for ( long i = 0 ; i < numRows ; i + + ) <nl> for ( long j = 0 ; j < numCols ; j + + ) <nl> { <nl> fstream > > tmp ; <nl> mat ( i , j ) = tmp ; <nl> - / / d_array [ i ] = ( ElemType ) tmp ; <nl> + / / d_array [ i ] = ( ElemType ) tmp ; <nl> } <nl> if ( ! CheckDbnTag ( fstream , " EMAT " ) ) <nl> RuntimeError ( " Error reading DBN file - did not find expected tag EMAT \ n " ) ; <nl> - / / fstream . GetMarker ( FileMarker : : fileMarkerBeginSection , " EMAT " ) ; <nl> + / / fstream . GetMarker ( FileMarker : : fileMarkerBeginSection , " EMAT " ) ; <nl> <nl> return mat ; <nl> } <nl> mmm a / Source / CNTK / SynchronousExecutionEngine . cpp <nl> ppp b / Source / CNTK / SynchronousExecutionEngine . cpp <nl> void SynchronousNodeEvaluator < ElemType > : : Evaluate ( NDLNode < ElemType > * node , const <nl> / / if we have three parameters the second is columns <nl> / / ignore legacy size_t cols = parameter . size ( ) > 2 ? ( ( NDLNode < ElemType > * ) params [ 1 ] ) - > GetScalar ( ) : 1 ; <nl> <nl> - / / bool needGradient = node - > GetOptionalParameter ( " needGradient " , " false " ) ; / / TODO : what ' s this for ? <nl> + / / bool needGradient = node - > GetOptionalParameter ( " needGradient " , " false " ) ; / / TODO : what ' s this for ? <nl> float defaultHiddenActivity = node - > GetOptionalParameter ( " defaultHiddenActivity " , " 0 . 1 " ) ; / / TODO : parameter should be called ' defaultHiddenActivation ' <nl> <nl> / / for backward compatibility we check ' timeStep ' first <nl> void SynchronousNodeEvaluator < ElemType > : : Evaluate ( NDLNode < ElemType > * node , const <nl> else <nl> nodePtr = builder . FutureValue ( NULL , defaultHiddenActivity , rows , timeStep , name ) ; <nl> <nl> - / / nodePtr - > SetParameterUpdateRequired ( needGradient ) ; / / TODO : what ' s this for ? <nl> + / / nodePtr - > SetParameterUpdateRequired ( needGradient ) ; / / TODO : what ' s this for ? <nl> } <nl> } <nl> else if ( cnNodeType = = OperationNameOf ( ConvolutionNode ) ) <nl> void SynchronousNodeEvaluator < ElemType > : : Evaluate ( NDLNode < ElemType > * node , const <nl> { <nl> std : : vector < void * > inputs = EvaluateParameters ( node , baseName , nodeParamStart , nodeParamCount , pass ) ; <nl> <nl> - if ( cnNodeType = = OperationNameOf ( RowStackNode ) ) / / support variable length inputs <nl> + if ( cnNodeType = = OperationNameOf ( RowStackNode ) ) / / support variable length inputs <nl> { <nl> std : : vector < ComputationNodeBasePtr > inputNodes ; <nl> inputNodes . resize ( inputs . size ( ) ) ; <nl> mmm a / Source / CNTK / SynchronousExecutionEngine . h <nl> ppp b / Source / CNTK / SynchronousExecutionEngine . h <nl> class SynchronousNodeEvaluator : public NDLNodeEvaluator < ElemType > <nl> / / A = MacroCall3 ( . . . ) <nl> / / D = Times ( A . B , X . B ) } <nl> / / } <nl> - / / <nl> + / / <nl> <nl> / / In this example , in the call D = Times ( A . B , X . B ) , we need to resolve A . B and X . B appropriately . <nl> / / Specifically , " A . B " must be resolved to the fully qualified name " C . A . B " , whereas " X . B " must be resolved to the fully qualified name " P . B " . <nl> mmm a / Source / CNTK / tests . cpp <nl> ppp b / Source / CNTK / tests . cpp <nl> void TestBing ( const ConfigParameters & config ) <nl> <nl> std : : cout < < std : : endl < < std : : endl < < std : : endl < < std : : endl < < " Testing . . . . . " < < std : : endl ; <nl> <nl> - / / test <nl> + / / test <nl> vector < wstring > testfilepaths ; <nl> testfilepaths . push_back ( config ( " test . set " ) ) ; <nl> size_t testSize = config ( " test . set . size " ) ; <nl> void TestSpeech ( const ConfigParameters & configBase ) <nl> template < typename ElemType > <nl> void TestReader ( const ConfigParameters & configBase ) <nl> { <nl> - / / int nonexistant = configBase ( " nonexistant " ) ; / / use to test global exception handler <nl> + / / int nonexistant = configBase ( " nonexistant " ) ; / / use to test global exception handler <nl> ConfigParameters config ( configBase ( " mnistTest " ) ) ; <nl> ConfigParameters readerConfig ( config ( " reader " ) ) ; <nl> readerConfig . Insert ( " traceLevel " , config ( " traceLevel " , " 0 " ) ) ; <nl> void TestReader ( const ConfigParameters & configBase ) <nl> template < typename ElemType > <nl> void TestSequenceReader ( const ConfigParameters & configBase ) <nl> { <nl> - / / int nonexistant = configBase ( " nonexistant " ) ; / / use to test global exception handler <nl> + / / int nonexistant = configBase ( " nonexistant " ) ; / / use to test global exception handler <nl> ConfigParameters config = configBase ( " sequenceTest " ) ; <nl> <nl> size_t mbSize = config ( " minibatchSize " ) ; <nl> void TestConfiguration ( const ConfigParameters & configBase ) <nl> } <nl> } <nl> <nl> - / / now link up all the nodes <nl> + / / now link up all the nodes <nl> configNodes = configCN ( " Relation " ) ; <nl> for ( auto iter = configNodes . begin ( ) ; iter ! = configNodes . end ( ) ; iter + + ) <nl> { <nl> void TestConfiguration ( const ConfigParameters & configBase ) <nl> } <nl> } <nl> <nl> - if ( configRoots . Exists ( " CriteriaNodes " ) ) / / legacy <nl> + if ( configRoots . Exists ( " CriteriaNodes " ) ) / / legacy <nl> { <nl> configNode = configRoots ( " CriteriaNodes " ) ; <nl> for ( size_t i = 0 ; i < configNode . size ( ) ; i + + ) <nl> void TestCommandLine ( const ConfigParameters & configBase ) <nl> / / # config file parsing , basic types <nl> / / int = 20 <nl> int i = config ( " int " , " 5555 " ) ; <nl> - / / cout < < i < < endl ; <nl> + / / cout < < i < < endl ; <nl> i = config ( " nothere " , " 1234 " ) ; <nl> - / / cout < < i < < endl ; <nl> + / / cout < < i < < endl ; <nl> / / long = 8100000 <nl> long l = config ( L " long " , " 5555 " ) ; <nl> - / / cout < < l < < endl ; <nl> + / / cout < < l < < endl ; <nl> l = config ( " nothere " , " 1234 " ) ; <nl> / / size_t = 12345678901234 <nl> / / should get the same thing asking from a double nested config <nl> l = unicodeTests ( L " long " , " 5555 " ) ; <nl> - / / cout < < l < < endl ; <nl> + / / cout < < l < < endl ; <nl> l = unicodeTests ( " nothere " , " 1234 " ) ; <nl> / / size_t = 12345678901234 <nl> size_t s = config ( " size_t " , " 5555 " ) ; <nl> - / / cout < < s < < endl ; <nl> + / / cout < < s < < endl ; <nl> s = config ( L " nothere " , " 1234 " ) ; <nl> <nl> / / get stuff from base level config ( 3 levels down ) <nl> void TestCommandLine ( const ConfigParameters & configBase ) <nl> bool bif = config . Exists ( L " boolImpliedFalse " ) ; <nl> bif ; <nl> bf = config ( " nothere " , " false " ) ; <nl> - / / cout < < bf < < endl ; <nl> + / / cout < < bf < < endl ; <nl> / / float = 1234 . 5678 <nl> float f = config ( " float " , " 555 . 555 " ) ; <nl> - / / cout < < f < < endl ; <nl> + / / cout < < f < < endl ; <nl> f = config ( " nothere " , " 1 . 234 " ) ; <nl> / / double = 1 . 23456e - 99 <nl> double d = config ( " double " , " 555 . 555 " ) ; <nl> - / / cout < < d < < endl ; <nl> + / / cout < < d < < endl ; <nl> d = stringTests ( " nothere " , " 1 . 2345 " ) ; <nl> / / string = string1 <nl> std : : string str = stringTests ( " string " ) ; <nl> str = stringTests ( L " nothere " , " default " ) ; <nl> - / / cout < < str < < endl ; <nl> + / / cout < < str < < endl ; <nl> str = stringTests ( " nothere " , " defString " ) ; <nl> - / / cout < < str < < endl ; <nl> + / / cout < < str < < endl ; <nl> / / stringQuotes = " This is a string with quotes " <nl> str = stringTests ( " stringQuotes " ) ; <nl> / / wstring = æ ± äº ¬ <nl> std : : wstring wstr = unicodeTests ( " wstring " ) ; <nl> wstr = ( std : : wstring ) unicodeTests ( L " nothere " , L " newValue " ) ; <nl> - / / wcout < < wstr < < endl ; <nl> + / / wcout < < wstr < < endl ; <nl> wstr = ( std : : wstring ) unicodeTests ( " nothere " , L " defWstring " ) ; <nl> / / wstringQuotes = " æ ± äº ¬ ã « è ¡ ã ã ¾ã ã ã ï¼ æ æ ¥ " <nl> std : : wstring wstrQuotes = unicodeTests ( " wstringQuotes " ) ; <nl> - / / <nl> + / / <nl> / / # array tests <nl> / / arrayEmpty = { } <nl> ConfigArray arrayEmpty = arrayTests ( " arrayEmpty " ) ; <nl> void TestCommandLine ( const ConfigParameters & configBase ) <nl> ConfigArray arrayMultiple = arrayTests ( L " arrayMultiple " ) ; <nl> / / arrayMultipleBraces = { hello : there : with : braces } <nl> ConfigArray arrayMultipleBraces = arrayTests ( " arrayMultipleBraces " ) ; <nl> - / / arrayMultiple = arrayTests ( " nothere " , arrayMultipleBraces ) ; - no longer supported , can add if we need it <nl> + / / arrayMultiple = arrayTests ( " nothere " , arrayMultipleBraces ) ; - no longer supported , can add if we need it <nl> / / arrayMultipleSeparatorBraces = { | hello | there | with | custom | separator | and | braces } <nl> ConfigArray arrayMultipleSeparatorBraces = arrayTests ( " arrayMultipleSeparatorBraces " ) ; <nl> / / arrayQuotedStrings = { <nl> void TestCommandLine ( const ConfigParameters & configBase ) <nl> ConfigArray array3 = arrayNested [ 2 ] ; <nl> name = array3 . Name ( ) ; <nl> ConfigArray array4 = arrayNested [ 3 ] ; <nl> - / / <nl> + / / <nl> / / # dictionary tests <nl> / / dictEmpty = [ ] <nl> ConfigParameters dictEmpty ( dictTests ( " dictEmpty " ) ) ; <nl> void TestCommandLine ( const ConfigParameters & configBase ) <nl> ConfigParameters dictMultiple ( dictTests ( " dictMultiple " ) ) ; <nl> / / dictMultipleBraces = [ first = hello ; second = there ; third = with ; forth = braces ] <nl> ConfigParameters dictMultipleBraces ( dictTests ( L " dictMultipleBraces " ) ) ; <nl> - / / dictMultiple = dictTests ( " nothere " , dictMultipleBraces ) ; no longer supported , can add if we need <nl> + / / dictMultiple = dictTests ( " nothere " , dictMultipleBraces ) ; no longer supported , can add if we need <nl> / / dictMultipleSeparatorBraces = [ | first = hello | second = 1 | thirdBool | forth = 12 . 345 | fifth = " quoted string " | sixth = å ¤ é ¨ | seventh = braces ] <nl> ConfigParameters dictMultipleSeparatorBraces ( dictTests ( " dictMultipleSeparatorBraces " ) ) ; <nl> / / dictQuotedStrings = [ <nl> void TestCommandLine ( const ConfigParameters & configBase ) <nl> arrayQuotedStrings = dictQuotedStrings ( " files " ) ; <nl> const char * mapping = dictQuotedStrings ( " mapping " ) ; <nl> mapping ; <nl> - / / <nl> + / / <nl> / / # super nesting <nl> / / dictNested = [ <nl> / / array = { <nl> void TestCommandLine ( const ConfigParameters & configBase ) <nl> name = dict3 . Name ( ) ; <nl> / / ] <nl> <nl> - / / File file ( L " c : \ \ temp \ \ testing . txt " , fileOptionsRead | fileOptionsText ) ; <nl> - / / char marker [ 5 ] ; <nl> - / / if ( file . TryGetMarker ( fileMarkerBeginSection , L " BVAL " ) ) <nl> - / / { <nl> + / / File file ( L " c : \ \ temp \ \ testing . txt " , fileOptionsRead | fileOptionsText ) ; <nl> + / / char marker [ 5 ] ; <nl> + / / if ( file . TryGetMarker ( fileMarkerBeginSection , L " BVAL " ) ) <nl> + / / { <nl> / / if ( file . TryGetMarker ( fileMarkerBeginSection , L " BNEW " ) ) <nl> / / { <nl> / / if ( ! file . TryGetMarker ( fileMarkerBeginSection , L " OTHER " ) ) <nl> void TestCommandLine ( const ConfigParameters & configBase ) <nl> / / printf ( " pass " ) ; <nl> / / } <nl> / / } <nl> - / / } <nl> - / / TestConfiguration < ElemType > ( configBase ) ; <nl> + / / } <nl> + / / TestConfiguration < ElemType > ( configBase ) ; <nl> TestMacros < ElemType > ( configBase ) ; <nl> } <nl> <nl> template < typename ElemType > <nl> void TestCn ( const ConfigParameters & config ) <nl> { <nl> TestCommandLine < ElemType > ( config ) ; <nl> - / / TestSequenceReader < ElemType > ( config ) ; <nl> + / / TestSequenceReader < ElemType > ( config ) ; <nl> TestReader < ElemType > ( config ) ; <nl> TestMNist < ElemType > ( config ) ; <nl> TestSpeech < ElemType > ( config ) ; <nl> - / / TestBing < ElemType > ( config ) ; <nl> + / / TestBing < ElemType > ( config ) ; <nl> } <nl> <nl> template void TestCn < float > ( const ConfigParameters & config ) ; <nl> mmm a / Source / Common / BestGpu . cpp <nl> ppp b / Source / Common / BestGpu . cpp <nl> int bestGPUDummy = 42 ; / / put something into this CPP , as to avoid a linker warn <nl> # define PATH_DELIMITER ' \ \ ' <nl> # elif defined ( __UNIX__ ) <nl> # define PATH_DELIMITER ' / ' <nl> - # endif / / __WINDOWS__ <nl> + # endif / / __WINDOWS__ <nl> # include < stdio . h > <nl> # include < string . h > <nl> # include < algorithm > <nl> mmm a / Source / Common / DataReader . cpp <nl> ppp b / Source / Common / DataReader . cpp <nl> DataReader < ElemType > : : DataReader ( const ConfigRecordType & config ) <nl> } <nl> <nl> / / now pass that to concurrent reader so we can read ahead <nl> - / / m_DataReader = new ConcurrentReader < ElemType > ( m_DataReader ) ; <nl> + / / m_DataReader = new ConcurrentReader < ElemType > ( m_DataReader ) ; <nl> / / NOW we can init <nl> / / TODO : merge with the code above , but we first need to get the nbrUttPerMinibatch initialized inside each reader <nl> for ( const auto & ioName : m_ioNames ) <nl> mmm a / Source / Common / File . cpp <nl> ppp b / Source / Common / File . cpp <nl> void File : : Init ( const wchar_t * filename , int fileOptions ) <nl> else <nl> options + = L " t " ; <nl> / / I attempted to use the translated characterset modes , but encountered strange errors <nl> - / / options + = L " t , ccs = " ; <nl> - / / options + = ( fileOptions & fileOptionsUnicode ) ? L " UNICODE " : L " UTF - 8 " ; <nl> + / / options + = L " t , ccs = " ; <nl> + / / options + = ( fileOptions & fileOptionsUnicode ) ? L " UNICODE " : L " UTF - 8 " ; <nl> } <nl> / / add sequential flag to allocate big read buffer <nl> if ( fileOptions & fileOptionsSequential ) <nl> bool File : : TryGetMarker ( FileMarker marker , const std : : wstring & section ) <nl> } <nl> catch ( . . . ) <nl> { <nl> - / / eat <nl> + / / eat <nl> } <nl> SetPosition ( pos ) ; <nl> return false ; <nl> mmm a / Source / Common / Include / Basics . h <nl> ppp b / Source / Common / Include / Basics . h <nl> static inline std : : wstring mbstowcs ( const std : : string & p ) / / input : MBCS <nl> size_t len = p . length ( ) ; <nl> std : : vector < wchar_t > buf ( len + 1 ) ; / / max : > 1 mb chars = > 1 wchar <nl> std : : fill ( buf . begin ( ) , buf . end ( ) , ( wchar_t ) 0 ) ; <nl> - / / OACR_WARNING_SUPPRESS ( UNSAFE_STRING_FUNCTION , " Reviewed OK . size checked . [ rogeryu 2006 / 03 / 21 ] " ) ; <nl> + / / OACR_WARNING_SUPPRESS ( UNSAFE_STRING_FUNCTION , " Reviewed OK . size checked . [ rogeryu 2006 / 03 / 21 ] " ) ; <nl> : : mbstowcs ( & buf [ 0 ] , p . c_str ( ) , len + 1 ) ; <nl> return std : : wstring ( & buf [ 0 ] ) ; <nl> } <nl> mmm a / Source / Common / Include / Config . h <nl> ppp b / Source / Common / Include / Config . h <nl> class ConfigValue : public std : : string <nl> / / TODO : do we want to allow accept non - empty strings and non - 0 numerical values as ' true ' ? <nl> } <nl> <nl> - / / ReplaceAppend - replace an existing value with another value , or append if it appears to be a " set " type <nl> + / / ReplaceAppend - replace an existing value with another value , or append if it appears to be a " set " type <nl> ConfigValue & ReplaceAppend ( const std : : string & configValue ) <nl> { <nl> static const std : : string openBraces = " [ " ; <nl> class ConfigParser <nl> { <nl> / / look for closing brace and also for another opening brace <nl> / / Inside strings we only accept the closing quote , and ignore any braces inside . <nl> - current = str . find_first_of ( braceStack . back ( ) = = ' " ' ? " \ " " : charsToLookFor , current + 1 ) ; / / <nl> + current = str . find_first_of ( braceStack . back ( ) = = ' " ' ? " \ " " : charsToLookFor , current + 1 ) ; / / <nl> if ( current = = string : : npos ) / / none found : done or error <nl> break ; <nl> char brace = str [ current ] ; <nl> class ConfigParser <nl> / / ( 12 : 45 : 23 : 46 ) <nl> / / However if you are using strings , and one of those strings contains a : , you might want to change the separator to something else : <nl> / / ( ; this ; is ; a ; path : ; c : \ mydir \ stuff ) <nl> - / / <nl> + / / <nl> / / This will fail for <nl> / / ( . . \ dirname , something else ) <nl> / / Hence there is an ugly fix for it below . This will go away when we replace all configuration parsing by BrainScript . <nl> class ConfigParameters : public ConfigParser , public ConfigDictionary <nl> Parse ( configString ) ; <nl> } <nl> <nl> - / / private : <nl> + / / private : <nl> / / copy and move constructors <nl> ConfigParameters ( const ConfigParameters & configValue ) <nl> : ConfigParser ( configValue ) <nl> mmm a / Source / Common / Include / DataReader . h <nl> ppp b / Source / Common / Include / DataReader . h <nl> class DataReader : public IDataReader < ElemType > , protected Plugin , public Script <nl> / / Init - Reader Initialize for multiple data sets <nl> / / config - [ in ] configuration parameters for the datareader <nl> / / Sample format below for UCIReader : <nl> - / / # Parameter values for the reader <nl> - / / reader = [ <nl> + / / # Parameter values for the reader <nl> + / / reader = [ <nl> / / # reader to use <nl> - / / readerType = UCIFastReader <nl> - / / miniBatchMode = Partial <nl> + / / readerType = " UCIFastReader " <nl> + / / miniBatchMode = " partial " <nl> / / randomize = None <nl> / / features = [ <nl> / / dim = 784 <nl> / / start = 1 <nl> - / / file = c : \ speech \ mnist \ mnist_test . txt <nl> + / / file = " c : \ speech \ mnist \ mnist_test . txt " <nl> / / ] <nl> / / labels = [ <nl> / / dim = 1 <nl> / / start = 0 <nl> - / / file = c : \ speech \ mnist \ mnist_test . txt <nl> - / / labelMappingFile = c : \ speech \ mnist \ labels . txt <nl> + / / file = " c : \ speech \ mnist \ mnist_test . txt " <nl> + / / labelMappingFile = " c : \ speech \ mnist \ labels . txt " <nl> / / labelDim = 10 <nl> - / / labelType = Category <nl> + / / labelType = " category " <nl> / / ] <nl> / / ] <nl> template < class ConfigRecordType > <nl> class DataReader : public IDataReader < ElemType > , protected Plugin , public Script <nl> } <nl> virtual ~ DataReader ( ) ; <nl> <nl> - / / StartMinibatchLoop - Startup a minibatch loop <nl> + / / StartMinibatchLoop - Startup a minibatch loop <nl> / / mbSize - [ in ] size of the minibatch ( number of frames , etc . ) <nl> / / epoch - [ in ] epoch number for this loop <nl> / / requestedEpochSamples - [ in ] number of samples to randomize , defaults to requestDataSize which uses the number of samples there are in the dataset <nl> mmm a / Source / Common / Include / DataWriter . h <nl> ppp b / Source / Common / Include / DataWriter . h <nl> class DataWriter : public IDataWriter < ElemType > , protected Plugin <nl> / / Init - Writer Initialize for multiple data sets <nl> / / config - [ in ] configuration parameters for the datawriter <nl> / / Sample format below for BinaryWriter : <nl> - / / writer = [ <nl> + / / writer = [ <nl> / / # writer to use , can implement both reader and writer <nl> / / writerType = BinaryWriter <nl> / / miniBatchMode = Partial <nl> class DataWriter : public IDataWriter < ElemType > , protected Plugin <nl> / / features = [ <nl> / / dim = 784 <nl> / / start = 1 <nl> - / / sectionType = data <nl> + / / sectionType = " data " <nl> / / stats = [ <nl> - / / sectionType = stats <nl> + / / sectionType = " stats " <nl> / / elementSize = 8 <nl> - / / compute = { sum : count : mean : variance : stddev : max : min : range } <nl> + / / compute = { " sum " : " count " : " mean : " v " ariance " : " stddev " : " max " : " min " : " range " } <nl> / / ] <nl> / / ] <nl> / / labels = [ <nl> / / dim = 1 <nl> / / # sizeof ( unsigned ) which is the label index type <nl> / / elementSize = 4 <nl> - / / wref = features <nl> - / / sectionType = labels <nl> + / / wref = " features " <nl> + / / sectionType = " labels " <nl> / / mapping = [ <nl> / / # redefine number of records for this section , since we don ' t need to save it for each data record <nl> / / wrecords = 10 <nl> / / # variable size so use an average string size <nl> / / elementSize = 10 <nl> - / / sectionType = stringMap <nl> + / / sectionType = " stringMap " <nl> / / ] <nl> / / category = [ <nl> / / dim = 10 <nl> / / # elementSize = sizeof ( ElemType ) is default <nl> - / / sectionType = categoryLabels <nl> + / / sectionType = " categoryLabels " <nl> / / ] <nl> - / / labelType = Category <nl> + / / labelType = " category " <nl> / / ] <nl> - / / <nl> / / ] <nl> template < class ConfigRecordType > <nl> void InitFromConfig ( const ConfigRecordType & ) ; <nl> mmm a / Source / Common / Include / File . h <nl> ppp b / Source / Common / Include / File . h <nl> static void attempt ( const FUNCTION & body ) <nl> { <nl> static const int retries = 5 ; <nl> attempt < FUNCTION > ( retries , body ) ; <nl> - / / msra : : util : : attempt < FUNCTION > ( retries , body ) ; <nl> + / / msra : : util : : attempt < FUNCTION > ( retries , body ) ; <nl> } <nl> <nl> class File <nl> mmm a / Source / Common / Include / Platform . h <nl> ppp b / Source / Common / Include / Platform . h <nl> unique_ptr < T > make_unique ( Args & & . . . args ) <nl> <nl> # endif / / ! _MSC_VER <nl> <nl> - # endif / / __PLATFORM_H <nl> + # endif / / __PLATFORM_H <nl> mmm a / Source / Common / Include / RandomOrdering . h <nl> ppp b / Source / Common / Include / RandomOrdering . h <nl> class RandomOrdering / / note : NOT thread - safe at all <nl> } <nl> <nl> / / this returns the map directly ( read - only ) and will lazily initialize it for a given seed <nl> - const std : : vector < INDEXTYPE > & operator ( ) ( size_t seed ) / / throw ( ) <nl> + const std : : vector < INDEXTYPE > & operator ( ) ( size_t seed ) / / throw ( ) <nl> { <nl> / / if wrong seed then lazily recache the sequence <nl> if ( seed ! = currentseed & & randomizationrange ! = randomizeDisable ) <nl> mmm a / Source / Common / Include / ScriptableObjects . h <nl> ppp b / Source / Common / Include / ScriptableObjects . h <nl> class ConfigValuePtr : public shared_ptr < Object > <nl> : shared_ptr < Object > ( p ) , failfn ( failfn ) , expressionName ( expressionName ) <nl> { <nl> } <nl> - / / ConfigValuePtr ( const function < ConfigValuePtr ( ) > & f , TextLocation location , const std : : wstring & expressionName ) : shared_ptr < Object > ( make_shared < Thunk > ( f , location ) ) , location ( location ) , expressionName ( expressionName ) { } <nl> + / / ConfigValuePtr ( const function < ConfigValuePtr ( ) > & f , TextLocation location , const std : : wstring & expressionName ) : shared_ptr < Object > ( make_shared < Thunk > ( f , location ) ) , location ( location ) , expressionName ( expressionName ) { } <nl> static ConfigValuePtr MakeThunk ( const function < ConfigValuePtr ( ) > & f , const function < void ( const std : : wstring & ) > & failfn , const std : : wstring & expressionName ) <nl> { <nl> return ConfigValuePtr ( make_shared < Thunk > ( f , failfn ) , failfn , expressionName ) ; <nl> class ConfigValuePtr : public shared_ptr < Object > <nl> / / TODO : factor these lines into a separate function <nl> / / Note : since this returns a reference into ' this ' , you must keep the object you call this on around as long as you use the returned reference <nl> EnsureIsResolved ( ) ; <nl> - / / const C * wanted = ( C * ) nullptr ; const auto * got = get ( ) ; wanted ; got ; / / allows to see C in the debugger <nl> + / / const C * wanted = ( C * ) nullptr ; const auto * got = get ( ) ; wanted ; got ; / / allows to see C in the debugger <nl> const auto p = dynamic_cast < C * > ( get ( ) ) ; <nl> if ( p = = nullptr ) / / TODO : can we make this look the same as TypeExpected in BrainScriptEvaluator . cpp ? We ' d need the type name <nl> Fail ( L " config member has wrong type ( " + msra : : strfun : : utf16 ( typeid ( * get ( ) ) . name ( ) ) + L " ) , expected a " + TypeId < C > ( ) ) ; <nl> class ConfigArray : public Object <nl> : firstIndex ( firstIndex ) , values ( move ( values ) ) <nl> { <nl> } <nl> - / / ConfigArray ( ConfigValuePtr & & val ) : firstIndex ( 0 ) , values ( std : : vector < ConfigValuePtr > { move ( val ) } ) { } <nl> + / / ConfigArray ( ConfigValuePtr & & val ) : firstIndex ( 0 ) , values ( std : : vector < ConfigValuePtr > { move ( val ) } ) { } <nl> pair < int , int > GetIndexRange ( ) const <nl> { <nl> return make_pair ( firstIndex , firstIndex + ( int ) values . size ( ) - 1 ) ; <nl> mmm a / Source / Common / Include / Sequences . h <nl> ppp b / Source / Common / Include / Sequences . h <nl> struct MBLayout <nl> LogicError ( " AddSequence : Sequence added to an MBLayout must overlap with minibatch . " ) ; <nl> <nl> / / remember it <nl> - # if 0 / / def _DEBUG <nl> + # if 0 / / def _DEBUG <nl> auto cap = m_sequences . capacity ( ) ; / / Some sanity check for debugging a speed regression . This should only show up during the first minibatches , and growing only . <nl> m_sequences . push_back ( seqDesc ) ; <nl> if ( cap ! = m_sequences . capacity ( ) ) <nl> struct MBLayout <nl> / / Lookup tables for determining whether any sequence at time t is a boundary or gap . <nl> / / An optional time delay can be given , then the test is whether going from t to ( t + time delay ) crosses a boundary . <nl> / / The purpose is for knowing when to reset state of a recurrent node . <nl> - / / <nl> + / / <nl> / / For every ( s , t ) , we store the distance to the corresponding sequence begin and end . <nl> / / We also store for every [ t ] an aggregate to know the nearest boundary . <nl> / / For example , two sentences used in parallel , one with 5 and one with 3 time steps , in one minibatch , both starting at step 0 <nl> mmm a / Source / Common / Include / fileutil . h <nl> ppp b / Source / Common / Include / fileutil . h <nl> const wchar_t * GetFormatString ( T / * t * / ) <nl> / / a read and / or write routine . <nl> / / If the type is a user defined class , you need to create some global functions that handles file in / out . <nl> / / for example : <nl> - / / File & operator > > ( File & stream , MyClass & test ) ; <nl> - / / File & operator < < ( File & stream , MyClass & test ) ; <nl> - / / <nl> + / / File & operator > > ( File & stream , MyClass & test ) ; <nl> + / / File & operator < < ( File & stream , MyClass & test ) ; <nl> + / / <nl> / / in your class you will probably want to add these functions as friends so you can access any private members <nl> / / friend File & operator > > ( File & stream , MyClass & test ) ; <nl> / / friend File & operator < < ( File & stream , MyClass & test ) ; <nl> - / / <nl> + / / <nl> / / if you are using wchar_t * or char * types , these use other methods because they require buffers to be passed <nl> / / either use std : : string and std : : wstring , or use the WriteString ( ) and ReadString ( ) methods <nl> assert ( false ) ; / / need a specialization <nl> mmm a / Source / Common / Include / latticearchive . h <nl> ppp b / Source / Common / Include / latticearchive . h <nl> class littlematrixheap ; <nl> enum mbrclassdefinition / / used to identify definition of class in minimum bayesian risk <nl> { <nl> senone = 1 , / / senone is default , which means no mapping ; sMBR <nl> - / / monophonestate = 2 , <nl> + / / monophonestate = 2 , <nl> monophone = 3 , / / pMBR ? <nl> } ; <nl> / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> class lattice <nl> } ; <nl> header_v1_v2 info ; / / information about the lattice <nl> static const unsigned int NOEDGE = 0xffffff ; / / 24 bits <nl> - / / static_assert ( sizeof ( nodeinfo ) = = 8 , " unexpected size of nodeeinfo " ) ; / / note : int64_t required to allow going across 32 - bit boundary <nl> + / / static_assert ( sizeof ( nodeinfo ) = = 8 , " unexpected size of nodeeinfo " ) ; / / note : int64_t required to allow going across 32 - bit boundary <nl> / / ensure type size as these are expected to be of this size in the files we read <nl> static_assert ( sizeof ( nodeinfo ) = = 2 , " unexpected size of nodeeinfo " ) ; / / note : int64_t required to allow going across 32 - bit boundary <nl> static_assert ( sizeof ( edgeinfowithscores ) = = 16 , " unexpected size of edgeinfowithscores " ) ; <nl> class lattice <nl> if ( diff ! = 0 ) <nl> return diff ; <nl> diff = ( int ) e1 . E - ( int ) e2 . E ; <nl> - / / if ( diff ! = 0 ) <nl> + / / if ( diff ! = 0 ) <nl> return diff ; <nl> } <nl> / / lattice sort order - - algorithms assume lattices are sorted by E , then by S <nl> class lattice <nl> align . push_back ( ai ) ; <nl> } <nl> } <nl> - / / fprintf ( stderr , " rebuildedges : % d edges reconstructed to % d alignment tokens \ n " , edges . size ( ) , align . size ( ) ) ; / / [ v - hansu ] comment out because it takes up most of the log <nl> + / / fprintf ( stderr , " rebuildedges : % d edges reconstructed to % d alignment tokens \ n " , edges . size ( ) , align . size ( ) ) ; / / [ v - hansu ] comment out because it takes up most of the log <nl> align . shrink_to_fit ( ) ; / / free up unused memory ( since we need it ! ! ) <nl> / / now get rid of the V2 data altogether <nl> uniquededgedatatokens . clear ( ) ; <nl> class lattice <nl> void dump ( FILE * f , const HMMLOOKUPFUNCTION & gethmmname ) const / / dump a lattice in HTK - like format <nl> { <nl> fprintf ( f , " N = % lu L = % lu \ n " , nodes . size ( ) , edges . size ( ) ) ; <nl> - / / foreach_index ( i , nodes ) <nl> + / / foreach_index ( i , nodes ) <nl> / / fprintf ( f , " I = % d \ tt = % . 2f \ n " , i , nodes [ i ] . t * 0 . 01f ) ; <nl> foreach_index ( j , edges ) <nl> { <nl> class lattice <nl> foreach_index ( k , align ) <nl> align [ k ] . updateunit ( idmap ) ; / / updates itself <nl> # if 0 / / TODO : this is not complete . Enable once we move to more compact5 data structure . <nl> - / / showstats ( ) ; <nl> + / / showstats ( ) ; <nl> / / version 1 is outdated - - we build the compact version now <nl> / / TODO : once all is converted , edges ( ) will become a local variable here <nl> buildedgegroupstorage ( ) ; <nl> class lattice <nl> { <nl> / / fprintf ( stderr , " fread : inconsistent spunit id in file % d vs . expected % d ; due to erroneous heuristic \ n " , info . impliedspunitid , spunit ) ; / / [ v - hansu ] comment out becaues it takes up most of the log <nl> / / it ' s actually OK , we can live with this , since we only decompress and then move on without any assumptions <nl> - / / RuntimeError ( " fread : mismatching / sp / units " ) ; <nl> + / / RuntimeError ( " fread : mismatching / sp / units " ) ; <nl> } <nl> / / reconstruct old lattice format from this - - TODO : remove once we change to new data representation <nl> rebuildedges ( info . impliedspunitid ! = spunit / * to be able to read somewhat broken V2 lattice archives * / ) ; <nl> class lattice <nl> const size_t getsilunitid ( ) ; <nl> void getedgeacscores ( std : : vector < float > & edgeacscores ) ; <nl> void getedgealignments ( std : : vector < unsigned short > & edgealignments ) ; <nl> - / / to work with CNTK ' s GPU memory <nl> + / / to work with CNTK ' s GPU memory <nl> void setdevice ( size_t DeviceId ) ; <nl> size_t getdevice ( ) ; <nl> void release ( bool cpumode ) ; <nl> class archive <nl> std : : unordered_map < std : : wstring , latticeref > toc ; / / [ key ] - > ( file , offset ) - - table of content ( . toc file ) <nl> public : <nl> / / construct = open the archive <nl> - / / archive ( ) : currentarchiveindex ( SIZE_MAX ) { } <nl> + / / archive ( ) : currentarchiveindex ( SIZE_MAX ) { } <nl> void setverbosity ( int veb ) const <nl> { <nl> verbosity = veb ; <nl> mmm a / Source / Common / Include / latticestorage . h <nl> ppp b / Source / Common / Include / latticestorage . h <nl> static void checkoverflow ( size_t fieldval , size_t targetval , const char * fieldna <nl> <nl> struct nodeinfo <nl> { <nl> - / / uint64_t firstinedge : 24 ; / / index of first incoming edge <nl> - / / uint64_t firstoutedge : 24 ; / / index of first outgoing edge <nl> - / / uint64_t t : 16 ; / / time associated with this <nl> + / / uint64_t firstinedge : 24 ; / / index of first incoming edge <nl> + / / uint64_t firstoutedge : 24 ; / / index of first outgoing edge <nl> + / / uint64_t t : 16 ; / / time associated with this <nl> unsigned short t ; / / time associated with this <nl> nodeinfo ( size_t pt ) <nl> - : t ( ( unsigned short ) pt ) / / , firstinedge ( NOEDGE ) , firstoutedge ( NOEDGE ) <nl> + : t ( ( unsigned short ) pt ) / / , firstinedge ( NOEDGE ) , firstoutedge ( NOEDGE ) <nl> { <nl> checkoverflow ( t , pt , " nodeinfo : : t " ) ; <nl> - / / checkoverflow ( firstinedge , NOEDGE , " nodeinfo : : firstinedge " ) ; <nl> - / / checkoverflow ( firstoutedge , NOEDGE , " nodeinfo : : firstoutedge " ) ; <nl> + / / checkoverflow ( firstinedge , NOEDGE , " nodeinfo : : firstinedge " ) ; <nl> + / / checkoverflow ( firstoutedge , NOEDGE , " nodeinfo : : firstoutedge " ) ; <nl> } <nl> nodeinfo ( ) / / [ v - hansu ] initialize to impossible values <nl> { <nl> mmm a / Source / Common / Include / simplesenonehmm . h <nl> ppp b / Source / Common / Include / simplesenonehmm . h <nl> class simplesenonehmm <nl> std : : vector < int > senoneid2transPindex ; / / or - 1 if ambiguous <nl> std : : vector < int > senoneid2stateindex ; / / 0 . . 2 , or - 1 if ambiguous <nl> <nl> - / / zhaorui load from file , add a null construct function <nl> + / / zhaorui load from file , add a null construct function <nl> simplesenonehmm ( ) <nl> { <nl> } <nl> mmm a / Source / Common / Include / ssefloat4 . h <nl> ppp b / Source / Common / Include / ssefloat4 . h <nl> class float4 <nl> : v ( _mm_load1_ps ( & f ) ) <nl> { <nl> } <nl> - / / float4 ( float f ) : v ( _mm_set_ss ( f ) ) { } / / code seems more complex than _mm_load1_ps ( ) <nl> + / / float4 ( float f ) : v ( _mm_set_ss ( f ) ) { } / / code seems more complex than _mm_load1_ps ( ) <nl> <nl> / / basic math <nl> float4 operator - ( ) const <nl> class float4 <nl> / / save a float4 to RAM bypassing the cache ( ' without polluting the cache ' ) <nl> void storewithoutcache ( float4 & r4 ) const <nl> { <nl> - / / _mm_stream_ps ( ( float * ) & r4 , v ) ; <nl> + / / _mm_stream_ps ( ( float * ) & r4 , v ) ; <nl> r4 = v ; <nl> } <nl> <nl> class float4 <nl> / / save a float4 to RAM bypassing the cache ( ' without polluting the cache ' ) <nl> void storewithoutcache ( float4 * p4 ) const <nl> { <nl> - / / _mm_stream_ps ( ( float * ) p4 , v ) ; <nl> + / / _mm_stream_ps ( ( float * ) p4 , v ) ; <nl> * p4 = v ; <nl> } <nl> <nl> mmm a / Source / Common / Include / ssematrix . h <nl> ppp b / Source / Common / Include / ssematrix . h <nl> class ssematrixbase <nl> <nl> / / operations - - add as we go <nl> <nl> - / / both m1 and m2 are passed in normal form ( i . e . , not transposed ) <nl> + / / both m1 and m2 are passed in normal form ( i . e . , not transposed ) <nl> void KhatriRaoProduct ( const ssematrixbase & m1 , const ssematrixbase & m2 ) <nl> { <nl> auto & us = * this ; <nl> class ssematrixbase <nl> <nl> if ( isehtransposed ) <nl> { <nl> - / / find nrows and ncols of the reshpaed eh <nl> + / / find nrows and ncols of the reshpaed eh <nl> size_t nrows = h . rows ( ) ; <nl> size_t ncols = eh . rows ( ) / nrows ; <nl> assert ( eh . rows ( ) % nrows = = 0 ) ; <nl> class ssematrixbase <nl> / / dot - product of vectors in matrix format ( matrix type , but only one column ) <nl> float dotprod ( const ssematrixbase & other ) const <nl> { <nl> - / / assert ( other . cols ( ) = = 1 ) ; <nl> - / / assert ( cols ( ) = = 1 ) ; <nl> + / / assert ( other . cols ( ) = = 1 ) ; <nl> + / / assert ( cols ( ) = = 1 ) ; <nl> assert ( rows ( ) = = other . rows ( ) ) ; <nl> assert ( cols ( ) = = other . cols ( ) ) ; <nl> float result = 0 . 0f ; <nl> class ssematrixbase <nl> assert ( ( 15 & reinterpret_cast < uintptr_t > ( & row [ 0 ] ) ) = = 0 ) ; <nl> assert ( ( 15 & reinterpret_cast < uintptr_t > ( & cols4 [ 0 ] ) ) = = 0 ) ; <nl> assert ( ( 15 & reinterpret_cast < uintptr_t > ( & cols4 [ cols4stride ] ) ) = = 0 ) ; <nl> - / / assert ( cols4stride * 4 = = cols4 . size ( ) ) ; / / ( passed in one vector with 4 columns stacked on top of each other ) <nl> - / / assert ( row . size ( ) * 4 = = cols4 . size ( ) ) ; / / this assert is no longer appropriate because of further breaking into blocks <nl> + / / assert ( cols4stride * 4 = = cols4 . size ( ) ) ; / / ( passed in one vector with 4 columns stacked on top of each other ) <nl> + / / assert ( row . size ( ) * 4 = = cols4 . size ( ) ) ; / / this assert is no longer appropriate because of further breaking into blocks <nl> <nl> / / perform multiple columns in parallel <nl> const size_t nlong = ( row . size ( ) + 3 ) / 4 ; / / number of SSE elements <nl> class ssematrixbase <nl> acc3 + = prow [ m ] * pcol3 [ m ] ; <nl> } <nl> # else <nl> - const size_t prefetch = 1 ; / / 128 / sizeof ( acc0 ) ; <nl> + const size_t prefetch = 1 ; / / 128 / sizeof ( acc0 ) ; <nl> size_t m ; <nl> for ( m = 1 ; m < nlong - prefetch ; m + + ) <nl> { <nl> class ssematrixbase <nl> / / is loaded once into cache . Each row of M is loaded into cache once per stripe of V , <nl> / / in the example every 195 columns . <nl> const size_t cacheablerowsV = 512 ; / / at most <nl> - const size_t cacheablecolsV = 16 ; / / V . cacheablecols ( ) ; / / don ' t get more than this of V per row of M <nl> + const size_t cacheablecolsV = 16 ; / / V . cacheablecols ( ) ; / / don ' t get more than this of V per row of M <nl> / / 512 * 16 - > 32 KB <nl> <nl> const size_t colstripewV = cacheablecolsV ; / / width of col stripe of V <nl> class ssematrixbase <nl> { <nl> const size_t k1 = std : : min ( k0 + dotprodstep , V . rows ( ) ) ; <nl> const bool first = k0 = = 0 ; <nl> - / / const bool last = k0 + dotprodstep > = V . rows ( ) ; <nl> + / / const bool last = k0 + dotprodstep > = V . rows ( ) ; <nl> <nl> / / loop over requested rows [ beginrow , endrow ) of result ( = rows of M ( = cols of Mt ) ) <nl> for ( size_t i = i0 ; i < i1 ; i + + ) / / remember that cols of Mt are the rows of M <nl> class ssematrixbase <nl> array_ref < float > usij ( & us ( i , j ) , 4 * us . colstride - i + 1 ) ; <nl> array_ref < float > patchij ( & patch ( i - i0 , j - j0 ) , 4 * patch . colstride - ( i - i0 ) + 1 ) ; <nl> <nl> - / / dotprod4 ( row , cols4 , V . colstride , usij , us . colstride ) ; <nl> + / / dotprod4 ( row , cols4 , V . colstride , usij , us . colstride ) ; <nl> if ( first ) <nl> dotprod4 ( row , cols4 , V . colstride , patchij , patch . colstride ) ; <nl> else <nl> class ssematrixbase <nl> / / dotprod ( Mt . col ( i ) , V . col ( j + 3 ) , us ( i , j + 3 ) ) ; <nl> } <nl> for ( size_t j = j14 ; j < j1 ; j + + ) / / remainder not grouped <nl> - / / dotprod ( Mt . col ( i ) , V . col ( j ) , us ( i , j ) ) ; <nl> + / / dotprod ( Mt . col ( i ) , V . col ( j ) , us ( i , j ) ) ; <nl> if ( first ) / / do it in one big step ignoring the cache issue <nl> dotprod ( Mt . col ( i ) , V . col ( j ) , patch ( i - i0 , j - j0 ) ) ; <nl> } <nl> class ssematrixbase <nl> assert ( us . rows ( ) = = A . rows ( ) ) ; <nl> assert ( us . cols ( ) = = Bt . rows ( ) ) ; / / Bt . rows ( ) = = B . cols ( ) <nl> assert ( A . cols ( ) = = Bt . cols ( ) ) ; / / Bt . cols ( ) = = B . rows ( ) <nl> - / / fprintf ( stderr , " 0x % x ( % d , % d ) x 0x % x ( % d , % d ) ' - > 0x % x ( % d , % d ) \ n " , A . p , A . rows ( ) , A . cols ( ) , Bt . p , Bt . rows ( ) , Bt . cols ( ) , us . p , us . rows ( ) , us . cols ( ) ) ; <nl> + / / fprintf ( stderr , " 0x % x ( % d , % d ) x 0x % x ( % d , % d ) ' - > 0x % x ( % d , % d ) \ n " , A . p , A . rows ( ) , A . cols ( ) , Bt . p , Bt . rows ( ) , Bt . cols ( ) , us . p , us . rows ( ) , us . cols ( ) ) ; <nl> <nl> foreach_coord ( i , j , us ) <nl> { <nl> class ssematrixbase <nl> assert ( us . cols ( ) = = V . cols ( ) ) ; <nl> assert ( i0 < i1 & & i1 < = Mt . cols ( ) ) ; / / remember that cols of Mt are the rows of M <nl> <nl> - / / for ( size_t i = 0 ; i < Mt . cols ( ) ; i + + ) / / remember that cols of Mt are the rows of M <nl> + / / for ( size_t i = 0 ; i < Mt . cols ( ) ; i + + ) / / remember that cols of Mt are the rows of M <nl> for ( size_t i = i0 ; i < i1 ; i + + ) / / remember that cols of Mt are the rows of M <nl> { <nl> size_t j0 = V . cols ( ) & ~ 3 ; <nl> class ssematrix : public ssematrixbase <nl> return ; / / no resize needed <nl> const size_t newcolstride = ( n + 3 ) & ~ 3 ; / / pad to multiples of four floats ( required SSE alignment ) <nl> const size_t totalelem = newcolstride * m ; <nl> - / / fprintf ( stderr , " resize ( % d , % d ) allocating % d elements \ n " , n , m , totalelem ) ; <nl> + / / fprintf ( stderr , " resize ( % d , % d ) allocating % d elements \ n " , n , m , totalelem ) ; <nl> float * pnew = totalelem > 0 ? new_sse < float > ( totalelem ) : NULL ; <nl> std : : swap ( this - > p , pnew ) ; <nl> delete_sse ( pnew ) ; / / pnew is now the old p <nl> class ssematrix : public ssematrixbase <nl> this - > colstride = newcolstride ; <nl> / / touch the memory to ensure the page is created <nl> for ( size_t offset = 0 ; offset < totalelem ; offset + = 4096 / sizeof ( float ) ) <nl> - this - > p [ offset ] = 0 . 0f ; / / nan ; <nl> + this - > p [ offset ] = 0 . 0f ; / / nan ; <nl> / / clear padding elements ( numrows < = i < colstride ) to 0 . 0 for SSE optimization <nl> for ( size_t j = 0 ; j < this - > numcols ; j + + ) <nl> for ( size_t i = this - > numrows ; i < this - > colstride ; i + + ) <nl> std : : pair < unsigned int , unsigned int > printmatvaluedistributionf ( const char * nam <nl> unsigned int numzeros = 0 ; <nl> foreach_coord ( i , j , m ) <nl> { <nl> - vals [ k ] = abs ( m ( i , j ) ) ; / / this is slower than memcpy but without assumption on how values are stored . <nl> + vals [ k ] = abs ( m ( i , j ) ) ; / / this is slower than memcpy but without assumption on how values are stored . <nl> numzeros + = ( vals [ k + + ] < 1e - 10f ) ; <nl> } <nl> <nl> mmm a / Source / Common / fileutil . cpp <nl> ppp b / Source / Common / fileutil . cpp <nl> bool funicode ( FILE * f ) <nl> ( int ) testCode = = 0xFEFF ) <nl> return true ; <nl> fseek ( f , 0 , SEEK_SET ) ; <nl> - / / rewind ( f ) ; <nl> + / / rewind ( f ) ; <nl> return false ; <nl> } <nl> <nl> wstring fgetwstring ( FILE * f ) <nl> wstring res ; <nl> for ( ; ; ) <nl> { <nl> - / / <nl> + / / <nl> / / there is a known vc + + runtime bug : Microsoft Connect 768113 <nl> / / fgetwc can skip a byte in certain condition <nl> / / this is already fixed in update release to VS 2012 <nl> / / for now the workaround is to use fgetc twice to simulate fgetwc <nl> - / / <nl> - / / wint_t c = fgetwc ( f ) ; <nl> + / / <nl> + / / wint_t c = fgetwc ( f ) ; <nl> int c1 = fgetc ( f ) ; <nl> int c2 = fgetc ( f ) ; <nl> <nl> void fgetwav ( FILE * f , std : : vector < short > & wav , int & sampleRate ) <nl> } <nl> else if ( wavhd . nChannels = = 2 ) <nl> { <nl> - / / read raw data <nl> + / / read raw data <nl> std : : vector < short > buf ; <nl> buf . resize ( numSamples * 2 ) ; <nl> fgetwavraw ( f , buf , wavhd ) ; <nl> <nl> - / / map to mono <nl> + / / map to mono <nl> wav . resize ( numSamples ) ; <nl> const short * p = & buf [ 0 ] ; <nl> for ( int i = 0 ; i < ( int ) numSamples ; i + + ) <nl> void fputwav ( FILE * f , const vector < short > & wav , int sampleRate , int nChannels <nl> f ; wav ; sampleRate ; nChannels ; <nl> / / construct WAVEFORMATEX <nl> WAVEFORMATEX wfx ; <nl> - wfx . cbSize = 16 + 2 ; / / fmt data + extra data <nl> - wfx . nAvgBytesPerSec = ( DWORD ) ( sampleRate * nChannels * 2 ) ; / / short : 2 bytes per sample <nl> - wfx . nBlockAlign = ( WORD ) nChannels * 2 ; / / short : 2bytes per sample <nl> + wfx . cbSize = 16 + 2 ; / / fmt data + extra data <nl> + wfx . nAvgBytesPerSec = ( DWORD ) ( sampleRate * nChannels * 2 ) ; / / short : 2 bytes per sample <nl> + wfx . nBlockAlign = ( WORD ) nChannels * 2 ; / / short : 2bytes per sample <nl> wfx . nChannels = ( WORD ) nChannels ; <nl> wfx . nSamplesPerSec = sampleRate ; <nl> wfx . wBitsPerSample = 16 ; <nl> wfx . wFormatTag = WAVE_FORMAT_PCM ; <nl> - / / putwfx <nl> + / / putwfx <nl> fputwfx ( f , wfx , ( unsigned int ) wav . size ( ) ) ; <nl> / / wrtie the data <nl> fwriteOrDie ( & wav [ 0 ] , sizeof ( wav [ 0 ] ) , wav . size ( ) , f ) ; <nl> static BOOL ExpandWildcards ( wstring path , vector < wstring > & paths ) <nl> path . erase ( last ) ; <nl> <nl> / / convert root to long filename convention <nl> - / / if ( path . find ( L " \ \ \ \ ? \ \ " ) ! = 0 ) <nl> + / / if ( path . find ( L " \ \ \ \ ? \ \ " ) ! = 0 ) <nl> / / path = L " \ \ \ \ ? \ \ " + root ; <nl> <nl> / / split off everything after first wildcard <nl> static inline std : : wstring mbstowcs ( const std : : string & p ) / / input : MBCS <nl> size_t len = p . length ( ) ; <nl> vector < wchar_t > buf ( len + 1 ) ; / / max : > 1 mb chars = > 1 wchar <nl> fill ( buf . begin ( ) , buf . end ( ) , ( wchar_t ) 0 ) ; <nl> - / / OACR_WARNING_SUPPRESS ( UNSAFE_STRING_FUNCTION , " Reviewed OK . size checked . [ rogeryu 2006 / 03 / 21 ] " ) ; <nl> + / / OACR_WARNING_SUPPRESS ( UNSAFE_STRING_FUNCTION , " Reviewed OK . size checked . [ rogeryu 2006 / 03 / 21 ] " ) ; <nl> : : mbstowcs ( & buf [ 0 ] , p . c_str ( ) , len + 1 ) ; <nl> return std : : wstring ( & buf [ 0 ] ) ; <nl> } <nl> mmm a / Source / ComputationNetworkLib / ComputationNetwork . cpp <nl> ppp b / Source / ComputationNetworkLib / ComputationNetwork . cpp <nl> void ComputationNetwork : : SaveToFileImpl ( const wstring & fileName , const FileOptio <nl> File fstream ( fileName , fileFormat | FileOptions : : fileOptionsWrite ) ; <nl> fstream . PutMarker ( FileMarker : : fileMarkerBeginSection , L " BCN " ) ; <nl> <nl> - / / model version <nl> + / / model version <nl> fstream . PutMarker ( FileMarker : : fileMarkerBeginSection , L " BVersion " ) ; <nl> fstream < < ( size_t ) CURRENT_CNTK_MODEL_VERSION ; <nl> fstream . PutMarker ( FileMarker : : fileMarkerEndSection , L " EVersion " ) ; <nl> <nl> fstream < < ( size_t ) m_nameToNodeMap . size ( ) ; <nl> <nl> - / / put all node info first <nl> + / / put all node info first <nl> fstream . PutMarker ( FileMarker : : fileMarkerBeginSection , L " BNodeList " ) ; <nl> for ( auto nodeIter = m_nameToNodeMap . begin ( ) ; nodeIter ! = m_nameToNodeMap . end ( ) ; nodeIter + + ) <nl> { <nl> void ComputationNetwork : : SaveToFileImpl ( const wstring & fileName , const FileOptio <nl> <nl> fstream . PutMarker ( FileMarker : : fileMarkerEndSection , L " ENodeList " ) ; <nl> <nl> - / / put relationship <nl> + / / put relationship <nl> fstream . PutMarker ( FileMarker : : fileMarkerBeginSection , L " BRelation " ) ; <nl> for ( auto nodeIter = m_nameToNodeMap . begin ( ) ; nodeIter ! = m_nameToNodeMap . end ( ) ; nodeIter + + ) <nl> { <nl> void ComputationNetwork : : Read ( const wstring & fileName , const FileOptions fileFor <nl> <nl> if ( ! fstream . TryGetMarker ( FileMarker : : fileMarkerEndSection , L " ECriteriaNodes " / * legacy * / ) ) <nl> { <nl> - fstream . GetMarker ( FileMarker : : fileMarkerEndSection , L " ECriterionNodes " ) ; / / check legacy first so err msg will use new name <nl> + fstream . GetMarker ( FileMarker : : fileMarkerEndSection , L " ECriterionNodes " ) ; / / check legacy first so err msg will use new name <nl> } <nl> } <nl> <nl> bool ComputationNetwork : : UnitTest ( bool allowFragment ) <nl> { <nl> if ( ! allowFragment ) <nl> FormRecurrentLoops ( node ) ; <nl> - / / this - > SetActualMiniBatchSizeFromFeatures ( ) ; <nl> + / / this - > SetActualMiniBatchSizeFromFeatures ( ) ; <nl> if ( ! UnitTest ( node ) ) <nl> vErrors . push_back ( node - > NodeName ( ) . c_str ( ) ) ; <nl> } <nl> void ComputationNetwork : : DescribeNetworkUsingDot ( list < ComputationArc > & arcs , <nl> fstream < < " strict digraph { \ n " ; <nl> fstream < < " rankdir = BT ; \ n " ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / special nodes <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> fstream < < L " / / special nodes \ n " ; <nl> <nl> / / learnable parameters : <nl> void ComputationNetwork : : DescribeNetworkUsingDot ( list < ComputationArc > & arcs , <nl> / / normal nodes <nl> fstream < < dotcfg . m_normalNodeStyle < < L " \ n " ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / add labels for each node <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> fstream < < L " \ n / / add labels and operation name \ n " ; <nl> wstring line ; <nl> for ( const auto & x : allnodes ) <nl> void ComputationNetwork : : DescribeNetworkUsingDot ( list < ComputationArc > & arcs , <nl> fstream < < line ; <nl> } <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / sub - graph <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / subgraph source <nl> fstream < < L " subgraph { \ n " ; <nl> fstream < < L " \ t \ t rank = source ; " ; <nl> void ComputationNetwork : : DescribeNetworkUsingDot ( list < ComputationArc > & arcs , <nl> <nl> fstream < < line < < L " \ n } \ n " ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / specify arc connections <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> for ( auto x = arcs . begin ( ) ; x ! = arcs . end ( ) ; x + + ) <nl> { <nl> ComputationNodeBasePtr src = ( * x ) . first ; <nl> void ComputationNetwork : : DescribeNetworkUsingDot ( list < ComputationArc > & arcs , <nl> void ComputationNetwork : : PlotNetworkTopology ( const wstring outputFile ) / / [ 1 / 13 / 2015 erw ] plot network topology using dot language <nl> { <nl> VerifyIsCompiled ( " PlotNetworkTopology " ) ; <nl> - / / ValidateNetwork ( false , true ) ; <nl> + / / ValidateNetwork ( false , true ) ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / step 1 . get all the arcs in the network <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> unordered_set < ComputationNodeBasePtr > visited ; <nl> list < ComputationArc > arcs ; <nl> <nl> void ComputationNetwork : : PlotNetworkTopology ( const wstring outputFile ) / / [ 1 / 13 <nl> group [ i ] - > EnumerateArcs ( visited , arcs ) ; <nl> } <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / step 2 . output dot description <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> DescribeNetworkUsingDot ( arcs , outputFile ) ; <nl> } <nl> <nl> mmm a / Source / ComputationNetworkLib / ComputationNetwork . h <nl> ppp b / Source / ComputationNetworkLib / ComputationNetwork . h <nl> class ComputationNetwork : public ScriptableObjects : : Object , public ScriptableOb <nl> <nl> void CompileNetwork ( ) ; / / call this after creation , Load ( ) , and any modification <nl> <nl> - / / void ValidateNetwork ( bool allowFragment = false , const bool bAllowNoCriterion = false ) ; <nl> + / / void ValidateNetwork ( bool allowFragment = false , const bool bAllowNoCriterion = false ) ; <nl> / / prepares the network for computation <nl> - / / void BuildAndValidateSubNetwork ( const ComputationNodeBasePtr rootNode ) ; <nl> + / / void BuildAndValidateSubNetwork ( const ComputationNodeBasePtr rootNode ) ; <nl> private : <nl> void ValidateNodes ( list < ComputationNodeBasePtr > nodes , bool isFinalValidationPass , size_t & todo ) ; <nl> void ValidateSubNetwork ( const ComputationNodeBasePtr & rootNode ) ; <nl> class ComputationNetwork : public ScriptableObjects : : Object , public ScriptableOb <nl> return m_isCompiled ; <nl> } <nl> void VerifyIsCompiled ( const char * where ) const ; <nl> - / / bool BuiltAndValidatedSubNetwork ( const ComputationNodeBasePtr & rootNode ) ; <nl> + / / bool BuiltAndValidatedSubNetwork ( const ComputationNodeBasePtr & rootNode ) ; <nl> public : <nl> void AllocateAllMatrices ( const std : : vector < ComputationNodeBasePtr > & evalRootNodes , const std : : vector < ComputationNodeBasePtr > & outValueRootNodes , ComputationNodeBasePtr trainRootNode ) ; <nl> <nl> class ComputationNetwork : public ScriptableObjects : : Object , public ScriptableOb <nl> auto iter = m_nameToNodeMap . find ( name ) ; <nl> if ( iter ! = m_nameToNodeMap . end ( ) ) <nl> { <nl> - / / found <nl> + / / found <nl> return iter - > second ; <nl> } <nl> <nl> class ComputationNetwork : public ScriptableObjects : : Object , public ScriptableOb <nl> { <nl> std : : list < ComputationNodeBasePtr > nodesWithType ; <nl> <nl> - / / find nodes from all available nodes <nl> + / / find nodes from all available nodes <nl> if ( rootNode = = nullptr ) <nl> { <nl> for ( auto nodeIter = m_nameToNodeMap . begin ( ) ; nodeIter ! = m_nameToNodeMap . end ( ) ; nodeIter + + ) <nl> class ComputationNetwork : public ScriptableObjects : : Object , public ScriptableOb <nl> } <nl> else <nl> { <nl> - / / for calculating a specific node <nl> + / / for calculating a specific node <nl> const std : : list < ComputationNodeBasePtr > & nodes = GetEvalOrder ( rootNode ) ; <nl> for ( auto nodeIter = nodes . begin ( ) ; nodeIter ! = nodes . end ( ) ; nodeIter + + ) <nl> { <nl> class ComputationNetwork : public ScriptableObjects : : Object , public ScriptableOb <nl> template < class ElemType > <nl> void GetHistory ( map < wstring , Matrix < ElemType > > & history , bool bLastTime = false ) <nl> { <nl> - / / put all node info first <nl> + / / put all node info first <nl> Matrix < ElemType > hist ; <nl> for ( auto nodeIter = m_nameToNodeMap . begin ( ) ; nodeIter ! = m_nameToNodeMap . end ( ) ; nodeIter + + ) <nl> { <nl> class ComputationNetwork : public ScriptableObjects : : Object , public ScriptableOb <nl> template < class ElemType > <nl> void SetHistory ( map < wstring , Matrix < ElemType > > & history ) <nl> { <nl> - / / put all node info first <nl> + / / put all node info first <nl> for ( auto nodeIter = m_nameToNodeMap . begin ( ) ; nodeIter ! = m_nameToNodeMap . end ( ) ; nodeIter + + ) <nl> { <nl> shared_ptr < ComputationNode < ElemType > > nodePtr = dynamic_pointer_cast < ComputationNode < ElemType > > ( nodeIter - > second ) ; <nl> class ComputationNetwork : public ScriptableObjects : : Object , public ScriptableOb <nl> { <nl> nodePtr - > AttachInputs ( std : : forward < _Types > ( _Args ) . . . ) ; <nl> return AddNodeToNetWithElemType ( nodePtr ) ; <nl> - / / return nodePtr ; / / allows e . g . return AddNodeToNetAndAttachInputs ( New . . . , inputs ) ; <nl> + / / return nodePtr ; / / allows e . g . return AddNodeToNetAndAttachInputs ( New . . . , inputs ) ; <nl> } <nl> <nl> public : <nl> class ComputationNetwork : public ScriptableObjects : : Object , public ScriptableOb <nl> const ComputationNodeBasePtr & nodePtr = GetNodeFromName ( nodeName ) ; <nl> nodePtr - > DumpNodeInfo ( printValues , fstream ) ; <nl> } <nl> - else / / node name is not found , dump all nodes <nl> + else / / node name is not found , dump all nodes <nl> { <nl> fprintf ( stderr , " Warning : node name % ls does not exist in the network . dumping all nodes . \ n " , <nl> nodeName . c_str ( ) ) ; <nl> class ComputationNetwork : public ScriptableObjects : : Object , public ScriptableOb <nl> <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> / / SEQTraversalFlowControlNode - - FlowControlNode to traverse a ( sub - ) network time step by time step <nl> - / / <nl> + / / <nl> / / This is to implement recurrent loops . All nodes inside a loop are listed <nl> / / inside this node . This node ' s ForwardProp ( ) function will execute <nl> / / them inside a loop over all time steps of the recurrence . <nl> class ComputationNetwork : public ScriptableObjects : : Object , public ScriptableOb <nl> virtual bool IsOutputOlderThanInputs ( ) const override ; <nl> <nl> public : <nl> - / / std : : vector < ComputationNodeBasePtr > m_nestedNodes ; / / all nodes involved in this loop , in evaluation order <nl> + / / std : : vector < ComputationNodeBasePtr > m_nestedNodes ; / / all nodes involved in this loop , in evaluation order <nl> ComputationNodeBasePtr m_sourceNode ; / / one of the nodes of the loop - - TODO : What is the special meaning of this node ? It seems to always be a delay node . <nl> int m_loopId ; / / unique loop id , index in m_allSEQNodes array <nl> int m_steppingDirection ; / / + 1 if left to right ( t = 0 . . T - 1 ) , - 1 if rightt to left ( t = T - 1 . . 0 ) <nl> class ComputationNetwork : public ScriptableObjects : : Object , public ScriptableOb <nl> <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> / / PARTraversalFlowControlNode - - FlowControlNode that traverses a ( sub - ) network <nl> - / / <nl> + / / <nl> / / This node contains a list of nodes in a ( sub - ) network . This node ' s <nl> / / ForwardProp ( ) method will execute all those nodes once in PAR mode , <nl> / / that is , by passing a FrameRange object that represents to operate <nl> / / on all frames in the node simultaneously . <nl> - / / <nl> + / / <nl> / / The outermost network level is also represented by this node for execution . <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> <nl> mmm a / Source / ComputationNetworkLib / ComputationNetworkAnalysis . cpp <nl> ppp b / Source / ComputationNetworkLib / ComputationNetworkAnalysis . cpp <nl> void ComputationNetwork : : FormRecurrentLoops ( const ComputationNodeBasePtr & rootNo <nl> { <nl> if ( node - > Input ( i ) - > m_loopId = = node - > m_loopId & & GetRecurrenceSteppingDirection ( node ) = = 0 ) <nl> { <nl> - / / assert ( node - > Input ( i ) - > m_indexInLoop = = 0 ) ; / / No . It seems this variable really counts the number of parents . <nl> + / / assert ( node - > Input ( i ) - > m_indexInLoop = = 0 ) ; / / No . It seems this variable really counts the number of parents . <nl> node - > Input ( i ) - > m_indexInLoop + + ; / / BUGBUG : this is bumping up the m_indexInLoop , but I don ' t think it is initialized anywhere other than PurgeStateForFormingRecurrentLoops ( ) . i - 1 ? <nl> } <nl> } <nl> mmm a / Source / ComputationNetworkLib / ComputationNetworkBuilder . h <nl> ppp b / Source / ComputationNetworkLib / ComputationNetworkBuilder . h <nl> class ComputationNetworkBuilder <nl> <nl> ComputationNodePtr CreateLearnableParameter ( const std : : wstring & paramName , const size_t rows , const size_t cols ) ; <nl> ComputationNodePtr CreateLearnableParameter ( const std : : wstring & paramName , const TensorShape & tensorShape ) ; <nl> - / / sparse matrix size is optionally specified <nl> - / / ComputationNodePtr CreateSparseLearnableParameter ( const std : : wstring & paramName , const size_t rows , const size_t cols , const size_t size = 0 ) ; <nl> + / / sparse matrix size is optionally specified <nl> + / / ComputationNodePtr CreateSparseLearnableParameter ( const std : : wstring & paramName , const size_t rows , const size_t cols , const size_t size = 0 ) ; <nl> ComputationNodePtr CreateInputNode ( const std : : wstring & inputName , const size_t rows ) ; <nl> ComputationNodePtr CreateSparseInputNode ( const std : : wstring & inputName , const size_t rows ) ; <nl> ComputationNodePtr CreateInputNode ( const std : : wstring & inputName , const TensorShape & sampleLayout ) ; <nl> mmm a / Source / ComputationNetworkLib / ComputationNetworkEditing . cpp <nl> ppp b / Source / ComputationNetworkLib / ComputationNetworkEditing . cpp <nl> void ComputationNetwork : : RenameNode ( const std : : wstring & nodeNameOrig , const std : <nl> ComputationNodeBasePtr nodeToRename = GetNodeFromName ( nodeNameOrig ) ; <nl> <nl> auto iter = m_nameToNodeMap . find ( nodeNameNew ) ; <nl> - if ( iter ! = m_nameToNodeMap . end ( ) ) / / found <nl> + if ( iter ! = m_nameToNodeMap . end ( ) ) / / found <nl> RuntimeError ( " RenameNode : Target name already exists . " ) ; <nl> <nl> - / / rename the node and update the mapping table <nl> + / / rename the node and update the mapping table <nl> nodeToRename - > SetNodeName ( nodeNameNew ) ; <nl> m_nameToNodeMap . erase ( nodeNameOrig ) ; <nl> m_nameToNodeMap [ nodeNameNew ] = nodeToRename ; <nl> void ComputationNetwork : : DeleteNode ( const std : : wstring & nodeName ) <nl> <nl> ComputationNodeBasePtr nodeToDelete = GetNodeFromName ( nodeName ) ; <nl> <nl> - / / first delete links , if this node is involved , the whole connection will be removed <nl> + / / first delete links , if this node is involved , the whole connection will be removed <nl> for ( auto nodeIter = m_nameToNodeMap . begin ( ) ; nodeIter ! = m_nameToNodeMap . end ( ) ; nodeIter + + ) <nl> { <nl> ComputationNodeBasePtr node = nodeIter - > second ; <nl> void ComputationNetwork : : DeleteNode ( const std : : wstring & nodeName ) <nl> { <nl> ComputationNodeBasePtr child = node - > GetInputs ( ) [ i ] ; <nl> <nl> - / / nodeToDelete is a child <nl> + / / nodeToDelete is a child <nl> if ( child = = nodeToDelete ) <nl> { <nl> / / this used to call DetatchInputs ( ) , but it ' s better for MEL to retain other inputs <nl> void ComputationNetwork : : DeleteNode ( const std : : wstring & nodeName ) <nl> <nl> / / Note : the necessary update of m_allSEQNodes is hanlded by the InvalidateCompiledNetwork ( ) call above <nl> <nl> - / / delete the node itself <nl> + / / delete the node itself <nl> m_nameToNodeMap . erase ( nodeName ) ; / / this will deref the node and possibly deallocate it <nl> } <nl> <nl> void ComputationNetwork : : ChangeNode ( wstring nodeName , ComputationNodeBasePtr new <nl> if ( oldNode - > OperationName ( ) ! = newNode - > OperationName ( ) ) <nl> InvalidArgument ( " newNode must have the same type as the old node . " ) ; <nl> <nl> - / / change children <nl> + / / change children <nl> for ( auto nodeIter = m_nameToNodeMap . begin ( ) ; nodeIter ! = m_nameToNodeMap . end ( ) ; nodeIter + + ) <nl> { <nl> ComputationNodeBasePtr node = nodeIter - > second ; <nl> void ComputationNetwork : : ChangeNode ( wstring nodeName , ComputationNodeBasePtr new <nl> node - > SetInput ( i , newNode ) ; <nl> } <nl> <nl> - / / change name map <nl> + / / change name map <nl> m_nameToNodeMap [ nodeName ] = newNode ; <nl> for ( int i = 0 ; i < oldNode - > GetNumInputs ( ) ; i + + ) <nl> newNode - > SetInput ( i , oldNode - > GetInputs ( ) [ i ] ) ; <nl> <nl> - / / change other maps <nl> + / / change other maps <nl> for ( auto groupIter : GetAllNodeGroups ( ) ) <nl> { <nl> auto & group = * groupIter ; <nl> void ComputationNetwork : : ReplaceLeafNode ( wstring oldNodeName , ComputationNodeBas <nl> <nl> / / now the old node becomes a orphan node , remove it <nl> DeleteNode ( oldNodeName ) ; <nl> - / / RemoveOrphanNode ( oldNode ) ; <nl> + / / RemoveOrphanNode ( oldNode ) ; <nl> } <nl> <nl> void ComputationNetwork : : ReplaceFinalCriterionNode ( wstring oldNodeName , ComputationNodeBasePtr newNode ) <nl> mmm a / Source / ComputationNetworkLib / ComputationNetworkEvaluation . cpp <nl> ppp b / Source / ComputationNetworkLib / ComputationNetworkEvaluation . cpp <nl> void ComputationNetwork : : DetermineSetOfAllRoots ( ) <nl> # ifdef _DEBUG <nl> PrintComputationTree ( node , false ) ; <nl> # endif <nl> - / / SetActualMiniBatchSizeFromFeatures ( ) ; <nl> + / / SetActualMiniBatchSizeFromFeatures ( ) ; <nl> ValidateSubNetwork ( node ) ; <nl> } <nl> } <nl> void ComputationNetwork : : ValidateSubNetwork ( const ComputationNodeBasePtr & rootNo <nl> if ( ! nonDefaultNodes . empty ( ) ) <nl> { <nl> fprintf ( stderr , " % d out of % d nodes do not share the minibatch layout with the input data . \ n " , ( int ) nonDefaultNodes . size ( ) , ( int ) nodes . size ( ) ) ; <nl> - / / for ( auto node : nonDefaultNodes ) <nl> + / / for ( auto node : nonDefaultNodes ) <nl> / / fprintf ( stderr , " % ls \ n " , node - > NodeName ( ) . c_str ( ) ) ; <nl> - / / fprintf ( stderr , " \ n \ n " ) ; <nl> + / / fprintf ( stderr , " \ n \ n " ) ; <nl> } <nl> } <nl> <nl> void ComputationNetwork : : AllocateAllMatrices ( const std : : vector < ComputationNodeBa <nl> else <nl> { <nl> nodeIter - > RequestMatricesBeforeForwardProp ( m_matrixPool ) ; <nl> - / / we only release matrices for the children since the root node ' s informatioin will be used and should not be shared <nl> - / / with others <nl> + / / we only release matrices for the children since the root node ' s informatioin will be used and should not be shared <nl> + / / with others <nl> ReleaseMatricesAfterEvalForChildren ( nodeIter , parentCount ) ; <nl> } <nl> } <nl> void ComputationNetwork : : AllocateAllMatrices ( const std : : vector < ComputationNodeBa <nl> { <nl> std : : list < ComputationNodeBasePtr > & backPropNodes = GetEvalOrder ( trainRootNode ) ; <nl> <nl> - / / now , simulate the gradient computation order to determine how to allocate matrices <nl> + / / now , simulate the gradient computation order to determine how to allocate matrices <nl> set < ComputationNodeBasePtr > completedGradient ; <nl> <nl> / / we need to call it here since we always compute gradients for children and root node is not children of other node <nl> mmm a / Source / ComputationNetworkLib / ComputationNode . h <nl> ppp b / Source / ComputationNetworkLib / ComputationNode . h <nl> class TimeStamp <nl> <nl> private : <nl> static atomic_ullong s_timeStampCounter ; <nl> - int64_t m_evalTimeStamp ; / / this is used to reduce unnecessary recomputation when a different node in the model is reevaluated <nl> + int64_t m_evalTimeStamp ; / / this is used to reduce unnecessary recomputation when a different node in the model is reevaluated <nl> } ; <nl> <nl> / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> class ComputationNodeBase : public IComputationNode , <nl> / / dimensions <nl> <nl> / / The value of a node is a tensor in one of two variants : <nl> - / / <nl> + / / <nl> / / - single matrix , vector , tensor <nl> / / - m_sampleLayout contains the shape . Accessed through GetSampleLayout ( ) . <nl> / / - m_pMBLayout is null <nl> class ComputationNodeBase : public IComputationNode , <nl> / / - m_sampleLayout is the tensor shape of the samples <nl> / / - m_pMBLayout defines the number of time steps and parallel sequences ( = " tensor shape " of the minibatch ) <nl> / / Accessed through GetMBLayout ( ) ; test for through HasMBLayout ( ) . <nl> - / / <nl> + / / <nl> / / The values can be accessed in three ways : <nl> - / / <nl> + / / <nl> / / - as a tensor <nl> / / - GetTensorShape ( ) forms the joint tensor that incorporates both m_sampleLayout and , if present , m_pMBLayout <nl> / / - Elementwise tensor operations operate on these . <nl> class ComputationNodeBase : public IComputationNode , <nl> / / - actual object is a 2D tensor without MB Layout <nl> / / - ValueAsMatrix ( ) , GradientAsMatrix ( ) returns tensor as a 2D Matrix object <nl> / / - nodes that do this are : TimesNode , DiagTimesNode , ConvolutionNode , NoiseContrastiveEstimationNode , ClassBasedCrossEntropyWithSoftmaxNode , TransposeNode , DiagonalNode <nl> - / / <nl> + / / <nl> / / How values are stored : <nl> - / / <nl> + / / <nl> / / - minibatch : Matrix of columns , where each column is a sample <nl> / / - tensor : Matrix where column dimension contains all but the first dimension <nl> / / - This only matters for sparse matrices , which cannot easily be Reshaped ( ) . <nl> class ComputationNodeBase : public IComputationNode , <nl> void InferMBLayoutFromInputsForStandardCase ( ) ; <nl> <nl> public : <nl> - bool IsEqualTo ( const ComputationNodeBasePtr & other ) const / / this will be used to determine whehter two nodes are the same <nl> + bool IsEqualTo ( const ComputationNodeBasePtr & other ) const / / this will be used to determine whehter two nodes are the same <nl> { <nl> if ( OperationName ( ) ! = other - > OperationName ( ) | | m_inputs . size ( ) ! = other - > m_inputs . size ( ) ) <nl> return false ; <nl> <nl> - if ( NodeName ( ) = = other - > NodeName ( ) ) / / assume names are unique in the system <nl> + if ( NodeName ( ) = = other - > NodeName ( ) ) / / assume names are unique in the system <nl> return true ; <nl> <nl> - if ( IsLeaf ( ) & & other - > IsLeaf ( ) ) / / since names are not equal otherwise will return above <nl> + if ( IsLeaf ( ) & & other - > IsLeaf ( ) ) / / since names are not equal otherwise will return above <nl> return false ; <nl> <nl> for ( size_t i = 0 ; i < m_inputs . size ( ) ; i + + ) <nl> class ComputationNode : public ComputationNodeBase / / abstract class that cannot <nl> typedef ComputationNodeBase Base ; <nl> <nl> protected : <nl> - / / std containers such as list and map does not support class reference so we need to use pointer <nl> + / / std containers such as list and map does not support class reference so we need to use pointer <nl> typedef shared_ptr < ComputationNode < ElemType > > ComputationNodePtr ; <nl> <nl> public : <nl> class ComputationNode : public ComputationNodeBase / / abstract class that cannot <nl> } <nl> <nl> public : <nl> - / / request matrices needed to do node function value evaluation <nl> + / / request matrices needed to do node function value evaluation <nl> virtual void RequestMatricesBeforeForwardProp ( MatrixPool & matrixPool ) <nl> { <nl> RequestMatrixFromPool ( m_value , matrixPool ) ; <nl> } <nl> <nl> - / / release temp matrices that are only used by forward computation <nl> - / / don ' t release matrices that need to be used in the gradient computation <nl> + / / release temp matrices that are only used by forward computation <nl> + / / don ' t release matrices that need to be used in the gradient computation <nl> virtual void ReleaseMatricesAfterForwardProp ( MatrixPool & matrixPool ) <nl> { <nl> if ( ! IsOutputNeededDuringBackprop ( ) & & ( m_value - > GetMatrixType ( ) ! = SPARSE ) & & isValueSharable ( ) ) <nl> class ComputationNode : public ComputationNodeBase / / abstract class that cannot <nl> } <nl> } <nl> <nl> - / / request matrices that are needed for gradient computation <nl> + / / request matrices that are needed for gradient computation <nl> virtual void RequestMatricesBeforeBackprop ( MatrixPool & matrixPool ) <nl> { <nl> RequestMatrixFromPool ( m_gradient , matrixPool ) ; <nl> } <nl> <nl> - / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> + / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> virtual void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) <nl> { <nl> if ( ! IsLeaf ( ) & & ! RequiresPreCompute ( ) ) <nl> { <nl> - if ( m_gradient ! = nullptr & & m_gradient - > GetMatrixType ( ) ! = SPARSE ) / / since we don ' t have a sparse pool yet <nl> + if ( m_gradient ! = nullptr & & m_gradient - > GetMatrixType ( ) ! = SPARSE ) / / since we don ' t have a sparse pool yet <nl> ReleaseMatrixToPool ( m_gradient , matrixPool ) ; <nl> <nl> / / Release the Value matrix only if the output value is needed during backprop <nl> class ComputationNode : public ComputationNodeBase / / abstract class that cannot <nl> public : <nl> static void MaskMissingColumnsToZero ( Matrix < ElemType > & matrixToBeMasked , const MBLayoutPtr & pMBLayout , const FrameRange & fr ) <nl> { <nl> - / / fprintf ( stderr , " masking column range % d \ n " , ( int ) fr . timeIdxInSeq ) ; <nl> + / / fprintf ( stderr , " masking column range % d \ n " , ( int ) fr . timeIdxInSeq ) ; <nl> MaskMissingColumnsTo ( matrixToBeMasked , pMBLayout , fr , ( ElemType ) 0 ) ; <nl> } <nl> <nl> void / * ComputationNodeBase : : * / MaskMissingValueColumnsToZero ( const FrameRange & fr ) override final <nl> { <nl> - / / fprintf ( stderr , " % ls % ls m_value " , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) ) ; <nl> + / / fprintf ( stderr , " % ls % ls m_value " , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) ) ; <nl> MaskMissingColumnsToZero ( * m_value , m_pMBLayout , fr ) ; <nl> } <nl> void / * ComputationNodeBase : : * / MaskMissingGradientColumnsToZero ( const FrameRange & fr ) override final <nl> { <nl> - / / fprintf ( stderr , " % ls % ls m_gradient " , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) ) ; <nl> + / / fprintf ( stderr , " % ls % ls m_gradient " , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) ) ; <nl> MaskMissingColumnsToZero ( * m_gradient , m_pMBLayout , fr ) ; <nl> } <nl> <nl> / / for debugging , set the gaps to NaN instead ( to track whether it bubbles up somewhere ) <nl> void InvalidateMissingValueColumns ( const FrameRange & fr ) override final <nl> { <nl> - / / fprintf ( stderr , " invalidating % ls % ls m_value column range % d \ n " , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) , ( int ) fr . timeIdxInSeq ) ; <nl> + / / fprintf ( stderr , " invalidating % ls % ls m_value column range % d \ n " , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) , ( int ) fr . timeIdxInSeq ) ; <nl> MaskMissingColumnsTo ( * m_value , m_pMBLayout , fr , Matrix < ElemType > : : MakeNan ( __LINE__ ) ) ; <nl> } <nl> void InvalidateMissingGradientColumns ( const FrameRange & fr ) override final <nl> { <nl> - / / fprintf ( stderr , " invalidating % ls % ls m_gradient column range % d \ n " , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) , ( int ) fr . timeIdxInSeq ) ; <nl> + / / fprintf ( stderr , " invalidating % ls % ls m_gradient column range % d \ n " , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) , ( int ) fr . timeIdxInSeq ) ; <nl> MaskMissingColumnsTo ( * m_gradient , m_pMBLayout , fr , Matrix < ElemType > : : MakeNan ( __LINE__ ) ) ; <nl> } <nl> <nl> class ComputationNode : public ComputationNodeBase / / abstract class that cannot <nl> { <nl> const ComputationNodePtr node = UpCast ( inode ) ; <nl> <nl> - / / require first nodes specified before the second to avoid null nodes condition . <nl> + / / require first nodes specified before the second to avoid null nodes condition . <nl> if ( childIndex > m_inputs . size ( ) ) <nl> InvalidArgument ( " SetInput : You must specify the input for children with index less than this one first . " ) ; <nl> <nl> class ComputationNode : public ComputationNodeBase / / abstract class that cannot <nl> ( childrenInThisLoop & & child - > IsPartOfLoop ( ) = = IsPartOfLoop ( ) | | <nl> childrenInOuterLoop & & child - > IsPartOfLoop ( ) ! = IsPartOfLoop ( ) ) ) <nl> { <nl> - / / fprintf ( stderr , " Backprop : % ls % ls operation - > child % d % ls % ls \ n " , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) , ( int ) i , child - > NodeName ( ) . c_str ( ) , child - > OperationName ( ) . c_str ( ) ) ; <nl> + / / fprintf ( stderr , " Backprop : % ls % ls operation - > child % d % ls % ls \ n " , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) , ( int ) i , child - > NodeName ( ) . c_str ( ) , child - > OperationName ( ) . c_str ( ) ) ; <nl> if ( ! m_needsGradient ) <nl> LogicError ( " % ls % ls operation has m_needsGradient set to false but children require it . " , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) ) ; <nl> # ifdef DISPLAY_DEBUG <nl> class ComputationNode : public ComputationNodeBase / / abstract class that cannot <nl> NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) , child - > NodeName ( ) . c_str ( ) , child - > OperationName ( ) . c_str ( ) ) ; <nl> } <nl> <nl> - / / fprintf ( stderr , " BackpropTo % d % d % ls % ls \ n " , ( int ) fr . timeIdxInSeq , ( int ) i , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) ) ; <nl> + / / fprintf ( stderr , " BackpropTo % d % d % ls % ls \ n " , ( int ) fr . timeIdxInSeq , ( int ) i , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) ) ; <nl> BackpropTo ( i , fr ) ; / / this computes partial wrt to the child and sums the gradient value in the child <nl> } <nl> # ifdef DISPLAY_DEBUG <nl> class ComputationNode : public ComputationNodeBase / / abstract class that cannot <nl> static const Matrix < ElemType > & ConstOnes ( const size_t rows , const size_t cols , const DEVICEID_TYPE deviceId ) <nl> { <nl> if ( s_constOnes . find ( rows ) = = s_constOnes . end ( ) | | <nl> - s_constOnes [ rows ] . find ( cols ) = = s_constOnes [ rows ] . end ( ) ) / / not found <nl> + s_constOnes [ rows ] . find ( cols ) = = s_constOnes [ rows ] . end ( ) ) / / not found <nl> { <nl> Matrix < ElemType > * matrix = new Matrix < ElemType > ( rows , cols , ( DEVICEID_TYPE ) deviceId ) ; <nl> matrix - > SetValue ( 1 ) ; <nl> mmm a / Source / ComputationNetworkLib / ConvolutionalNodes . h <nl> ppp b / Source / ComputationNetworkLib / ConvolutionalNodes . h <nl> class ConvolutionNode : public ComputationNode < ElemType > , public NumInputs < 2 > <nl> / / set up the various engines and descriptor objects <nl> / / REVIEW alexeyk : is there a better place to create engines ? <nl> assert ( m_factory ) ; <nl> - / / if ( m_factory = = nullptr ) <nl> + / / if ( m_factory = = nullptr ) <nl> / / m_factory = ConvolutionEngineFactory < ElemType > : : Create ( m_deviceId , ConvolutionEngineFactory < ElemType > : : EngineType : : Auto , m_imageLayoutKind ) ; <nl> / / TODO : This seems to expose too much internal knowlegde of the engine to the ConvolutionNode ( ) . <nl> / / Why not just pass everything to the engine creator , and get one object that holds everything . <nl> class ConvolutionNode : public ComputationNode < ElemType > , public NumInputs < 2 > <nl> m_maxTempMemSizeInSamples = maxTempMemSizeInSamples ; <nl> } <nl> <nl> - / / request matrices needed to do node function value evaluation <nl> + / / request matrices needed to do node function value evaluation <nl> void RequestMatricesBeforeForwardProp ( MatrixPool & matrixPool ) override <nl> { <nl> Base : : RequestMatricesBeforeForwardProp ( matrixPool ) ; <nl> RequestMatrixFromPool ( m_tempMatrix , matrixPool ) ; <nl> } <nl> <nl> - / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> + / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) override <nl> { <nl> Base : : ReleaseMatricesAfterBackprop ( matrixPool ) ; <nl> class PoolingNodeBase : public ComputationNode < ElemType > , public NumInputs < 1 > <nl> / / set up various engines and descriptor objects <nl> / / REVIEW alexeyk : is there a better place to create engines ? <nl> assert ( m_factory ) ; <nl> - / / if ( m_factory = = nullptr ) <nl> + / / if ( m_factory = = nullptr ) <nl> / / m_factory = ConvolutionEngineFactory < ElemType > : : Create ( m_deviceId , ConvolutionEngineFactory < ElemType > : : EngineType : : Auto , m_imageLayoutKind ) ; <nl> if ( m_poolEng = = nullptr ) <nl> m_poolEng = m_factory - > CreatePoolEngine ( m_deviceId ) ; <nl> mmm a / Source / ComputationNetworkLib / EvaluationNodes . h <nl> ppp b / Source / ComputationNetworkLib / EvaluationNodes . h <nl> class ErrorPredictionNode : public ComputationNodeNonLooping / * ComputationNode * / <nl> * node - > m_maxValues = * m_maxValues ; <nl> } <nl> } <nl> - / / request matrices needed to do node function value evaluation <nl> + / / request matrices needed to do node function value evaluation <nl> virtual void RequestMatricesBeforeForwardProp ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeForwardProp ( matrixPool ) ; <nl> class ErrorPredictionNode : public ComputationNodeNonLooping / * ComputationNode * / <nl> RequestMatrixFromPool ( m_maxValues , matrixPool ) ; <nl> } <nl> <nl> - / / release temp matrices that are only used by forward computation <nl> - / / don ' t release matrices that need to be used in the gradient computation <nl> + / / release temp matrices that are only used by forward computation <nl> + / / don ' t release matrices that need to be used in the gradient computation <nl> virtual void ReleaseMatricesAfterForwardProp ( MatrixPool & matrixPool ) <nl> { <nl> Base : : ReleaseMatricesAfterForwardProp ( matrixPool ) ; <nl> class SequenceDecoderNode : public ComputationNodeNonLooping / * ComputationNode * / <nl> stp = lastLbl ; <nl> } ; <nl> <nl> - virtual void BackpropToNonLooping ( size_t / * inputIndex * / ) override / / scaled by 2 * number of elements in the Matrix < ElemType > <nl> + virtual void BackpropToNonLooping ( size_t / * inputIndex * / ) override / / scaled by 2 * number of elements in the Matrix < ElemType > <nl> { <nl> LogicError ( " SequenceDecoder is used for evaluation only . " ) ; <nl> } <nl> mmm a / Source / ComputationNetworkLib / InputAndParamNodes . h <nl> ppp b / Source / ComputationNetworkLib / InputAndParamNodes . h <nl> class LearnableParameter : public ComputationNode < ElemType > , public NumInputs < 0 > <nl> const ElemType initValueScale , <nl> bool initOnCPUOnly ) / / if true then always init on CPU , making initialization consistent across both ( for testing ) <nl> { <nl> - / / fprintf ( stderr , " % d x % d : % d % ls \ n " , ( int ) GetNumRows ( ) , ( int ) GetNumCols ( ) , ( int ) randomSeed , NodeName ( ) . c_str ( ) ) ; <nl> + / / fprintf ( stderr , " % d x % d : % d % ls \ n " , ( int ) GetNumRows ( ) , ( int ) GetNumCols ( ) , ( int ) randomSeed , NodeName ( ) . c_str ( ) ) ; <nl> <nl> / / the random seed offset is set via the " randomSeedOffset " parameter in config <nl> if ( initOnCPUOnly ) <nl> mmm a / Source / ComputationNetworkLib / LinearAlgebraNodes . h <nl> ppp b / Source / ComputationNetworkLib / LinearAlgebraNodes . h <nl> class PlusNode : public BinaryElementWiseNode < ElemType > <nl> <nl> virtual void / * ComputationNode : : * / ForwardProp ( const FrameRange & fr ) override <nl> { <nl> - / / static int c = 0 ; if ( c + + = = 0 ) { fprintf ( stderr , " # PLUS # \ n " ) ; } <nl> + / / static int c = 0 ; if ( c + + = = 0 ) { fprintf ( stderr , " # PLUS # \ n " ) ; } <nl> size_t rank = DetermineElementwiseTensorRank ( ) ; <nl> auto result = ValueTensorFor ( rank , fr ) ; <nl> auto input0 = Input ( 0 ) - > ValueTensorFor ( rank , fr . AllowBroadcast ( ) ) ; <nl> class DiagTimesNode : public ComputationNode < ElemType > , public NumInputs < 2 > <nl> * node - > m_rightGradient = * m_rightGradient ; <nl> } <nl> } <nl> - / / request matrices that are needed for gradient computation <nl> + / / request matrices that are needed for gradient computation <nl> virtual void RequestMatricesBeforeBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeBackprop ( matrixPool ) ; <nl> class DiagTimesNode : public ComputationNode < ElemType > , public NumInputs < 2 > <nl> RequestMatrixFromPool ( m_rightGradient , matrixPool ) ; <nl> } <nl> <nl> - / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> + / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> virtual void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : ReleaseMatricesAfterBackprop ( matrixPool ) ; <nl> class CosDistanceNode : public ComputationNode < ElemType > , public NumInputs < 2 > <nl> * node - > m_temp = * m_temp ; <nl> } <nl> } <nl> - / / request matrices needed to do node function value evaluation <nl> + / / request matrices needed to do node function value evaluation <nl> virtual void RequestMatricesBeforeForwardProp ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeForwardProp ( matrixPool ) ; <nl> class CosDistanceNode : public ComputationNode < ElemType > , public NumInputs < 2 > <nl> RequestMatrixFromPool ( m_invNorm1 , matrixPool ) ; <nl> } <nl> <nl> - / / request matrices that are needed for gradient computation <nl> + / / request matrices that are needed for gradient computation <nl> virtual void RequestMatricesBeforeBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeBackprop ( matrixPool ) ; <nl> class CosDistanceNode : public ComputationNode < ElemType > , public NumInputs < 2 > <nl> RequestMatrixFromPool ( m_temp , matrixPool ) ; <nl> } <nl> <nl> - / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> + / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> virtual void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : ReleaseMatricesAfterBackprop ( matrixPool ) ; <nl> class KhatriRaoProductNode : public ComputationNode < ElemType > , public NumInputs < <nl> { <nl> Matrix < ElemType > sliceOutputGrad = GradientFor ( fr ) ; <nl> <nl> - if ( inputIndex = = 0 ) / / left derivative <nl> + if ( inputIndex = = 0 ) / / left derivative <nl> { <nl> Matrix < ElemType > sliceInput0Grad = Input ( 0 ) - > GradientFor ( fr ) ; <nl> Matrix < ElemType > sliceInput1Value = Input ( 1 ) - > ValueFor ( fr ) ; <nl> <nl> sliceInput0Grad . AddColumnReshapeProductOf ( sliceOutputGrad , sliceInput1Value , false ) ; <nl> } <nl> - else / / right derivative <nl> + else / / right derivative <nl> { <nl> Matrix < ElemType > sliceInput0Value = Input ( 0 ) - > ValueFor ( fr ) ; <nl> Matrix < ElemType > sliceInput1Grad = Input ( 1 ) - > GradientFor ( fr ) ; <nl> class CosDistanceWithNegativeSamplesNode : public ComputationNode < ElemType > , pub <nl> } <nl> else / / right part <nl> { <nl> - invNormSquare . AssignElementProductOf ( invNorm1 , invNorm1 ) ; / / this matrix should be save and unchanged . It should not be changed <nl> + invNormSquare . AssignElementProductOf ( invNorm1 , invNorm1 ) ; / / this matrix should be save and unchanged . It should not be changed <nl> <nl> for ( long m = 0 ; m < negNumber + 1 ; m + + ) <nl> { <nl> class CosDistanceWithNegativeSamplesNode : public ComputationNode < ElemType > , pub <nl> size_t currshift = ( m + shift - 1 ) % numCols ; <nl> size_t reverseshift = numCols - currshift ; <nl> <nl> - leftTerm . AssignElementProductOfWithShift ( invNormSquare , temp , reverseshift ) ; / / use leftTerm as a temp variable here <nl> + leftTerm . AssignElementProductOfWithShift ( invNormSquare , temp , reverseshift ) ; / / use leftTerm as a temp variable here <nl> <nl> Matrix < ElemType > : : ConductRowElementMultiplyWithShift ( leftTerm , in1 , rightTerm , 0 , true ) ; <nl> <nl> class CosDistanceWithNegativeSamplesNode : public ComputationNode < ElemType > , pub <nl> * node - > m_temp = * m_temp ; <nl> } <nl> } <nl> - / / request matrices needed to do node function value evaluation <nl> + / / request matrices needed to do node function value evaluation <nl> virtual void RequestMatricesBeforeForwardProp ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeForwardProp ( matrixPool ) ; <nl> class CosDistanceWithNegativeSamplesNode : public ComputationNode < ElemType > , pub <nl> RequestMatrixFromPool ( m_rightTerm , matrixPool ) ; <nl> } <nl> <nl> - / / request matrices that are needed for gradient computation <nl> + / / request matrices that are needed for gradient computation <nl> virtual void RequestMatricesBeforeBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeBackprop ( matrixPool ) ; <nl> class CosDistanceWithNegativeSamplesNode : public ComputationNode < ElemType > , pub <nl> RequestMatrixFromPool ( m_temp , matrixPool ) ; <nl> } <nl> <nl> - / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> + / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> virtual void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : ReleaseMatricesAfterBackprop ( matrixPool ) ; <nl> mmm a / Source / ComputationNetworkLib / MatrixPool . h <nl> ppp b / Source / ComputationNetworkLib / MatrixPool . h <nl> class MatrixPool <nl> vector < shared_ptr < Matrix < ElemType > > > & GetReleasedMatrices ( ) ; <nl> <nl> public : <nl> - / / release here means the matrix can be put back and shared by others <nl> + / / release here means the matrix can be put back and shared by others <nl> template < class ElemType > <nl> void Release ( shared_ptr < Matrix < ElemType > > freeMatrix ) <nl> { <nl> mmm a / Source / ComputationNetworkLib / NonlinearityNodes . h <nl> ppp b / Source / ComputationNetworkLib / NonlinearityNodes . h <nl> class SoftmaxNodeBase : public ComputationNode < ElemType > , public NumInputs < 1 > <nl> UsingComputationNodeMembers ; <nl> <nl> public : <nl> - / / virtual ComputationNodeBase * NewThis ( DEVICEID_TYPE deviceId , const wstring & name ) = 0 ; <nl> + / / virtual ComputationNodeBase * NewThis ( DEVICEID_TYPE deviceId , const wstring & name ) = 0 ; <nl> DeclareConstructorFromConfigWithNumInputs ( SoftmaxNodeBase ) ; <nl> SoftmaxNodeBase ( DEVICEID_TYPE deviceId , const wstring & name ) <nl> : Base ( deviceId , name ) <nl> class SoftmaxNode : public SoftmaxNodeBase < ElemType > <nl> * node - > m_diff = * m_diff ; <nl> } <nl> } <nl> - / / request matrices that are needed for gradient computation <nl> + / / request matrices that are needed for gradient computation <nl> virtual void RequestMatricesBeforeBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeBackprop ( matrixPool ) ; <nl> RequestMatrixFromPool ( m_diff , matrixPool ) ; <nl> } <nl> <nl> - / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> + / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> virtual void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : ReleaseMatricesAfterBackprop ( matrixPool ) ; <nl> class LogSoftmaxNode : public SoftmaxNodeBase < ElemType > <nl> * node - > m_softmax = * m_softmax ; <nl> } <nl> } <nl> - / / request matrices that are needed for gradient computation <nl> + / / request matrices that are needed for gradient computation <nl> virtual void RequestMatricesBeforeBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeBackprop ( matrixPool ) ; <nl> RequestMatrixFromPool ( m_softmax , matrixPool ) ; <nl> } <nl> <nl> - / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> + / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> virtual void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : ReleaseMatricesAfterBackprop ( matrixPool ) ; <nl> class HardmaxNode : public SoftmaxNodeBase / * ComputationNode * / < ElemType > <nl> <nl> / * virtual * / void ForwardPropV ( Matrix < ElemType > & functionValues , const Matrix < ElemType > & inputFunctionValues ) override <nl> { <nl> - / / TODO : temp solution , we need to write a math function specifically for this <nl> + / / TODO : temp solution , we need to write a math function specifically for this <nl> functionValues . AssignHardmaxOf ( inputFunctionValues , true ) ; <nl> } <nl> } ; <nl> mmm a / Source / ComputationNetworkLib / PreComputeNodes . h <nl> ppp b / Source / ComputationNetworkLib / PreComputeNodes . h <nl> class MeanInvStdDevNodeBase : public PreComputedNodeBase < ElemType > , public NumIn <nl> { <nl> typedef PreComputedNodeBase < ElemType > Base ; <nl> UsingPreComputedNodeMembers ; <nl> - / / static const std : : wstring TypeName ( ) { return L " MeanInvStdDev ( base ) " ; } <nl> + / / static const std : : wstring TypeName ( ) { return L " MeanInvStdDev ( base ) " ; } <nl> public : <nl> - / / DeclareConstructorFromConfigWithNumInputs ( MeanInvStdDevNodeBase ) ; <nl> + / / DeclareConstructorFromConfigWithNumInputs ( MeanInvStdDevNodeBase ) ; <nl> MeanInvStdDevNodeBase ( DEVICEID_TYPE deviceId , const wstring & name ) <nl> : PreComputedNodeBase < ElemType > ( deviceId , name ) , <nl> m_numSamples ( SIZE_MAX ) <nl> class MeanInvStdDevNodeBase : public PreComputedNodeBase < ElemType > , public NumIn <nl> <nl> virtual void BackpropToNonLooping ( size_t / * inputIndex * / ) override <nl> { <nl> - / / LogicError ( " Mean operation should not be involved in the gradient calculation . " ) ; <nl> + / / LogicError ( " Mean operation should not be involved in the gradient calculation . " ) ; <nl> } <nl> <nl> virtual void CopyTo ( ComputationNodeBasePtr nodeP , const std : : wstring & newName , const CopyNodeFlags flags ) const override <nl> class PerDimMeanVarDeNormalizationNode : public ComputationNode < ElemType > , publi <nl> InvalidArgument ( " PerDimMeanVarDeNormalizationNode should only be called in the evaluation stage . " ) ; <nl> } <nl> <nl> - / / ( feature - mean ) . * InvStdDev <nl> + / / ( feature - mean ) . * InvStdDev <nl> virtual void / * ComputationNode : : * / ForwardProp ( const FrameRange & fr ) override <nl> { <nl> / / only feature ( input0 ) and output needs to be sliced <nl> class PerDimMeanVarDeNormalizationNode : public ComputationNode < ElemType > , publi <nl> input1 . HasNan ( " PerDimMeanVarDeNormalization - input1 " ) ; <nl> input2 . HasNan ( " PerDimMeanVarDeNormalization - input2 " ) ; <nl> # endif <nl> - / / functionValues . AssignDifferenceOf ( input0 , input1 ) ; <nl> - / / functionValues . ColumnElementMultiplyWith ( input2 ) ; <nl> - / / functionValues . AssignDifferenceOf ( input0 , input0 ) ; <nl> - / / functionValues + = input2 ; <nl> - / / functionValues . ElementInverse ( ) ; <nl> - / / functionValues . ElementMultiplyWith ( input0 ) ; <nl> + / / functionValues . AssignDifferenceOf ( input0 , input1 ) ; <nl> + / / functionValues . ColumnElementMultiplyWith ( input2 ) ; <nl> + / / functionValues . AssignDifferenceOf ( input0 , input0 ) ; <nl> + / / functionValues + = input2 ; <nl> + / / functionValues . ElementInverse ( ) ; <nl> + / / functionValues . ElementMultiplyWith ( input0 ) ; <nl> functionValues . SetValue ( input0 ) ; <nl> functionValues . ColumnElementDivideBy ( input2 ) ; <nl> functionValues + = input1 ; <nl> mmm a / Source / ComputationNetworkLib / RecurrentNodes . h <nl> ppp b / Source / ComputationNetworkLib / RecurrentNodes . h <nl> class ShiftNode : public ComputationNode < ElemType > , public IRecurrentNode , publi <nl> public : <nl> virtual void ForwardProp ( const FrameRange & fr ) override <nl> { <nl> - / / for ( size_t xx = 0 ; xx < 3 ; xx + + ) / / for testing the strange slow - down <nl> + / / for ( size_t xx = 0 ; xx < 3 ; xx + + ) / / for testing the strange slow - down <nl> { <nl> if ( fr . GetIterationDimension ( ) ! = m_shiftDimParam ) <nl> LogicError ( " ShiftNode : : ForwardProp ( ) : FrameRange not iterating over user - specified dimension . " ) ; <nl> class DelayedValueNodeBase : public ComputationNode < ElemType > , public IRecurrent <nl> { <nl> / / Boundary frames must not propagate . Gaps must also not propagate . <nl> / / if there is a boundary in this frame , we treat each stream separately ; otherwise we do all in one go <nl> - / / assert ( m_pShiftedMBLayout - > Is ( t , SequenceStart_or_End | MinibatchPackingFlags : : NoFeature ) = = <nl> + / / assert ( m_pShiftedMBLayout - > Is ( t , SequenceStart_or_End | MinibatchPackingFlags : : NoFeature ) = = <nl> / / m_pMBLayout - > IsGap ( fr ) | | m_pMBLayout - > IsBeyondStartOrEnd ( frDelayed ) ) ; <nl> if ( m_pMBLayout - > IsGap ( fr ) | | m_pMBLayout - > IsBeyondStartOrEnd ( frDelayed ) ) / / true if at least one parallel sequence has a boundary or gap <nl> { <nl> size_t mNbr = m_pMBLayout - > GetNumParallelSequences ( ) ; <nl> for ( size_t id = 0 ; id < mNbr ; id + + ) <nl> { <nl> - / / assert ( m_pShiftedMBLayout - > Is ( id , t , SequenceStart_or_End | MinibatchPackingFlags : : NoFeature ) = = <nl> + / / assert ( m_pShiftedMBLayout - > Is ( id , t , SequenceStart_or_End | MinibatchPackingFlags : : NoFeature ) = = <nl> / / m_pMBLayout - > IsGap ( fr . Sequence ( id ) ) | | m_pMBLayout - > IsBeyondStartOrEnd ( frDelayed . Sequence ( id ) ) ) ; <nl> if ( ! ( m_pMBLayout - > IsGap ( fr . Sequence ( id ) ) | | m_pMBLayout - > IsBeyondStartOrEnd ( frDelayed . Sequence ( id ) ) ) ) / / don ' t propagate boundary frames or gaps <nl> { <nl> Matrix < ElemType > frm = GradientFor ( fr . Sequence ( id ) ) ; <nl> / / TODO : use delayed FrameRange here as well <nl> - / / Matrix < ElemType > to = Input ( 0 ) - > GradientFor ( FrameRange ( m_pMBLayout , t_delayed ) . Sequence ( id ) ) ; <nl> + / / Matrix < ElemType > to = Input ( 0 ) - > GradientFor ( FrameRange ( m_pMBLayout , t_delayed ) . Sequence ( id ) ) ; <nl> Matrix < ElemType > to = Input ( 0 ) - > GradientFor ( frDelayed . Sequence ( id ) ) ; <nl> to + = frm ; <nl> } <nl> class DelayedValueNodeBase : public ComputationNode < ElemType > , public IRecurrent <nl> { <nl> Matrix < ElemType > frm = GradientFor ( fr ) ; <nl> / / TODO : use something like fr . WithDelay ( t ) instead , instead of recreating FrameRanges <nl> - / / Matrix < ElemType > to = Input ( 0 ) - > GradientFor ( FrameRange ( m_pMBLayout , t_delayed ) ) ; <nl> + / / Matrix < ElemType > to = Input ( 0 ) - > GradientFor ( FrameRange ( m_pMBLayout , t_delayed ) ) ; <nl> Matrix < ElemType > to = Input ( 0 ) - > GradientFor ( frDelayed ) ; <nl> to + = frm ; <nl> } <nl> class DelayedValueNodeBase : public ComputationNode < ElemType > , public IRecurrent <nl> <nl> / / if any sequence at this time step has a boundary flag , then process one by one <nl> / / TODO : Would there be an efficiency gain from grouping consecutive sequences with identical flags ? <nl> - / / assert ( m_pShiftedMBLayout - > Is ( t , SequenceStart_or_End ) = = m_pMBLayout - > IsBeyondStartOrEnd ( frDelayed ) ) ; <nl> + / / assert ( m_pShiftedMBLayout - > Is ( t , SequenceStart_or_End ) = = m_pMBLayout - > IsBeyondStartOrEnd ( frDelayed ) ) ; <nl> if ( m_pMBLayout - > IsBeyondStartOrEnd ( frDelayed ) ) <nl> { <nl> for ( size_t id = 0 ; id < GetNumParallelSequences ( ) ; id + + ) <nl> class DelayedValueNodeBase : public ComputationNode < ElemType > , public IRecurrent <nl> <nl> Matrix < ElemType > out = ValueFor ( fr . Sequence ( id ) ) ; <nl> <nl> - / / assert ( m_pShiftedMBLayout - > Is ( id , t , SequenceStart_or_End ) = = m_pMBLayout - > IsBeyondStartOrEnd ( frDelayed . Sequence ( id ) ) ) ; <nl> + / / assert ( m_pShiftedMBLayout - > Is ( id , t , SequenceStart_or_End ) = = m_pMBLayout - > IsBeyondStartOrEnd ( frDelayed . Sequence ( id ) ) ) ; <nl> if ( m_pMBLayout - > IsBeyondStartOrEnd ( frDelayed . Sequence ( id ) ) ) <nl> out . SetValue ( m_initialActivationValue ) ; / / crossed a boundary <nl> else / / not a boundary : just copy the delayed value <nl> class DelayedValueNodeBase : public ComputationNode < ElemType > , public IRecurrent <nl> inp = DataWithMBLayoutFor ( m_delayedValue , FrameRange ( m_delayedActivationMBLayout , t_delayed - T ) . Sequence ( id ) , m_delayedActivationMBLayout ) ; / / delay reaches in previous minibatch <nl> else <nl> inp = Input ( 0 ) - > ValueFor ( frDelayed . Sequence ( id ) ) ; <nl> - / / inp = Input ( 0 ) - > ValueFor ( FrameRange ( m_pMBLayout , t_delayed ) . Sequence ( id ) ) ; <nl> + / / inp = Input ( 0 ) - > ValueFor ( FrameRange ( m_pMBLayout , t_delayed ) . Sequence ( id ) ) ; <nl> <nl> out . SetValue ( inp ) ; <nl> } <nl> class DelayedValueNodeBase : public ComputationNode < ElemType > , public IRecurrent <nl> inp = DataWithMBLayoutFor ( m_delayedValue , FrameRange ( m_delayedActivationMBLayout , t_delayed - T ) , m_delayedActivationMBLayout ) ; <nl> else <nl> inp = Input ( 0 ) - > ValueFor ( frDelayed ) ; <nl> - / / inp = Input ( 0 ) - > ValueFor ( FrameRange ( m_pMBLayout , t_delayed ) ) ; <nl> + / / inp = Input ( 0 ) - > ValueFor ( FrameRange ( m_pMBLayout , t_delayed ) ) ; <nl> <nl> out . SetValue ( inp ) ; <nl> } <nl> mmm a / Source / ComputationNetworkLib / ReshapingNodes . h <nl> ppp b / Source / ComputationNetworkLib / ReshapingNodes . h <nl> class ReinterpretNodeBase : public ComputationNode < ElemType > , public NumInputs < 1 <nl> UsingComputationNodeMembers ; <nl> <nl> public : <nl> - / / DeclareConstructorFromConfigWithNumInputs ( ReinterpretNodeBase ) ; <nl> + / / DeclareConstructorFromConfigWithNumInputs ( ReinterpretNodeBase ) ; <nl> ReinterpretNodeBase ( DEVICEID_TYPE deviceId , const wstring & name ) <nl> : Base ( deviceId , name ) <nl> { <nl> class ReinterpretNodeBase : public ComputationNode < ElemType > , public NumInputs < 1 <nl> / / input : T = 2 , D = 2 , K = 3 , S = 2 ( abcdef and uvwxyz ) <nl> / / abc def <nl> / / ABC DEF <nl> - / / <nl> + / / <nl> / / uvw xyz <nl> / / UVW XYZ <nl> / / target : <nl> class ReinterpretNodeBase : public ComputationNode < ElemType > , public NumInputs < 1 <nl> / / B E <nl> / / c f <nl> / / C F <nl> - / / <nl> + / / <nl> / / u x <nl> / / U X <nl> / / v y <nl> mmm a / Source / ComputationNetworkLib / SpecialPurposeNodes . h <nl> ppp b / Source / ComputationNetworkLib / SpecialPurposeNodes . h <nl> class GMMLogLikelihoodNode : public ComputationNode < ElemType > , public NumInputs < <nl> size_t numSamples = posterior . GetNumCols ( ) ; <nl> size_t featureSize = normedDeviationVectors . GetNumRows ( ) / numComponent ; <nl> <nl> - temp . SetValue ( normedDeviationVectors ) ; / / recall normedDeviationVectors < - - ( x - u_c ) / ( stddev ^ 2 ) <nl> + temp . SetValue ( normedDeviationVectors ) ; / / recall normedDeviationVectors < - - ( x - u_c ) / ( stddev ^ 2 ) <nl> temp . Reshape ( featureSize , numSamples * numComponent ) ; <nl> <nl> posterior . Reshape ( 1 , numSamples * numComponent ) ; <nl> - temp . RowElementMultiplyWith ( posterior ) ; / / temp < - - posterior * ( x - u_c ) / ( stddev ^ 2 ) <nl> + temp . RowElementMultiplyWith ( posterior ) ; / / temp < - - posterior * ( x - u_c ) / ( stddev ^ 2 ) <nl> <nl> - posterior . Reshape ( numComponent , numSamples ) ; / / reshape back <nl> - temp . Reshape ( featureSize * numComponent , numSamples ) ; / / reshape back <nl> + posterior . Reshape ( numComponent , numSamples ) ; / / reshape back <nl> + temp . Reshape ( featureSize * numComponent , numSamples ) ; / / reshape back <nl> <nl> temp . RowElementMultiplyWith ( gradientValues ) ; <nl> <nl> class GMMLogLikelihoodNode : public ComputationNode < ElemType > , public NumInputs < <nl> ForwardPropS ( sliceOutputValue , sliceUnnormedPrior , sliceMean , sliceLogstddev , sliceFeature , <nl> slicePrior , sliceStddev , sliceNormedDeviationVectors , sliceNormedDeviation , slicePosterior , * m_temp ) ; <nl> } <nl> - else / / should not reach the code since validation should fail already <nl> + else / / should not reach the code since validation should fail already <nl> RuntimeError ( " GMMLogLikelihoodNode : UnnormedPrior should either have same number of columns as the features or have only one column . " ) ; <nl> } <nl> <nl> - / / input0 = unnormedPrior , input1 = mean , input2 = logstddev , input3 = feature <nl> - / / If we want to speed up we need to replace following code with a several specialized GPU functions <nl> + / / input0 = unnormedPrior , input1 = mean , input2 = logstddev , input3 = feature <nl> + / / If we want to speed up we need to replace following code with a several specialized GPU functions <nl> / * TODO : merge with call site * / void ForwardPropS ( Matrix < ElemType > & functionValues , const Matrix < ElemType > & unnormedPrior , const Matrix < ElemType > & mean , Matrix < ElemType > & logstddev , <nl> const Matrix < ElemType > & feature , Matrix < ElemType > & prior , Matrix < ElemType > & stddev , Matrix < ElemType > & normedDeviationVectors , <nl> Matrix < ElemType > & normedDeviation , Matrix < ElemType > & posterior , Matrix < ElemType > & temp ) <nl> class GMMLogLikelihoodNode : public ComputationNode < ElemType > , public NumInputs < <nl> size_t numSamples = feature . GetNumCols ( ) ; <nl> size_t featureDim = feature . GetNumRows ( ) ; <nl> <nl> - / / compute prior which is softmax of unnormedPrior <nl> - prior . AssignLogSoftmaxOf ( unnormedPrior , true ) ; / / log prior <nl> + / / compute prior which is softmax of unnormedPrior <nl> + prior . AssignLogSoftmaxOf ( unnormedPrior , true ) ; / / log prior <nl> <nl> prior . InplaceExp ( ) ; <nl> <nl> - / / compute stddev <nl> + / / compute stddev <nl> stddev . AssignExpOf ( logstddev ) ; <nl> <nl> # if DUMPOUTPUT <nl> class GMMLogLikelihoodNode : public ComputationNode < ElemType > , public NumInputs < <nl> stddev . Print ( " stddev " , 0 , min ( 5 , stddev . GetNumRows ( ) - 1 ) , 0 , min ( 10 , stddev . GetNumCols ( ) - 1 ) ) ; <nl> # endif <nl> <nl> - / / compute normedDeviation < - - | | x - u_c | | ^ 2 / ( stddev ^ 2 ) <nl> + / / compute normedDeviation < - - | | x - u_c | | ^ 2 / ( stddev ^ 2 ) <nl> normedDeviationVectors . AssignRepeatOf ( feature , numComponent , 1 ) ; <nl> - normedDeviationVectors - = mean ; / / each column of the mean has multiple mean components <nl> - normedDeviationVectors . Reshape ( featureDim , numSamples * numComponent ) ; / / now each column is feature - mean_i <nl> + normedDeviationVectors - = mean ; / / each column of the mean has multiple mean components <nl> + normedDeviationVectors . Reshape ( featureDim , numSamples * numComponent ) ; / / now each column is feature - mean_i <nl> <nl> normedDeviation . AssignVectorNorm2Of ( normedDeviationVectors , true ) ; <nl> normedDeviation ^ = 2 ; <nl> - temp . AssignRepeatOf ( stddev , 1 , numSamples / stddev . GetNumCols ( ) ) ; / / stddev . GetNumCols ( ) is either 1 or = numSamples <nl> - temp . Reshape ( 1 , temp . GetNumElements ( ) ) ; / / one stddev value for each component for each sample <nl> + temp . AssignRepeatOf ( stddev , 1 , numSamples / stddev . GetNumCols ( ) ) ; / / stddev . GetNumCols ( ) is either 1 or = numSamples <nl> + temp . Reshape ( 1 , temp . GetNumElements ( ) ) ; / / one stddev value for each component for each sample <nl> temp ^ = 2 ; <nl> - normedDeviation . ElementDivideBy ( temp ) ; / / normedDeviation and temp have same dim ( 1 , numSamples * numComponent ) <nl> + normedDeviation . ElementDivideBy ( temp ) ; / / normedDeviation and temp have same dim ( 1 , numSamples * numComponent ) <nl> <nl> - / / compute normedDeviationVectors < - - ( x - u_c ) / ( stddev ^ 2 ) <nl> - normedDeviationVectors . RowElementDivideBy ( temp ) ; / / divide twice <nl> - normedDeviationVectors . Reshape ( featureDim * numComponent , numSamples ) ; / / reshape back <nl> + / / compute normedDeviationVectors < - - ( x - u_c ) / ( stddev ^ 2 ) <nl> + normedDeviationVectors . RowElementDivideBy ( temp ) ; / / divide twice <nl> + normedDeviationVectors . Reshape ( featureDim * numComponent , numSamples ) ; / / reshape back <nl> <nl> - / / compute per - component likelihood <nl> - posterior . AssignProductOf ( - 0 . 5f , normedDeviation ) ; / / posterior < - - - | | x - u_c | | ^ 2 / ( stddev ^ 2 ) / 2 and in ( 1 , numSamples * numComponent ) dim <nl> + / / compute per - component likelihood <nl> + posterior . AssignProductOf ( - 0 . 5f , normedDeviation ) ; / / posterior < - - - | | x - u_c | | ^ 2 / ( stddev ^ 2 ) / 2 and in ( 1 , numSamples * numComponent ) dim <nl> temp . InplaceLog ( ) ; <nl> - temp * = ( ( ElemType ) numComponent / 2 . 0f ) ; / / temp < - - stddev ^ c and in ( 1 , numSamples * numComponent ) dim <nl> + temp * = ( ( ElemType ) numComponent / 2 . 0f ) ; / / temp < - - stddev ^ c and in ( 1 , numSamples * numComponent ) dim <nl> posterior - = temp ; / / posterior < - - exp [ - | | x - u_c | | ^ 2 / ( stddev ^ 2 ) / 2 ] / ( stddev ^ c ) <nl> - posterior - = ( ElemType ) ( numComponent / 2 . 0f * log ( TWO_PI ) ) ; / / likelihood for each component and sample is now computed and stored in posterior <nl> - posterior . InplaceExp ( ) ; / / posterior < - - exp ( - | | x - u_c | | ^ 2 / ( stddev ^ 2 ) / 2 ) <nl> + posterior - = ( ElemType ) ( numComponent / 2 . 0f * log ( TWO_PI ) ) ; / / likelihood for each component and sample is now computed and stored in posterior <nl> + posterior . InplaceExp ( ) ; / / posterior < - - exp ( - | | x - u_c | | ^ 2 / ( stddev ^ 2 ) / 2 ) <nl> <nl> - normedDeviation . Reshape ( numComponent , numSamples ) ; / / reshape back <nl> - posterior . Reshape ( numComponent , numSamples ) ; / / reshape back <nl> + normedDeviation . Reshape ( numComponent , numSamples ) ; / / reshape back <nl> + posterior . Reshape ( numComponent , numSamples ) ; / / reshape back <nl> <nl> - / / compute posterior < - - prior_i * likelihood_i <nl> - if ( unnormedPrior . GetNumCols ( ) = = numSamples ) / / each sample has different prior <nl> + / / compute posterior < - - prior_i * likelihood_i <nl> + if ( unnormedPrior . GetNumCols ( ) = = numSamples ) / / each sample has different prior <nl> posterior . ElementMultiplyWith ( prior ) ; <nl> - else / / all samples share the same prior <nl> + else / / all samples share the same prior <nl> posterior . ColumnElementMultiplyWith ( prior ) ; <nl> <nl> - / / compute GMM log - likelihood <nl> - Matrix < ElemType > : : Multiply ( ConstOnes ( 1 , numComponent , posterior . GetDeviceId ( ) ) , false , posterior , false , functionValues ) ; / / functionValues < - - total likelihood <nl> - posterior . RowElementDivideBy ( functionValues ) ; / / posterior < - - per - comp likelihood / total likelihood <nl> - functionValues . InplaceLog ( ) ; / / log likelihood <nl> + / / compute GMM log - likelihood <nl> + Matrix < ElemType > : : Multiply ( ConstOnes ( 1 , numComponent , posterior . GetDeviceId ( ) ) , false , posterior , false , functionValues ) ; / / functionValues < - - total likelihood <nl> + posterior . RowElementDivideBy ( functionValues ) ; / / posterior < - - per - comp likelihood / total likelihood <nl> + functionValues . InplaceLog ( ) ; / / log likelihood <nl> <nl> # if DUMPOUTPUT <nl> temp . Print ( " temp " , 0 , min ( 5 , temp . GetNumRows ( ) - 1 ) , 0 , min ( 10 , temp . GetNumCols ( ) - 1 ) ) ; <nl> class GMMLogLikelihoodNode : public ComputationNode < ElemType > , public NumInputs < <nl> } <nl> } <nl> <nl> - / / request matrices needed to do node function value evaluation <nl> + / / request matrices needed to do node function value evaluation <nl> virtual void RequestMatricesBeforeForwardProp ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeForwardProp ( matrixPool ) ; <nl> class GMMLogLikelihoodNode : public ComputationNode < ElemType > , public NumInputs < <nl> RequestMatrixFromPool ( m_temp , matrixPool ) ; <nl> } <nl> <nl> - / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> + / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> virtual void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : ReleaseMatricesAfterBackprop ( matrixPool ) ; <nl> class SequenceWithSoftmaxNode : public ComputationNodeNonLooping < ElemType > , publ <nl> { <nl> } <nl> <nl> - / / compute gradients to input observations , the weights to the observations , and the class log posterior probabilites <nl> + / / compute gradients to input observations , the weights to the observations , and the class log posterior probabilites <nl> virtual void BackpropToNonLooping ( size_t inputIndex ) override <nl> { <nl> - / / auto t_start_time = Timer : : MilliSecondElapsed ( ) ; <nl> - / / left Node must be a scalar <nl> - if ( inputIndex = = 0 ) / / left derivative <nl> + / / auto t_start_time = Timer : : MilliSecondElapsed ( ) ; <nl> + / / left Node must be a scalar <nl> + if ( inputIndex = = 0 ) / / left derivative <nl> { <nl> BackpropToLeft ( * m_logSoftmaxOfRight , Input ( inputIndex ) - > Gradient ( ) , Gradient ( ) ) ; <nl> } <nl> class SequenceWithSoftmaxNode : public ComputationNodeNonLooping < ElemType > , publ <nl> m_gammaCalculator . init ( m_hmm , m_deviceId ) ; <nl> m_gammaCalcInitialized = true ; <nl> } <nl> - / / softmax <nl> + / / softmax <nl> m_logSoftmaxOfRight - > AssignLogSoftmaxOf ( Input ( 1 ) - > Value ( ) / * prediction * / , true ) ; <nl> m_softmaxOfRight - > SetValue ( * m_logSoftmaxOfRight ) ; <nl> m_softmaxOfRight - > InplaceExp ( ) ; <nl> class SequenceWithSoftmaxNode : public ComputationNodeNonLooping < ElemType > , publ <nl> LogicError ( " SequenceWithSoftmaxNode criterion requires the first input to be the label . " ) ; <nl> <nl> if ( isFinalValidationPass ) <nl> - if ( ! ( Input ( 0 ) - > GetSampleMatrixNumRows ( ) = = Input ( 1 ) - > GetSampleMatrixNumRows ( ) & & / / match size <nl> + if ( ! ( Input ( 0 ) - > GetSampleMatrixNumRows ( ) = = Input ( 1 ) - > GetSampleMatrixNumRows ( ) & & / / match size <nl> Input ( 1 ) - > GetSampleMatrixNumRows ( ) = = Input ( 2 ) - > GetSampleMatrixNumRows ( ) & & <nl> Input ( 0 ) - > HasMBLayout ( ) & & <nl> Input ( 0 ) - > GetMBLayout ( ) = = Input ( 1 ) - > GetMBLayout ( ) & & <nl> class SequenceWithSoftmaxNode : public ComputationNodeNonLooping < ElemType > , publ <nl> } <nl> } <nl> <nl> - / / request matrices needed to do node function value evaluation <nl> + / / request matrices needed to do node function value evaluation <nl> virtual void RequestMatricesBeforeForwardProp ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeForwardProp ( matrixPool ) ; <nl> class SequenceWithSoftmaxNode : public ComputationNodeNonLooping < ElemType > , publ <nl> RequestMatrixFromPool ( m_gammaFromLattice , matrixPool ) ; <nl> } <nl> <nl> - / / request matrices needed to do node function value evaluation <nl> + / / request matrices needed to do node function value evaluation <nl> virtual void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : ReleaseMatricesAfterBackprop ( matrixPool ) ; <nl> mmm a / Source / ComputationNetworkLib / TrainingNodes . h <nl> ppp b / Source / ComputationNetworkLib / TrainingNodes . h <nl> class SquareErrorNode : public ComputationNodeNonLooping / * ComputationNode * / < Ele <nl> } <nl> } <nl> <nl> - / / request matrices needed to do node function value evaluation <nl> + / / request matrices needed to do node function value evaluation <nl> virtual void RequestMatricesBeforeForwardProp ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeForwardProp ( matrixPool ) ; <nl> RequestMatrixFromPool ( m_leftMinusRight , matrixPool ) ; <nl> } <nl> <nl> - / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> + / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> virtual void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : ReleaseMatricesAfterBackprop ( matrixPool ) ; <nl> class CrossEntropyWithSoftmaxNode : public ComputationNodeNonLooping / * Computati <nl> { <nl> FrameRange fr ( Input ( 0 ) - > GetMBLayout ( ) ) ; <nl> / / left input is scalar <nl> - if ( inputIndex = = 0 ) / / left derivative <nl> + if ( inputIndex = = 0 ) / / left derivative <nl> { <nl> # if DUMPOUTPUT <nl> * m_logSoftmaxOfRight . Print ( " CrossEntropyWithSoftmax Partial - logSoftmaxOfRight " ) ; <nl> class CrossEntropyWithSoftmaxNode : public ComputationNodeNonLooping / * Computati <nl> m_softmaxOfRight - > Resize ( * m_logSoftmaxOfRight ) ; <nl> } <nl> <nl> - virtual void / * ComputationNodeNonLooping : : * / ForwardPropNonLooping ( ) override / / - sum ( left_i * log ( softmax_i ( right ) ) ) <nl> + virtual void / * ComputationNodeNonLooping : : * / ForwardPropNonLooping ( ) override / / - sum ( left_i * log ( softmax_i ( right ) ) ) <nl> { <nl> FrameRange fr ( Input ( 0 ) - > GetMBLayout ( ) ) ; <nl> / / first compute the softmax ( column - wise ) <nl> class CrossEntropyWithSoftmaxNode : public ComputationNodeNonLooping / * Computati <nl> } <nl> } <nl> <nl> - / / request matrices needed to do node function value evaluation <nl> + / / request matrices needed to do node function value evaluation <nl> virtual void RequestMatricesBeforeForwardProp ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeForwardProp ( matrixPool ) ; <nl> class CrossEntropyNode : public ComputationNodeNonLooping / * ComputationNode * / < El <nl> virtual void BackpropToNonLooping ( size_t inputIndex ) override <nl> { <nl> FrameRange fr ( Input ( 0 ) - > GetMBLayout ( ) ) ; <nl> - / / left Node must be a scalar <nl> - if ( inputIndex = = 0 ) / / left derivative <nl> + / / left Node must be a scalar <nl> + if ( inputIndex = = 0 ) / / left derivative <nl> { <nl> BackpropToLeft ( * m_logOfRight , Input ( 0 ) - > GradientFor ( fr ) , Gradient ( ) ) ; <nl> } <nl> class CrossEntropyNode : public ComputationNodeNonLooping / * ComputationNode * / < El <nl> m_leftDivRight - > Resize ( Input ( 1 ) - > Value ( ) ) ; <nl> } <nl> <nl> - / / - sum ( left_i * log ( right_i ) ) <nl> + / / - sum ( left_i * log ( right_i ) ) <nl> virtual void / * ComputationNodeNonLooping : : * / ForwardPropNonLooping ( ) override <nl> { <nl> FrameRange fr ( Input ( 0 ) - > GetMBLayout ( ) ) ; <nl> class CrossEntropyNode : public ComputationNodeNonLooping / * ComputationNode * / < El <nl> } <nl> } <nl> <nl> - / / request matrices needed to do node function value evaluation <nl> + / / request matrices needed to do node function value evaluation <nl> virtual void RequestMatricesBeforeForwardProp ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeForwardProp ( matrixPool ) ; <nl> RequestMatrixFromPool ( m_logOfRight , matrixPool ) ; <nl> } <nl> <nl> - / / request matrices that are needed for gradient computation <nl> + / / request matrices that are needed for gradient computation <nl> virtual void RequestMatricesBeforeBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeBackprop ( matrixPool ) ; <nl> RequestMatrixFromPool ( m_leftDivRight , matrixPool ) ; <nl> } <nl> <nl> - / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> + / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> virtual void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : ReleaseMatricesAfterBackprop ( matrixPool ) ; <nl> class MatrixL1RegNode : public ComputationNodeNonLooping / * ComputationNode * / < Ele <nl> } <nl> } <nl> <nl> - / / request matrices that are needed for gradient computation <nl> + / / request matrices that are needed for gradient computation <nl> virtual void RequestMatricesBeforeBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeBackprop ( matrixPool ) ; <nl> RequestMatrixFromPool ( m_gradientOfL1Norm , matrixPool ) ; <nl> } <nl> <nl> - / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> + / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> virtual void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : ReleaseMatricesAfterBackprop ( matrixPool ) ; <nl> class NoiseContrastiveEstimationNode : public ComputationNodeNonLooping / * Comput <nl> { <nl> FrameRange fr ( Input ( 0 ) - > GetMBLayout ( ) ) ; <nl> m_needRecomputeGradientToSoftmaxInput = false ; <nl> - / / gradient computation @ yinggongzhao <nl> - / / inputIndex should be 2 this time <nl> + / / gradient computation @ yinggongzhao <nl> + / / inputIndex should be 2 this time <nl> if ( m_evalMode ! = NCEEvalMode : : None ) <nl> LogicError ( " BackpropTo should only be called in training mode " ) ; <nl> if ( inputIndex = = 0 ) <nl> InvalidArgument ( " ComputeInput partial should not be called for label " ) ; <nl> / / samples + probs hidden embedding <nl> - / / Input ( inputIndex ) - > GradientFor ( fr ) . AssignNCEDerivative ( m_ncePrediction , Input ( 0 ) - > ValueFor ( fr ) , Input ( 1 ) - > ValueFor ( fr ) , Input ( 2 ) - > Value ( ) , inputIndex ) ; <nl> + / / Input ( inputIndex ) - > GradientFor ( fr ) . AssignNCEDerivative ( m_ncePrediction , Input ( 0 ) - > ValueFor ( fr ) , Input ( 1 ) - > ValueFor ( fr ) , Input ( 2 ) - > Value ( ) , inputIndex ) ; <nl> if ( inputIndex > = 2 ) <nl> Input ( inputIndex ) - > Gradient ( ) . AssignNCEDerivative ( m_ncePrediction , Input ( 0 ) - > ValueFor ( fr ) , Input ( 1 ) - > ValueFor ( fr ) , Input ( 2 ) - > ValueAsMatrix ( ) , inputIndex ) ; <nl> else <nl> class NoiseContrastiveEstimationNode : public ComputationNodeNonLooping / * Comput <nl> / / TODO ( this does not really break it since for full matrices , class Matrix will resize by itself ) <nl> } <nl> <nl> - virtual void / * ComputationNodeNonLooping : : * / ForwardPropNonLooping ( ) override / / - sum ( left_i * log ( softmax_i ( right ) ) ) <nl> + virtual void / * ComputationNodeNonLooping : : * / ForwardPropNonLooping ( ) override / / - sum ( left_i * log ( softmax_i ( right ) ) ) <nl> { <nl> FrameRange fr ( Input ( 0 ) - > GetMBLayout ( ) ) ; <nl> if ( Input ( 0 ) - > HasMBLayout ( ) & & Input ( 0 ) - > GetMBLayout ( ) - > HasGaps ( ) ) <nl> class NoiseContrastiveEstimationNode : public ComputationNodeNonLooping / * Comput <nl> { <nl> / / TODO : are we treating gaps correctly here ? <nl> / / training criterion uses NCE <nl> - / / likelihood samples + probs hidden embedding bias <nl> + / / likelihood samples + probs hidden embedding bias <nl> Value ( ) . AssignNoiseContrastiveEstimation ( Input ( 0 ) - > Value ( ) , Input ( 1 ) - > Value ( ) , Input ( 2 ) - > ValueAsMatrix ( ) , Input ( 3 ) - > Value ( ) , m_ncePrediction ) ; <nl> } <nl> m_needRecomputeGradientToSoftmaxInput = true ; <nl> class ClassBasedCrossEntropyWithSoftmaxNode : public ComputationNodeNonLooping / <nl> { <nl> FrameRange fr = FrameRange ( Input ( LABELDATA ) - > GetMBLayout ( ) , t ) . Sequence ( s ) ; <nl> <nl> - / / if ( Input ( LABELDATA ) - > GetMBLayout ( ) - > IsGap ( s , t ) ) / / skip gaps <nl> + / / if ( Input ( LABELDATA ) - > GetMBLayout ( ) - > IsGap ( s , t ) ) / / skip gaps <nl> if ( Input ( LABELDATA ) - > GetMBLayout ( ) - > IsGap ( fr ) ) / / skip gaps <nl> continue ; <nl> <nl> class CRFNode : public ComputationNodeNonLooping / * ComputationNode * / < ElemType > , <nl> } <nl> } <nl> <nl> - virtual void BackpropToNonLooping ( size_t inputIndex ) override / / scaled by 2 * number of colmns ( samples ) in the Matrix < ElemType > <nl> + virtual void BackpropToNonLooping ( size_t inputIndex ) override / / scaled by 2 * number of colmns ( samples ) in the Matrix < ElemType > <nl> { <nl> FrameRange fr ( Input ( 0 ) - > GetMBLayout ( ) ) ; <nl> / / inputIndex 0 should not get us here , it should be prevented by the needGradient flag of input [ 0 ] <nl> class CRFNode : public ComputationNodeNonLooping / * ComputationNode * / < ElemType > , <nl> if ( ! ( Input ( 1 ) - > GetSampleMatrixNumRows ( ) = = Input ( 2 ) - > GetAsMatrixNumRows ( ) & & / / position dependent and pair scores have same number of labels <nl> Input ( 0 ) - > GetSampleMatrixNumRows ( ) = = Input ( 1 ) - > GetSampleMatrixNumRows ( ) & & <nl> Input ( 0 ) - > HasMBLayout ( ) & & Input ( 0 ) - > GetMBLayout ( ) = = Input ( 1 ) - > GetMBLayout ( ) & & <nl> - / / Input ( 0 ) - > GetNumCols ( ) = = Input ( 1 ) - > GetNumCols ( ) & & / / position dependent and pair scores have the same observation numbers <nl> + / / Input ( 0 ) - > GetNumCols ( ) = = Input ( 1 ) - > GetNumCols ( ) & & / / position dependent and pair scores have the same observation numbers <nl> Input ( 2 ) - > GetAsMatrixNumCols ( ) = = Input ( 2 ) - > GetAsMatrixNumRows ( ) ) ) <nl> { <nl> LogicError ( " The Matrix dimension in the CRFNode operation does not match . " ) ; <nl> class LogisticNode : public ComputationNodeNonLooping / * ComputationNode * / < ElemTy <nl> if ( inputIndex ! = 1 ) <nl> InvalidArgument ( " % ls % ls operation cannot compute the gradient for its first inpute . " , NodeName ( ) . c_str ( ) , OperationName ( ) . c_str ( ) ) ; <nl> <nl> - / / BackpropToRight ( m_temp , Input ( 0 ) - > Value ( ) , Input ( 2 ) - > Value ( ) , Input ( inputIndex ) - > Gradient ( ) , Gradient ( ) , m_classZeroLabels , m_result ) ; <nl> + / / BackpropToRight ( m_temp , Input ( 0 ) - > Value ( ) , Input ( 2 ) - > Value ( ) , Input ( inputIndex ) - > Gradient ( ) , Gradient ( ) , m_classZeroLabels , m_result ) ; <nl> / / Create vector with 1 for class 1 , and - 1 for class 0 <nl> m_temp - > AssignDifferenceOf ( Input ( 0 ) - > ValueFor ( fr ) , * m_classZeroLabels ) ; / / TODO : need a slice for m_classZeroLabels ? <nl> <nl> class LogisticNode : public ComputationNodeNonLooping / * ComputationNode * / < ElemTy <nl> } <nl> } <nl> <nl> - / / request matrices needed to do node function value evaluation <nl> + / / request matrices needed to do node function value evaluation <nl> virtual void RequestMatricesBeforeForwardProp ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeForwardProp ( matrixPool ) ; <nl> class LogisticNode : public ComputationNodeNonLooping / * ComputationNode * / < ElemTy <nl> RequestMatrixFromPool ( m_temp , matrixPool ) ; <nl> } <nl> <nl> - / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> + / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> virtual void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : ReleaseMatricesAfterBackprop ( matrixPool ) ; <nl> class DropoutNode : public ComputationNode < ElemType > , public NumInputs < 1 > <nl> node - > m_maskOfDropout = m_maskOfDropout ; <nl> } <nl> } <nl> - / / request matrices needed to do node function value evaluation <nl> + / / request matrices needed to do node function value evaluation <nl> virtual void RequestMatricesBeforeForwardProp ( MatrixPool & matrixPool ) <nl> { <nl> Base : : RequestMatricesBeforeForwardProp ( matrixPool ) ; <nl> RequestMatrixFromPool ( m_maskOfDropout , matrixPool ) ; <nl> } <nl> <nl> - / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> + / / release gradient and temp matrices that no longer needed after all the children ' s gradients are computed . <nl> virtual void ReleaseMatricesAfterBackprop ( MatrixPool & matrixPool ) <nl> { <nl> Base : : ReleaseMatricesAfterBackprop ( matrixPool ) ; <nl> class BatchNormalizationNode : public ComputationNode < ElemType > , public NumInput <nl> private : <nl> struct VersionInfo <nl> { <nl> - / / int32_t VerWrittenCur ( ) const { return 0x00010001 ; } / / Initial <nl> + / / int32_t VerWrittenCur ( ) const { return 0x00010001 ; } / / Initial <nl> int32_t VerWrittenCur ( ) const <nl> { <nl> return 0x00010002 ; <nl> mmm a / Source / EvalDll / CNTKEval . cpp <nl> ppp b / Source / EvalDll / CNTKEval . cpp <nl> void CNTKEval < ElemType > : : Evaluate ( std : : map < std : : wstring , std : : vector < ElemType > * > <nl> vector < wstring > outNodeNames ; <nl> <nl> ConfigParameters config ; <nl> - / / config [ " deviceId " ] = to_string ( m_net - > GetDeviceId ( ) ) ; <nl> + / / config [ " deviceId " ] = to_string ( m_net - > GetDeviceId ( ) ) ; <nl> <nl> / / create the reader if necessary <nl> if ( m_reader = = nullptr ) <nl> mmm a / Source / EvalDll / EvalReader . h <nl> ppp b / Source / EvalDll / EvalReader . h <nl> class EvalReader : public IDataReader < ElemType > <nl> { <nl> } <nl> <nl> - / / StartMinibatchLoop - Startup a minibatch loop <nl> + / / StartMinibatchLoop - Startup a minibatch loop <nl> / / mbSize - [ in ] size of the minibatch ( number of frames , etc . ) <nl> / / epoch - [ in ] epoch number for this loop <nl> / / requestedEpochSamples - [ in ] number of samples to randomize , defaults to requestDataSize which uses the number of samples there are in the dataset <nl> class EvalReader : public IDataReader < ElemType > <nl> / / figure out the dimension of the data <nl> std : : wstring val = iter - > first ; <nl> size_t rows = ( * m_dimensions ) [ val ] ; <nl> - / / size_t count = rows * recordCount ; <nl> + / / size_t count = rows * recordCount ; <nl> <nl> / / find the output matrix we want to fill <nl> auto iterIn = matrices . find ( val ) ; <nl> class EvalReader : public IDataReader < ElemType > <nl> <nl> / / copy over the data <nl> std : : vector < ElemType > * data = iter - > second ; <nl> - / / size_t = m_currentRecord * rows ; <nl> + / / size_t = m_currentRecord * rows ; <nl> void * mat = & ( * matrix ) ( 0 , 0 ) ; <nl> size_t matSize = matrix - > GetNumElements ( ) * sizeof ( ElemType ) ; <nl> void * dataPtr = ( void * ) ( ( ElemType * ) data - > data ( ) + m_currentRecord * rows ) ; <nl> class EvalReader : public IDataReader < ElemType > <nl> / / start the new sequence <nl> / / We use a fake end of 1 frame beyond the actual end of the minibatch . <nl> pMBLayout - > AddSequence ( 0 , 0 , m_switchFrame [ 0 ] , m_mbSize + 1 ) ; <nl> - / / pMBLayout - > Set ( 0 , m_switchFrame [ 0 ] , MinibatchPackingFlags : : SequenceStart ) ; <nl> - / / if ( m_switchFrame [ 0 ] > 0 ) <nl> + / / pMBLayout - > Set ( 0 , m_switchFrame [ 0 ] , MinibatchPackingFlags : : SequenceStart ) ; <nl> + / / if ( m_switchFrame [ 0 ] > 0 ) <nl> / / pMBLayout - > Set ( 0 , m_switchFrame [ 0 ] - 1 , MinibatchPackingFlags : : SequenceEnd ) ; / / TODO : can ' t we use Set ( ) ? <nl> } <nl> else / / all frames in this MB belong to the same utterance <nl> mmm a / Source / EvalDll / EvalWriter . h <nl> ppp b / Source / EvalDll / EvalWriter . h <nl> class EvalWriter : public IDataWriter < ElemType > <nl> / / figure out the dimension of the data <nl> std : : wstring val = iter - > first ; <nl> size_t rows = ( * m_dimensions ) [ val ] ; <nl> - / / size_t count = rows * numRecords ; <nl> + / / size_t count = rows * numRecords ; <nl> <nl> / / find the output matrix we want to fill <nl> const std : : map < std : : wstring , void * , nocase_compare > : : const_iterator iterIn = matrices . find ( val ) ; <nl> mmm a / Source / Math / CPUMatrix . cpp <nl> ppp b / Source / Math / CPUMatrix . cpp <nl> <nl> # include < mkl . h > <nl> # endif <nl> <nl> - # ifndef USE_MKL / / MKL has one additional parameter for different matrix order <nl> + # ifndef USE_MKL / / MKL has one additional parameter for different matrix order <nl> # define BLAS_COLMAJOR <nl> # else <nl> # define BLAS_COLMAJOR ( int ) MatrixOrder : : ColMajor , <nl> enum class SymMatrixType : char <nl> { <nl> Up = ' U ' , / / symmetric matrix is stored in the upper part <nl> Low = ' L ' , / / symmetric matrix is stored in thelower part <nl> - Full = ' F ' , / / full populated <nl> - NotSymmetric = ' N ' / / not a symmetric matrix <nl> + Full = ' F ' , / / full populated <nl> + NotSymmetric = ' N ' / / not a symmetric matrix <nl> } ; <nl> <nl> enum class MatrixOpSide : char <nl> template < class ElemType > <nl> static ElemType * NewArray ( size_t n ) <nl> { <nl> ElemType * p = new ElemType [ n ] ( ) ; <nl> - # if 0 / / _DEBUG <nl> + # if 0 / / _DEBUG <nl> ElemType nan = Matrix < ElemType > : : MakeNan ( __LINE__ ) ; <nl> for ( size_t i = 0 ; i < n ; i + + ) <nl> p [ i ] = nan ; <nl> CPUMatrix < ElemType > : : CPUMatrix ( CPUMatrix < ElemType > & & moveFrom ) <nl> m_numRows = moveFrom . m_numRows ; <nl> m_numCols = moveFrom . m_numCols ; <nl> m_elemSizeAllocated = moveFrom . m_elemSizeAllocated ; <nl> - m_pArray = moveFrom . m_pArray ; / / shallow copy the pointer <nl> + m_pArray = moveFrom . m_pArray ; / / shallow copy the pointer <nl> m_matrixName = moveFrom . m_matrixName ; <nl> m_format = moveFrom . m_format ; <nl> m_externalBuffer = moveFrom . m_externalBuffer ; <nl> - / / release the pointer from the source object so that the destructor won ' t release it twice <nl> + / / release the pointer from the source object so that the destructor won ' t release it twice <nl> moveFrom . ZeroInit ( ) ; <nl> } <nl> <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : operator = ( CPUMatrix < ElemType > & & moveFr <nl> if ( this ! = & moveFrom ) <nl> { <nl> if ( OwnBuffer ( ) & & m_pArray ! = nullptr ) <nl> - delete [ ] m_pArray ; / / always delete the data pointer since we will use the pointer from moveFrom <nl> + delete [ ] m_pArray ; / / always delete the data pointer since we will use the pointer from moveFrom <nl> <nl> m_computeDevice = moveFrom . m_computeDevice ; <nl> m_numRows = moveFrom . m_numRows ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : operator = ( CPUMatrix < ElemType > & & moveFr <nl> m_format = moveFrom . m_format ; <nl> m_externalBuffer = moveFrom . m_externalBuffer ; <nl> <nl> - / / release the pointer from the source object so that the destructor won ' t release it twice <nl> + / / release the pointer from the source object so that the destructor won ' t release it twice <nl> moveFrom . ZeroInit ( ) ; <nl> } <nl> return * this ; <nl> void CPUMatrix < ElemType > : : Clear ( ) <nl> template < class ElemType > <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : ColumnSlice ( size_t startColumn , size_t numCols ) const <nl> { <nl> - / / if ( numCols = = 0 ) <nl> + / / if ( numCols = = 0 ) <nl> / / LogicError ( " The slice cannot have 0 columns . " ) ; <nl> <nl> if ( startColumn + numCols > m_numCols ) <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : ColumnSlice ( size_t startColumn , size_t <nl> <nl> CPUMatrix < ElemType > slice ; <nl> <nl> - slice . m_externalBuffer = true ; / / memory of a slice is managed externally . <nl> + slice . m_externalBuffer = true ; / / memory of a slice is managed externally . <nl> slice . m_numRows = m_numRows ; <nl> slice . m_numCols = numCols ; <nl> slice . m_elemSizeAllocated = slice . GetNumElements ( ) ; <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : ColumnSlice ( size_t startColumn , size_t <nl> template < class ElemType > <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignColumnSlice ( const CPUMatrix < ElemType > & fromMatrix , size_t startColumn , size_t numCols ) <nl> { <nl> - / / if ( numCols = = 0 ) <nl> + / / if ( numCols = = 0 ) <nl> / / LogicError ( " The slice cannot have 0 columns . " ) ; <nl> <nl> if ( startColumn + numCols > fromMatrix . m_numCols ) <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignColumnSlice ( const CPUMatrix < Elem <nl> <nl> Clear ( ) ; <nl> <nl> - SetOwnBuffer ( false ) ; / / memory of a slice is managed externally . <nl> + SetOwnBuffer ( false ) ; / / memory of a slice is managed externally . <nl> m_numRows = fromMatrix . m_numRows ; <nl> m_numCols = numCols ; <nl> m_elemSizeAllocated = GetNumElements ( ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignColumnSlice ( const CPUMatrix < Elem <nl> template < class ElemType > <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : SetColumnSlice ( const CPUMatrix < ElemType > & fromMatrix , size_t startColumn , size_t numCols ) <nl> { <nl> - / / if ( numCols = = 0 ) <nl> + / / if ( numCols = = 0 ) <nl> / / LogicError ( " The slice cannot have 0 columns . " ) ; <nl> if ( startColumn + numCols > m_numCols ) <nl> LogicError ( " The slice is out of range of the destination matrix . " ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : SetColumnSlice ( const CPUMatrix < ElemTyp <nl> if ( m_numRows ! = fromMatrix . m_numRows ) <nl> LogicError ( " The number of rows in source and destination matrices do not match " ) ; <nl> <nl> - / / SetOwnBuffer ( false ) ; <nl> + / / SetOwnBuffer ( false ) ; <nl> memcpy ( m_pArray + startColumn * m_numRows , fromMatrix . m_pArray , numCols * m_numRows * sizeof ( ElemType ) ) ; <nl> <nl> return * this ; <nl> void CPUMatrix < ElemType > : : CopyColumnsStrided ( const CPUMatrix < ElemType > & fromMatr <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( size_t i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j * destNumColsStride ) = fromMatrix ( i , j * srcNumColsStride ) ; <nl> void CPUMatrix < ElemType > : : CopyColumnsStrided ( const CPUMatrix < ElemType > & fromMatr <nl> us ( i + 3 , j * destNumColsStride ) = fromMatrix ( i + 3 , j * srcNumColsStride ) ; <nl> } <nl> <nl> - / / handle remaining <nl> + / / handle remaining <nl> for ( size_t i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j * destNumColsStride ) = fromMatrix ( i , j * srcNumColsStride ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignToRowSliceValuesOf ( const CPUMatr <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( size_t i = 0 , startRow = startIndex ; i < ( m & ~ 3 ) ; i + = 4 , startRow + = 4 ) <nl> { <nl> us ( startRow , j ) = a ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignToRowSliceValuesOf ( const CPUMatr <nl> us ( startRow + 2 , j ) = a ( i + 2 , j ) ; <nl> us ( startRow + 3 , j ) = a ( i + 3 , j ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( size_t i = m & ~ 3 , startRow = startIndex + ( m & ~ 3 ) ; i < m ; i + + , startRow + + ) <nl> { <nl> us ( startRow , j ) = a ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignRowSliceValuesOf ( const CPUMatrix <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / memory copy might be faster ? <nl> + / / memory copy might be faster ? <nl> memcpy ( m_pArray + j * numRows , a . m_pArray + j * k + startIndex , sizeof ( ElemType ) * numRows ) ; <nl> <nl> - / / / / four - way unrolling <nl> - / / for ( long i = 0 , startRow = startIndex ; i < ( m & ~ 3 ) ; i + = 4 , startRow + = 4 ) <nl> - / / { <nl> + / / / / four - way unrolling <nl> + / / for ( long i = 0 , startRow = startIndex ; i < ( m & ~ 3 ) ; i + = 4 , startRow + = 4 ) <nl> + / / { <nl> / / us ( i , j ) = a ( startRow , j ) ; <nl> / / us ( i + 1 , j ) = a ( startRow + 1 , j ) ; <nl> / / us ( i + 2 , j ) = a ( startRow + 2 , j ) ; <nl> / / us ( i + 3 , j ) = a ( startRow + 3 , j ) ; <nl> - / / } <nl> - / / / / handle remaining stuffs <nl> - / / for ( long i = m & ~ 3 , startRow = startIndex + ( m & ~ 3 ) ; i < m ; i + + , startRow + + ) <nl> - / / { <nl> + / / } <nl> + / / / / handle remaining stuffs <nl> + / / for ( long i = m & ~ 3 , startRow = startIndex + ( m & ~ 3 ) ; i < m ; i + + , startRow + + ) <nl> + / / { <nl> / / us ( i , j ) = a ( startRow , j ) ; <nl> - / / } <nl> + / / } <nl> } <nl> <nl> return * this ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AddToRowSliceValuesOf ( const CPUMatrix < <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 , startRow = ( long ) startIndex ; i < ( m & ~ 3 ) ; i + = 4 , startRow + = 4 ) <nl> { <nl> us ( startRow , j ) + = a ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AddToRowSliceValuesOf ( const CPUMatrix < <nl> us ( startRow + 2 , j ) + = a ( i + 2 , j ) ; <nl> us ( startRow + 3 , j ) + = a ( i + 3 , j ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 , startRow = ( long ) startIndex + ( m & ~ 3 ) ; i < m ; i + + , startRow + + ) <nl> { <nl> us ( startRow , j ) + = a ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AddWithRowSliceValuesOf ( const CPUMatri <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 , startRow = ( long ) startIndex ; i < ( m & ~ 3 ) ; i + = 4 , startRow + = 4 ) <nl> { <nl> us ( i , j ) + = a ( startRow , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AddWithRowSliceValuesOf ( const CPUMatri <nl> us ( i + 2 , j ) + = a ( startRow + 2 , j ) ; <nl> us ( i + 3 , j ) + = a ( startRow + 3 , j ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 , startRow = ( long ) startIndex + ( m & ~ 3 ) ; i < m ; i + + , startRow + + ) <nl> { <nl> us ( i , j ) + = a ( startRow , j ) ; <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : Diagonal ( ) const <nl> } <nl> <nl> # if 0 <nl> - / / stack the columns in inputMatrices ( starting from sliceStartCol for sliceNumCols columns ) and assign it to [ this ] object . <nl> + / / stack the columns in inputMatrices ( starting from sliceStartCol for sliceNumCols columns ) and assign it to [ this ] object . <nl> template < class ElemType > <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignRowStackValuesOf ( const std : : vector < const CPUMatrix < ElemType > * > & inputMatrices , const size_t sliceStartCol , const size_t sliceNumCols ) <nl> { <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignRepeatOf ( const CPUMatrix < ElemTyp <nl> { <nl> long rowOffset = p * m ; <nl> <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 , rowOffset + = 4 ) <nl> { <nl> us ( rowOffset , colOffset ) = a ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignRepeatOf ( const CPUMatrix < ElemTyp <nl> us ( rowOffset + 2 , colOffset ) = a ( i + 2 , j ) ; <nl> us ( rowOffset + 3 , colOffset ) = a ( i + 3 , j ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + , rowOffset + + ) <nl> { <nl> us ( rowOffset , colOffset ) = a ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AddToRowRepeatValuesOf ( const CPUMatrix <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> for ( long k = 0 ; k < numRepeats ; k + + ) <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AddToRowRepeatValuesOf ( const CPUMatrix <nl> us ( i + 3 , j ) + = a ( k * m + i + 3 , j ) ; <nl> } <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> for ( long k = 0 ; k < numRepeats ; k + + ) <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignTransposeOf ( const CPUMatrix < Elem <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( j , i ) = a ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignTransposeOf ( const CPUMatrix < Elem <nl> us ( j , i + 2 ) = a ( i + 2 , j ) ; <nl> us ( j , i + 3 ) = a ( i + 3 , j ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( j , i ) = a ( i , j ) ; <nl> void CPUMatrix < ElemType > : : SetValue ( const ElemType v ) <nl> / / operation of just setting the values of an array . <nl> const unsigned SETVALUE_NUM_THREADS = 2 ; <nl> # pragma omp parallel for num_threads ( SETVALUE_NUM_THREADS ) <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> m_pArray [ i ] = v ; <nl> void CPUMatrix < ElemType > : : SetValue ( const ElemType v ) <nl> m_pArray [ i + 2 ] = v ; <nl> m_pArray [ i + 3 ] = v ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> m_pArray [ i ] = v ; <nl> void CPUMatrix < ElemType > : : MaskColumnsValue ( const CPUMatrix < char > & columnsMask , E <nl> if ( columnsMask ( 0 , j ) = = 1 ) <nl> continue ; <nl> <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( size_t i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) = val ; <nl> void CPUMatrix < ElemType > : : MaskColumnsValue ( const CPUMatrix < char > & columnsMask , E <nl> us ( i + 3 , j ) = val ; <nl> } <nl> <nl> - / / handle remaining <nl> + / / handle remaining <nl> for ( size_t i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) = val ; <nl> void CPUMatrix < ElemType > : : SetColumn ( const ElemType * colPointer , size_t j ) <nl> auto & us = * this ; <nl> long m = ( long ) GetNumRows ( ) ; <nl> # pragma omp parallel for <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) = colPointer [ i ] ; <nl> void CPUMatrix < ElemType > : : SetColumn ( const ElemType * colPointer , size_t j ) <nl> us ( i + 2 , j ) = colPointer [ i + 2 ] ; <nl> us ( i + 3 , j ) = colPointer [ i + 3 ] ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) = colPointer [ i ] ; <nl> void CPUMatrix < ElemType > : : SetColumn ( const ElemType val , size_t j ) <nl> auto & us = * this ; <nl> long m = ( long ) GetNumRows ( ) ; <nl> # pragma omp parallel for <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) = val ; <nl> void CPUMatrix < ElemType > : : SetColumn ( const ElemType val , size_t j ) <nl> us ( i + 2 , j ) = val ; <nl> us ( i + 3 , j ) = val ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) = val ; <nl> void CPUMatrix < ElemType > : : SetColumn ( const CPUMatrix < ElemType > & valMat , size_t j ) <nl> auto & us = * this ; <nl> long m = ( long ) GetNumRows ( ) ; <nl> # pragma omp parallel for <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) = valMat ( i , 0 ) ; <nl> void CPUMatrix < ElemType > : : SetColumn ( const CPUMatrix < ElemType > & valMat , size_t j ) <nl> us ( i + 2 , j ) = valMat ( i + 2 , 0 ) ; <nl> us ( i + 3 , j ) = valMat ( i + 3 , 0 ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) = valMat ( i , 0 ) ; <nl> void CPUMatrix < ElemType > : : SetValue ( const size_t numRows , const size_t numCols , E <nl> } <nl> else <nl> { <nl> - if ( ! ( matrixFlags & matrixFormatRowMajor ) ) / / compatible to internal structure <nl> + if ( ! ( matrixFlags & matrixFormatRowMajor ) ) / / compatible to internal structure <nl> { <nl> memcpy ( m_pArray , pArray , GetNumElements ( ) * sizeof ( ElemType ) ) ; <nl> } <nl> - else / / need to transpose <nl> + else / / need to transpose <nl> { <nl> auto & us = * this ; <nl> if ( sizeof ( ElemType ) = = sizeof ( double ) ) <nl> void CPUMatrix < ElemType > : : SetDiagonalValue ( const ElemType v ) <nl> auto & us = * this ; <nl> long m = ( long ) GetNumRows ( ) ; <nl> # pragma omp parallel for <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , i ) = v ; <nl> void CPUMatrix < ElemType > : : SetDiagonalValue ( const ElemType v ) <nl> us ( i + 2 , i + 2 ) = v ; <nl> us ( i + 3 , i + 3 ) = v ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , i ) = v ; <nl> void CPUMatrix < ElemType > : : SetDiagonalValue ( const CPUMatrix < ElemType > & vector ) <nl> if ( vector . GetNumRows ( ) ! = 1 & & vector . GetNumCols ( ) ! = 1 ) <nl> LogicError ( " SetDiagonalValue : input vector must be a vector . " ) ; <nl> <nl> - if ( vector . GetNumElements ( ) = = 1 ) / / reduce to simple form <nl> + if ( vector . GetNumElements ( ) = = 1 ) / / reduce to simple form <nl> SetDiagonalValue ( vector ( 0 , 0 ) ) ; <nl> else if ( vector . GetNumRows ( ) ! = GetNumRows ( ) ) <nl> LogicError ( " SetDiagonalValue : input vector ' s dimension does not agree with [ this ] . " ) ; <nl> void CPUMatrix < ElemType > : : SetDiagonalValue ( const CPUMatrix < ElemType > & vector ) <nl> auto & us = * this ; <nl> <nl> long m = ( long ) GetNumRows ( ) ; <nl> - if ( vector . GetNumRows ( ) = = 1 ) / / row vector <nl> + if ( vector . GetNumRows ( ) = = 1 ) / / row vector <nl> { <nl> # pragma omp parallel for <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , i ) = vector ( 0 , i ) ; <nl> void CPUMatrix < ElemType > : : SetDiagonalValue ( const CPUMatrix < ElemType > & vector ) <nl> us ( i + 2 , i + 2 ) = vector ( 0 , i + 2 ) ; <nl> us ( i + 3 , i + 3 ) = vector ( 0 , i + 3 ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , i ) = vector ( 0 , i ) ; <nl> void CPUMatrix < ElemType > : : SetDiagonalValue ( const CPUMatrix < ElemType > & vector ) <nl> else <nl> { <nl> # pragma omp parallel for <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , i ) = vector ( i , 0 ) ; <nl> void CPUMatrix < ElemType > : : SetDiagonalValue ( const CPUMatrix < ElemType > & vector ) <nl> us ( i + 2 , i + 2 ) = vector ( i + 2 , 0 ) ; <nl> us ( i + 3 , i + 3 ) = vector ( i + 3 , 0 ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , i ) = vector ( i , 0 ) ; <nl> void CPUMatrix < ElemType > : : SetUniformRandomValue ( const ElemType low , const ElemTy <nl> std : : uniform_real_distribution < ElemType > r ( low , high ) ; <nl> <nl> long m = ( long ) GetNumElements ( ) ; <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> m_pArray [ i ] = r ( generator ) ; <nl> void CPUMatrix < ElemType > : : SetUniformRandomValue ( const ElemType low , const ElemTy <nl> m_pArray [ i + 2 ] = r ( generator ) ; <nl> m_pArray [ i + 3 ] = r ( generator ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> m_pArray [ i ] = r ( generator ) ; <nl> void CPUMatrix < ElemType > : : SetGaussianRandomValue ( const ElemType mean , const Elem <nl> std : : default_random_engine generator ( seed ) ; <nl> # endif <nl> std : : normal_distribution < ElemType > r ( mean , sigma ) ; <nl> - / / # pragma omp parallel for / / is it thread safe ? <nl> + / / # pragma omp parallel for / / is it thread safe ? <nl> foreach_coord ( i , j , us ) <nl> { <nl> us ( i , j ) = r ( generator ) ; <nl> void CPUMatrix < ElemType > : : AddGaussianRandomValue ( const ElemType mean , const Elem <nl> long m = ( long ) GetNumRows ( ) , n = ( long ) GetNumCols ( ) ; <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) = r ( generator ) ; <nl> void CPUMatrix < ElemType > : : AddGaussianRandomValue ( const ElemType mean , const Elem <nl> us ( i + 2 , j ) = r ( generator ) ; <nl> us ( i + 3 , j ) = r ( generator ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) = r ( generator ) ; <nl> void CPUMatrix < ElemType > : : SetUniformRandomMask ( const ElemType maskRate , const El <nl> ElemType v ; <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> v = r ( generator ) ; <nl> void CPUMatrix < ElemType > : : SetUniformRandomMask ( const ElemType maskRate , const El <nl> v = r ( generator ) ; <nl> us ( i + 3 , j ) = v < = maskRate ? 0 : scaleValue ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> v = r ( generator ) ; <nl> ElemType CPUMatrix < ElemType > : : Adagrad ( CPUMatrix < ElemType > & gradients , const bool <nl> const ElemType floor = 1e - 16f ; <nl> ElemType a0 , a1 , a2 , a3 ; <nl> <nl> - / / disable omp here because aveMultiper needs to be added atomically . however , it seems the result is incorrect even if rmp atomic and amp critical are used . <nl> - / / # pragma omp parallel for <nl> - for ( long i = 0 ; i < ( n & ~ 3 ) ; i + = 4 ) / / four - way unrolling <nl> + / / disable omp here because aveMultiper needs to be added atomically . however , it seems the result is incorrect even if rmp atomic and amp critical are used . <nl> + / / # pragma omp parallel for <nl> + for ( long i = 0 ; i < ( n & ~ 3 ) ; i + = 4 ) / / four - way unrolling <nl> { <nl> a [ i ] + = d_v [ i ] * d_v [ i ] ; <nl> a [ i + 1 ] + = d_v [ i + 1 ] * d_v [ i + 1 ] ; <nl> ElemType CPUMatrix < ElemType > : : RmsProp ( CPUMatrix < ElemType > & gradients , <nl> assert ( GetNumRows ( ) = = gradients . GetNumRows ( ) & & GetNumCols ( ) = = gradients . GetNumCols ( ) * 3 ) ; <nl> <nl> ElemType ONE_MINUS_GAMMA = ElemType ( 1 . 0 ) - RMS_GAMMA ; <nl> - / / int upd [ ] = { <nl> + / / int upd [ ] = { <nl> / / 2 , 2 , 0 , <nl> / / 2 , 2 , 0 , <nl> / / 1 , 1 , 1 , <nl> ElemType CPUMatrix < ElemType > : : RmsProp ( CPUMatrix < ElemType > & gradients , <nl> / / 1 , 1 , 1 , <nl> / / 0 , 2 , 2 , <nl> / / 0 , 2 , 2 , <nl> - / / } ; <nl> + / / } ; <nl> <nl> / / for ( long i = 0 ; i < n ; i + + ) <nl> / / { <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignSumOf ( const ElemType alpha , cons <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) = alpha + a ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignSumOf ( const ElemType alpha , cons <nl> us ( i + 2 , j ) = alpha + a ( i + 2 , j ) ; <nl> us ( i + 3 , j ) = alpha + a ( i + 3 , j ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) = alpha + a ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignSumOf ( const ElemType alpha , cons <nl> template < class ElemType > <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : operator + = ( const CPUMatrix < ElemType > & a ) <nl> { <nl> - / / if ( a . GetNumElements ( ) = = 1 ) <nl> + / / if ( a . GetNumElements ( ) = = 1 ) <nl> / / * this + = a ( 0 , 0 ) ; <nl> - / / else <nl> + / / else <nl> ScaleAndAdd ( 1 , a , * this ) ; <nl> <nl> return * this ; <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : operator + ( const CPUMatrix < ElemType > & a ) <nl> } <nl> else <nl> { <nl> - CPUMatrix < ElemType > c ( * this ) ; / / this implementation will introduce a copy overhead . but make resue of the code <nl> + CPUMatrix < ElemType > c ( * this ) ; / / this implementation will introduce a copy overhead . but make resue of the code <nl> c + = a ; <nl> return c ; <nl> } <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignDifferenceOf ( const ElemType alph <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) = alpha - a ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignDifferenceOf ( const ElemType alph <nl> us ( i + 2 , j ) = alpha - a ( i + 2 , j ) ; <nl> us ( i + 3 , j ) = alpha - a ( i + 3 , j ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) = alpha - a ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignDifferenceOf ( const CPUMatrix < Ele <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) = a ( i , j ) - alpha ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignDifferenceOf ( const CPUMatrix < Ele <nl> us ( i + 2 , j ) = a ( i + 2 , j ) - alpha ; <nl> us ( i + 3 , j ) = a ( i + 3 , j ) - alpha ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) = a ( i , j ) - alpha ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : operator - = ( const CPUMatrix < ElemType > & <nl> template < class ElemType > <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : operator - ( const CPUMatrix < ElemType > & a ) const <nl> { <nl> - CPUMatrix < ElemType > c ( * this ) ; / / this implementation will introduce a copy overhead . but make resue of the code <nl> + CPUMatrix < ElemType > c ( * this ) ; / / this implementation will introduce a copy overhead . but make resue of the code <nl> c - = a ; <nl> return c ; <nl> } <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignElementProductOf ( const CPUMatrix <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) = a ( i , j ) * b ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignElementProductOf ( const CPUMatrix <nl> us ( i + 2 , j ) = a ( i + 2 , j ) * b ( i + 2 , j ) ; <nl> us ( i + 3 , j ) = a ( i + 3 , j ) * b ( i + 3 , j ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) = a ( i , j ) * b ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AddElementProductOf ( const CPUMatrix < El <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) + = a ( i , j ) * b ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AddElementProductOf ( const CPUMatrix < El <nl> us ( i + 2 , j ) + = a ( i + 2 , j ) * b ( i + 2 , j ) ; <nl> us ( i + 3 , j ) + = a ( i + 3 , j ) * b ( i + 3 , j ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) + = a ( i , j ) * b ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : ColumnElementMultiplyWith ( const CPUMat <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) * = a ( i , 0 ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : ColumnElementMultiplyWith ( const CPUMat <nl> us ( i + 2 , j ) * = a ( i + 2 , 0 ) ; <nl> us ( i + 3 , j ) * = a ( i + 3 , 0 ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) * = a ( i , 0 ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : RowElementMultiplyWith ( const CPUMatrix <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> ElemType v = a ( 0 , j ) ; <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) * = v ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : RowElementMultiplyWith ( const CPUMatrix <nl> us ( i + 2 , j ) * = v ; <nl> us ( i + 3 , j ) * = v ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) * = v ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : RowElementDivideBy ( const CPUMatrix < Ele <nl> else if ( v < 0 & & v > - EPS_IN_INVERSE ) <nl> v = ( - EPS_IN_INVERSE ) ; <nl> <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) / = v ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : RowElementDivideBy ( const CPUMatrix < Ele <nl> us ( i + 2 , j ) / = v ; <nl> us ( i + 3 , j ) / = v ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) / = v ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignLinearRectifierDerivativeOf ( cons <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) = a ( i , j ) > 0 . 0f ? 1 . 0f : 0 . 0f ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignLinearRectifierDerivativeOf ( cons <nl> us ( i + 2 , j ) = a ( i + 2 , j ) > 0 . 0f ? 1 . 0f : 0 . 0f ; <nl> us ( i + 3 , j ) = a ( i + 3 , j ) > 0 . 0f ? 1 . 0f : 0 . 0f ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) = a ( i , j ) > 0 . 0f ? 1 . 0f : 0 . 0f ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignSigmoidDerivativeOf ( const CPUMat <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> ElemType v = a ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignSigmoidDerivativeOf ( const CPUMat <nl> ElemType v3 = a ( i + 3 , j ) ; <nl> us ( i + 3 , j ) = v3 * ( 1 - v3 ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> ElemType v = a ( i , j ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignTanhOf ( const CPUMatrix < ElemType > <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) = tanh ( a ( i , j ) ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignTanhOf ( const CPUMatrix < ElemType > <nl> us ( i + 2 , j ) = tanh ( a ( i + 2 , j ) ) ; <nl> us ( i + 3 , j ) = tanh ( a ( i + 3 , j ) ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) = tanh ( a ( i , j ) ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignLogSoftmaxOf ( const CPUMatrix < Ele <nl> # pragma omp parallel for <nl> foreach_column ( j , a ) <nl> { <nl> - / / we need to extract max before applying exp to avoid overflow <nl> + / / we need to extract max before applying exp to avoid overflow <nl> ElemType maxV = a ( 0 , j ) ; <nl> foreach_row ( i , a ) <nl> maxV = max ( maxV , a ( i , j ) ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignLogSoftmaxOf ( const CPUMatrix < Ele <nl> # pragma omp parallel for <nl> foreach_row ( i , a ) <nl> { <nl> - / / we need to extract max before applying exp to avoid overflow <nl> + / / we need to extract max before applying exp to avoid overflow <nl> ElemType maxV = a ( i , 0 ) ; <nl> foreach_column ( j , a ) <nl> maxV = max ( maxV , a ( i , j ) ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignHardmaxOf ( const CPUMatrix < ElemTy <nl> # pragma omp parallel for <nl> foreach_column ( j , a ) <nl> { <nl> - / / we need to extract max <nl> + / / we need to extract max <nl> ElemType maxV = a ( 0 , j ) ; <nl> long maxI = 0 ; <nl> foreach_row ( i , a ) <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignHardmaxOf ( const CPUMatrix < ElemTy <nl> # pragma omp parallel for <nl> foreach_row ( i , a ) <nl> { <nl> - / / we need to extract max <nl> + / / we need to extract max <nl> ElemType maxV = a ( i , 0 ) ; <nl> long maxJ = 0 ; <nl> foreach_column ( j , a ) <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignExpOf ( const CPUMatrix < ElemType > & <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) = exp ( a ( i , j ) ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignExpOf ( const CPUMatrix < ElemType > & <nl> us ( i + 2 , j ) = exp ( a ( i + 2 , j ) ) ; <nl> us ( i + 3 , j ) = exp ( a ( i + 3 , j ) ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) = exp ( a ( i , j ) ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignAbsOf ( const CPUMatrix < ElemType > & <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> us ( i , j ) = abs ( a ( i , j ) ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignAbsOf ( const CPUMatrix < ElemType > & <nl> us ( i + 2 , j ) = abs ( a ( i + 2 , j ) ) ; <nl> us ( i + 3 , j ) = abs ( a ( i + 3 , j ) ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> us ( i , j ) = abs ( a ( i , j ) ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : InplaceTruncateBottom ( const ElemType t <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> if ( us ( i , j ) < threshold ) <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : InplaceTruncateBottom ( const ElemType t <nl> if ( us ( i + 3 , j ) < threshold ) <nl> us ( i + 3 , j ) = threshold ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> if ( us ( i , j ) < threshold ) <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : InplaceTruncate ( const ElemType thresho <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> if ( us ( i , j ) > locThresholdPos ) <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : InplaceTruncate ( const ElemType thresho <nl> else if ( us ( i + 3 , j ) < locTHresholdNeg ) <nl> us ( i + 3 , j ) = locTHresholdNeg ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> if ( us ( i , j ) > locThresholdPos ) <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : InplaceSoftThreshold ( const ElemType th <nl> long m = ( long ) GetNumElements ( ) ; <nl> <nl> # pragma omp parallel for <nl> - for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) / / four - way unrolling <nl> + for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) / / four - way unrolling <nl> { <nl> if ( m_pArray [ i ] > threshold ) <nl> m_pArray [ i ] - = threshold ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : InplaceSoftThreshold ( const ElemType th <nl> else <nl> m_pArray [ i + 3 ] = 0 ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> if ( m_pArray [ i ] > threshold ) <nl> ElemType CPUMatrix < ElemType > : : SumOfElements ( ) const <nl> { <nl> sum + = m_pArray [ i ] + m_pArray [ i + 1 ] + m_pArray [ i + 2 ] + m_pArray [ i + 3 ] ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> sum + = m_pArray [ i ] ; <nl> void CPUMatrix < ElemType > : : VectorSum ( const CPUMatrix < ElemType > & a , CPUMatrix < Elem <nl> const int m = ( int ) a . GetNumRows ( ) ; <nl> const int n = ( int ) a . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> - if ( isColWise ) / / col - wise <nl> + if ( isColWise ) / / col - wise <nl> { <nl> c . Resize ( 1 , n ) ; <nl> <nl> void CPUMatrix < ElemType > : : VectorNorm1 ( CPUMatrix < ElemType > & c , const bool isColWi <nl> const int m = ( int ) us . GetNumRows ( ) ; <nl> const int n = ( int ) us . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> - if ( isColWise ) / / col - wise <nl> + if ( isColWise ) / / col - wise <nl> { <nl> c . Resize ( 1 , n ) ; <nl> <nl> void CPUMatrix < ElemType > : : VectorNorm2 ( CPUMatrix < ElemType > & c , const bool isColWi <nl> const int m = ( int ) us . GetNumRows ( ) ; <nl> const int n = ( int ) us . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> - if ( isColWise ) / / col - wise <nl> + if ( isColWise ) / / col - wise <nl> { <nl> c . Resize ( 1 , n ) ; <nl> <nl> void CPUMatrix < ElemType > : : VectorNormInf ( CPUMatrix < ElemType > & c , const bool isCol <nl> const int m = ( int ) us . GetNumRows ( ) ; <nl> const int n = ( int ) us . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> - if ( isColWise ) / / col - wise <nl> + if ( isColWise ) / / col - wise <nl> { <nl> c . Resize ( 1 , n ) ; <nl> <nl> - / / # pragma omp parallel for <nl> + / / # pragma omp parallel for <nl> foreach_column ( j , us ) <nl> { <nl> ElemType v = 0 ; <nl> void CPUMatrix < ElemType > : : VectorNormInf ( CPUMatrix < ElemType > & c , const bool isCol <nl> { <nl> c . Resize ( m , 1 ) ; <nl> <nl> - / / # pragma omp parallel for <nl> + / / # pragma omp parallel for <nl> foreach_row ( i , us ) <nl> { <nl> ElemType v = 0 ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AddColumnReshapeProductOf ( const CPUMat <nl> <nl> if ( transposeAColumn ) <nl> { <nl> - / / find nrows and ncols of tbe reshaped a <nl> + / / find nrows and ncols of tbe reshaped a <nl> long nrows = rowsB ; <nl> long ncols = rowsC ; <nl> <nl> ElemType CPUMatrix < ElemType > : : FrobeniusNorm ( ) const <nl> { <nl> v + = m_pArray [ i ] * m_pArray [ i ] + m_pArray [ i + 1 ] * m_pArray [ i + 1 ] + m_pArray [ i + 2 ] * m_pArray [ i + 2 ] + m_pArray [ i + 3 ] * m_pArray [ i + 3 ] ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> v + = m_pArray [ i ] * m_pArray [ i ] ; <nl> void CPUMatrix < ElemType > : : VectorMax ( CPUMatrix < ElemType > & maxIndexes , CPUMatrix < E <nl> const int n = ( int ) GetNumCols ( ) ; <nl> assert ( topK < = m ) ; <nl> <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> - if ( isColWise ) / / col - wise <nl> + if ( isColWise ) / / col - wise <nl> { <nl> maxValues . Resize ( topK , n ) ; <nl> maxIndexes . Resize ( topK , n ) ; <nl> void CPUMatrix < ElemType > : : VectorMax ( CPUMatrix < ElemType > & maxIndexes , CPUMatrix < E <nl> return curVal [ a ] > curVal [ b ] ; <nl> } ) ; <nl> / / REVIEW alexeyk : the following produces warning ( see SCL_SECURE_NO_WARNINGS ) so use loop instead . <nl> - / / std : : transform ( indices . begin ( ) , indices . begin ( ) + topK , curIdx , [ ] ( const int & a ) { return static_cast < ElemType > ( a ) ; } ) ; <nl> + / / std : : transform ( indices . begin ( ) , indices . begin ( ) + topK , curIdx , [ ] ( const int & a ) { return static_cast < ElemType > ( a ) ; } ) ; <nl> for ( int i = 0 ; i < topK ; i + + ) <nl> { <nl> curIdx [ i ] = static_cast < ElemType > ( indices [ i ] ) ; <nl> void CPUMatrix < ElemType > : : VectorMin ( CPUMatrix < ElemType > & minIndexes , CPUMatrix < E <nl> const int m = ( int ) GetNumRows ( ) ; <nl> const int n = ( int ) GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> - if ( isColWise ) / / col - wise <nl> + if ( isColWise ) / / col - wise <nl> { <nl> minValues . Resize ( 1 , n ) ; <nl> minIndexes . Resize ( 1 , n ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignNumOfDiff ( const CPUMatrix < ElemTy <nl> } <nl> } <nl> <nl> - Resize ( 1 , 1 ) ; / / result should be one element <nl> + Resize ( 1 , 1 ) ; / / result should be one element <nl> ( * this ) ( 0 , 0 ) = n ; <nl> <nl> return * this ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignPackedConvolutionInput ( const CPU <nl> assert ( verticalSubsample < = kernelHeight & & horizontalSubsample < = kernelWidth ) ; <nl> <nl> const size_t packedInputRows = kernelWidth * kernelHeight * inputChannels ; <nl> - const size_t packedInputColsPerSample = outputWidth * outputHeight ; / / output size per channel <nl> + const size_t packedInputColsPerSample = outputWidth * outputHeight ; / / output size per channel <nl> const size_t inputDim = inputWidth * inputHeight * inputChannels ; <nl> const size_t smallBatchSize = inputSubBatch . GetNumCols ( ) ; <nl> const long inputHeightTimesChannel = ( long ) ( inputHeight * inputChannels ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignPackedConvolutionInput ( const CPU <nl> const long halfKernelWidth = ( long ) kernelWidth / 2 ; <nl> const long halfKernelHeight = ( long ) kernelHeight / 2 ; <nl> <nl> - # pragma omp parallel for / / each input element is copied to many places <nl> + # pragma omp parallel for / / each input element is copied to many places <nl> for ( long sample = 0 ; sample < smallBatchSize ; sample + + ) <nl> { <nl> for ( long id = 0 ; id < inputDim ; id + + ) <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignPackedConvolutionInput ( const CPU <nl> / / IN_ELEM_ROWPOS ( channel , row , col ) = ( channel + ( row + col * inputHeight ) * inputChannels ) <nl> / / IN_ELEM_COLPOS = sample <nl> <nl> - const long y = id / inputHeightTimesChannel ; / / inputCol <nl> - const long nXC = id % inputHeightTimesChannel ; / / channel + inputRow * inputChannels <nl> - const long x = nXC / ( long ) inputChannels ; / / inputRow <nl> - const long c = nXC % ( long ) inputChannels ; / / channel <nl> + const long y = id / inputHeightTimesChannel ; / / inputCol <nl> + const long nXC = id % inputHeightTimesChannel ; / / channel + inputRow * inputChannels <nl> + const long x = nXC / ( long ) inputChannels ; / / inputRow <nl> + const long c = nXC % ( long ) inputChannels ; / / channel <nl> <nl> long x0 = 0 , y0 = 0 , x1 = 0 , y1 = 0 ; <nl> if ( zeroPadding ) <nl> { <nl> - x0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( x - ( ElemType ) kernelHeight + 1 . 0f + halfKernelHeight ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> - x1 = ( long ) ( x + halfKernelHeight - x0 * verticalSubsample ) ; / / first posxInKernel <nl> - y0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( y - ( ElemType ) kernelWidth + 1 . 0f + halfKernelWidth ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> - y1 = ( long ) ( y + halfKernelWidth - y0 * horizontalSubsample ) ; / / first posyInKernel <nl> + x0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( x - ( ElemType ) kernelHeight + 1 . 0f + halfKernelHeight ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> + x1 = ( long ) ( x + halfKernelHeight - x0 * verticalSubsample ) ; / / first posxInKernel <nl> + y0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( y - ( ElemType ) kernelWidth + 1 . 0f + halfKernelWidth ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> + y1 = ( long ) ( y + halfKernelWidth - y0 * horizontalSubsample ) ; / / first posyInKernel <nl> } <nl> else <nl> { <nl> - x0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( x - ( ElemType ) kernelHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> - x1 = ( long ) ( x - x0 * verticalSubsample ) ; / / first posxInKernel <nl> - y0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( y - ( ElemType ) kernelWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> - y1 = ( long ) ( y - y0 * horizontalSubsample ) ; / / first posyInKernel <nl> + x0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( x - ( ElemType ) kernelHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> + x1 = ( long ) ( x - x0 * verticalSubsample ) ; / / first posxInKernel <nl> + y0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( y - ( ElemType ) kernelWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> + y1 = ( long ) ( y - y0 * horizontalSubsample ) ; / / first posyInKernel <nl> } <nl> <nl> assert ( x1 > = 0 & & x1 < kernelHeight & & y1 > = 0 & & y1 < kernelWidth ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : UnpackConvolutionInput ( CPUMatrix < ElemT <nl> { <nl> assert ( verticalSubsample < = kernelHeight & & horizontalSubsample < = kernelWidth ) ; <nl> <nl> - const size_t packedInputColsPerSample = outputWidth * outputHeight ; / / output size per channel <nl> + const size_t packedInputColsPerSample = outputWidth * outputHeight ; / / output size per channel <nl> const size_t inputDim = inputWidth * inputHeight * inputChannels ; <nl> const size_t smallBatchSize = inputSubBatch . GetNumCols ( ) ; <nl> const long inputHeightTimesChannel = ( long ) ( inputHeight * inputChannels ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : UnpackConvolutionInput ( CPUMatrix < ElemT <nl> const long halfKernelWidth = ( long ) kernelWidth / 2 ; <nl> const long halfKernelHeight = ( long ) kernelHeight / 2 ; <nl> <nl> - # pragma omp parallel for / / each input element is copied to many places <nl> + # pragma omp parallel for / / each input element is copied to many places <nl> for ( long sample = 0 ; sample < smallBatchSize ; sample + + ) <nl> { <nl> for ( long id = 0 ; id < inputDim ; id + + ) <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : UnpackConvolutionInput ( CPUMatrix < ElemT <nl> / / IN_ELEM_ROWPOS ( channel , row , col ) = ( channel + ( row + col * inputHeight ) * inputChannels ) <nl> / / IN_ELEM_COLPOS = sample <nl> <nl> - const long y = id / inputHeightTimesChannel ; / / inputCol <nl> - const long nXC = id % inputHeightTimesChannel ; / / channel + inputRow * inputChannels <nl> - const long x = nXC / ( long ) inputChannels ; / / inputRow <nl> - const long c = nXC % ( long ) inputChannels ; / / channel <nl> + const long y = id / inputHeightTimesChannel ; / / inputCol <nl> + const long nXC = id % inputHeightTimesChannel ; / / channel + inputRow * inputChannels <nl> + const long x = nXC / ( long ) inputChannels ; / / inputRow <nl> + const long c = nXC % ( long ) inputChannels ; / / channel <nl> <nl> long x0 = 0 , y0 = 0 , x1 = 0 , y1 = 0 ; <nl> if ( zeroPadding ) <nl> { <nl> - x0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( x - ( ElemType ) kernelHeight + 1 . 0f + halfKernelHeight ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> - x1 = ( long ) ( x + halfKernelHeight - x0 * verticalSubsample ) ; / / first posxInKernel <nl> - y0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( y - ( ElemType ) kernelWidth + 1 . 0f + halfKernelWidth ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> - y1 = ( long ) ( y + halfKernelWidth - y0 * horizontalSubsample ) ; / / first posyInKernel <nl> + x0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( x - ( ElemType ) kernelHeight + 1 . 0f + halfKernelHeight ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> + x1 = ( long ) ( x + halfKernelHeight - x0 * verticalSubsample ) ; / / first posxInKernel <nl> + y0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( y - ( ElemType ) kernelWidth + 1 . 0f + halfKernelWidth ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> + y1 = ( long ) ( y + halfKernelWidth - y0 * horizontalSubsample ) ; / / first posyInKernel <nl> } <nl> else <nl> { <nl> - x0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( x - ( ElemType ) kernelHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> - x1 = ( long ) ( x - x0 * verticalSubsample ) ; / / first posxInKernel <nl> - y0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( y - ( ElemType ) kernelWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> - y1 = ( long ) ( y - y0 * horizontalSubsample ) ; / / first posyInKernel <nl> + x0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( x - ( ElemType ) kernelHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> + x1 = ( long ) ( x - x0 * verticalSubsample ) ; / / first posxInKernel <nl> + y0 = ( long ) max ( ( ElemType ) 0 , ceil ( ( y - ( ElemType ) kernelWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> + y1 = ( long ) ( y - y0 * horizontalSubsample ) ; / / first posyInKernel <nl> } <nl> <nl> assert ( x1 > = 0 & & x1 < kernelHeight & & y1 > = 0 & & y1 < kernelWidth ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignMaxPoolingResult ( const CPUMatrix <nl> { <nl> for ( long outputIndexWithinSample = 0 ; outputIndexWithinSample < outputSizePerSample ; outputIndexWithinSample + + ) <nl> { <nl> - const long y = outputIndexWithinSample / outputHeightTimesChannel ; / / wcol <nl> - const long nXC = outputIndexWithinSample % outputHeightTimesChannel ; / / channel + wrow * channels <nl> - const long x = ( long ) ( nXC / channels ) ; / / wrow <nl> - const long c = ( long ) ( nXC % channels ) ; / / channel <nl> + const long y = outputIndexWithinSample / outputHeightTimesChannel ; / / wcol <nl> + const long nXC = outputIndexWithinSample % outputHeightTimesChannel ; / / channel + wrow * channels <nl> + const long x = ( long ) ( nXC / channels ) ; / / wrow <nl> + const long c = ( long ) ( nXC % channels ) ; / / channel <nl> <nl> ElemType maxVal = - FLT_MAX ; <nl> ElemType minVal = FLT_MAX ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignMaxPoolingResult ( const CPUMatrix <nl> long rowInInput = rowInWindowBase + colInWindow * inputHeightTimesChannel ; <nl> for ( long rowInWindow = 0 ; rowInWindow < windowHeight ; rowInWindow + + ) <nl> { <nl> - const ElemType val = inputBatch ( rowInInput , sample ) ; / / pf [ rowInWindow * channels ] ; <nl> + const ElemType val = inputBatch ( rowInInput , sample ) ; / / pf [ rowInWindow * channels ] ; <nl> maxVal = max ( maxVal , val ) ; <nl> minVal = min ( minVal , val ) ; <nl> rowInInput + = ( long ) channels ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AddMaxPoolingGradient ( const CPUMatrix < <nl> { <nl> for ( long inputIndexWithinSample = 0 ; inputIndexWithinSample < inputSizePerSample ; inputIndexWithinSample + + ) <nl> { <nl> - const long y = inputIndexWithinSample / inputHeightTimesChannel ; / / col in input <nl> - const long nXC = inputIndexWithinSample % inputHeightTimesChannel ; / / channel + row * chanels <nl> - const long x = ( long ) ( nXC / channels ) ; / / row in input <nl> - const long c = ( long ) ( nXC % channels ) ; / / channel <nl> + const long y = inputIndexWithinSample / inputHeightTimesChannel ; / / col in input <nl> + const long nXC = inputIndexWithinSample % inputHeightTimesChannel ; / / channel + row * chanels <nl> + const long x = ( long ) ( nXC / channels ) ; / / row in input <nl> + const long c = ( long ) ( nXC % channels ) ; / / channel <nl> <nl> - long startOutX = ( long ) max ( ( ElemType ) 0 , ceil ( ( x - ( ElemType ) windowHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / inclusive start <nl> - long endOutX = ( long ) ( ( x / verticalSubsample < outputHeight - 1 ) ? x / verticalSubsample : outputHeight - 1 ) ; / / inclusive end <nl> - long startOutY = ( long ) max ( ( ElemType ) 0 , ceil ( ( y - ( ElemType ) windowWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / inclusive start <nl> - long endOutY = ( long ) ( ( y / horizontalSubsample < outputWidth - 1 ) ? y / horizontalSubsample : outputWidth - 1 ) ; / / inclusive end <nl> + long startOutX = ( long ) max ( ( ElemType ) 0 , ceil ( ( x - ( ElemType ) windowHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / inclusive start <nl> + long endOutX = ( long ) ( ( x / verticalSubsample < outputHeight - 1 ) ? x / verticalSubsample : outputHeight - 1 ) ; / / inclusive end <nl> + long startOutY = ( long ) max ( ( ElemType ) 0 , ceil ( ( y - ( ElemType ) windowWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / inclusive start <nl> + long endOutY = ( long ) ( ( y / horizontalSubsample < outputWidth - 1 ) ? y / horizontalSubsample : outputWidth - 1 ) ; / / inclusive end <nl> <nl> ElemType inputValue = inputBatch ( inputIndexWithinSample , sample ) ; <nl> for ( long outY = startOutY ; outY < = endOutY ; outY + + ) <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignAveragePoolingResult ( const CPUMa <nl> { <nl> for ( long outputIndexWithinSample = 0 ; outputIndexWithinSample < outputSizePerSample ; outputIndexWithinSample + + ) <nl> { <nl> - const long y = outputIndexWithinSample / outputHeightTimesChannel ; / / wcol <nl> - const long nXC = outputIndexWithinSample % outputHeightTimesChannel ; / / channel + wrow * channels <nl> - const long x = ( long ) ( nXC / channels ) ; / / wrow <nl> - const long c = ( long ) ( nXC % channels ) ; / / channel <nl> + const long y = outputIndexWithinSample / outputHeightTimesChannel ; / / wcol <nl> + const long nXC = outputIndexWithinSample % outputHeightTimesChannel ; / / channel + wrow * channels <nl> + const long x = ( long ) ( nXC / channels ) ; / / wrow <nl> + const long c = ( long ) ( nXC % channels ) ; / / channel <nl> <nl> ElemType sum = 0 ; <nl> const long rowInWindowBase = ( long ) ( ( x * verticalSubsample + y * horizontalSubsample * inputHeight ) * channels + c ) ; <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AddAveragePoolingGradient ( const CPUMat <nl> { <nl> for ( long inputIndexWithinSample = 0 ; inputIndexWithinSample < inputSizePerSample ; inputIndexWithinSample + + ) <nl> { <nl> - const long y = inputIndexWithinSample / inputHeightTimesChannel ; / / col in input <nl> - const long nXC = inputIndexWithinSample % inputHeightTimesChannel ; / / channel + row * chanels <nl> - const long x = nXC / ( long ) channels ; / / row in input <nl> - const long c = nXC % ( long ) channels ; / / channel <nl> + const long y = inputIndexWithinSample / inputHeightTimesChannel ; / / col in input <nl> + const long nXC = inputIndexWithinSample % inputHeightTimesChannel ; / / channel + row * chanels <nl> + const long x = nXC / ( long ) channels ; / / row in input <nl> + const long c = nXC % ( long ) channels ; / / channel <nl> <nl> - long startOutX = ( long ) max ( ( ElemType ) 0 , ceil ( ( x - ( ElemType ) windowHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / inclusive start <nl> - long endOutX = ( long ) ( ( x / verticalSubsample < outputHeight - 1 ) ? x / ( long ) verticalSubsample : outputHeight - 1 ) ; / / inclusive end <nl> - long startOutY = ( long ) max ( ( ElemType ) 0 , ceil ( ( y - ( ElemType ) windowWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / inclusive start <nl> - long endOutY = ( long ) ( ( y / horizontalSubsample < outputWidth - 1 ) ? y / horizontalSubsample : outputWidth - 1 ) ; / / inclusive end <nl> + long startOutX = ( long ) max ( ( ElemType ) 0 , ceil ( ( x - ( ElemType ) windowHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / inclusive start <nl> + long endOutX = ( long ) ( ( x / verticalSubsample < outputHeight - 1 ) ? x / ( long ) verticalSubsample : outputHeight - 1 ) ; / / inclusive end <nl> + long startOutY = ( long ) max ( ( ElemType ) 0 , ceil ( ( y - ( ElemType ) windowWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / inclusive start <nl> + long endOutY = ( long ) ( ( y / horizontalSubsample < outputWidth - 1 ) ? y / horizontalSubsample : outputWidth - 1 ) ; / / inclusive end <nl> <nl> for ( long outY = startOutY ; outY < = endOutY ; outY + + ) <nl> { <nl> void CPUMatrix < ElemType > : : MultiplyAndWeightedAdd ( ElemType alpha , const CPUMatrix <nl> # endif <nl> } <nl> <nl> - assert ( m > 0 & & k > 0 & & l > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & k > 0 & & l > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> assert ( k = = l ) ; <nl> if ( k ! = l ) <nl> InvalidArgument ( " CPUMatrix < ElemType > : : MultiplyAndWeightedAdd : The inner dimensions of a and b must match . " ) ; <nl> void CPUMatrix < ElemType > : : SVD ( const CPUMatrix < ElemType > & A , CPUMatrix < ElemType > & <nl> int m , n , lda , ldu , ldvt ; <nl> m = ( int ) A . GetNumRows ( ) ; <nl> n = ( int ) A . GetNumCols ( ) ; <nl> - W . GetNumRows ( ) ; / / W is used as temp working memory <nl> + W . GetNumRows ( ) ; / / W is used as temp working memory <nl> lda = m ; <nl> ldu = m ; <nl> ldvt = n ; <nl> void CPUMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const CPUMatrix < ElemType > & <nl> const int incx = 1 ; <nl> const int incy = 1 ; <nl> <nl> - assert ( m > 0 & & n > 0 & & len > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & len > 0 ) ; / / converting from size_t to int may cause overflow <nl> assert ( ( int ) c . GetNumRows ( ) = = m & & ( int ) c . GetNumCols ( ) = = n ) ; <nl> if ( ( int ) c . GetNumRows ( ) ! = m | | ( int ) c . GetNumCols ( ) ! = n ) <nl> InvalidArgument ( " Dimension of matrix c does not match dimension of matrix a . " ) ; <nl> void CPUMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const CPUMatrix < ElemType > & <nl> # endif <nl> } <nl> } <nl> - else if ( a . GetNumElements ( ) = = 1 ) / / scalar , add to all elements <nl> + else if ( a . GetNumElements ( ) = = 1 ) / / scalar , add to all elements <nl> { <nl> ElemType v = alpha * a ( 0 , 0 ) ; <nl> long m = ( long ) c . GetNumRows ( ) , n = ( long ) c . GetNumCols ( ) ; <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> c ( i , j ) + = v ; <nl> void CPUMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const CPUMatrix < ElemType > & <nl> c ( i + 2 , j ) + = v ; <nl> c ( i + 3 , j ) + = v ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> c ( i , j ) + = v ; <nl> } <nl> } <nl> } <nl> - else if ( a . GetNumCols ( ) = = 1 ) / / col vector , add it to all columns <nl> + else if ( a . GetNumCols ( ) = = 1 ) / / col vector , add it to all columns <nl> { <nl> int m = ( int ) c . GetNumRows ( ) ; <nl> assert ( m = = ( int ) a . GetNumRows ( ) ) ; <nl> void CPUMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const CPUMatrix < ElemType > & <nl> } <nl> } <nl> } <nl> - else / / row vector , add it to all rows <nl> + else / / row vector , add it to all rows <nl> { <nl> int m = ( int ) c . GetNumRows ( ) ; <nl> int n = ( int ) c . GetNumCols ( ) ; <nl> void CPUMatrix < ElemType > : : AddScaledDifference ( const ElemType alpha , const CPUMat <nl> <nl> long m = ( long ) c . GetNumElements ( ) ; <nl> # pragma omp parallel for <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> c . m_pArray [ i ] + = alpha * ( a . m_pArray [ i ] - b . m_pArray [ i ] ) ; <nl> void CPUMatrix < ElemType > : : AddScaledDifference ( const ElemType alpha , const CPUMat <nl> c . m_pArray [ i + 2 ] + = alpha * ( a . m_pArray [ i + 2 ] - b . m_pArray [ i + 2 ] ) ; <nl> c . m_pArray [ i + 3 ] + = alpha * ( a . m_pArray [ i + 3 ] - b . m_pArray [ i + 3 ] ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> c . m_pArray [ i ] + = alpha * ( a . m_pArray [ i ] - b . m_pArray [ i ] ) ; <nl> void CPUMatrix < ElemType > : : AssignScaledDifference ( const ElemType alpha , const CPU <nl> <nl> long m = ( long ) c . GetNumElements ( ) ; <nl> # pragma omp parallel for <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) <nl> { <nl> c . m_pArray [ i ] = alpha * ( a . m_pArray [ i ] - b . m_pArray [ i ] ) ; <nl> void CPUMatrix < ElemType > : : AssignScaledDifference ( const ElemType alpha , const CPU <nl> c . m_pArray [ i + 2 ] = alpha * ( a . m_pArray [ i + 2 ] - b . m_pArray [ i + 2 ] ) ; <nl> c . m_pArray [ i + 3 ] = alpha * ( a . m_pArray [ i + 3 ] - b . m_pArray [ i + 3 ] ) ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> c . m_pArray [ i ] = alpha * ( a . m_pArray [ i ] - b . m_pArray [ i ] ) ; <nl> void CPUMatrix < ElemType > : : Scale ( ElemType alpha , const CPUMatrix < ElemType > & a , CP <nl> const int m = ( int ) a . GetNumRows ( ) ; <nl> const int n = ( int ) a . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> c . Resize ( m , n ) ; <nl> <nl> long size = ( long ) c . GetNumElements ( ) ; <nl> # pragma omp parallel for <nl> - / / four - way unrolling <nl> + / / four - way unrolling <nl> for ( long i = 0 ; i < ( size & ~ 3 ) ; i + = 4 ) <nl> { <nl> c . m_pArray [ i ] = alpha * a . m_pArray [ i ] ; <nl> void CPUMatrix < ElemType > : : Scale ( ElemType alpha , const CPUMatrix < ElemType > & a , CP <nl> c . m_pArray [ i + 2 ] = alpha * a . m_pArray [ i + 2 ] ; <nl> c . m_pArray [ i + 3 ] = alpha * a . m_pArray [ i + 3 ] ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = size & ~ 3 ; i < size ; i + + ) <nl> { <nl> c . m_pArray [ i ] = alpha * a . m_pArray [ i ] ; <nl> void CPUMatrix < ElemType > : : Scale ( ElemType alpha , CPUMatrix < ElemType > & a ) <nl> const int len = m * n ; <nl> const int incx = 1 ; <nl> <nl> - assert ( m > 0 & & n > 0 & & len > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & len > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> if ( sizeof ( ElemType ) = = sizeof ( double ) ) <nl> { <nl> void CPUMatrix < ElemType > : : InnerProduct ( const CPUMatrix < ElemType > & a , const CPUMa <nl> const int k = ( int ) b . GetNumRows ( ) ; <nl> const int l = ( int ) b . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> - assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> if ( m ! = k | | n ! = l ) <nl> InvalidArgument ( " InnerProduct : Matrices a and b should have same dimension . " ) ; <nl> <nl> - if ( ( isColWise & & m = = 1 ) | | ! isColWise & & n = = 1 ) / / in this case it ' s equivalent to element - wise product <nl> + if ( ( isColWise & & m = = 1 ) | | ! isColWise & & n = = 1 ) / / in this case it ' s equivalent to element - wise product <nl> { <nl> c . AssignElementProductOf ( a , b ) ; <nl> } <nl> - else if ( isColWise ) / / col - wise <nl> + else if ( isColWise ) / / col - wise <nl> { <nl> c . Resize ( 1 , n ) ; <nl> <nl> ElemType CPUMatrix < ElemType > : : InnerProductOfMatrices ( const CPUMatrix < ElemType > & <nl> const int k = ( int ) b . GetNumRows ( ) ; <nl> const int l = ( int ) b . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> - assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> if ( m ! = k | | n ! = l ) <nl> InvalidArgument ( " InnerProductOfMatrices : Matrices a and b should have same dimension . " ) ; <nl> <nl> void CPUMatrix < ElemType > : : TensorShuffleScaleAndAdd ( ElemType keepWeight , const CP <nl> template < class ElemType > <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : Ones ( const size_t rows , const size_t cols ) <nl> { <nl> - CPUMatrix < ElemType > c ( rows , cols ) ; / / will initialize to 0 <nl> + CPUMatrix < ElemType > c ( rows , cols ) ; / / will initialize to 0 <nl> c . SetValue ( 1 ) ; <nl> return c ; <nl> } <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : Ones ( const size_t rows , const size_t co <nl> template < class ElemType > <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : Zeros ( const size_t rows , const size_t cols ) <nl> { <nl> - CPUMatrix < ElemType > c ( rows , cols ) ; / / will initialize to 0 <nl> + CPUMatrix < ElemType > c ( rows , cols ) ; / / will initialize to 0 <nl> c . SetValue ( 0 ) ; <nl> return c ; <nl> } <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : Zeros ( const size_t rows , const size_t c <nl> template < class ElemType > <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : Eye ( const size_t rows ) <nl> { <nl> - CPUMatrix < ElemType > c ( rows , rows ) ; / / will initialize to 0 <nl> + CPUMatrix < ElemType > c ( rows , rows ) ; / / will initialize to 0 <nl> c . SetDiagonalValue ( 1 ) ; <nl> return c ; <nl> } <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : Eye ( const size_t rows ) <nl> template < class ElemType > <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : RandomUniform ( const size_t rows , const size_t cols , const ElemType low , const ElemType high , unsigned long seed ) <nl> { <nl> - CPUMatrix < ElemType > c ( rows , cols ) ; / / will initialize to 0 <nl> + CPUMatrix < ElemType > c ( rows , cols ) ; / / will initialize to 0 <nl> c . SetUniformRandomValue ( low , high , seed ) ; <nl> return c ; <nl> } <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : RandomUniform ( const size_t rows , const <nl> template < class ElemType > <nl> CPUMatrix < ElemType > CPUMatrix < ElemType > : : RandomGaussian ( const size_t rows , const size_t cols , const ElemType mean , const ElemType sigma , unsigned long seed ) <nl> { <nl> - CPUMatrix < ElemType > c ( rows , cols ) ; / / will initialize to 0 <nl> + CPUMatrix < ElemType > c ( rows , cols ) ; / / will initialize to 0 <nl> c . SetGaussianRandomValue ( mean , sigma , seed ) ; <nl> return c ; <nl> } <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignElementProductOfWithShiftNeg ( con <nl> } <nl> <nl> long m = ( long ) GetNumRows ( ) , n = ( long ) GetNumCols ( ) ; / / a and b are of size ( 1 , n ) <nl> - / / # pragma omp parallel for <nl> + / / # pragma omp parallel for <nl> <nl> for ( long j = 0 ; j < n ; j + + ) <nl> { <nl> void CPUMatrix < ElemType > : : InnerProductWithShiftNeg ( const CPUMatrix < ElemType > & a , <nl> const int k = ( int ) b . GetNumRows ( ) ; <nl> const int l = ( int ) b . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> - assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> if ( m ! = k | | n ! = l ) <nl> InvalidArgument ( " InnerProduct : Matrices a and b should have same dimension . " ) ; <nl> <nl> - if ( ( isColWise & & m = = 1 ) | | ! isColWise & & n = = 1 ) / / in this case it ' s equivalent to element - wise product <nl> + if ( ( isColWise & & m = = 1 ) | | ! isColWise & & n = = 1 ) / / in this case it ' s equivalent to element - wise product <nl> { <nl> InvalidArgument ( " InnerProduct : Both matrices should be normal ones , not vectors " ) ; <nl> / / c . AssignElementProductOf ( a , b ) ; <nl> } <nl> - else if ( isColWise ) / / col - wise <nl> + else if ( isColWise ) / / col - wise <nl> { <nl> c . Resize ( negnumber + 1 , n ) ; / / this line ischanged <nl> <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : GetARowByIndex ( const CPUMatrix < ElemTyp <nl> if ( index < 0 | | index > = m ) <nl> LogicError ( " GetARowByIndex : the row index is out of range . " ) ; <nl> <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> auto & us = * this ; <nl> this - > Resize ( 1 , n ) ; <nl> void CPUMatrix < ElemType > : : ConductRowElementMultiplyWithShift ( const CPUMatrix < Ele <nl> const int k = ( int ) b . GetNumRows ( ) ; <nl> const int l = ( int ) b . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> - assert ( m = = 1 & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m = = 1 & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> if ( m ! = 1 | | n ! = l ) <nl> InvalidArgument ( " InnerProduct : Matrices a and b should have same dimension . " ) ; <nl> <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignElementProductOfWithShift ( const <nl> / / Resize ( a . GetNumRows ( ) , a . GetNumCols ( ) ) ; <nl> } <nl> <nl> - / / long m = ( long ) GetNumRows ( ) , n = ( long ) GetNumCols ( ) ; / / a and b are of size ( 1 , n ) <nl> + / / long m = ( long ) GetNumRows ( ) , n = ( long ) GetNumCols ( ) ; / / a and b are of size ( 1 , n ) <nl> long n = ( long ) GetNumCols ( ) ; / / a and b are of size ( 1 , n ) <nl> # pragma omp parallel for <nl> for ( long j = 0 ; j < n ; j + + ) <nl> CPUMatrix < ElemType > & CPUMatrix < ElemType > : : AssignSequenceError ( const ElemType hsm <nl> template < class ElemType > <nl> int CPUMatrix < ElemType > : : SetNumThreads ( int numThreads ) <nl> { <nl> - if ( numThreads = = 0 ) / / use default <nl> + if ( numThreads = = 0 ) / / use default <nl> return numThreads ; <nl> <nl> int mthreads = ( int ) std : : thread : : hardware_concurrency ( ) ; <nl> mmm a / Source / Math / CPUMatrix . h <nl> ppp b / Source / Math / CPUMatrix . h <nl> class MATH_API CPUMatrix : public BaseMatrix < ElemType > <nl> using B : : m_matrixName ; / / without this , base members would require to use thi - > in GCC <nl> public : <nl> CPUMatrix ( ) ; <nl> - CPUMatrix ( FILE * f , const char * matrixName ) ; / / matrixName is used to verify that correct matrix is read . <nl> + CPUMatrix ( FILE * f , const char * matrixName ) ; / / matrixName is used to verify that correct matrix is read . <nl> CPUMatrix ( const size_t numRows , const size_t numCols ) ; <nl> CPUMatrix ( const size_t numRows , const size_t numCols , ElemType * pArray , const size_t matrixFlags = matrixFlagNormal ) ; <nl> - CPUMatrix ( const CPUMatrix < ElemType > & deepCopyFrom ) ; / / copy constructor , deep copy <nl> - CPUMatrix < ElemType > & operator = ( const CPUMatrix < ElemType > & deepCopyFrom ) ; / / assignment operator , deep copy <nl> - CPUMatrix ( CPUMatrix < ElemType > & & moveFrom ) ; / / move constructor , shallow copy <nl> - CPUMatrix < ElemType > & operator = ( CPUMatrix < ElemType > & & moveFrom ) ; / / move assignment operator , shallow copy <nl> + CPUMatrix ( const CPUMatrix < ElemType > & deepCopyFrom ) ; / / copy constructor , deep copy <nl> + CPUMatrix < ElemType > & operator = ( const CPUMatrix < ElemType > & deepCopyFrom ) ; / / assignment operator , deep copy <nl> + CPUMatrix ( CPUMatrix < ElemType > & & moveFrom ) ; / / move constructor , shallow copy <nl> + CPUMatrix < ElemType > & operator = ( CPUMatrix < ElemType > & & moveFrom ) ; / / move assignment operator , shallow copy <nl> <nl> ~ CPUMatrix ( ) ; <nl> <nl> class MATH_API CPUMatrix : public BaseMatrix < ElemType > <nl> const bool needAveMultiplier ) ; <nl> <nl> void Reshape ( const size_t numRows , const size_t numCols ) ; <nl> - void Resize ( const size_t numRows , const size_t numCols , bool growOnly = true ) ; / / by default we only reallocate if need to grow <nl> - ElemType * CopyToArray ( ) const ; / / allocated by the callee but need to be deleted by the caller <nl> - size_t CopyToArray ( ElemType * & arrayCopyTo , size_t & currentArraySize ) const ; / / allocated by the callee but need to be deleted by the caller <nl> + void Resize ( const size_t numRows , const size_t numCols , bool growOnly = true ) ; / / by default we only reallocate if need to grow <nl> + ElemType * CopyToArray ( ) const ; / / allocated by the callee but need to be deleted by the caller <nl> + size_t CopyToArray ( ElemType * & arrayCopyTo , size_t & currentArraySize ) const ; / / allocated by the callee but need to be deleted by the caller <nl> void CopySection ( size_t numRows , size_t numCols , ElemType * dst , size_t colStride ) const ; <nl> <nl> inline ElemType & operator ( ) ( const size_t row , const size_t col ) <nl> class MATH_API CPUMatrix : public BaseMatrix < ElemType > <nl> CPUMatrix < ElemType > & operator / = ( ElemType alpha ) ; <nl> CPUMatrix < ElemType > operator / ( ElemType alpha ) const ; <nl> <nl> - CPUMatrix < ElemType > & operator ^ = ( ElemType alpha ) ; / / element - wise power <nl> - CPUMatrix < ElemType > operator ^ ( ElemType alpha ) const ; / / element - wise power <nl> + CPUMatrix < ElemType > & operator ^ = ( ElemType alpha ) ; / / element - wise power <nl> + CPUMatrix < ElemType > operator ^ ( ElemType alpha ) const ; / / element - wise power <nl> CPUMatrix < ElemType > & AssignElementPowerOf ( const CPUMatrix < ElemType > & a , const ElemType power ) ; <nl> <nl> CPUMatrix < ElemType > & ElementMultiplyWith ( const CPUMatrix < ElemType > & a ) ; <nl> class MATH_API CPUMatrix : public BaseMatrix < ElemType > <nl> CPUMatrix < ElemType > & InplaceHardmax ( const bool isColWise ) ; <nl> CPUMatrix < ElemType > & AssignHardmaxOf ( const CPUMatrix < ElemType > & a , const bool isColWise ) ; <nl> <nl> - / / sequence training <nl> + / / sequence training <nl> CPUMatrix < ElemType > & DropFrame ( const CPUMatrix < ElemType > & label , const CPUMatrix < ElemType > & gamma , const ElemType & threshhold ) ; <nl> CPUMatrix < ElemType > & AssignSequenceError ( const ElemType hsmoothingWeight , const CPUMatrix < ElemType > & label , const CPUMatrix < ElemType > & dnnoutput , const CPUMatrix < ElemType > & gamma , ElemType alpha ) ; <nl> CPUMatrix < ElemType > & InplaceSqrt ( ) ; <nl> class MATH_API CPUMatrix : public BaseMatrix < ElemType > <nl> <nl> CPUMatrix < ElemType > & SetToZeroIfAbsLessThan ( const ElemType threshold ) ; <nl> <nl> - ElemType SumOfAbsElements ( ) const ; / / sum of all abs ( elements ) <nl> - ElemType SumOfElements ( ) const ; / / sum of all elements <nl> + ElemType SumOfAbsElements ( ) const ; / / sum of all abs ( elements ) <nl> + ElemType SumOfElements ( ) const ; / / sum of all elements <nl> CPUMatrix < ElemType > & AssignSumOfElements ( const CPUMatrix < ElemType > & a ) ; <nl> <nl> bool IsEqualTo ( const CPUMatrix < ElemType > & a , const ElemType threshold = 1e - 8 ) const ; <nl> class MATH_API CPUMatrix : public BaseMatrix < ElemType > <nl> <nl> ElemType MatrixNormInf ( ) const ; <nl> ElemType MatrixNorm1 ( ) const ; <nl> - ElemType MatrixNorm0 ( ) const ; / / number of non - zero elemets <nl> + ElemType MatrixNorm0 ( ) const ; / / number of non - zero elemets <nl> CPUMatrix < ElemType > & AssignSignOf ( const CPUMatrix < ElemType > & a ) ; <nl> CPUMatrix < ElemType > & AddSignOf ( const CPUMatrix < ElemType > & a ) ; <nl> <nl> CPUMatrix < ElemType > & AssignRowSliceValuesOf ( const CPUMatrix < ElemType > & a , const size_t startIndex , const size_t numRows ) ; <nl> CPUMatrix < ElemType > & AddToRowSliceValuesOf ( const CPUMatrix < ElemType > & a , const size_t startIndex , const size_t numRows ) ; <nl> CPUMatrix < ElemType > & AddWithRowSliceValuesOf ( const CPUMatrix < ElemType > & a , const size_t startIndex , const size_t numRows ) ; <nl> - / / CPUMatrix < ElemType > & AssignRowStackValuesOf ( const std : : vector < const CPUMatrix < ElemType > * > & inputMatrices , const size_t sliceStartCol , const size_t sliceNumCols ) ; <nl> + / / CPUMatrix < ElemType > & AssignRowStackValuesOf ( const std : : vector < const CPUMatrix < ElemType > * > & inputMatrices , const size_t sliceStartCol , const size_t sliceNumCols ) ; <nl> <nl> CPUMatrix < ElemType > & AssignToRowSliceValuesOf ( const CPUMatrix < ElemType > & a , const size_t startIndex , const size_t numRows ) ; <nl> <nl> class MATH_API CPUMatrix : public BaseMatrix < ElemType > <nl> CPUMatrix < ElemType > & AssignNumOfDiff ( const CPUMatrix < ElemType > & a , const CPUMatrix < ElemType > & b , bool searchInCol = false ) ; <nl> <nl> void Print ( const char * matrixName , size_t rowStart , size_t rowEnd , size_t colStart , size_t colEnd ) const ; <nl> - void Print ( const char * matrixName = nullptr ) const ; / / print whole matrix . can be expensive <nl> + void Print ( const char * matrixName = nullptr ) const ; / / print whole matrix . can be expensive <nl> <nl> - void ReadFromFile ( FILE * f , const char * matrixName ) ; / / matrixName is used to verify that correct matrix is read . <nl> - void WriteToFile ( FILE * f , const char * matrixName ) ; / / matrixName is used to verify that correct matrix is read . <nl> + void ReadFromFile ( FILE * f , const char * matrixName ) ; / / matrixName is used to verify that correct matrix is read . <nl> + void WriteToFile ( FILE * f , const char * matrixName ) ; / / matrixName is used to verify that correct matrix is read . <nl> <nl> CPUMatrix < ElemType > & AssignPackedConvolutionInput ( const CPUMatrix < ElemType > & inputSubBatch , <nl> const size_t inputWidth , const size_t inputHeight , const size_t inputChannels , <nl> class MATH_API CPUMatrix : public BaseMatrix < ElemType > <nl> public : <nl> static int SetNumThreads ( int numThreads ) ; / / note : this does not depend on < ElemType > , i . e . you can call it on any < ElemType > <nl> <nl> - / / static BLAS functions <nl> + / / static BLAS functions <nl> static void SVD ( const CPUMatrix < ElemType > & A , CPUMatrix < ElemType > & SIGMA , CPUMatrix < ElemType > & U , CPUMatrix < ElemType > & VT , CPUMatrix < ElemType > & W ) ; <nl> <nl> static void MultiplyAndWeightedAdd ( ElemType alpha , const CPUMatrix < ElemType > & a , const bool transposeA , const CPUMatrix < ElemType > & b , const bool transposeB , ElemType beta , CPUMatrix < ElemType > & c ) ; <nl> class MATH_API CPUMatrix : public BaseMatrix < ElemType > <nl> static void ScaleAndAdd ( ElemType alpha , const CPUMatrix < ElemType > & a , CPUMatrix < ElemType > & c ) ; <nl> static void AddScaledDifference ( const ElemType alpha , const CPUMatrix < ElemType > & a , const CPUMatrix < ElemType > & b , CPUMatrix < ElemType > & c ) ; <nl> static void AssignScaledDifference ( const ElemType alpha , const CPUMatrix < ElemType > & a , const CPUMatrix < ElemType > & b , CPUMatrix < ElemType > & c ) ; <nl> - static void AddScaledDifference ( const CPUMatrix < ElemType > & alpha , const CPUMatrix < ElemType > & a , const CPUMatrix < ElemType > & b , CPUMatrix < ElemType > & c ) ; / / alpha must be 1X1 <nl> - static void AssignScaledDifference ( const CPUMatrix < ElemType > & alpha , const CPUMatrix < ElemType > & a , const CPUMatrix < ElemType > & b , CPUMatrix < ElemType > & c ) ; / / alpha must be 1X1 <nl> + static void AddScaledDifference ( const CPUMatrix < ElemType > & alpha , const CPUMatrix < ElemType > & a , const CPUMatrix < ElemType > & b , CPUMatrix < ElemType > & c ) ; / / alpha must be 1X1 <nl> + static void AssignScaledDifference ( const CPUMatrix < ElemType > & alpha , const CPUMatrix < ElemType > & a , const CPUMatrix < ElemType > & b , CPUMatrix < ElemType > & c ) ; / / alpha must be 1X1 <nl> <nl> static void AddElementToElement ( const CPUMatrix < ElemType > & a , const size_t ai , const size_t aj , CPUMatrix < ElemType > & c , const size_t ci , const size_t cj ) ; <nl> - / / static void AddLogElementToElement ( const CPUMatrix < ElemType > & a , const size_t ai , const size_t aj , CPUMatrix < ElemType > & c , const size_t ci , const size_t cj ) ; <nl> + / / static void AddLogElementToElement ( const CPUMatrix < ElemType > & a , const size_t ai , const size_t aj , CPUMatrix < ElemType > & c , const size_t ci , const size_t cj ) ; <nl> static void AssignElementToElement ( const CPUMatrix < ElemType > & a , const size_t ai , const size_t aj , CPUMatrix < ElemType > & c , const size_t ci , const size_t cj ) ; <nl> <nl> static void MinusOneAt ( CPUMatrix < ElemType > & c , const size_t position ) ; <nl> <nl> static void Scale ( ElemType alpha , CPUMatrix < ElemType > & a ) ; <nl> - static void Scale ( CPUMatrix < ElemType > alpha , CPUMatrix < ElemType > & a ) ; / / In this case Matrix alpha must be 1x1 <nl> + static void Scale ( CPUMatrix < ElemType > alpha , CPUMatrix < ElemType > & a ) ; / / In this case Matrix alpha must be 1x1 <nl> static void Scale ( ElemType alpha , const CPUMatrix < ElemType > & a , CPUMatrix < ElemType > & c ) ; <nl> static void InnerProduct ( const CPUMatrix < ElemType > & a , const CPUMatrix < ElemType > & b , CPUMatrix < ElemType > & c , const bool isColWise ) ; <nl> static ElemType InnerProductOfMatrices ( const CPUMatrix < ElemType > & a , const CPUMatrix < ElemType > & b ) ; <nl> class MATH_API CPUMatrix : public BaseMatrix < ElemType > <nl> size_t LocateColumn ( const size_t j ) const ; <nl> <nl> private : <nl> - void ZeroInit ( ) ; / / should only be used by constructors . <nl> + void ZeroInit ( ) ; / / should only be used by constructors . <nl> void Clear ( ) ; <nl> } ; <nl> <nl> mmm a / Source / Math / CPUSparseMatrix . cpp <nl> ppp b / Source / Math / CPUSparseMatrix . cpp <nl> <nl> / / return 42 ; <nl> / / } <nl> <nl> - # ifndef USE_MKL / / MKL has one additional parameter for different matrix order <nl> + # ifndef USE_MKL / / MKL has one additional parameter for different matrix order <nl> # define BLAS_COLMAJOR <nl> # else <nl> # define BLAS_COLMAJOR ( int ) MatrixOrder : : ColMajor , <nl> enum class SymMatrixType : char <nl> { <nl> Up = ' U ' , / / symmetric matrix is stored in the upper part <nl> Low = ' L ' , / / symmetric matrix is stored in thelower part <nl> - Full = ' F ' , / / full populated <nl> - NotSymmetric = ' N ' / / not a symmetric matrix <nl> + Full = ' F ' , / / full populated <nl> + NotSymmetric = ' N ' / / not a symmetric matrix <nl> } ; <nl> <nl> enum class MatrixOpSide : char <nl> void CPUSparseMatrix < ElemType > : : ZeroInit ( ) <nl> m_nz = 0 ; <nl> m_matrixName = NULL ; <nl> <nl> - / / if ( m_format = = MatrixFormat : : matrixFormatSparseCSC | | m_format = = MatrixFormat : : matrixFormatSparseCSR ) <nl> + / / if ( m_format = = MatrixFormat : : matrixFormatSparseCSC | | m_format = = MatrixFormat : : matrixFormatSparseCSR ) <nl> { <nl> m_colIdx = - 1 ; <nl> m_pArray = NULL ; <nl> m_unCompIndex = NULL ; <nl> m_compIndex = NULL ; <nl> } <nl> - / / else if ( m_format = = MatrixFormat : : matrixFormatSparseBlockCol | | m_format = = MatrixFormat : : matrixFormatSparseBlockRow ) <nl> + / / else if ( m_format = = MatrixFormat : : matrixFormatSparseBlockCol | | m_format = = MatrixFormat : : matrixFormatSparseBlockRow ) <nl> { <nl> m_blockSize = 0 ; <nl> m_blockIdShift = 0 ; <nl> CPUSparseMatrix < ElemType > : : CPUSparseMatrix ( CPUSparseMatrix < ElemType > & & moveFrom ) <nl> m_blockIdShift = moveFrom . m_blockIdShift ; <nl> m_blockIds = moveFrom . m_blockIds ; <nl> <nl> - / / release the pointer from the source object so that the destructor won ' t release it twice <nl> + / / release the pointer from the source object so that the destructor won ' t release it twice <nl> moveFrom . ZeroInit ( ) ; <nl> } <nl> <nl> CPUSparseMatrix < ElemType > & CPUSparseMatrix < ElemType > : : operator = ( CPUSparseMatrix < <nl> if ( this ! = & moveFrom ) <nl> { <nl> if ( OwnBuffer ( ) ) <nl> - ReleaseMemory ( ) ; / / always delete the data pointer since we will use the pointer from moveFrom <nl> + ReleaseMemory ( ) ; / / always delete the data pointer since we will use the pointer from moveFrom <nl> <nl> m_format = moveFrom . m_format ; <nl> m_numRows = moveFrom . m_numRows ; <nl> CPUSparseMatrix < ElemType > & CPUSparseMatrix < ElemType > : : operator = ( CPUSparseMatrix < <nl> m_blockIdShift = moveFrom . m_blockIdShift ; <nl> m_blockIds = moveFrom . m_blockIds ; <nl> <nl> - / / release the pointer from the source object so that the destructor won ' t release it twice <nl> + / / release the pointer from the source object so that the destructor won ' t release it twice <nl> moveFrom . ZeroInit ( ) ; <nl> } <nl> return * this ; <nl> void CPUSparseMatrix < ElemType > : : SetValue ( const size_t row , const size_t col , con <nl> LogicError ( " CPUSparseMatrix : unsupported SetValue ( ) call . " ) ; <nl> } <nl> <nl> - if ( m_elemSizeAllocated < m_nz + 1 ) / / automatic resize <nl> + if ( m_elemSizeAllocated < m_nz + 1 ) / / automatic resize <nl> { <nl> - Resize ( m_numRows , m_numCols , m_nz + 100 , true , true ) ; / / allocate 100 more elelemnts and keep existing values <nl> + Resize ( m_numRows , m_numCols , m_nz + 100 , true , true ) ; / / allocate 100 more elelemnts and keep existing values <nl> } <nl> <nl> if ( row < 0 | | row > = m_numRows ) <nl> void CPUSparseMatrix < ElemType > : : SetValue ( const size_t row , const size_t col , con <nl> m_pArray [ m_nz ] = v ; <nl> m_unCompIndex [ m_nz ] = ( CPUSPARSE_INDEX_TYPE ) r ; <nl> <nl> - / / consistency check <nl> + / / consistency check <nl> if ( m_nz > 0 ) <nl> { <nl> if ( c = = m_colIdx & & r < = m_unCompIndex [ m_nz - 1 ] ) <nl> void CPUSparseMatrix < ElemType > : : Print ( const char * matrixName , size_t / * rowStart * <nl> if ( this - > GetFormat ( ) ! = matrixFormatSparseCSC & & this - > GetFormat ( ) ! = matrixFormatSparseCSR ) <nl> { <nl> return ; <nl> - / / NOT_IMPLEMENTED ; <nl> + / / NOT_IMPLEMENTED ; <nl> } <nl> <nl> fprintf ( stderr , " % s \ n " , matrixName ) ; <nl> CPUSparseMatrix < ElemType > CPUSparseMatrix < ElemType > : : ColumnSlice ( size_t startCol <nl> if ( m_format = = MatrixFormat : : matrixFormatSparseCSC ) <nl> { <nl> slice . m_pArray = m_pArray ; <nl> - slice . m_nzValues = m_pArray + m_compIndex [ startColumn ] ; / / note : m_compIndex is always against m_pArray <nl> + slice . m_nzValues = m_pArray + m_compIndex [ startColumn ] ; / / note : m_compIndex is always against m_pArray <nl> slice . m_unCompIndex = m_unCompIndex ; <nl> slice . m_compIndex = m_compIndex + startColumn ; / / Just shift the compressed index location to the new startColumn - that ' s it ! <nl> slice . m_externalBuffer = true ; <nl> CPUSparseMatrix < ElemType > CPUSparseMatrix < ElemType > : : ColumnSlice ( size_t startCol <nl> { <nl> if ( j > 0 ) <nl> { <nl> - assert ( m_blockIds [ j ] > m_blockIds [ j - 1 ] ) ; / / assume ids are increasing . Is this valid ? <nl> + assert ( m_blockIds [ j ] > m_blockIds [ j - 1 ] ) ; / / assume ids are increasing . Is this valid ? <nl> } <nl> <nl> if ( ! foundStart & & ( long long ) m_blockIds [ j ] - ( long long ) m_blockIdShift > = ( long long ) startColumn ) / / start column with values <nl> CPUSparseMatrix < ElemType > CPUSparseMatrix < ElemType > : : ColumnSlice ( size_t startCol <nl> startColBlock = j ; <nl> foundStart = true ; <nl> } <nl> - else if ( ( long long ) m_blockIds [ j ] - ( long long ) m_blockIdShift > = ( long long ) ( startColumn + numCols ) ) / / end column with values <nl> + else if ( ( long long ) m_blockIds [ j ] - ( long long ) m_blockIdShift > = ( long long ) ( startColumn + numCols ) ) / / end column with values <nl> { <nl> endColBlock = j ; <nl> foundEnd = true ; <nl> CPUSparseMatrix < ElemType > CPUSparseMatrix < ElemType > : : ColumnSlice ( size_t startCol <nl> <nl> slice . m_pArray = m_pArray + startColBlock * m_numRows ; <nl> slice . m_nzValues = slice . m_pArray ; <nl> - slice . m_blockIds = m_blockIds + startColBlock ; / / the value stored in the block id is based on the original column numbers <nl> + slice . m_blockIds = m_blockIds + startColBlock ; / / the value stored in the block id is based on the original column numbers <nl> slice . m_blockSize = ( size_t ) max ( ( long long ) 0 , endColBlock - startColBlock ) ; <nl> slice . m_blockIdShift = m_blockIdShift + startColumn ; <nl> slice . m_externalBuffer = true ; <nl> CPUSparseMatrix < ElemType > CPUSparseMatrix < ElemType > : : ColumnSlice ( size_t startCol <nl> template < class ElemType > <nl> CPUMatrix < ElemType > CPUSparseMatrix < ElemType > : : CopyColumnSliceToDense ( size_t startColumn , size_t numCols ) const <nl> { <nl> - / / if ( numCols = = 0 ) <nl> + / / if ( numCols = = 0 ) <nl> / / LogicError ( " The slice cannot have 0 columns . " ) ; <nl> <nl> if ( startColumn + numCols > m_numCols ) <nl> void CPUSparseMatrix < ElemType > : : MultiplyAndWeightedAdd ( ElemType alpha , const CPU <nl> int l = transposeB ? ( int ) rhs . GetNumCols ( ) : ( int ) rhs . GetNumRows ( ) ; <nl> int n = transposeB ? ( int ) rhs . GetNumRows ( ) : ( int ) rhs . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & k > 0 & & l > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & k > 0 & & l > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> assert ( k = = l ) ; <nl> if ( k ! = l ) <nl> { <nl> void CPUSparseMatrix < ElemType > : : MultiplyAndWeightedAdd ( ElemType alpha , const CPU <nl> { <nl> for ( size_t j = 0 ; j < rhs . GetNumCols ( ) ; j + + ) <nl> { <nl> - size_t start = rhs . m_compIndex [ j ] ; / / ColLocation <nl> + size_t start = rhs . m_compIndex [ j ] ; / / ColLocation <nl> size_t end = rhs . m_compIndex [ j + 1 ] ; <nl> for ( size_t p = start ; p < end ; p + + ) <nl> { <nl> - size_t i = rhs . m_unCompIndex [ p ] ; / / RowLocation <nl> + size_t i = rhs . m_unCompIndex [ p ] ; / / RowLocation <nl> ElemType val = rhs . m_pArray [ p ] ; <nl> <nl> for ( size_t h = 0 ; h < lhs . GetNumRows ( ) ; h + + ) <nl> void CPUSparseMatrix < ElemType > : : MultiplyAndAdd ( ElemType alpha , const CPUMatrix < E <nl> <nl> assert ( m > 0 & & k > 0 & & l > 0 & & n > 0 ) ; <nl> m ; <nl> - n ; / / converting from size_t to int may cause overflow <nl> + n ; / / converting from size_t to int may cause overflow <nl> assert ( k = = l ) ; <nl> if ( k ! = l ) <nl> { <nl> void CPUSparseMatrix < ElemType > : : MultiplyAndAdd ( ElemType alpha , const CPUMatrix < E <nl> if ( rhs . GetFormat ( ) ! = matrixFormatSparseCSC ) <nl> NOT_IMPLEMENTED ; <nl> <nl> - / / allocate enough memory <nl> + / / allocate enough memory <nl> c . SetFormat ( matrixFormatSparseBlockCol ) ; <nl> c . Resize ( m , n , m * min ( n , rhs . m_nz ) , true , false ) ; <nl> <nl> void CPUSparseMatrix < ElemType > : : MultiplyAndAdd ( ElemType alpha , const CPUMatrix < E <nl> <nl> for ( size_t p = start ; p < end ; p + + ) <nl> { <nl> - size_t i = rhs . m_unCompIndex [ p ] ; / / i ranges over words <nl> - ElemType val = rhs . m_pArray [ p ] ; / / 1 for ( i , j ) <nl> + size_t i = rhs . m_unCompIndex [ p ] ; / / i ranges over words <nl> + ElemType val = rhs . m_pArray [ p ] ; / / 1 for ( i , j ) <nl> <nl> bool first = true ; <nl> if ( w2Id . find ( i ) = = w2Id . end ( ) ) <nl> void CPUSparseMatrix < ElemType > : : MultiplyAndAdd ( ElemType alpha , const CPUMatrix < E <nl> { <nl> LogicError ( " sparse matrix out of range . " ) ; <nl> } <nl> - / / c . SetFormat ( matrixFormatSparseBlockCol ) ; <nl> + / / c . SetFormat ( matrixFormatSparseBlockCol ) ; <nl> } <nl> else if ( transposeA & & ! transposeB ) <nl> { <nl> CPUSparseMatrix < ElemType > & CPUSparseMatrix < ElemType > : : InplaceTruncateTop ( const E <nl> ElemType * nzValues = NzValues ( ) ; <nl> <nl> # pragma omp parallel for <nl> - for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) / / four - way unrolling <nl> + for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) / / four - way unrolling <nl> { <nl> if ( nzValues [ i ] > threshold ) <nl> nzValues [ i ] = threshold ; <nl> CPUSparseMatrix < ElemType > & CPUSparseMatrix < ElemType > : : InplaceTruncateTop ( const E <nl> if ( nzValues [ i + 3 ] > threshold ) <nl> nzValues [ i + 3 ] = threshold ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> if ( nzValues [ i ] > threshold ) <nl> CPUSparseMatrix < ElemType > & CPUSparseMatrix < ElemType > : : InplaceTruncateBottom ( cons <nl> ElemType * nzValues = NzValues ( ) ; <nl> <nl> # pragma omp parallel for <nl> - for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) / / four - way unrolling <nl> + for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) / / four - way unrolling <nl> { <nl> if ( nzValues [ i ] < threshold ) <nl> nzValues [ i ] = threshold ; <nl> CPUSparseMatrix < ElemType > & CPUSparseMatrix < ElemType > : : InplaceTruncateBottom ( cons <nl> if ( nzValues [ i + 3 ] < threshold ) <nl> nzValues [ i + 3 ] = threshold ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> if ( nzValues [ i ] < threshold ) <nl> CPUSparseMatrix < ElemType > & CPUSparseMatrix < ElemType > : : InplaceTruncate ( const Elem <nl> ElemType * nzValues = NzValues ( ) ; <nl> <nl> # pragma omp parallel for <nl> - for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) / / four - way unrolling <nl> + for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) / / four - way unrolling <nl> { <nl> if ( nzValues [ i ] > locThresholdPos ) <nl> nzValues [ i ] = locThresholdPos ; <nl> CPUSparseMatrix < ElemType > & CPUSparseMatrix < ElemType > : : InplaceTruncate ( const Elem <nl> else if ( nzValues [ i + 3 ] < locTHresholdNeg ) <nl> nzValues [ i + 3 ] = locTHresholdNeg ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> if ( nzValues [ i ] > locThresholdPos ) <nl> CPUSparseMatrix < ElemType > & CPUSparseMatrix < ElemType > : : InplaceSoftThreshold ( const <nl> ElemType * nzValues = NzValues ( ) ; <nl> <nl> # pragma omp parallel for <nl> - for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) / / four - way unrolling <nl> + for ( long i = 0 ; i < ( m & ~ 3 ) ; i + = 4 ) / / four - way unrolling <nl> { <nl> if ( nzValues [ i ] > threshold ) <nl> nzValues [ i ] - = threshold ; <nl> CPUSparseMatrix < ElemType > & CPUSparseMatrix < ElemType > : : InplaceSoftThreshold ( const <nl> else <nl> nzValues [ i + 3 ] = 0 ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> if ( nzValues [ i ] > threshold ) <nl> ElemType CPUSparseMatrix < ElemType > : : FrobeniusNorm ( ) const <nl> { <nl> v + = nzValues [ i ] * nzValues [ i ] + nzValues [ i + 1 ] * nzValues [ i + 1 ] + nzValues [ i + 2 ] * nzValues [ i + 2 ] + nzValues [ i + 3 ] * nzValues [ i + 3 ] ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> v + = nzValues [ i ] * nzValues [ i ] ; <nl> ElemType CPUSparseMatrix < ElemType > : : SumOfElements ( ) const <nl> { <nl> sum + = nzValues [ i ] + nzValues [ i + 1 ] + nzValues [ i + 2 ] + nzValues [ i + 3 ] ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( long i = m & ~ 3 ; i < m ; i + + ) <nl> { <nl> sum + = nzValues [ i ] ; <nl> mmm a / Source / Math / CPUSparseMatrix . h <nl> ppp b / Source / Math / CPUSparseMatrix . h <nl> class MATH_API CPUSparseMatrix : public BaseMatrix < ElemType > <nl> public : <nl> CPUSparseMatrix ( const MatrixFormat format ) ; <nl> CPUSparseMatrix ( const MatrixFormat format , const size_t numRows , const size_t numCols , const size_t size ) ; <nl> - CPUSparseMatrix ( const CPUSparseMatrix < ElemType > & deepCopyFrom ) ; / / copy constructor , deep copy <nl> - CPUSparseMatrix < ElemType > & operator = ( const CPUSparseMatrix < ElemType > & deepCopyFrom ) ; / / assignment operator , deep copy <nl> - CPUSparseMatrix ( CPUSparseMatrix < ElemType > & & moveFrom ) ; / / move constructor , shallow copy <nl> - CPUSparseMatrix < ElemType > & operator = ( CPUSparseMatrix < ElemType > & & moveFrom ) ; / / move assignment operator , shallow copy <nl> + CPUSparseMatrix ( const CPUSparseMatrix < ElemType > & deepCopyFrom ) ; / / copy constructor , deep copy <nl> + CPUSparseMatrix < ElemType > & operator = ( const CPUSparseMatrix < ElemType > & deepCopyFrom ) ; / / assignment operator , deep copy <nl> + CPUSparseMatrix ( CPUSparseMatrix < ElemType > & & moveFrom ) ; / / move constructor , shallow copy <nl> + CPUSparseMatrix < ElemType > & operator = ( CPUSparseMatrix < ElemType > & & moveFrom ) ; / / move assignment operator , shallow copy <nl> ~ CPUSparseMatrix ( ) ; <nl> <nl> public : <nl> class MATH_API CPUSparseMatrix : public BaseMatrix < ElemType > <nl> CPUSparseMatrix < ElemType > & InplaceTruncate ( const ElemType threshold ) ; <nl> CPUSparseMatrix < ElemType > & InplaceSoftThreshold ( const ElemType threshold ) ; <nl> <nl> - ElemType FrobeniusNorm ( ) const ; / / useful for comparing CPU and GPU results <nl> + ElemType FrobeniusNorm ( ) const ; / / useful for comparing CPU and GPU results <nl> <nl> - ElemType SumOfAbsElements ( ) const ; / / sum of all abs ( elements ) <nl> - ElemType SumOfElements ( ) const ; / / sum of all elements <nl> + ElemType SumOfAbsElements ( ) const ; / / sum of all abs ( elements ) <nl> + ElemType SumOfElements ( ) const ; / / sum of all elements <nl> <nl> public : <nl> - / / void Print ( const char * / * matrixName * / ) const { NOT_IMPLEMENTED ; } <nl> + / / void Print ( const char * / * matrixName * / ) const { NOT_IMPLEMENTED ; } <nl> void Print ( const char * matrixName , size_t rowStart , size_t rowEnd , size_t colStart , size_t colEnd ) const ; <nl> - void Print ( const char * matrixName = NULL ) const ; / / print whole matrix . can be expensive <nl> + void Print ( const char * matrixName = NULL ) const ; / / print whole matrix . can be expensive <nl> <nl> public : <nl> const ElemType * NzValues ( ) const <nl> class MATH_API CPUSparseMatrix : public BaseMatrix < ElemType > <nl> CPUSPARSE_INDEX_TYPE * MajorIndexLocation ( ) const <nl> { <nl> return m_unCompIndex ; <nl> - } / / this is the major index , row / col ids in CSC / CSR format <nl> + } / / this is the major index , row / col ids in CSC / CSR format <nl> size_t MajorIndexCount ( ) const <nl> { <nl> return m_nz ; <nl> class MATH_API CPUSparseMatrix : public BaseMatrix < ElemType > <nl> CPUSPARSE_INDEX_TYPE * SecondaryIndexLocation ( ) const <nl> { <nl> return m_compIndex ; <nl> - } / / this is the compressed index , col / row in CSC / CSR format <nl> + } / / this is the compressed index , col / row in CSC / CSR format <nl> size_t SecondaryIndexCount ( ) const <nl> { <nl> if ( m_format & matrixFormatCompressed ) <nl> class MATH_API CPUSparseMatrix : public BaseMatrix < ElemType > <nl> } / / actual number of bytes in use <nl> <nl> private : <nl> - int m_colIdx ; / / used to SetValue ( ) <nl> + int m_colIdx ; / / used to SetValue ( ) <nl> size_t m_compIndexSize ; <nl> ElemType * m_nzValues ; <nl> <nl> - / / non - zero values are stored in m_pArray <nl> - CPUSPARSE_INDEX_TYPE * m_unCompIndex ; / / row / col ids in CSC / CSR format <nl> - CPUSPARSE_INDEX_TYPE * m_compIndex ; / / begin ids of col / row in CSC / CSR format <nl> + / / non - zero values are stored in m_pArray <nl> + CPUSPARSE_INDEX_TYPE * m_unCompIndex ; / / row / col ids in CSC / CSR format <nl> + CPUSPARSE_INDEX_TYPE * m_compIndex ; / / begin ids of col / row in CSC / CSR format <nl> <nl> - size_t m_blockSize ; / / block size <nl> - size_t * m_blockIds ; / / block ids <nl> - size_t m_blockIdShift ; / / used to get efficient slice , actual col = blockIds [ j ] - m_blockIdShift <nl> + size_t m_blockSize ; / / block size <nl> + size_t * m_blockIds ; / / block ids <nl> + size_t m_blockIdShift ; / / used to get efficient slice , actual col = blockIds [ j ] - m_blockIdShift <nl> } ; <nl> <nl> typedef CPUSparseMatrix < float > CPUSingleSparseMatrix ; <nl> mmm a / Source / Math / CommonMatrix . h <nl> ppp b / Source / Math / CommonMatrix . h <nl> <nl> # define MINLOGEXP - 9 . 2103 <nl> # define LSMALL - 0 . 5E10 <nl> <nl> - # define GPUSPARSE_INDEX_TYPE int / / cuSparse only supports int array indexes <nl> - # define CPUSPARSE_INDEX_TYPE int / / to be consistent with cuSparse but limited the possible size of the matrix . <nl> + # define GPUSPARSE_INDEX_TYPE int / / cuSparse only supports int array indexes <nl> + # define CPUSPARSE_INDEX_TYPE int / / to be consistent with cuSparse but limited the possible size of the matrix . <nl> <nl> MATH_API DEVICEID_TYPE EnforceOneGPUOnly ( DEVICEID_TYPE requestedDeviceId ) ; <nl> <nl> enum ElementWiseOperator <nl> opElementwiseProductWithLogDerivativeFromOutput , <nl> opElementwiseProductWithCosDerivative , <nl> / / binary ops for indexing <nl> - / / opIndex , <nl> + / / opIndex , <nl> / / ternary <nl> opCond / * a ? b : c * / , <nl> opClip / * clip a within interval b . . c * / <nl> enum MatrixFormat <nl> matrixFormatSparseCSR = matrixFormatSparse + matrixFormatRowMajor + matrixFormatCompressed , <nl> matrixFormatSparseOther = matrixFormatSparse + matrixFormatRowMajor , / / currently used for CPU sparse format , will change to CSC / CSR eventually <nl> matrixFormatMask = matrixFormatRowMajor + matrixFormatSparse + matrixFormatCompressed , / / mask that covers all the <nl> - matrixFormatSparseBlockCol , / / col block based sparse matrix <nl> - matrixFormatSparseBlockRow , / / row block based sparse matrix <nl> + matrixFormatSparseBlockCol , / / col block based sparse matrix <nl> + matrixFormatSparseBlockRow , / / row block based sparse matrix <nl> } ; <nl> <nl> / / common matrix flags for use on all matrices <nl> class BaseMatrix <nl> MatrixFormat m_format ; <nl> bool m_externalBuffer ; / / is the buffer used by this matrix , <nl> ElemType * m_pArray ; <nl> - mutable DEVICEID_TYPE m_computeDevice ; / / current GPU device Id or CPUDEVICE <nl> - size_t m_nz ; / / Number of non - zero elements for sparse matrices ( unused in other formats ) <nl> + mutable DEVICEID_TYPE m_computeDevice ; / / current GPU device Id or CPUDEVICE <nl> + size_t m_nz ; / / Number of non - zero elements for sparse matrices ( unused in other formats ) <nl> wchar_t * m_matrixName ; <nl> } ; <nl> } } } <nl> mmm a / Source / Math / ConvolutionEngine . cpp <nl> ppp b / Source / Math / ConvolutionEngine . cpp <nl> class DefaultConvolutionEngine : public ConvolutionEngine < ElemType > <nl> size_t packedInputRows = filterT . w ( ) * filterT . h ( ) * filterT . c ( ) ; <nl> size_t packedInputColsPerSample = outT . w ( ) * outT . h ( ) ; <nl> size_t outputSizePerChannel = packedInputColsPerSample ; <nl> - / / size_t packedInputDim = packedInputRows * packedInputColsPerSample ; / / size of each packed input sample <nl> - / / size_t inputDim = inT . w ( ) * inT . h ( ) * inT . c ( ) ; / / size of each input sample <nl> + / / size_t packedInputDim = packedInputRows * packedInputColsPerSample ; / / size of each packed input sample <nl> + / / size_t inputDim = inT . w ( ) * inT . h ( ) * inT . c ( ) ; / / size of each input sample <nl> <nl> size_t batchSize = inT . n ( ) ; <nl> size_t maxTempMemSizeInSamples = ( m_maxTempMemSizeInSamples = = 0 ? batchSize : m_maxTempMemSizeInSamples ) ; <nl> class DefaultConvolutionEngine : public ConvolutionEngine < ElemType > <nl> <nl> Mat outputSubBatch = out . ColumnSlice ( outputSizePerChannel * startSampleId , outputSizePerChannel * smallBatchSize ) ; <nl> <nl> - / / workspace . Resize ( packedInputRows , packedInputColsPerSample * smallBatchSize ) ; <nl> + / / workspace . Resize ( packedInputRows , packedInputColsPerSample * smallBatchSize ) ; <nl> / / BUGBUG : This ^ ^ destroys the content of the matrix . Also it seems not to change the size . Does it ? Should this be a Reshape ( ) ? <nl> Mat : : Multiply ( filter , false , workspace , false , outputSubBatch ) ; <nl> } <nl> } <nl> <nl> - out . Reshape ( outT . c ( ) * outputSizePerChannel , batchSize ) ; / / each sample becomes a column <nl> + out . Reshape ( outT . c ( ) * outputSizePerChannel , batchSize ) ; / / each sample becomes a column <nl> <nl> assert ( outT . w ( ) * outT . h ( ) * outT . c ( ) = = out . GetNumRows ( ) ) ; <nl> assert ( outT . n ( ) = = out . GetNumCols ( ) ) ; <nl> class DefaultConvolutionEngine : public ConvolutionEngine < ElemType > <nl> size_t packedInputRows = filterT . w ( ) * filterT . h ( ) * filterT . c ( ) ; <nl> size_t packedInputColsPerSample = srcGradT . w ( ) * srcGradT . h ( ) ; <nl> size_t outputSizePerChannel = packedInputColsPerSample ; <nl> - / / size_t packedInputDim = packedInputRows * packedInputColsPerSample ; / / size of each packed input sample <nl> - / / size_t inputDim = gradT . w ( ) * gradT . h ( ) * gradT . c ( ) ; / / size of each input sample <nl> + / / size_t packedInputDim = packedInputRows * packedInputColsPerSample ; / / size of each packed input sample <nl> + / / size_t inputDim = gradT . w ( ) * gradT . h ( ) * gradT . c ( ) ; / / size of each input sample <nl> <nl> size_t batchSize = srcGradT . n ( ) ; <nl> <nl> class DefaultConvolutionEngine : public ConvolutionEngine < ElemType > <nl> <nl> / / Create slice which is the same as full matrix so we can reshape it . <nl> Matrix < ElemType > srcGradTmp = srcGrad . ColumnSlice ( 0 , srcGrad . GetNumCols ( ) ) ; <nl> - srcGradTmp . Reshape ( srcGradT . c ( ) , outputSizePerChannel * batchSize ) ; / / reshape to match the longernal operation <nl> + srcGradTmp . Reshape ( srcGradT . c ( ) , outputSizePerChannel * batchSize ) ; / / reshape to match the longernal operation <nl> <nl> size_t subBatchSize = min ( batchSize , maxTempMemSizeInSamples ) ; <nl> size_t numSubBatches = ( batchSize + subBatchSize - 1 ) / subBatchSize ; <nl> class DefaultConvolutionEngine : public ConvolutionEngine < ElemType > <nl> size_t packedInputRows = filterT . w ( ) * filterT . h ( ) * filterT . c ( ) ; <nl> size_t packedInputColsPerSample = srcGradT . w ( ) * srcGradT . h ( ) ; <nl> size_t outputSizePerChannel = packedInputColsPerSample ; <nl> - / / size_t packedInputDim = packedInputRows * packedInputColsPerSample ; / / size of each packed input sample <nl> - / / size_t inputDim = m_inputImageLayout . width * m_inputImageLayout . height * m_inputImageLayout . channels ; / / size of each input sample <nl> + / / size_t packedInputDim = packedInputRows * packedInputColsPerSample ; / / size of each packed input sample <nl> + / / size_t inputDim = m_inputImageLayout . width * m_inputImageLayout . height * m_inputImageLayout . channels ; / / size of each input sample <nl> <nl> size_t batchSize = inT . n ( ) ; <nl> <nl> size_t maxTempMemSizeInSamples = ( m_maxTempMemSizeInSamples = = 0 ? batchSize : m_maxTempMemSizeInSamples ) ; <nl> <nl> - / / const Matrix < ElemType > & weightMatrix = input0 ; <nl> - / / inputGradientValues . Resize ( weightMatrix . GetNumRows ( ) , weightMatrix . GetNumCols ( ) ) ; / / should have been resized when preparing gradient computation <nl> + / / const Matrix < ElemType > & weightMatrix = input0 ; <nl> + / / inputGradientValues . Resize ( weightMatrix . GetNumRows ( ) , weightMatrix . GetNumCols ( ) ) ; / / should have been resized when preparing gradient computation <nl> <nl> / / Create slice which is the same as full matrix so we can reshape it . <nl> Matrix < ElemType > srcGradTmp = srcGrad . ColumnSlice ( 0 , srcGrad . GetNumCols ( ) ) ; <nl> - srcGradTmp . Reshape ( srcGradT . c ( ) , outputSizePerChannel * batchSize ) ; / / reshape to match the longernal operation <nl> + srcGradTmp . Reshape ( srcGradT . c ( ) , outputSizePerChannel * batchSize ) ; / / reshape to match the longernal operation <nl> <nl> size_t subBatchSize = min ( batchSize , maxTempMemSizeInSamples ) ; <nl> size_t numSubBatches = ( batchSize + subBatchSize - 1 ) / subBatchSize ; <nl> <nl> - if ( numSubBatches = = 1 & & allowReuse & & ! m_gpuSparseOpt ) / / reuse packed input from evaluation step if it ' s not changed by either subbatch or recurrent steps . <nl> + if ( numSubBatches = = 1 & & allowReuse & & ! m_gpuSparseOpt ) / / reuse packed input from evaluation step if it ' s not changed by either subbatch or recurrent steps . <nl> / / REVIEW alexeyk : the following makes an assumption that data in workspace was filled by Forward call and remained unchanged . Find way to enforce / verify that . <nl> Matrix < ElemType > : : MultiplyAndAdd ( srcGradTmp , false , workspace , true , filter ) ; <nl> else <nl> std : : unique_ptr < ConvolutionEngineFactory < ElemType > > ConvolutionEngineFactory < Ele <nl> / / REVIEW alexeyk : temp hack to allow this to work in MEL scenarios . InvalidArgument should be used instead . <nl> if ( imageLayoutKind ! = ImageLayoutKind : : HWC ) <nl> fprintf ( stderr , " WARNING : trying to use cuDNN on unsupported platform . It is safe to ignore the warning if it ' s produced during model editing command . \ n " ) ; <nl> - / / InvalidArgument ( " ConvolutionEngineFactory : ImageLayout ' % s ' is not compatible with the legacy convolution engine . " , ToString ( imageLayoutKind ) . c_str ( ) ) ; <nl> + / / InvalidArgument ( " ConvolutionEngineFactory : ImageLayout ' % s ' is not compatible with the legacy convolution engine . " , ToString ( imageLayoutKind ) . c_str ( ) ) ; <nl> return std : : make_unique < DefaultConvolutionEngineFactory < ElemType > > ( ) ; <nl> } <nl> <nl> mmm a / Source / Math / ConvolutionEngine . h <nl> ppp b / Source / Math / ConvolutionEngine . h <nl> class ConvolutionTensor4D <nl> ConvolutionTensor4D ( const ConvolutionTensor4D & ) = delete ; <nl> ConvolutionTensor4D & operator = ( const ConvolutionTensor4D & ) = delete ; <nl> / / REVIEW alexeyk : Have to implement move ctor explicitly as VS2013 does not support default move ctors . <nl> - / / ConvolutionTensor4D ( ConvolutionTensor4D & & ) ; <nl> - / / ConvolutionTensor4D & operator = ( ConvolutionTensor4D & & ) ; <nl> + / / ConvolutionTensor4D ( ConvolutionTensor4D & & ) ; <nl> + / / ConvolutionTensor4D & operator = ( ConvolutionTensor4D & & ) ; <nl> <nl> private : <nl> size_t m_w ; <nl> class MATH_API ConvolutionEngineFactory <nl> virtual ConvDescPtr CreateConvDescriptor ( const Tensor4D & inT , const Filter & filterT , <nl> size_t wStride , size_t hStride , bool padding ) = 0 ; <nl> virtual PoolDescPtr CreatePoolDescriptor ( PoolDesc : : PoolKind kind , size_t w , size_t h , size_t wStride , size_t hStride , size_t wPad , size_t hPad ) = 0 ; <nl> - / / virtual Tensor4DPtr CreateLrnDescriptor ( ) = 0 ; <nl> + / / virtual Tensor4DPtr CreateLrnDescriptor ( ) = 0 ; <nl> <nl> virtual ConvEnginePtr CreateConvEngine ( DEVICEID_TYPE deviceId , size_t maxTempMemSizeInSamples ) = 0 ; <nl> virtual PoolEnginePtr CreatePoolEngine ( DEVICEID_TYPE deviceId ) = 0 ; <nl> mmm a / Source / Math / CuDnnConvolutionEngine . cpp <nl> ppp b / Source / Math / CuDnnConvolutionEngine . cpp <nl> template < class ElemType > <nl> typename CuDnnConvolutionEngineFactory < ElemType > : : Tensor4DPtr CuDnnConvolutionEngineFactory < ElemType > : : CreateTensor ( size_t w , size_t h , size_t c , size_t n ) <nl> { <nl> / / REVIEW alexeyk : assert fires in GCC but not in VC + + . <nl> - / / static_assert ( false , " cuDNN engine currently supports only single and double precision tensors . " ) ; <nl> + / / static_assert ( false , " cuDNN engine currently supports only single and double precision tensors . " ) ; <nl> } <nl> template < > <nl> typename CuDnnConvolutionEngineFactory < float > : : Tensor4DPtr CuDnnConvolutionEngineFactory < float > : : CreateTensor ( size_t w , size_t h , size_t c , size_t n ) <nl> template < class ElemType > <nl> typename CuDnnConvolutionEngineFactory < ElemType > : : FilterPtr CuDnnConvolutionEngineFactory < ElemType > : : CreateFilter ( size_t w , size_t h , size_t c , size_t k ) <nl> { <nl> / / REVIEW alexeyk : assert fires in GCC but not in VC + + . <nl> - / / static_assert ( false , " cuDNN engine currently supports only single and double precision filters . " ) ; <nl> + / / static_assert ( false , " cuDNN engine currently supports only single and double precision filters . " ) ; <nl> } <nl> template < > <nl> typename CuDnnConvolutionEngineFactory < float > : : FilterPtr CuDnnConvolutionEngineFactory < float > : : CreateFilter ( size_t w , size_t h , size_t c , size_t k ) <nl> mmm a / Source / Math / GPUMatrix . cu <nl> ppp b / Source / Math / GPUMatrix . cu <nl> static DEVICEID_TYPE SelectBestGPUDeviceId ( ) / / this is an internal version that <nl> cudaDeviceProp deviceProp ; <nl> cudaGetDeviceProperties ( & deviceProp , dev ) ; <nl> int power = _ConvertSMVer2Cores ( deviceProp . major , deviceProp . minor ) * deviceProp . multiProcessorCount ; <nl> - / / CUDA_LONG power = _GetFreeMemoryOnCUDADevice ( dev ) ; <nl> + / / CUDA_LONG power = _GetFreeMemoryOnCUDADevice ( dev ) ; <nl> if ( power > curPower ) <nl> { <nl> curPower = power ; <nl> void GPUMatrix < ElemType > : : SetDevice ( DEVICEID_TYPE deviceId ) <nl> } <nl> <nl> template < class ElemType > <nl> - / * static * / DEVICEID_TYPE GPUMatrix < ElemType > : : GetBestGPUDeviceId ( ) / / returns - 1 if no GPUs can be used <nl> + / * static * / DEVICEID_TYPE GPUMatrix < ElemType > : : GetBestGPUDeviceId ( ) / / returns - 1 if no GPUs can be used <nl> { <nl> / / route the result through EnforceOneGPUOnly ( ) which only lets the first choice through ( see comment there ) <nl> return EnforceOneGPUOnly ( SelectBestGPUDeviceId ( ) ) ; <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : operator = ( GPUMatrix < ElemType > & & moveFr <nl> m_format = moveFrom . m_format ; <nl> m_externalBuffer = moveFrom . m_externalBuffer ; <nl> <nl> - / / release the pointer from the source object so that the destructor won ' t release it twice <nl> + / / release the pointer from the source object so that the destructor won ' t release it twice <nl> moveFrom . ZeroInit ( 0 ) ; <nl> } <nl> return * this ; <nl> void GPUMatrix < ElemType > : : ReleaseWorkspace ( std : : unique_ptr < GPUMatrix < ElemType > > <nl> template < class ElemType > <nl> GPUMatrix < ElemType > GPUMatrix < ElemType > : : ColumnSlice ( size_t startColumn , size_t numCols ) const <nl> { <nl> - / / if ( numCols = = 0 ) <nl> + / / if ( numCols = = 0 ) <nl> / / LogicError ( " The slice cannot have 0 columns . " ) ; <nl> <nl> if ( startColumn + numCols > m_numCols ) <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : AssignColumnSlice ( const GPUMatrix < Elem <nl> template < class ElemType > <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : SetColumnSlice ( const GPUMatrix < ElemType > & fromMatrix , size_t startColumn , size_t numCols ) <nl> { <nl> - / / if ( numCols = = 0 ) <nl> + / / if ( numCols = = 0 ) <nl> / / LogicError ( " The slice cannot have 0 columns . " ) ; <nl> if ( startColumn + numCols > m_numCols ) <nl> LogicError ( " The slice is out of range of the destination matrix . " ) ; <nl> GPUMatrix < ElemType > GPUMatrix < ElemType > : : Diagonal ( ) const <nl> return diag ; <nl> } <nl> # if 0 <nl> - / / stack the columns in inputMatrices ( starting from sliceStartCol for sliceNumCols columns ) and assign it to [ this ] object . <nl> + / / stack the columns in inputMatrices ( starting from sliceStartCol for sliceNumCols columns ) and assign it to [ this ] object . <nl> template < class ElemType > <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : AssignRowStackValuesOf ( const std : : vector < const GPUMatrix < ElemType > * > & inputMatrices , const size_t sliceStartCol , const size_t sliceNumCols ) <nl> { <nl> void GPUMatrix < ElemType > : : SetValue ( const ElemType v ) <nl> } <nl> <nl> template < class ElemType > <nl> - void GPUMatrix < ElemType > : : SetValue ( const ElemType * d_v ) / / d_v is pointer to the the value in GPU memory <nl> + void GPUMatrix < ElemType > : : SetValue ( const ElemType * d_v ) / / d_v is pointer to the the value in GPU memory <nl> { <nl> if ( IsEmpty ( ) ) <nl> LogicError ( " SetValue : Matrix is empty . " ) ; <nl> void GPUMatrix < ElemType > : : SetDiagonalValue ( const GPUMatrix < ElemType > & vector ) <nl> if ( vector . GetNumRows ( ) ! = 1 & & vector . GetNumCols ( ) ! = 1 ) <nl> LogicError ( " SetDiagonalValue : input vector must be a vector . " ) ; <nl> <nl> - if ( vector . GetNumElements ( ) = = 1 ) / / reduce to simple form <nl> + if ( vector . GetNumElements ( ) = = 1 ) / / reduce to simple form <nl> SetDiagonalValue ( vector . m_pArray [ 0 ] ) ; <nl> <nl> else if ( vector . GetNumRows ( ) ! = GetNumRows ( ) ) <nl> void GPUMatrix < ElemType > : : SetUniformRandomValue ( const ElemType low , const ElemTy <nl> } <nl> CUDA_CALL ( cudaEventRecord ( done ) ) ; <nl> CUDA_CALL ( cudaEventSynchronize ( done ) ) ; <nl> - / / CURAND_CALL ( curandDestroyGenerator ( gen ) ) ; <nl> + / / CURAND_CALL ( curandDestroyGenerator ( gen ) ) ; <nl> CUDA_CALL ( cudaEventDestroy ( done ) ) ; <nl> <nl> size_t N = GetNumElements ( ) ; <nl> void GPUMatrix < ElemType > : : SetGaussianRandomValue ( const ElemType mean , const Elem <nl> { <nl> CURAND_CALL ( curandGenerateNormalDouble ( ( ( curandGenerator_t * ) s_curandGenerator ) [ 0 ] , reinterpret_cast < double * > ( m_pArray ) , GetNumElements ( ) , ( double ) mean , ( double ) sigma ) ) ; <nl> } <nl> - / / CURAND_CALL ( curandDestroyGenerator ( gen ) ) ; <nl> + / / CURAND_CALL ( curandDestroyGenerator ( gen ) ) ; <nl> } <nl> <nl> / / maskRate : percentage of values masked out ( similar to dropout rate ) <nl> void GPUMatrix < ElemType > : : SetUniformRandomMask ( const ElemType maskRate , const El <nl> CUDA_CALL ( cudaEventRecord ( done ) ) ; <nl> CUDA_CALL ( cudaEventSynchronize ( done ) ) ; <nl> CUDA_CALL ( cudaEventDestroy ( done ) ) ; <nl> - / / CURAND_CALL ( curandDestroyGenerator ( gen ) ) ; <nl> + / / CURAND_CALL ( curandDestroyGenerator ( gen ) ) ; <nl> <nl> size_t N = GetNumElements ( ) ; <nl> size_t blocksPerGrid = ( size_t ) ceil ( N / ( double ) GridDim : : maxThreadsPerBlock ) ; <nl> ElemType GPUMatrix < ElemType > : : RmsProp ( GPUMatrix < ElemType > & gradients , <nl> ElemType * avars = m_pArray ; / / accumulated variances for RMS scaling <nl> ElemType * signs = m_pArray + n ; / / sign of previous gradient <nl> ElemType * steps = m_pArray + 2 * n ; / / current step size <nl> - / / m_pArray + 3 * n is temp memory used to store multipliers , no need to initialize <nl> + / / m_pArray + 3 * n is temp memory used to store multipliers , no need to initialize <nl> <nl> _rmsprop_init < ElemType > < < < blocksPerGrid , GridDim : : maxThreadsPerBlock > > > ( avars , signs , steps , gradients . m_pArray , n ) ; <nl> } <nl> void GPUMatrix < ElemType > : : Resize ( const size_t numRows , const size_t numCols , boo <nl> } <nl> else <nl> { <nl> - / / if ( ! OwnBuffer ( ) ) <nl> + / / if ( ! OwnBuffer ( ) ) <nl> / / InvalidArgument ( " Can ' t resize a externally managed matrix " ) ; <nl> if ( m_pArray ) <nl> { <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : AssignSumOf ( const ElemType alpha , cons <nl> template < class ElemType > <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : operator + = ( const GPUMatrix < ElemType > & a ) <nl> { <nl> - / / if ( a . GetNumElements ( ) = = 1 ) <nl> - / / { <nl> - / / / / * this + = a . Get00Element ( ) ; <nl> + / / if ( a . GetNumElements ( ) = = 1 ) <nl> + / / { <nl> + / / / / * this + = a . Get00Element ( ) ; <nl> / / CUDA_LONG N = ( CUDA_LONG ) GetNumElements ( ) ; <nl> / / int blocksPerGrid = ( int ) ceil ( 1 . 0 * N / GridDim : : maxThreadsPerBlock ) ; <nl> / / cudaEvent_t done = nullptr ; <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : operator + = ( const GPUMatrix < ElemType > & <nl> / / if ( do_sync ) CUDA_CALL ( cudaEventRecord ( done ) ) ; <nl> / / if ( do_sync ) CUDA_CALL ( cudaEventSynchronize ( done ) ) ; <nl> / / if ( do_sync ) CUDA_CALL ( cudaEventDestroy ( done ) ) ; <nl> - / / } <nl> - / / else <nl> - / / { <nl> + / / } <nl> + / / else <nl> + / / { <nl> ScaleAndAdd ( 1 , a , * this ) ; <nl> - / / } <nl> + / / } <nl> return * this ; <nl> } <nl> <nl> GPUMatrix < ElemType > GPUMatrix < ElemType > : : operator + ( const GPUMatrix < ElemType > & a ) <nl> } <nl> else <nl> { <nl> - GPUMatrix < ElemType > c ( * this ) ; / / this implementation will introduce a copy overhead . but make resue of the code <nl> + GPUMatrix < ElemType > c ( * this ) ; / / this implementation will introduce a copy overhead . but make resue of the code <nl> c + = a ; <nl> return c ; <nl> } <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : AssignDifferenceOf ( const GPUMatrix < Ele <nl> template < class ElemType > <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : operator - = ( const GPUMatrix < ElemType > & a ) <nl> { <nl> - / / if ( a . GetNumElements ( ) = = 1 ) <nl> + / / if ( a . GetNumElements ( ) = = 1 ) <nl> / / AssignDifferenceOf ( * this , a . Get00Element ( ) ) ; <nl> - / / else if ( GetNumElements ( ) = = 1 ) <nl> + / / else if ( GetNumElements ( ) = = 1 ) <nl> / / AssignDifferenceOf ( Get00Element ( ) , a ) ; <nl> - / / else <nl> + / / else <nl> ScaleAndAdd ( - 1 , a , * this ) ; <nl> <nl> return * this ; <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : operator - = ( const GPUMatrix < ElemType > & <nl> template < class ElemType > <nl> GPUMatrix < ElemType > GPUMatrix < ElemType > : : operator - ( const GPUMatrix < ElemType > & a ) const <nl> { <nl> - GPUMatrix < ElemType > c ( * this ) ; / / this implementation will introduce a copy overhead . but make resue of the code <nl> + GPUMatrix < ElemType > c ( * this ) ; / / this implementation will introduce a copy overhead . but make resue of the code <nl> c - = a ; <nl> return c ; <nl> } <nl> void GPUMatrix < ElemType > : : AssignNoiseContrastiveEstimation ( const GPUMatrix < ElemT <nl> cudaEvent_t done = nullptr ; <nl> if ( do_sync ) <nl> CUDA_CALL ( cudaEventCreate ( & done ) ) ; <nl> - / / a : dim * minibatch <nl> - / / b : dim * | vocab | <nl> + / / a : dim * minibatch <nl> + / / b : dim * | vocab | <nl> int p = 512 ; <nl> - int width = a . GetNumRows ( ) ; / / dimension of hidden vector <nl> + int width = a . GetNumRows ( ) ; / / dimension of hidden vector <nl> <nl> while ( p / 2 > width ) <nl> p = p / 2 ; <nl> void GPUMatrix < ElemType > : : AssignNoiseContrastiveEstimation ( const GPUMatrix < ElemT <nl> this - > GetArray ( ) , <nl> sampleCount , <nl> m_numRows / 2 , <nl> - my_a . GetArray ( ) , / / a <nl> + my_a . GetArray ( ) , / / a <nl> a . GetNumRows ( ) , <nl> - my_b . GetArray ( ) , / / b <nl> + my_b . GetArray ( ) , / / b <nl> my_bias . GetArray ( ) , <nl> - tmp . GetArray ( ) ) ; / / tmp <nl> + tmp . GetArray ( ) ) ; / / tmp <nl> <nl> p = 512 ; <nl> while ( p / 2 > this - > GetNumElements ( ) / 2 ) <nl> void GPUMatrix < ElemType > : : AssignNCEUnnormalizedEval ( const GPUMatrix < ElemType > & a <nl> b . GetNumRows ( ) , <nl> m_res ) ; <nl> <nl> - / / sum up the results <nl> + / / sum up the results <nl> _reductionSum32 < ElemType > < < < 1 , 32 > > > ( m_res , c . GetArray ( ) , m_nz ) ; * / <nl> } <nl> <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : InplaceLogSoftmax ( const bool isColWise <nl> PrepareDevice ( ) ; <nl> if ( isColWise ) <nl> { <nl> - CUDA_LONG N = ( CUDA_LONG ) GetNumCols ( ) ; / / one kernel per column <nl> + CUDA_LONG N = ( CUDA_LONG ) GetNumCols ( ) ; / / one kernel per column <nl> int blocksPerGrid = ( int ) ceil ( N * 1 . 0 / GridDim : : maxThreadsPerBlock ) ; <nl> cudaEvent_t done = nullptr ; <nl> if ( do_sync ) <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : InplaceLogSoftmax ( const bool isColWise <nl> } <nl> else <nl> { <nl> - CUDA_LONG N = ( CUDA_LONG ) GetNumRows ( ) ; / / one kernel per column <nl> + CUDA_LONG N = ( CUDA_LONG ) GetNumRows ( ) ; / / one kernel per column <nl> int blocksPerGrid = ( int ) ceil ( N * 1 . 0 / GridDim : : maxThreadsPerBlock ) ; <nl> cudaEvent_t done = nullptr ; <nl> if ( do_sync ) <nl> ElemType GPUMatrix < ElemType > : : SumOfElements ( ) const <nl> ElemType * d_sum = TracingGPUMemoryAllocator : : Allocate < ElemType > ( m_computeDevice , 1 ) ; <nl> ElemType h_sum ; <nl> <nl> - / / WARNING : THIS kernel is not the most efficient way ! <nl> + / / WARNING : THIS kernel is not the most efficient way ! <nl> _reductionSum < ElemType > < < < 1 , 1024 , 0 , t_stream > > > ( m_pArray , d_sum , ( CUDA_LONG ) GetNumElements ( ) ) ; <nl> CUDA_CALL ( cudaMemcpy ( & h_sum , d_sum , sizeof ( ElemType ) , cudaMemcpyDeviceToHost ) ) ; <nl> TracingGPUMemoryAllocator : : Free < ElemType > ( m_computeDevice , d_sum ) ; <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : AssignSumOfElements ( const GPUMatrix < El <nl> cudaEvent_t done = nullptr ; <nl> if ( do_sync ) <nl> CUDA_CALL ( cudaEventCreate ( & done ) ) ; <nl> - / / WARNING : THIS kernel is not the most efficient way ! <nl> + / / WARNING : THIS kernel is not the most efficient way ! <nl> _reductionSumAndAssign < ElemType > < < < 1 , 1024 > > > ( m_pArray , a . m_pArray , ( CUDA_LONG ) a . GetNumElements ( ) , ( CUDA_LONG ) GetNumElements ( ) ) ; <nl> if ( do_sync ) <nl> CUDA_CALL ( cudaEventRecord ( done ) ) ; <nl> DeviceBoundNumber < ElemType > GPUMatrix < ElemType > : : Sum_AsDeviceBoundNum ( ) const <nl> LogicError ( " Matrix is empty " ) ; <nl> ElemType * d_sum = TracingGPUMemoryAllocator : : Allocate < ElemType > ( m_computeDevice , 1 ) ; <nl> <nl> - / / WARNING : THIS kernel is not the most efficient way ! <nl> + / / WARNING : THIS kernel is not the most efficient way ! <nl> _reductionSum < ElemType > < < < 1 , 1024 , 0 , t_stream > > > ( m_pArray , d_sum , ( CUDA_LONG ) GetNumElements ( ) ) ; <nl> DeviceBoundNumber < ElemType > result ; <nl> result . ShallowCopyFrom ( d_sum , GetComputeDeviceId ( ) ) ; <nl> void GPUMatrix < ElemType > : : VectorSum ( const GPUMatrix < ElemType > & a , GPUMatrix < Elem <nl> <nl> const CUDA_LONG n = ( CUDA_LONG ) a . GetNumRows ( ) ; <nl> const CUDA_LONG m = ( CUDA_LONG ) a . GetNumCols ( ) ; <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> cudaEvent_t done = nullptr ; <nl> <nl> int blocksPerGrid = 0 ; <nl> - if ( isColWise ) / / col - wise <nl> + if ( isColWise ) / / col - wise <nl> { <nl> c . Resize ( 1 , m ) ; <nl> blocksPerGrid = ( int ) ceil ( 1 . 0 * m / GridDim : : maxThreadsPerBlock ) ; <nl> void GPUMatrix < ElemType > : : VectorNorm1 ( GPUMatrix < ElemType > & c , const bool isColWi <nl> <nl> const CUDA_LONG n = ( CUDA_LONG ) GetNumRows ( ) ; <nl> const CUDA_LONG m = ( CUDA_LONG ) GetNumCols ( ) ; <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> cudaEvent_t done = nullptr ; <nl> PrepareDevice ( ) ; <nl> c . ChangeDeviceTo ( GetComputeDeviceId ( ) ) ; <nl> <nl> int blocksPerGrid = 0 ; <nl> - if ( isColWise ) / / col - wise <nl> + if ( isColWise ) / / col - wise <nl> { <nl> c . Resize ( 1 , m ) ; <nl> blocksPerGrid = ( int ) ceil ( 1 . 0 * m / GridDim : : maxThreadsPerBlock ) ; <nl> void GPUMatrix < ElemType > : : VectorNorm2 ( GPUMatrix < ElemType > & c , const bool isColWi <nl> <nl> const CUDA_LONG n = ( CUDA_LONG ) GetNumRows ( ) ; <nl> const CUDA_LONG m = ( CUDA_LONG ) GetNumCols ( ) ; <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> cudaEvent_t done = nullptr ; <nl> PrepareDevice ( ) ; <nl> c . ChangeDeviceTo ( GetComputeDeviceId ( ) ) ; <nl> <nl> int blocksPerGrid = 0 ; <nl> - if ( isColWise ) / / col - wise <nl> + if ( isColWise ) / / col - wise <nl> { <nl> c . Resize ( 1 , m ) ; <nl> blocksPerGrid = ( int ) ceil ( 1 . 0 * m / GridDim : : maxThreadsPerBlock ) ; <nl> void GPUMatrix < ElemType > : : VectorNormInf ( GPUMatrix < ElemType > & c , const bool isCol <nl> if ( IsEmpty ( ) ) <nl> LogicError ( " VectorMax : Matrix is empty . " ) ; <nl> <nl> - / / this implementation is not efficient <nl> + / / this implementation is not efficient <nl> GPUMatrix < ElemType > tmp ( GetComputeDeviceId ( ) ) ; <nl> GPUMatrix < ElemType > tmp1 ( GetComputeDeviceId ( ) ) ; <nl> tmp . AssignAbsOf ( ( * this ) ) ; <nl> ElemType GPUMatrix < ElemType > : : FrobeniusNorm ( ) const <nl> ElemType * d_sum = TracingGPUMemoryAllocator : : Allocate < ElemType > ( m_computeDevice , 1 ) ; <nl> <nl> ElemType h_sum = 0 ; <nl> - / / WARNING : THIS kernel is not the most efficient way ! <nl> + / / WARNING : THIS kernel is not the most efficient way ! <nl> _reductionSum2 < ElemType > < < < 1 , 1024 , 0 , t_stream > > > ( m_pArray , d_sum , ( CUDA_LONG ) GetNumElements ( ) , true ) ; <nl> CUDA_CALL ( cudaMemcpy ( & h_sum , d_sum , sizeof ( ElemType ) , cudaMemcpyDeviceToHost ) ) ; <nl> TracingGPUMemoryAllocator : : Free < ElemType > ( m_computeDevice , d_sum ) ; <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : AssignFrobeniusNormOf ( const GPUMatrix < <nl> Resize ( 1 , 1 ) ; <nl> <nl> PrepareDevice ( ) ; <nl> - / / WARNING : THIS kernel is not the most efficient way ! <nl> + / / WARNING : THIS kernel is not the most efficient way ! <nl> _reductionSum2 < ElemType > < < < 1 , 1024 , 0 , t_stream > > > ( a . m_pArray , m_pArray , ( CUDA_LONG ) a . GetNumElements ( ) , true ) ; <nl> <nl> return * this ; <nl> ElemType GPUMatrix < ElemType > : : MatrixNormInf ( ) const <nl> ElemType * d_maxAbs = TracingGPUMemoryAllocator : : Allocate < ElemType > ( m_computeDevice , 1 ) ; <nl> <nl> ElemType h_maxAbs = 0 ; <nl> - / / WARNING : THIS kernel is not the most efficient way ! <nl> + / / WARNING : THIS kernel is not the most efficient way ! <nl> _reductionMatrixNormInf < ElemType > < < < 1 , 1024 , 0 , t_stream > > > ( m_pArray , d_maxAbs , ( CUDA_LONG ) GetNumElements ( ) ) ; <nl> CUDA_CALL ( cudaMemcpy ( & h_maxAbs , d_maxAbs , sizeof ( ElemType ) , cudaMemcpyDeviceToHost ) ) ; <nl> TracingGPUMemoryAllocator : : Free < ElemType > ( m_computeDevice , d_maxAbs ) ; <nl> ElemType GPUMatrix < ElemType > : : MatrixNorm0 ( ) const <nl> <nl> ElemType * d_nz = TracingGPUMemoryAllocator : : Allocate < ElemType > ( m_computeDevice , 1 ) ; <nl> ElemType h_nz = 0 ; <nl> - / / WARNING : THIS kernel is not the most efficient way ! <nl> + / / WARNING : THIS kernel is not the most efficient way ! <nl> _reductionMatrixNorm0 < ElemType > < < < 1 , 1024 , 0 , t_stream > > > ( m_pArray , d_nz , ( CUDA_LONG ) GetNumElements ( ) ) ; <nl> CUDA_CALL ( cudaMemcpy ( & h_nz , d_nz , sizeof ( ElemType ) , cudaMemcpyDeviceToHost ) ) ; <nl> TracingGPUMemoryAllocator : : Free < ElemType > ( m_computeDevice , d_nz ) ; <nl> void GPUMatrix < ElemType > : : VectorMax ( GPUMatrix < ElemType > & maxIndexes , GPUMatrix < E <nl> const GPUMatrix < ElemType > & us = * this ; <nl> const CUDA_LONG m = ( CUDA_LONG ) GetNumRows ( ) ; <nl> const CUDA_LONG n = ( CUDA_LONG ) GetNumCols ( ) ; <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> PrepareDevice ( ) ; <nl> cudaEvent_t done = nullptr ; <nl> void GPUMatrix < ElemType > : : VectorMax ( GPUMatrix < ElemType > & maxIndexes , GPUMatrix < E <nl> maxValues . Resize ( 1 , n ) ; <nl> maxIndexes . Resize ( 1 , n ) ; <nl> <nl> - int blocksPerGrid = n ; / / we ' ll have 1 block processing 1 column <nl> + int blocksPerGrid = n ; / / we ' ll have 1 block processing 1 column <nl> _vectorMaxMinReduce < ElemType , true > < < < blocksPerGrid , GridDim : : maxThreadsPerBlock , 0 , t_stream > > > ( us . m_pArray , maxIndexes . m_pArray , maxValues . m_pArray , m , n ) ; <nl> <nl> / * int blocksPerGrid = ( int ) ceil ( 1 . 0 * n / GridDim : : maxThreadsPerBlock ) ; <nl> void GPUMatrix < ElemType > : : VectorMax ( GPUMatrix < ElemType > & maxIndexes , GPUMatrix < E <nl> const CUDA_LONG m = ( CUDA_LONG ) GetNumRows ( ) ; <nl> const CUDA_LONG n = ( CUDA_LONG ) GetNumCols ( ) ; <nl> assert ( topK < = m ) ; <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> PrepareDevice ( ) ; <nl> cudaEvent_t done = nullptr ; <nl> void GPUMatrix < ElemType > : : VectorMin ( GPUMatrix < ElemType > & minIndexes , GPUMatrix < E <nl> const int m = ( int ) GetNumRows ( ) ; <nl> const int n = ( int ) GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> PrepareDevice ( ) ; <nl> cudaEvent_t done = nullptr ; <nl> if ( do_sync ) <nl> void GPUMatrix < ElemType > : : VectorMin ( GPUMatrix < ElemType > & minIndexes , GPUMatrix < E <nl> minValues . Resize ( 1 , n ) ; <nl> minIndexes . Resize ( 1 , n ) ; <nl> <nl> - int blocksPerGrid = n ; / / we ' ll have 1 block processing 1 column <nl> + int blocksPerGrid = n ; / / we ' ll have 1 block processing 1 column <nl> _vectorMaxMinReduce < ElemType , false > < < < blocksPerGrid , GridDim : : maxThreadsPerBlock , 0 , t_stream > > > ( us . m_pArray , minIndexes . m_pArray , minValues . m_pArray , m , n ) ; <nl> <nl> / * <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : AssignNumOfDiff ( const GPUMatrix < ElemTy <nl> if ( ! searchInCol & & a . GetNumRows ( ) ! = b . GetNumRows ( ) ) <nl> InvalidArgument ( " AssignNumOfDiff : a and b must have the same number of rows . " ) ; <nl> <nl> - Resize ( 1 , 1 ) ; / / result should be one element <nl> + Resize ( 1 , 1 ) ; / / result should be one element <nl> <nl> PrepareDevice ( ) ; <nl> cudaEvent_t done = nullptr ; <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : AssignNumOfDiff ( const GPUMatrix < ElemTy <nl> CUDA_CALL ( cudaEventCreate ( & done ) ) ; <nl> if ( ! searchInCol ) <nl> { <nl> - / / int blocksPerGrid = ( int ) ceil ( 1 . 0 * a . GetNumElements ( ) / GridDim : : maxThreadsPerBlock ) ; <nl> - / / _assignNumOfDiff < ElemType > < < < blocksPerGrid , GridDim : : maxThreadsPerBlock , 0 , t_stream > > > ( a . m_pArray , b . m_pArray , m_pArray , a . GetNumElements ( ) ) ; <nl> + / / int blocksPerGrid = ( int ) ceil ( 1 . 0 * a . GetNumElements ( ) / GridDim : : maxThreadsPerBlock ) ; <nl> + / / _assignNumOfDiff < ElemType > < < < blocksPerGrid , GridDim : : maxThreadsPerBlock , 0 , t_stream > > > ( a . m_pArray , b . m_pArray , m_pArray , a . GetNumElements ( ) ) ; <nl> _assignNumOfDiff < ElemType > < < < 1 , 1024 , 0 , t_stream > > > ( a . m_pArray , b . m_pArray , m_pArray , ( CUDA_LONG ) a . GetNumElements ( ) ) ; <nl> } <nl> else <nl> void GPUMatrix < ElemType > : : MultiplyAndWeightedAdd ( ElemType alpha , const GPUMatrix <nl> ElemType beta , GPUMatrix < ElemType > & c ) <nl> { <nl> a . PrepareDevice ( ) ; <nl> - if ( ( a . GetComputeDeviceId ( ) ! = b . GetComputeDeviceId ( ) ) | | ( b . GetComputeDeviceId ( ) ! = c . GetComputeDeviceId ( ) ) ) / / different GPUs <nl> + if ( ( a . GetComputeDeviceId ( ) ! = b . GetComputeDeviceId ( ) ) | | ( b . GetComputeDeviceId ( ) ! = c . GetComputeDeviceId ( ) ) ) / / different GPUs <nl> InvalidArgument ( " All matrices must be on the same GPU " ) ; <nl> <nl> cublasHandle_t cuHandle = GetCublasHandle ( b . GetComputeDeviceId ( ) ) ; <nl> void GPUMatrix < ElemType > : : MultiplyAndWeightedAdd ( ElemType alpha , const GPUMatrix <nl> c . VerifySize ( m , n ) ; / / Can ' t resize if beta ! = 0 <nl> <nl> if ( ! ( m > 0 & & k > 0 & & l > 0 & & n > 0 ) ) <nl> - RuntimeError ( " ! ( m > 0 & & k > 0 & & l > 0 & & n > 0 ) " ) ; / / converting from size_t to int may cause overflow <nl> + RuntimeError ( " ! ( m > 0 & & k > 0 & & l > 0 & & n > 0 ) " ) ; / / converting from size_t to int may cause overflow <nl> if ( k ! = l ) <nl> RuntimeError ( " matrix dim mismatch in MultiplyAndWeightedAdd " ) ; <nl> CUBLAS_CALL ( cublas_gemm ( cuHandle , transA , transB , m , n , k , & alpha , a . m_pArray , ( int ) a . m_numRows , b . m_pArray , ( int ) b . m_numRows , & beta , c . m_pArray , ( int ) c . m_numRows ) ) ; <nl> template < class ElemType > <nl> void GPUMatrix < ElemType > : : Multiply1x1AndWeightedAdd ( ElemType alpha , const GPUMatrix < ElemType > & a , const GPUMatrix < ElemType > & b , ElemType beta , GPUMatrix < ElemType > & c ) <nl> { <nl> a . PrepareDevice ( ) ; <nl> - if ( ( a . GetComputeDeviceId ( ) ! = b . GetComputeDeviceId ( ) ) | | ( b . GetComputeDeviceId ( ) ! = c . GetComputeDeviceId ( ) ) ) / / different GPUs <nl> + if ( ( a . GetComputeDeviceId ( ) ! = b . GetComputeDeviceId ( ) ) | | ( b . GetComputeDeviceId ( ) ! = c . GetComputeDeviceId ( ) ) ) / / different GPUs <nl> InvalidArgument ( " All matrices must be on the same GPU " ) ; <nl> CUDA_LONG N = ( CUDA_LONG ) c . GetNumElements ( ) ; <nl> int blocksPerGrid = ( int ) ceil ( 1 . 0 * N / GridDim : : maxThreadsPerBlock ) ; <nl> void GPUMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const GPUMatrix < ElemType > & <nl> a . PrepareDevice ( ) ; <nl> if ( a . IsEmpty ( ) | | c . IsEmpty ( ) ) <nl> LogicError ( " ScaleAndAdd : one of the input matrices is empty . " ) ; <nl> - / / if ( a . GetNumRows ( ) ! = 1 & & a . GetNumCols ( ) ! = 1 ) / / a is not a col or row vector <nl> + / / if ( a . GetNumRows ( ) ! = 1 & & a . GetNumCols ( ) ! = 1 ) / / a is not a col or row vector <nl> if ( a . GetNumRows ( ) = = c . GetNumRows ( ) & & a . GetNumCols ( ) = = c . GetNumCols ( ) ) / / dimensions match <nl> { <nl> const int m = ( int ) a . GetNumRows ( ) ; <nl> void GPUMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const GPUMatrix < ElemType > & <nl> const int incx = 1 ; <nl> const int incy = 1 ; <nl> <nl> - assert ( m > 0 & & n > 0 & & len > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & len > 0 ) ; / / converting from size_t to int may cause overflow <nl> assert ( ( int ) c . GetNumRows ( ) = = m & & ( int ) c . GetNumCols ( ) = = n ) ; <nl> if ( ( int ) c . GetNumRows ( ) ! = m | | ( int ) c . GetNumCols ( ) ! = n ) <nl> InvalidArgument ( " dimension of matrix c does not match dimension of matrix a . " ) ; <nl> void GPUMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const GPUMatrix < ElemType > & <nl> if ( do_sync ) <nl> CUDA_CALL ( cudaEventDestroy ( done ) ) ; <nl> } <nl> - else if ( a . GetNumCols ( ) = = 1 ) / / col vector , add it to all columns <nl> + else if ( a . GetNumCols ( ) = = 1 ) / / col vector , add it to all columns <nl> { <nl> CUDA_LONG m = ( CUDA_LONG ) c . GetNumRows ( ) ; <nl> CUDA_LONG n = ( CUDA_LONG ) c . GetNumCols ( ) ; <nl> void GPUMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const GPUMatrix < ElemType > & <nl> if ( do_sync ) <nl> CUDA_CALL ( cudaEventDestroy ( done ) ) ; <nl> } <nl> - else if ( a . GetNumRows ( ) = = 1 ) / / row vector , add it to all rows <nl> + else if ( a . GetNumRows ( ) = = 1 ) / / row vector , add it to all rows <nl> { <nl> cublasHandle_t cuHandle = GetCublasHandle ( a . GetComputeDeviceId ( ) ) ; <nl> int m = ( int ) c . GetNumRows ( ) ; <nl> void GPUMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const GPUMatrix < ElemType > & <nl> if ( a . IsEmpty ( ) | | b . IsEmpty ( ) ) <nl> LogicError ( " ScaleAndAdd : one of the input matrices is empty . " ) ; <nl> c . Resize ( b . GetNumRows ( ) , b . GetNumCols ( ) ) ; <nl> - / / if ( a . GetNumRows ( ) ! = 1 & & a . GetNumCols ( ) ! = 1 ) / / a is not a col or row vector <nl> + / / if ( a . GetNumRows ( ) ! = 1 & & a . GetNumCols ( ) ! = 1 ) / / a is not a col or row vector <nl> if ( a . GetNumRows ( ) = = b . GetNumRows ( ) & & a . GetNumCols ( ) = = b . GetNumCols ( ) ) / / dimensions match <nl> { <nl> / * <nl> void GPUMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const GPUMatrix < ElemType > & <nl> const int len = m * n ; <nl> const int incx = 1 ; <nl> const int incy = 1 ; <nl> - assert ( m > 0 & & n > 0 & & len > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & len > 0 ) ; / / converting from size_t to int may cause overflow <nl> * / <nl> CUDA_LONG N = ( CUDA_LONG ) c . GetNumElements ( ) ; <nl> int blocksPerGrid = ( int ) ceil ( 1 . 0 * N / GridDim : : maxThreadsPerBlock ) ; <nl> void GPUMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const GPUMatrix < ElemType > & <nl> if ( do_sync ) <nl> CUDA_CALL ( cudaEventDestroy ( done ) ) ; <nl> } <nl> - else if ( a . GetNumCols ( ) = = 1 ) / / col vector , add it to all columns <nl> + else if ( a . GetNumCols ( ) = = 1 ) / / col vector , add it to all columns <nl> { <nl> CUDA_LONG m = ( CUDA_LONG ) c . GetNumRows ( ) ; <nl> CUDA_LONG n = ( CUDA_LONG ) c . GetNumCols ( ) ; <nl> void GPUMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const GPUMatrix < ElemType > & <nl> if ( do_sync ) <nl> CUDA_CALL ( cudaEventDestroy ( done ) ) ; <nl> } <nl> - else if ( a . GetNumRows ( ) = = 1 ) / / row vector , add it to all rows <nl> + else if ( a . GetNumRows ( ) = = 1 ) / / row vector , add it to all rows <nl> { <nl> CUDA_LONG m = ( CUDA_LONG ) c . GetNumRows ( ) ; <nl> CUDA_LONG n = ( CUDA_LONG ) c . GetNumCols ( ) ; <nl> void GPUMatrix < ElemType > : : AddElementToElement ( const GPUMatrix < ElemType > & a , cons <nl> <nl> a . PrepareDevice ( ) ; <nl> cudaEvent_t done = nullptr ; <nl> - int blocksPerGrid = 1 ; / / only one element - - BUGBUG : then why not launch only 1 thread per block ? <nl> + int blocksPerGrid = 1 ; / / only one element - - BUGBUG : then why not launch only 1 thread per block ? <nl> if ( do_sync ) <nl> CUDA_CALL ( cudaEventCreate ( & done ) ) ; <nl> _addElementToElement < ElemType > < < < blocksPerGrid , GridDim : : maxThreadsPerBlock / * BUGBUG : should be 1 ? * / , 0 , t_stream > > > ( a . m_pArray , ( CUDA_LONG ) a . LocateElement ( ai , aj ) , c . m_pArray , ( CUDA_LONG ) c . LocateElement ( ci , cj ) ) ; <nl> void GPUMatrix < ElemType > : : Scale ( GPUMatrix < ElemType > & alpha , GPUMatrix < ElemType > & <nl> cublasSetPointerMode ( cuHandle , CUBLAS_POINTER_MODE_HOST ) ; <nl> } <nl> <nl> - template < class ElemType > / / c = alpha * a <nl> + template < class ElemType > / / c = alpha * a <nl> void GPUMatrix < ElemType > : : Scale ( ElemType alpha , const GPUMatrix < ElemType > & a , GPUMatrix < ElemType > & c ) <nl> { <nl> if ( a . IsEmpty ( ) ) <nl> void GPUMatrix < ElemType > : : Scale ( ElemType alpha , const GPUMatrix < ElemType > & a , GP <nl> template < class ElemType > <nl> void GPUMatrix < ElemType > : : InnerProduct ( const GPUMatrix < ElemType > & a , const GPUMatrix < ElemType > & b , GPUMatrix < ElemType > & c , const bool isColWise ) <nl> { <nl> - if ( a . GetComputeDeviceId ( ) ! = b . GetComputeDeviceId ( ) | | b . GetComputeDeviceId ( ) ! = c . GetComputeDeviceId ( ) ) / / different GPUs <nl> + if ( a . GetComputeDeviceId ( ) ! = b . GetComputeDeviceId ( ) | | b . GetComputeDeviceId ( ) ! = c . GetComputeDeviceId ( ) ) / / different GPUs <nl> InvalidArgument ( " All matrices must be on the same GPU " ) ; <nl> <nl> if ( a . IsEmpty ( ) | | b . IsEmpty ( ) ) <nl> void GPUMatrix < ElemType > : : InnerProduct ( const GPUMatrix < ElemType > & a , const GPUMa <nl> const int k = ( int ) b . GetNumRows ( ) ; <nl> const int l = ( int ) b . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> - assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> if ( m ! = k | | n ! = l ) <nl> InvalidArgument ( " Matrices a and b should have same dimension . " ) ; <nl> <nl> void GPUMatrix < ElemType > : : InnerProduct ( const GPUMatrix < ElemType > & a , const GPUMa <nl> else <nl> c . Resize ( m , 1 ) ; <nl> <nl> - if ( ( isColWise & & m = = 1 ) | | ! isColWise & & n = = 1 ) / / in this case it ' s equivalent to element - wise product <nl> + if ( ( isColWise & & m = = 1 ) | | ! isColWise & & n = = 1 ) / / in this case it ' s equivalent to element - wise product <nl> { <nl> c . AssignElementProductOf ( a , b ) ; <nl> } <nl> void GPUMatrix < ElemType > : : InnerProduct ( const GPUMatrix < ElemType > & a , const GPUMa <nl> c . PrepareDevice ( ) ; <nl> <nl> int blocksPerGrid = 0 ; <nl> - if ( isColWise ) / / col - wise <nl> + if ( isColWise ) / / col - wise <nl> { <nl> c . Resize ( 1 , n ) ; <nl> blocksPerGrid = ( int ) ceil ( 1 . 0 * n / GridDim : : maxThreadsPerBlock ) ; <nl> ElemType GPUMatrix < ElemType > : : InnerProductOfMatrices ( const GPUMatrix < ElemType > & <nl> const int k = ( int ) b . GetNumRows ( ) ; <nl> const int l = ( int ) b . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> - assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> if ( m ! = k | | n ! = l ) <nl> InvalidArgument ( " InnerProductOfMatrices : Matrices a and b should have same dimension . " ) ; <nl> <nl> ElemType GPUMatrix < ElemType > : : InnerProductOfMatrices ( const GPUMatrix < ElemType > & <nl> double tmp = 0 ; <nl> CUBLAS_CALL ( cublasDdot ( cuHandle , m * n , reinterpret_cast < double * > ( a . m_pArray ) , 1 , reinterpret_cast < double * > ( b . m_pArray ) , 1 , & tmp ) ) ; <nl> return ElemType ( tmp ) ; <nl> - / / return ( ElemType ) ddot ( ( int ) a . GetNumElements ( ) , reinterpret_cast < double * > ( a . m_pArray ) , 1 , reinterpret_cast < double * > ( b . m_pArray ) , 1 ) ; <nl> + / / return ( ElemType ) ddot ( ( int ) a . GetNumElements ( ) , reinterpret_cast < double * > ( a . m_pArray ) , 1 , reinterpret_cast < double * > ( b . m_pArray ) , 1 ) ; <nl> } <nl> else <nl> { <nl> float tmp = 0 ; <nl> CUBLAS_CALL ( cublasSdot ( cuHandle , m * n , reinterpret_cast < float * > ( a . m_pArray ) , 1 , reinterpret_cast < float * > ( b . m_pArray ) , 1 , & tmp ) ) ; <nl> return tmp ; <nl> - / / return ( ElemType ) sdot ( ( int ) a . GetNumElements ( ) , reinterpret_cast < float * > ( a . m_pArray ) , 1 , reinterpret_cast < float * > ( b . m_pArray ) , 1 ) ; <nl> + / / return ( ElemType ) sdot ( ( int ) a . GetNumElements ( ) , reinterpret_cast < float * > ( a . m_pArray ) , 1 , reinterpret_cast < float * > ( b . m_pArray ) , 1 ) ; <nl> } <nl> } <nl> <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : AssignInnerProductOfMatrices ( const GPU <nl> const int k = ( int ) b . GetNumRows ( ) ; <nl> const int l = ( int ) b . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> - assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> if ( m ! = k | | n ! = l ) <nl> InvalidArgument ( " InnerProductOfMatrices : Matrices a and b should have same dimension . " ) ; <nl> <nl> void GPUMatrix < ElemType > : : ResetCurandObject ( unsigned long seed , const char * call <nl> template < class ElemType > <nl> GPUMatrix < ElemType > GPUMatrix < ElemType > : : Ones ( const size_t rows , const size_t cols , int deviceId ) <nl> { <nl> - GPUMatrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> + GPUMatrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> c . SetValue ( 1 ) ; <nl> return c ; <nl> } <nl> GPUMatrix < ElemType > GPUMatrix < ElemType > : : Ones ( const size_t rows , const size_t co <nl> template < class ElemType > <nl> GPUMatrix < ElemType > GPUMatrix < ElemType > : : Zeros ( const size_t rows , const size_t cols , int deviceId ) <nl> { <nl> - GPUMatrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> - / / c . SetValue ( 0 ) ; <nl> + GPUMatrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> + / / c . SetValue ( 0 ) ; <nl> return c ; <nl> } <nl> <nl> template < class ElemType > <nl> GPUMatrix < ElemType > GPUMatrix < ElemType > : : Eye ( const size_t rows , int deviceId ) <nl> { <nl> - GPUMatrix < ElemType > c ( rows , rows , deviceId ) ; / / will initialize to 0 <nl> + GPUMatrix < ElemType > c ( rows , rows , deviceId ) ; / / will initialize to 0 <nl> c . SetDiagonalValue ( 1 ) ; <nl> return c ; <nl> } <nl> GPUMatrix < ElemType > GPUMatrix < ElemType > : : Eye ( const size_t rows , int deviceId ) <nl> template < class ElemType > <nl> GPUMatrix < ElemType > GPUMatrix < ElemType > : : RandomUniform ( const size_t rows , const size_t cols , int deviceId , const ElemType low , const ElemType high , unsigned long seed ) <nl> { <nl> - GPUMatrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> + GPUMatrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> c . SetUniformRandomValue ( low , high , seed ) ; <nl> return c ; <nl> } <nl> GPUMatrix < ElemType > GPUMatrix < ElemType > : : RandomUniform ( const size_t rows , const <nl> template < class ElemType > <nl> GPUMatrix < ElemType > GPUMatrix < ElemType > : : RandomGaussian ( const size_t rows , const size_t cols , int deviceId , const ElemType mean , const ElemType sigma , unsigned long seed ) <nl> { <nl> - GPUMatrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> + GPUMatrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> c . SetGaussianRandomValue ( mean , sigma , seed ) ; <nl> return c ; <nl> } <nl> ElemType GPUMatrix < ElemType > : : GetLearnRateForBlock_Helper ( const GPUMatrix < ElemTy <nl> { <nl> ElemType * d_res = TracingGPUMemoryAllocator : : Allocate < ElemType > ( Gradients . GetComputeDeviceId ( ) , 1 ) ; <nl> <nl> - / / Compute inner product of matrices and keep it on device <nl> + / / Compute inner product of matrices and keep it on device <nl> const int m = ( int ) Gradients . GetNumRows ( ) ; <nl> const int n = ( int ) Gradients . GetNumCols ( ) ; <nl> const int k = ( int ) SmoothedGradients . GetNumRows ( ) ; <nl> const int l = ( int ) SmoothedGradients . GetNumCols ( ) ; <nl> - assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> - assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> if ( m ! = k | | n ! = l ) <nl> InvalidArgument ( " InnerProductOfMatrices : Matrices a and b should have same dimension . " ) ; <nl> <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : AssignElementProductOfWithShiftNeg ( con <nl> template < class ElemType > <nl> void GPUMatrix < ElemType > : : InnerProductWithShiftNeg ( const GPUMatrix < ElemType > & a , const GPUMatrix < ElemType > & b , GPUMatrix < ElemType > & c , const size_t shift , const size_t nt ) <nl> { <nl> - if ( a . GetComputeDeviceId ( ) ! = b . GetComputeDeviceId ( ) | | b . GetComputeDeviceId ( ) ! = c . GetComputeDeviceId ( ) ) / / different GPUs <nl> + if ( a . GetComputeDeviceId ( ) ! = b . GetComputeDeviceId ( ) | | b . GetComputeDeviceId ( ) ! = c . GetComputeDeviceId ( ) ) / / different GPUs <nl> InvalidArgument ( " All matrices must be on the same GPU " ) ; <nl> <nl> if ( a . IsEmpty ( ) | | b . IsEmpty ( ) ) <nl> void GPUMatrix < ElemType > : : InnerProductWithShiftNeg ( const GPUMatrix < ElemType > & a , <nl> const int k = ( int ) b . GetNumRows ( ) ; <nl> const int l = ( int ) b . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> - assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & k > 0 & & l > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m = = k & & n = = l ) ; / / converting from size_t to int may cause overflow <nl> if ( m ! = k | | n ! = l ) <nl> InvalidArgument ( " Matrices a and b should have same dimension . " ) ; <nl> <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : GetARowByIndex ( const GPUMatrix < ElemTyp <nl> template < class ElemType > <nl> void GPUMatrix < ElemType > : : ConductRowElementMultiplyWithShift ( const GPUMatrix < ElemType > & a , const GPUMatrix < ElemType > & b , GPUMatrix < ElemType > & c , const size_t shift , const bool isafixed ) <nl> { <nl> - if ( a . GetComputeDeviceId ( ) ! = b . GetComputeDeviceId ( ) | | b . GetComputeDeviceId ( ) ! = c . GetComputeDeviceId ( ) ) / / different GPUs <nl> + if ( a . GetComputeDeviceId ( ) ! = b . GetComputeDeviceId ( ) | | b . GetComputeDeviceId ( ) ! = c . GetComputeDeviceId ( ) ) / / different GPUs <nl> InvalidArgument ( " All matrices must be on the same GPU " ) ; <nl> <nl> if ( a . IsEmpty ( ) | | b . IsEmpty ( ) ) <nl> void GPUMatrix < ElemType > : : ConductRowElementMultiplyWithShift ( const GPUMatrix < Ele <nl> const int O = ( int ) b . GetNumRows ( ) ; <nl> const int P = ( int ) b . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & n > 0 & & O > 0 & & P > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & n > 0 & & O > 0 & & P > 0 ) ; / / converting from size_t to int may cause overflow <nl> if ( m ! = 1 | | n ! = P ) <nl> InvalidArgument ( " Matrices a and b should have same dimension . " ) ; <nl> <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : AssignElementProductOfWithShift ( const <nl> if ( ! ( a . GetNumRows ( ) = = b . GetNumRows ( ) & & a . GetNumCols ( ) = = b . GetNumCols ( ) ) ) <nl> InvalidArgument ( " The input matrix dimensions do not match . " ) ; <nl> <nl> - / / int O = a . GetNumRows ( ) ; <nl> + / / int O = a . GetNumRows ( ) ; <nl> int P = a . GetNumCols ( ) ; <nl> <nl> Resize ( 1 , P ) ; <nl> GPUMatrix < ElemType > & GPUMatrix < ElemType > : : DropFrame ( const GPUMatrix < ElemType > & l <nl> <nl> PrepareDevice ( ) ; <nl> <nl> - long N = ( long ) GetNumCols ( ) ; / / one kernel per column <nl> + long N = ( long ) GetNumCols ( ) ; / / one kernel per column <nl> int blocksPerGrid = ( int ) ceil ( N * 1 . 0 / GridDim : : maxThreadsPerBlock ) ; <nl> cudaEvent_t done = nullptr ; <nl> if ( do_sync ) <nl> int _ConvertSMVer2Cores ( int major , int minor ) <nl> / / return 0 ; <nl> / / } <nl> / / <nl> - / / / / create cuda context <nl> + / / / / create cuda context <nl> / / CUcontext cudaContext ; <nl> / / result = cuCtxCreate ( & cudaContext , CU_CTX_SCHED_AUTO , cudaDevice ) ; <nl> / / if ( result ! = CUDA_SUCCESS ) <nl> int _ConvertSMVer2Cores ( int major , int minor ) <nl> / / return 0 ; <nl> / / } <nl> / / <nl> - / / / / get the amount of free memory on the graphics card <nl> + / / / / get the amount of free memory on the graphics card <nl> / / size_t free ; <nl> / / size_t total ; <nl> / / result = cuMemGetInfo ( & free , & total ) ; <nl> mmm a / Source / Math / GPUMatrix . h <nl> ppp b / Source / Math / GPUMatrix . h <nl> class MATH_API DeviceBoundNumber <nl> { <nl> return m_data ; <nl> } <nl> - / / performs shallow copy only <nl> + / / performs shallow copy only <nl> void ShallowCopyFrom ( ElemType * newVal , int newValsDevceId ) ; <nl> } ; <nl> <nl> class MATH_API GPUMatrix : public BaseMatrix < ElemType > <nl> GPUMatrix ( const size_t numRows , const size_t numCols , int deviceId ) ; <nl> GPUMatrix ( const size_t numRows , const size_t numCols , int deviceId , ElemType * pArray , const size_t matrixFlags = matrixFlagNormal ) ; <nl> GPUMatrix ( const GPUMatrix < ElemType > & deepCopyFrom ) ; <nl> - GPUMatrix < ElemType > & operator = ( const GPUMatrix < ElemType > & deepCopyFrom ) ; / / assignment operator , deep copy <nl> + GPUMatrix < ElemType > & operator = ( const GPUMatrix < ElemType > & deepCopyFrom ) ; / / assignment operator , deep copy <nl> GPUMatrix ( GPUMatrix < ElemType > & & moveFrom ) ; <nl> - GPUMatrix < ElemType > & operator = ( GPUMatrix < ElemType > & & moveFrom ) ; / / move assignment operator , shallow copy <nl> + GPUMatrix < ElemType > & operator = ( GPUMatrix < ElemType > & & moveFrom ) ; / / move assignment operator , shallow copy <nl> ~ GPUMatrix ( void ) ; <nl> <nl> static void SetDevice ( DEVICEID_TYPE deviceId ) ; <nl> class MATH_API GPUMatrix : public BaseMatrix < ElemType > <nl> DEVICEID_TYPE PrepareDevice ( DEVICEID_TYPE deviceId = - 1 ) const ; <nl> <nl> static cublasHandle_t GetCublasHandle ( int computeDevice = - 1 ) ; <nl> - ElemType * CopyToArray ( ) const ; / / allocated by the callee but need to be deleted by the caller <nl> - size_t CopyToArray ( ElemType * & arrayCopyTo , size_t & currentArraySize ) const ; / / allocated by the callee but need to be deleted by the caller <nl> + ElemType * CopyToArray ( ) const ; / / allocated by the callee but need to be deleted by the caller <nl> + size_t CopyToArray ( ElemType * & arrayCopyTo , size_t & currentArraySize ) const ; / / allocated by the callee but need to be deleted by the caller <nl> void CopySection ( size_t numRows , size_t numCols , ElemType * dst , size_t colStride ) const ; <nl> <nl> void ChangeDeviceTo ( DEVICEID_TYPE to_id ) ; <nl> class MATH_API GPUMatrix : public BaseMatrix < ElemType > <nl> ElemType RmsProp ( GPUMatrix < ElemType > & gradients , ElemType RMS_GAMMA , ElemType RMS_WGT_INC , ElemType RMS_WGT_MAX , ElemType RMS_WGT_DEC , ElemType RMS_WGT_MIN , const bool needAveMultiplier ) ; <nl> <nl> void Reshape ( const size_t numRows , const size_t numCols ) ; <nl> - void Resize ( const size_t numRows , const size_t numCols , bool growOnly = true ) ; / / by default we only reallocate if need to grow <nl> + void Resize ( const size_t numRows , const size_t numCols , bool growOnly = true ) ; / / by default we only reallocate if need to grow <nl> <nl> ElemType & operator ( ) ( const size_t / * row * / , const size_t / * col * / ) <nl> { <nl> class MATH_API GPUMatrix : public BaseMatrix < ElemType > <nl> ElemType Get00Element ( ) const ; <nl> <nl> void SetValue ( const ElemType v ) ; <nl> - void SetValue ( const ElemType * d_v ) ; / / d_v is pointer to the the value in GPU memory <nl> + void SetValue ( const ElemType * d_v ) ; / / d_v is pointer to the the value in GPU memory <nl> void SetColumn ( const ElemType * colPointer , size_t colInd ) ; <nl> void SetColumn ( const GPUMatrix < ElemType > & valMat , size_t colInd ) ; <nl> <nl> class MATH_API GPUMatrix : public BaseMatrix < ElemType > <nl> GPUMatrix < ElemType > & operator / = ( ElemType alpha ) ; <nl> GPUMatrix < ElemType > operator / ( ElemType alpha ) const ; <nl> <nl> - GPUMatrix < ElemType > & operator ^ = ( ElemType alpha ) ; / / element - wise power <nl> - GPUMatrix < ElemType > operator ^ ( ElemType alpha ) const ; / / element - wise power <nl> + GPUMatrix < ElemType > & operator ^ = ( ElemType alpha ) ; / / element - wise power <nl> + GPUMatrix < ElemType > operator ^ ( ElemType alpha ) const ; / / element - wise power <nl> GPUMatrix < ElemType > & AssignElementPowerOf ( const GPUMatrix < ElemType > & a , const ElemType power ) ; <nl> <nl> GPUMatrix < ElemType > & ElementMultiplyWith ( const GPUMatrix < ElemType > & a ) ; <nl> class MATH_API GPUMatrix : public BaseMatrix < ElemType > <nl> GPUMatrix < ElemType > & InplaceHardmax ( const bool isColWise ) ; <nl> GPUMatrix < ElemType > & AssignHardmaxOf ( const GPUMatrix < ElemType > & a , const bool isColWise ) ; <nl> <nl> - / / sequence training <nl> + / / sequence training <nl> GPUMatrix < ElemType > & DropFrame ( const GPUMatrix < ElemType > & label , const GPUMatrix < ElemType > & gamma , const ElemType & threshhold ) ; <nl> GPUMatrix < ElemType > & AssignSequenceError ( const ElemType hsmoothingWeight , const GPUMatrix < ElemType > & label , const GPUMatrix < ElemType > & dnnoutput , const GPUMatrix < ElemType > & gamma , ElemType alpha ) ; <nl> <nl> class MATH_API GPUMatrix : public BaseMatrix < ElemType > <nl> GPUMatrix < ElemType > & SetToZeroIfAbsLessThan ( const ElemType threshold ) ; <nl> <nl> DeviceBoundNumber < ElemType > Sum_AsDeviceBoundNum ( ) const ; <nl> - ElemType SumOfAbsElements ( ) const ; / / sum of all abs ( elements ) <nl> - ElemType SumOfElements ( ) const ; / / sum of all elements <nl> + ElemType SumOfAbsElements ( ) const ; / / sum of all abs ( elements ) <nl> + ElemType SumOfElements ( ) const ; / / sum of all elements <nl> GPUMatrix < ElemType > & AssignSumOfElements ( const GPUMatrix < ElemType > & a ) ; <nl> <nl> ElemType Max ( ) const ; <nl> class MATH_API GPUMatrix : public BaseMatrix < ElemType > <nl> <nl> ElemType MatrixNormInf ( ) const ; <nl> ElemType MatrixNorm1 ( ) const ; <nl> - ElemType MatrixNorm0 ( ) const ; / / number of non - zero elemets <nl> + ElemType MatrixNorm0 ( ) const ; / / number of non - zero elemets <nl> GPUMatrix < ElemType > & AssignSignOf ( const GPUMatrix < ElemType > & a ) ; <nl> GPUMatrix < ElemType > & AddSignOf ( const GPUMatrix < ElemType > & a ) ; <nl> <nl> class MATH_API GPUMatrix : public BaseMatrix < ElemType > <nl> GPUMatrix < ElemType > & AssignRowSliceValuesOf ( const GPUMatrix < ElemType > & a , const size_t startIndex , const size_t numRows ) ; <nl> GPUMatrix < ElemType > & AddToRowSliceValuesOf ( const GPUMatrix < ElemType > & a , const size_t startIndex , const size_t numRows ) ; <nl> GPUMatrix < ElemType > & AddWithRowSliceValuesOf ( const GPUMatrix < ElemType > & a , const size_t startIndex , const size_t numRows ) ; <nl> - / / GPUMatrix < ElemType > & AssignRowStackValuesOf ( const std : : vector < const GPUMatrix < ElemType > * > & inputMatrices , const size_t sliceStartCol , const size_t sliceNumCols ) ; <nl> + / / GPUMatrix < ElemType > & AssignRowStackValuesOf ( const std : : vector < const GPUMatrix < ElemType > * > & inputMatrices , const size_t sliceStartCol , const size_t sliceNumCols ) ; <nl> <nl> GPUMatrix < ElemType > & AssignRepeatOf ( const GPUMatrix < ElemType > & a , const size_t numRowRepeats , const size_t numColRepeats ) ; <nl> GPUMatrix < ElemType > & AddToRowRepeatValuesOf ( const GPUMatrix < ElemType > & a , const size_t numRowRepeats ) ; <nl> class MATH_API GPUMatrix : public BaseMatrix < ElemType > <nl> void AssignSoftmaxSum ( const GPUMatrix < ElemType > & a , GPUMatrix < ElemType > & softmax ) ; <nl> <nl> void Print ( const char * matrixName , size_t rowStart , size_t rowEnd , size_t colStart , size_t colEnd ) const ; <nl> - void Print ( const char * matrixName = NULL ) const ; / / print whole matrix . can be expensive <nl> + void Print ( const char * matrixName = NULL ) const ; / / print whole matrix . can be expensive <nl> <nl> - void ReadFromFile ( FILE * f , const char * matrixName ) ; / / matrixName is used to verify that correct matrix is read . <nl> - void WriteToFile ( FILE * f , const char * matrixName ) ; / / matrixName is used to verify that correct matrix is read . <nl> + void ReadFromFile ( FILE * f , const char * matrixName ) ; / / matrixName is used to verify that correct matrix is read . <nl> + void WriteToFile ( FILE * f , const char * matrixName ) ; / / matrixName is used to verify that correct matrix is read . <nl> <nl> GPUMatrix < ElemType > & AssignPackedConvolutionInput ( const GPUMatrix < ElemType > & inputSubBatch , <nl> const size_t inputWidth , const size_t inputHeight , const size_t inputChannels , <nl> class MATH_API GPUMatrix : public BaseMatrix < ElemType > <nl> const size_t windowWidth , const size_t windowHeight , const size_t horizontalSubsample , const size_t verticalSubsample ) ; <nl> <nl> public : <nl> - / / static BLAS functions <nl> + / / static BLAS functions <nl> static void MultiplyAndWeightedAdd ( ElemType alpha , const GPUMatrix < ElemType > & a , const bool transposeA , const GPUMatrix < ElemType > & b , const bool transposeB , ElemType beta , GPUMatrix < ElemType > & c ) ; <nl> static void MultiplyAndAdd ( const GPUMatrix < ElemType > & a , const bool transposeA , const GPUMatrix < ElemType > & b , const bool transposeB , GPUMatrix < ElemType > & c ) ; <nl> static void Multiply ( const GPUMatrix < ElemType > & a , const bool transposeA , const GPUMatrix < ElemType > & b , const bool transposeB , GPUMatrix < ElemType > & c ) ; <nl> class MATH_API GPUMatrix : public BaseMatrix < ElemType > <nl> static void MinusOneAt ( GPUMatrix < ElemType > & c , const size_t position ) ; <nl> <nl> static void Scale ( ElemType alpha , const GPUMatrix < ElemType > & a , GPUMatrix < ElemType > & c ) ; <nl> - static void Scale ( GPUMatrix < ElemType > & alpha , GPUMatrix < ElemType > & a ) ; / / In this case matrix alpha must be 1x1 <nl> + static void Scale ( GPUMatrix < ElemType > & alpha , GPUMatrix < ElemType > & a ) ; / / In this case matrix alpha must be 1x1 <nl> static void Scale ( ElemType alpha , GPUMatrix < ElemType > & a ) ; <nl> static void InnerProduct ( const GPUMatrix < ElemType > & a , const GPUMatrix < ElemType > & b , GPUMatrix < ElemType > & c , const bool isColWise ) ; <nl> static ElemType InnerProductOfMatrices ( const GPUMatrix < ElemType > & a , const GPUMatrix < ElemType > & b ) ; <nl> class MATH_API GPUMatrix : public BaseMatrix < ElemType > <nl> delete [ ] d_array ; <nl> us . m_matrixName = new wchar_t [ matrixName . length ( ) + 1 ] ; <nl> wmemcpy ( us . m_matrixName , matrixName . c_str ( ) , matrixName . length ( ) + 1 ) ; <nl> - / / us . m_matrixName = matrixName ; <nl> + / / us . m_matrixName = matrixName ; <nl> return stream ; <nl> } <nl> friend File & operator < < ( File & stream , const GPUMatrix < ElemType > & us ) <nl> mmm a / Source / Math / GPUMatrixCUDAKernels . cuh <nl> ppp b / Source / Math / GPUMatrixCUDAKernels . cuh <nl> __global__ void _assignRowSliceValuesOf ( ElemType * dest , ElemType * src , const CUD <nl> CUDA_LONG col = id / destRows ; <nl> CUDA_LONG row = id - ( col * destRows ) ; <nl> <nl> - / / dest [ id ] = src [ col * srcRows + row + startIndex ] ; <nl> + / / dest [ id ] = src [ col * srcRows + row + startIndex ] ; <nl> dest [ id ] = src [ IDX2C ( row + startIndex , col , srcRows ) ] ; <nl> } <nl> <nl> __global__ void _addToRowSliceValuesOf ( ElemType * dest , ElemType * src , const CUDA <nl> if ( id > = N ) <nl> return ; <nl> <nl> - CUDA_LONG col = id / srcRows ; / / src is the full matrix , rowslice is taken from the dest <nl> + CUDA_LONG col = id / srcRows ; / / src is the full matrix , rowslice is taken from the dest <nl> CUDA_LONG row = id - ( col * srcRows ) ; <nl> <nl> - / / dest [ col * destRows + row + startIndex ] + = src [ id ] ; <nl> + / / dest [ col * destRows + row + startIndex ] + = src [ id ] ; <nl> dest [ IDX2C ( row + startIndex , col , destRows ) ] + = src [ id ] ; <nl> } <nl> <nl> __global__ void _addWithRowSliceValuesOf ( ElemType * dest , ElemType * src , const CU <nl> if ( id > = N ) <nl> return ; <nl> <nl> - CUDA_LONG col = id / destRows ; / / dest is the full matrix , rowslice is taken from the src <nl> + CUDA_LONG col = id / destRows ; / / dest is the full matrix , rowslice is taken from the src <nl> CUDA_LONG row = id - ( col * destRows ) ; <nl> <nl> dest [ id ] + = src [ IDX2C ( row + startIndex , col , srcRows ) ] ; <nl> __global__ void _assignRowStackValuesOf ( ElemType * dest , ElemType * * srces , size_t <nl> if ( id > = N ) <nl> return ; <nl> <nl> - CUDA_LONG col = id / destRows ; / / dest is the full matrix , rowslice is taken from the src <nl> + CUDA_LONG col = id / destRows ; / / dest is the full matrix , rowslice is taken from the src <nl> CUDA_LONG row = id - ( col * destRows ) ; <nl> <nl> - / / can we replace the for loop with something better ? <nl> + / / can we replace the for loop with something better ? <nl> int srcId = 0 ; <nl> for ( ; srcId < numSrces ; srcId + + ) <nl> { <nl> __global__ void _addToRowRepeatValuesOf ( ElemType * dest , ElemType * src , const CUD <nl> CUDA_LONG col = id / srcRows ; <nl> CUDA_LONG row = ( id - ( col * srcRows ) ) % destRows ; <nl> <nl> - / / dest [ col * destRows + row + startIndex ] + = src [ id ] ; <nl> + / / dest [ col * destRows + row + startIndex ] + = src [ id ] ; <nl> dest [ IDX2C ( row , col , destRows ) ] + = src [ id ] ; <nl> } <nl> <nl> template < class ElemType > <nl> __global__ void _logSoftMaxColWise ( <nl> ElemType * a , <nl> const CUDA_LONG m_numCols , <nl> - const CUDA_LONG m_numRows ) / / ld <nl> + const CUDA_LONG m_numRows ) / / ld <nl> { <nl> int col_id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> if ( col_id > = m_numCols ) <nl> __global__ void _logSoftMaxColWise ( <nl> / / const ElemType * a , <nl> / / ElemType * us , <nl> / / const CUDA_LONG m_numCols , <nl> - / / const CUDA_LONG m_numRows ) / / thead per column <nl> + / / const CUDA_LONG m_numRows ) / / thead per column <nl> / / { <nl> / / int col_id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> / / if ( col_id > = m_numCols ) <nl> template < class ElemType > <nl> __global__ void _logSoftMaxRowWise ( <nl> ElemType * a , <nl> const CUDA_LONG m_numCols , <nl> - const CUDA_LONG m_numRows ) / / ld <nl> + const CUDA_LONG m_numRows ) / / ld <nl> { <nl> int row_id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> if ( row_id > = m_numRows ) <nl> __global__ void _tensorShuffleScaleAndAdd ( <nl> / / see Matrix < ElemType > : : TensorShuffleScaleAndAdd ( ) for comments <nl> template < class ElemType > <nl> __global__ void _tensorShuffleScaleAndAddRowSparse ( <nl> - const ElemType * anzValues , / / source nz values <nl> + const ElemType * anzValues , / / source nz values <nl> const GPUSPARSE_INDEX_TYPE * aRowIndex , <nl> const GPUSPARSE_INDEX_TYPE * aColCSCIndex , <nl> - ElemType * cnzValues , / / target nz values <nl> + ElemType * cnzValues , / / target nz values <nl> GPUSPARSE_INDEX_TYPE * cRowIndex , <nl> GPUSPARSE_INDEX_TYPE * cColCSCIndex , <nl> size_t D , size_t S , size_t M , size_t K , size_t T , <nl> __global__ void _adagrad ( <nl> <nl> template < class ElemType > <nl> __global__ void _adagrad4BlockSparse ( <nl> - ElemType * a , / / dense <nl> - const size_t numRows , / / number of rows in a and in d_v <nl> - ElemType * d_v , / / block sparse <nl> + ElemType * a , / / dense <nl> + const size_t numRows , / / number of rows in a and in d_v <nl> + ElemType * d_v , / / block sparse <nl> const GPUSPARSE_INDEX_TYPE * blockId2ColOrRow , <nl> ElemType * multipliers , <nl> const bool colMajor , <nl> - const size_t len , / / major dim , numRows in colMajor and numcols in rowMajor <nl> - const CUDA_LONG N ) / / total number of non - zero values <nl> + const size_t len , / / major dim , numRows in colMajor and numcols in rowMajor <nl> + const CUDA_LONG N ) / / total number of non - zero values <nl> { <nl> CUDA_LONG id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> if ( id > = N ) <nl> __global__ void _rmsprop ( <nl> <nl> avars [ i ] = RMS_GAMMA * avars [ i ] + ( ElemType ( 1 . 0 ) - RMS_GAMMA ) * ( curr_grad [ i ] * curr_grad [ i ] ) ; <nl> <nl> - / / / / grad sign base 3 : 0 - > neg , 1 - > zero , 2 - > pos <nl> - / / const int grad_sign = 1 + ( ElemType ( 0 ) < curr_grad [ i ] ) - ( curr_grad [ i ] < ElemType ( 0 ) ) ; <nl> + / / / / grad sign base 3 : 0 - > neg , 1 - > zero , 2 - > pos <nl> + / / const int grad_sign = 1 + ( ElemType ( 0 ) < curr_grad [ i ] ) - ( curr_grad [ i ] < ElemType ( 0 ) ) ; <nl> <nl> - / / / / signs [ i ] contains three consecutive grad_sign <nl> - / / signs [ i ] = 3 * ( int ( signs [ i ] ) % 9 ) + grad_sign ; <nl> + / / / / signs [ i ] contains three consecutive grad_sign <nl> + / / signs [ i ] = 3 * ( int ( signs [ i ] ) % 9 ) + grad_sign ; <nl> <nl> - / / / / update according to the following table : <nl> - / / / / ( ! pos , ! pos , ! pos ) or ( ! neg , ! neg , ! neg ) : RMS_WGT_INC <nl> - / / / / ( ! neg , ! neg , neg ) or ( ! pos , ! pos , pos ) : RMS_WGT_DEC <nl> - / / / / otherwise : no action <nl> + / / / / update according to the following table : <nl> + / / / / ( ! pos , ! pos , ! pos ) or ( ! neg , ! neg , ! neg ) : RMS_WGT_INC <nl> + / / / / ( ! neg , ! neg , neg ) or ( ! pos , ! pos , pos ) : RMS_WGT_DEC <nl> + / / / / otherwise : no action <nl> <nl> - / / switch ( int ( upd_gpu [ int ( signs [ i ] ) ] ) ) <nl> - / / { <nl> - / / case 0 : <nl> + / / switch ( int ( upd_gpu [ int ( signs [ i ] ) ] ) ) <nl> + / / { <nl> + / / case 0 : <nl> / / steps [ i ] = max ( steps [ i ] * RMS_WGT_DEC , RMS_WGT_MIN ) ; <nl> / / break ; <nl> - / / case 2 : <nl> + / / case 2 : <nl> / / steps [ i ] = min ( steps [ i ] * RMS_WGT_INC , RMS_WGT_MAX ) ; <nl> / / break ; <nl> - / / } <nl> - / / curr_grad [ i ] * = steps [ i ] / sqrt ( avars [ i ] + floor ) ; <nl> + / / } <nl> + / / curr_grad [ i ] * = steps [ i ] / sqrt ( avars [ i ] + floor ) ; <nl> <nl> const int grad_sign = ( ElemType ( 0 ) < curr_grad [ i ] ) - ( curr_grad [ i ] < ElemType ( 0 ) ) ; <nl> <nl> __global__ void _setMaskAndScale ( <nl> <nl> template < class ElemType > <nl> __global__ void _vectorSum ( <nl> - ElemType * c , / / output <nl> - const ElemType * a , / / input <nl> - const CUDA_LONG n , / / a . numRows <nl> - const CUDA_LONG m , / / a . numCols <nl> + ElemType * c , / / output <nl> + const ElemType * a , / / input <nl> + const CUDA_LONG n , / / a . numRows <nl> + const CUDA_LONG m , / / a . numCols <nl> const bool isColWise ) <nl> { <nl> int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> __global__ void _vectorSum ( <nl> <nl> template < class ElemType > <nl> __global__ void _vectorNorm1 ( <nl> - ElemType * c , / / output <nl> - const ElemType * a , / / input <nl> - const CUDA_LONG n , / / a . numRows <nl> - const CUDA_LONG m , / / a . numCols <nl> + ElemType * c , / / output <nl> + const ElemType * a , / / input <nl> + const CUDA_LONG n , / / a . numRows <nl> + const CUDA_LONG m , / / a . numCols <nl> const bool isColWise ) <nl> { <nl> int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> __global__ void _vectorNorm1 ( <nl> / / one column per thread <nl> template < class ElemType > <nl> __global__ void _vectorNorm2 ( <nl> - ElemType * c , / / output <nl> - const ElemType * a , / / input <nl> - const CUDA_LONG N , / / a . GetNumRows ( ) ; <nl> - const CUDA_LONG M , / / a . GetNumCols ( ) ; <nl> + ElemType * c , / / output <nl> + const ElemType * a , / / input <nl> + const CUDA_LONG N , / / a . GetNumRows ( ) ; <nl> + const CUDA_LONG M , / / a . GetNumCols ( ) ; <nl> const bool isColWise ) <nl> { <nl> CUDA_LONG id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> __global__ void _convertInd2ValsAdjustInd ( <nl> ElemType * inds , <nl> const ElemType * M , <nl> ElemType * vals , <nl> - const CUDA_LONG n , / / number of cols <nl> - const CUDA_LONG m , / / number of rows <nl> + const CUDA_LONG n , / / number of cols <nl> + const CUDA_LONG m , / / number of rows <nl> const bool isColWise ) <nl> { <nl> int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> __global__ void _assignPackedConvolutionInput ( ElemType * packedMatrix , const Elem <nl> return ; <nl> <nl> const CUDA_LONG id = idall % inputDim ; <nl> - const CUDA_LONG y = id / inputHeightTimesChannel ; / / inputCol <nl> + const CUDA_LONG y = id / inputHeightTimesChannel ; / / inputCol <nl> <nl> const size_t packedInputRows = kernelWidth * kernelHeight * inputChannels ; <nl> - const size_t packedInputColsPerSample = outputWidth * outputHeight ; / / output size per channel <nl> + const size_t packedInputColsPerSample = outputWidth * outputHeight ; / / output size per channel <nl> <nl> / / IN_ELEM_ROWPOS ( channel , row , col ) = ( channel + ( row + col * inputHeight ) * inputChannels ) <nl> / / IN_ELEM_COLPOS = sample <nl> <nl> - const CUDA_LONG nXC = id % inputHeightTimesChannel ; / / channel + inputRow * inputChannels <nl> - const CUDA_LONG x = nXC / inputChannels ; / / inputRow <nl> - const CUDA_LONG c = nXC % inputChannels ; / / channel <nl> + const CUDA_LONG nXC = id % inputHeightTimesChannel ; / / channel + inputRow * inputChannels <nl> + const CUDA_LONG x = nXC / inputChannels ; / / inputRow <nl> + const CUDA_LONG c = nXC % inputChannels ; / / channel <nl> <nl> ElemType currentInputValue = inputSubBatch [ id + sample * inputDim ] ; <nl> <nl> __global__ void _assignPackedConvolutionInput ( ElemType * packedMatrix , const Elem <nl> const CUDA_LONG halfKernelWidth = kernelWidth / 2 ; <nl> const CUDA_LONG halfKernelHeight = kernelHeight / 2 ; <nl> <nl> - x0 = max ( ( ElemType ) 0 . 0f , ceil ( ( x - ( ElemType ) kernelHeight + 1 . 0f + halfKernelHeight ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> - x1 = x + halfKernelHeight - x0 * verticalSubsample ; / / first posxInKernel <nl> - y0 = max ( ( ElemType ) 0 . 0f , ceil ( ( y - ( ElemType ) kernelWidth + 1 . 0f + halfKernelWidth ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> - y1 = y + halfKernelWidth - y0 * horizontalSubsample ; / / first posyInKernel <nl> + x0 = max ( ( ElemType ) 0 . 0f , ceil ( ( x - ( ElemType ) kernelHeight + 1 . 0f + halfKernelHeight ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> + x1 = x + halfKernelHeight - x0 * verticalSubsample ; / / first posxInKernel <nl> + y0 = max ( ( ElemType ) 0 . 0f , ceil ( ( y - ( ElemType ) kernelWidth + 1 . 0f + halfKernelWidth ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> + y1 = y + halfKernelWidth - y0 * horizontalSubsample ; / / first posyInKernel <nl> } <nl> else <nl> { <nl> - x0 = max ( ( ElemType ) 0 . 0f , ceil ( ( x - ( ElemType ) kernelHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> - x1 = x - x0 * verticalSubsample ; / / first posxInKernel <nl> - y0 = max ( ( ElemType ) 0 . 0f , ceil ( ( y - ( ElemType ) kernelWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> - y1 = y - y0 * horizontalSubsample ; / / first posyInKernel <nl> + x0 = max ( ( ElemType ) 0 . 0f , ceil ( ( x - ( ElemType ) kernelHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> + x1 = x - x0 * verticalSubsample ; / / first posxInKernel <nl> + y0 = max ( ( ElemType ) 0 . 0f , ceil ( ( y - ( ElemType ) kernelWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> + y1 = y - y0 * horizontalSubsample ; / / first posyInKernel <nl> } <nl> <nl> / / PACK_ELEM_ROWPOS ( channel , posxInKernel , posyInKernel ) = ( channel * kernelWidth * kernelHeight + posxInKernel + posyInKernel * kernelHeight ) <nl> __global__ void _unpackConvolutionInput ( const ElemType * packedMatrix , ElemType * <nl> return ; <nl> <nl> const CUDA_LONG id = idall % inputDim ; <nl> - const CUDA_LONG y = id / inputHeightTimesChannel ; / / inputCol <nl> + const CUDA_LONG y = id / inputHeightTimesChannel ; / / inputCol <nl> <nl> const size_t packedInputRows = kernelWidth * kernelHeight * inputChannels ; <nl> - const size_t packedInputColsPerSample = outputWidth * outputHeight ; / / output size per channel <nl> + const size_t packedInputColsPerSample = outputWidth * outputHeight ; / / output size per channel <nl> <nl> / / IN_ELEM_ROWPOS ( channel , row , col ) = ( channel + ( row + col * inputHeight ) * inputChannels ) <nl> / / IN_ELEM_COLPOS = sample <nl> <nl> - const CUDA_LONG nXC = id % inputHeightTimesChannel ; / / channel + inputRow * inputChannels <nl> - const CUDA_LONG x = nXC / inputChannels ; / / inputRow <nl> - const CUDA_LONG c = nXC % inputChannels ; / / channel <nl> + const CUDA_LONG nXC = id % inputHeightTimesChannel ; / / channel + inputRow * inputChannels <nl> + const CUDA_LONG x = nXC / inputChannels ; / / inputRow <nl> + const CUDA_LONG c = nXC % inputChannels ; / / channel <nl> <nl> CUDA_LONG x0 = 0 , y0 = 0 , x1 = 0 , y1 = 0 ; <nl> if ( zeroPadding ) <nl> __global__ void _unpackConvolutionInput ( const ElemType * packedMatrix , ElemType * <nl> const CUDA_LONG halfKernelWidth = kernelWidth / 2 ; <nl> const CUDA_LONG halfKernelHeight = kernelHeight / 2 ; <nl> <nl> - x0 = max ( 0 . 0f , ceil ( ( x - ( ElemType ) kernelHeight + 1 . 0f + halfKernelHeight ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> - x1 = x + halfKernelHeight - x0 * verticalSubsample ; / / first posxInKernel <nl> - y0 = max ( 0 . 0f , ceil ( ( y - ( ElemType ) kernelWidth + 1 . 0f + halfKernelWidth ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> - y1 = y + halfKernelWidth - y0 * horizontalSubsample ; / / first posyInKernel <nl> + x0 = max ( 0 . 0f , ceil ( ( x - ( ElemType ) kernelHeight + 1 . 0f + halfKernelHeight ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> + x1 = x + halfKernelHeight - x0 * verticalSubsample ; / / first posxInKernel <nl> + y0 = max ( 0 . 0f , ceil ( ( y - ( ElemType ) kernelWidth + 1 . 0f + halfKernelWidth ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> + y1 = y + halfKernelWidth - y0 * horizontalSubsample ; / / first posyInKernel <nl> } <nl> else <nl> { <nl> - x0 = max ( 0 . 0f , ceil ( ( x - ( ElemType ) kernelHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> - x1 = x - x0 * verticalSubsample ; / / first posxInKernel <nl> - y0 = max ( 0 . 0f , ceil ( ( y - ( ElemType ) kernelWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> - y1 = y - y0 * horizontalSubsample ; / / first posyInKernel <nl> + x0 = max ( 0 . 0f , ceil ( ( x - ( ElemType ) kernelHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / row : first wrow in which x is in <nl> + x1 = x - x0 * verticalSubsample ; / / first posxInKernel <nl> + y0 = max ( 0 . 0f , ceil ( ( y - ( ElemType ) kernelWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / col : first wcol in which y is in <nl> + y1 = y - y0 * horizontalSubsample ; / / first posyInKernel <nl> } <nl> <nl> / / PACK_ELEM_ROWPOS ( channel , posxInKernel , posyInKernel ) = ( channel * kernelWidth * kernelHeight + posxInKernel + posyInKernel * kernelHeight ) <nl> __global__ void _assignMaxPoolingResult ( ElemType * outputBatch , const ElemType * i <nl> / / OUT_ELEM_ROWPOS ( channel , wrow , wcol ) = ( channel + ( wrow + wcol * outputHeight ) * channels ) <nl> / / OUT_ELEM_COLPOS = sample <nl> <nl> - const CUDA_LONG y = outputIndexWithinSample / outputHeightTimesChannel ; / / wcol <nl> - const CUDA_LONG nXC = outputIndexWithinSample % outputHeightTimesChannel ; / / channel + wrow * channels <nl> - const CUDA_LONG x = nXC / channels ; / / wrow <nl> - const CUDA_LONG c = nXC % channels ; / / channel <nl> + const CUDA_LONG y = outputIndexWithinSample / outputHeightTimesChannel ; / / wcol <nl> + const CUDA_LONG nXC = outputIndexWithinSample % outputHeightTimesChannel ; / / channel + wrow * channels <nl> + const CUDA_LONG x = nXC / channels ; / / wrow <nl> + const CUDA_LONG c = nXC % channels ; / / channel <nl> <nl> const ElemType * inputBatchBase4Sample = inputBatch + sample * inputSizePerSample ; <nl> register ElemType maxVal = - FLT_MAX ; <nl> __global__ void _addMaxPoolingGradient ( ElemType * inputGradientBatch , const ElemT <nl> / / OUT_ELEM_ROWPOS ( channel , wrow , wcol ) = ( channel + ( wrow + wcol * outputHeight ) * channels ) <nl> / / OUT_ELEM_COLPOS = sample <nl> <nl> - const CUDA_LONG y = inputIndexWithinSample / inputHeightTimesChannel ; / / col in input <nl> - const CUDA_LONG nXC = inputIndexWithinSample % inputHeightTimesChannel ; / / channel + row * chanels <nl> - const CUDA_LONG x = nXC / channels ; / / row in input <nl> - const CUDA_LONG c = nXC % channels ; / / channel <nl> + const CUDA_LONG y = inputIndexWithinSample / inputHeightTimesChannel ; / / col in input <nl> + const CUDA_LONG nXC = inputIndexWithinSample % inputHeightTimesChannel ; / / channel + row * chanels <nl> + const CUDA_LONG x = nXC / channels ; / / row in input <nl> + const CUDA_LONG c = nXC % channels ; / / channel <nl> <nl> - CUDA_LONG startOutX = max ( 0 . 0f , ceil ( ( x - ( ElemType ) windowHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / inclusive start <nl> - CUDA_LONG endOutX = ( x / verticalSubsample < outputHeight - 1 ) ? x / verticalSubsample : outputHeight - 1 ; / / inclusive end <nl> - CUDA_LONG startOutY = max ( 0 . 0f , ceil ( ( y - ( ElemType ) windowWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / inclusive start <nl> - CUDA_LONG endOutY = ( y / horizontalSubsample < outputWidth - 1 ) ? y / horizontalSubsample : outputWidth - 1 ; / / inclusive end <nl> + CUDA_LONG startOutX = max ( 0 . 0f , ceil ( ( x - ( ElemType ) windowHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / inclusive start <nl> + CUDA_LONG endOutX = ( x / verticalSubsample < outputHeight - 1 ) ? x / verticalSubsample : outputHeight - 1 ; / / inclusive end <nl> + CUDA_LONG startOutY = max ( 0 . 0f , ceil ( ( y - ( ElemType ) windowWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / inclusive start <nl> + CUDA_LONG endOutY = ( y / horizontalSubsample < outputWidth - 1 ) ? y / horizontalSubsample : outputWidth - 1 ; / / inclusive end <nl> <nl> ElemType * inputGradientBatchBase4Sample = inputGradientBatch + sample * inputSizePerSample ; <nl> const ElemType * outputGradientBatchBase4Sample = outputGradientBatch + sample * outputSizePerSample ; <nl> __global__ void _assignAveragePoolingResult ( ElemType * outputBatch , const ElemTyp <nl> / / OUT_ELEM_ROWPOS ( channel , wrow , wcol ) = ( channel + ( wrow + wcol * outputHeight ) * channels ) <nl> / / OUT_ELEM_COLPOS = sample <nl> <nl> - const CUDA_LONG y = outputIndexWithinSample / outputHeightTimesChannel ; / / wcol <nl> - const CUDA_LONG nXC = outputIndexWithinSample % outputHeightTimesChannel ; / / channel + wrow * channels <nl> - const CUDA_LONG x = nXC / channels ; / / wrow <nl> - const CUDA_LONG c = nXC % channels ; / / channel <nl> + const CUDA_LONG y = outputIndexWithinSample / outputHeightTimesChannel ; / / wcol <nl> + const CUDA_LONG nXC = outputIndexWithinSample % outputHeightTimesChannel ; / / channel + wrow * channels <nl> + const CUDA_LONG x = nXC / channels ; / / wrow <nl> + const CUDA_LONG c = nXC % channels ; / / channel <nl> <nl> const ElemType * inputBatchBase4Sample = inputBatch + sample * inputSizePerSample ; <nl> <nl> __global__ void _addAveragePoolingGradient ( ElemType * inputGradientBatch , const E <nl> / / OUT_ELEM_ROWPOS ( channel , wrow , wcol ) = ( channel + ( wrow + wcol * outputHeight ) * channels ) <nl> / / OUT_ELEM_COLPOS = sample <nl> <nl> - const CUDA_LONG y = inputIndexWithinSample / inputHeightTimesChannel ; / / col in input <nl> - const CUDA_LONG nXC = inputIndexWithinSample % inputHeightTimesChannel ; / / channel + row * chanels <nl> - const CUDA_LONG x = nXC / channels ; / / row in input <nl> - const CUDA_LONG c = nXC % channels ; / / channel <nl> + const CUDA_LONG y = inputIndexWithinSample / inputHeightTimesChannel ; / / col in input <nl> + const CUDA_LONG nXC = inputIndexWithinSample % inputHeightTimesChannel ; / / channel + row * chanels <nl> + const CUDA_LONG x = nXC / channels ; / / row in input <nl> + const CUDA_LONG c = nXC % channels ; / / channel <nl> <nl> - CUDA_LONG startOutX = max ( 0 . 0f , ceil ( ( x - ( ElemType ) windowHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / inclusive start <nl> - CUDA_LONG endOutX = ( x / verticalSubsample < outputHeight - 1 ) ? x / verticalSubsample : outputHeight - 1 ; / / inclusive end <nl> - CUDA_LONG startOutY = max ( 0 . 0f , ceil ( ( y - ( ElemType ) windowWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / inclusive start <nl> - CUDA_LONG endOutY = ( y / horizontalSubsample < outputWidth - 1 ) ? y / horizontalSubsample : outputWidth - 1 ; / / inclusive end <nl> + CUDA_LONG startOutX = max ( 0 . 0f , ceil ( ( x - ( ElemType ) windowHeight + 1 ) / ( ElemType ) verticalSubsample ) ) ; / / inclusive start <nl> + CUDA_LONG endOutX = ( x / verticalSubsample < outputHeight - 1 ) ? x / verticalSubsample : outputHeight - 1 ; / / inclusive end <nl> + CUDA_LONG startOutY = max ( 0 . 0f , ceil ( ( y - ( ElemType ) windowWidth + 1 ) / ( ElemType ) horizontalSubsample ) ) ; / / inclusive start <nl> + CUDA_LONG endOutY = ( y / horizontalSubsample < outputWidth - 1 ) ? y / horizontalSubsample : outputWidth - 1 ; / / inclusive end <nl> <nl> ElemType * inputGradientBatchBase4Sample = inputGradientBatch + sample * inputSizePerSample ; <nl> const ElemType * outputGradientBatchBase4Sample = outputGradientBatch + sample * outputSizePerSample ; <nl> __global__ void _addMaxPoolingGradientLoopOut ( ElemType * inputGradientBatch , cons <nl> const CUDA_LONG offset2 = xx * channels ; <nl> if ( pf0 [ offset2 ] = = outputBatch [ outputIndex ] ) <nl> { <nl> - pf1 [ offset2 ] + = outputGradientBatch [ outputIndex ] ; / / need to be atomic however atomicAdd on double is not supported . <nl> + pf1 [ offset2 ] + = outputGradientBatch [ outputIndex ] ; / / need to be atomic however atomicAdd on double is not supported . <nl> } <nl> } <nl> } <nl> template < class ElemType > <nl> __global__ void _columnElementMultiplyWith ( <nl> ElemType * us , <nl> const ElemType * a , <nl> - const CUDA_LONG N , / / a . GetNumRows ( ) ; <nl> - const CUDA_LONG M ) / / us . GetNumCols ( ) ; <nl> + const CUDA_LONG N , / / a . GetNumRows ( ) ; <nl> + const CUDA_LONG M ) / / us . GetNumCols ( ) ; <nl> { <nl> CUDA_LONG id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> if ( id > = N ) <nl> return ; <nl> <nl> - / / __shared__ ElemType _a [ GridDim : : maxThreadsPerBlock ] ; <nl> - / / _a [ threadIdx . x ] = a [ id ] ; <nl> + / / __shared__ ElemType _a [ GridDim : : maxThreadsPerBlock ] ; <nl> + / / _a [ threadIdx . x ] = a [ id ] ; <nl> ElemType mul = a [ id ] ; <nl> for ( CUDA_LONG j = 0 ; j < M ; + + j ) <nl> { <nl> template < class ElemType > <nl> __global__ void _rowElementMultiplyWith ( <nl> ElemType * us , <nl> const ElemType * a , <nl> - const CUDA_LONG N , / / us . GetNumRows ( ) ; <nl> - const CUDA_LONG M ) / / a . GetNumCols ( ) ; <nl> + const CUDA_LONG N , / / us . GetNumRows ( ) ; <nl> + const CUDA_LONG M ) / / a . GetNumCols ( ) ; <nl> { <nl> CUDA_LONG id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> if ( id > = M ) <nl> return ; <nl> <nl> - / / __shared__ ElemType _a [ GridDim : : maxThreadsPerBlock ] ; <nl> - / / _a [ threadIdx . x ] = a [ id ] ; <nl> + / / __shared__ ElemType _a [ GridDim : : maxThreadsPerBlock ] ; <nl> + / / _a [ threadIdx . x ] = a [ id ] ; <nl> ElemType mul = a [ id ] ; <nl> for ( CUDA_LONG i = 0 ; i < N ; + + i ) <nl> { <nl> template < class ElemType > <nl> __global__ void _rowElementDivideBy ( <nl> ElemType * us , <nl> const ElemType * a , <nl> - const CUDA_LONG N , / / us . GetNumRows ( ) ; <nl> - const CUDA_LONG M ) / / a . GetNumCols ( ) ; <nl> + const CUDA_LONG N , / / us . GetNumRows ( ) ; <nl> + const CUDA_LONG M ) / / a . GetNumCols ( ) ; <nl> { <nl> CUDA_LONG id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> if ( id > = M ) <nl> return ; <nl> <nl> - / / __shared__ ElemType _a [ GridDim : : maxThreadsPerBlock ] ; <nl> - / / _a [ threadIdx . x ] = a [ id ] ; <nl> + / / __shared__ ElemType _a [ GridDim : : maxThreadsPerBlock ] ; <nl> + / / _a [ threadIdx . x ] = a [ id ] ; <nl> ElemType v = a [ id ] ; <nl> if ( v > = 0 & & v < EPS_IN_INVERSE ) <nl> v = EPS_IN_INVERSE ; <nl> template < class ElemType > <nl> __global__ void _ColumnElementDivideBy ( <nl> ElemType * us , <nl> const ElemType * a , <nl> - const CUDA_LONG N , / / a . GetNumRows ( ) ; <nl> - const CUDA_LONG M ) / / us . GetNumCols ( ) ; <nl> + const CUDA_LONG N , / / a . GetNumRows ( ) ; <nl> + const CUDA_LONG M ) / / us . GetNumCols ( ) ; <nl> { <nl> CUDA_LONG id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> if ( id > = N ) <nl> __global__ void _ColumnElementDivideBy ( <nl> <nl> ElemType smallValue = EPS_IN_INVERSE ; <nl> <nl> - / / __shared__ ElemType _a [ GridDim : : maxThreadsPerBlock ] ; <nl> - / / _a [ threadIdx . x ] = a [ id ] ; <nl> + / / __shared__ ElemType _a [ GridDim : : maxThreadsPerBlock ] ; <nl> + / / _a [ threadIdx . x ] = a [ id ] ; <nl> ElemType v = a [ id ] ; <nl> for ( CUDA_LONG j = 0 ; j < M ; + + j ) <nl> { <nl> __global__ void _innerProduct ( <nl> ElemType * c , <nl> const ElemType * a , <nl> const ElemType * b , <nl> - const CUDA_LONG N , / / a . GetNumRows ( ) ; <nl> - const CUDA_LONG M , / / a . GetNumCols ( ) ; <nl> + const CUDA_LONG N , / / a . GetNumRows ( ) ; <nl> + const CUDA_LONG M , / / a . GetNumCols ( ) ; <nl> const bool isColWise ) <nl> { <nl> CUDA_LONG id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> __global__ void _vectorMaxMinReduce ( <nl> const CUDA_LONG numRows , <nl> const CUDA_LONG numCols ) <nl> { <nl> - / / we first find max per column <nl> + / / we first find max per column <nl> __shared__ ElemType partials [ 512 ] ; <nl> __shared__ int partialsInd [ 512 ] ; <nl> if ( IsMax ) <nl> __global__ void _vectorMax ( <nl> const ElemType * us , <nl> ElemType * maxIndexes , <nl> ElemType * maxValues , <nl> - const CUDA_LONG m , / / number of rows <nl> - const CUDA_LONG n , / / number of cols <nl> + const CUDA_LONG m , / / number of rows <nl> + const CUDA_LONG n , / / number of cols <nl> const bool isColWise ) <nl> { <nl> CUDA_LONG id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> __global__ void _vectorMin ( <nl> const ElemType * us , <nl> ElemType * minIndexes , <nl> ElemType * minValues , <nl> - const CUDA_LONG m , / / number of rows <nl> - const CUDA_LONG n , / / number of cols <nl> + const CUDA_LONG m , / / number of rows <nl> + const CUDA_LONG n , / / number of cols <nl> const bool isColWise ) <nl> { <nl> CUDA_LONG id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> __global__ void _matrixVectorRowWiseAddWithThreadPerElem ( <nl> const ElemType * b , <nl> ElemType * us , <nl> ElemType alpha , <nl> - const CUDA_LONG m , / / number of rows <nl> - const CUDA_LONG n ) / / number of cols <nl> + const CUDA_LONG m , / / number of rows <nl> + const CUDA_LONG n ) / / number of cols <nl> { <nl> CUDA_LONG N = m * n ; / / used in CALCULATE_ELEMENTWISE_INDEX_OR_EXIT ( id , N ) macro <nl> CALCULATE_ELEMENTWISE_INDEX_OR_EXIT ( id , N ) ; <nl> __global__ void _matrixVectorColumnWiseAddWithThreadPerElem ( <nl> const ElemType * b , <nl> ElemType * us , <nl> ElemType alpha , <nl> - const CUDA_LONG m , / / number of rows <nl> - const CUDA_LONG n ) / / number of cols <nl> + const CUDA_LONG m , / / number of rows <nl> + const CUDA_LONG n ) / / number of cols <nl> { <nl> CUDA_LONG N = m * n ; / / used in CALCULATE_ELEMENTWISE_INDEX_OR_EXIT ( id , N ) macro <nl> CALCULATE_ELEMENTWISE_INDEX_OR_EXIT ( id , N ) ; <nl> __global__ void _matrixVectorColumnWiseAddWithThreadPerRow ( <nl> const ElemType * a , <nl> ElemType * us , <nl> ElemType alpha , <nl> - const CUDA_LONG m , / / number of rows <nl> - const CUDA_LONG n ) / / number of cols <nl> + const CUDA_LONG m , / / number of rows <nl> + const CUDA_LONG n ) / / number of cols <nl> { <nl> # ifdef VALIDATION <nl> if ( blockDim . x * blockIdx . x + threadIdx . x = = 0 ) <nl> __global__ void _matrixVectorColumnWiseAddBlockPerRow ( <nl> const ElemType * a , <nl> ElemType * us , <nl> ElemType alpha , <nl> - const CUDA_LONG m , / / number of rows <nl> - const CUDA_LONG n ) / / number of cols <nl> + const CUDA_LONG m , / / number of rows <nl> + const CUDA_LONG n ) / / number of cols <nl> { <nl> ElemType tmp ; <nl> <nl> __global__ void _assignNumOfDiff ( <nl> { <nl> __shared__ ElemType partialSums [ 1024 ] ; <nl> partialSums [ threadIdx . x ] = 0 ; <nl> - / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> + / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> CUDA_LONG loadPerThread = N / blockDim . x ; <nl> for ( CUDA_LONG i = threadIdx . x * loadPerThread ; i < ( threadIdx . x = = blockDim . x - 1 ? N : ( threadIdx . x + 1 ) * loadPerThread ) ; + + i ) <nl> { <nl> __global__ void _assignNumOfDiff ( <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 512 <nl> + / / 512 <nl> if ( threadIdx . x < 512 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 512 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 256 <nl> + / / 256 <nl> if ( threadIdx . x < 256 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 256 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 128 <nl> + / / 128 <nl> if ( threadIdx . x < 128 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 128 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 64 <nl> + / / 64 <nl> if ( threadIdx . x < 64 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 64 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 32 <nl> + / / 32 <nl> if ( threadIdx . x < 32 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 32 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 16 <nl> + / / 16 <nl> if ( threadIdx . x < 16 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 16 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 8 <nl> + / / 8 <nl> if ( threadIdx . x < 8 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 8 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 4 <nl> + / / 4 <nl> if ( threadIdx . x < 4 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 4 ] ; <nl> __global__ void _sparseCSRPlusDense ( <nl> return ; <nl> int start = m_dRow [ id ] ; <nl> int end = m_dRow [ id + 1 ] ; <nl> - for ( int _i = start ; _i < end ; + + _i ) / / _i is index in m_dVal and m_dCol <nl> + for ( int _i = start ; _i < end ; + + _i ) / / _i is index in m_dVal and m_dCol <nl> { <nl> int j = m_dCol [ _i ] ; <nl> pArrayDev [ IDX2C ( id , j , M ) ] + = ( alpha * m_dVal [ _i ] ) ; <nl> __global__ void _sparseCSRElemMulDense ( <nl> return ; <nl> int start = m_dRow [ id ] ; <nl> int end = m_dRow [ id + 1 ] ; <nl> - for ( int _i = start ; _i < end ; + + _i ) / / _i is index in m_dVal and m_dCol <nl> + for ( int _i = start ; _i < end ; + + _i ) / / _i is index in m_dVal and m_dCol <nl> { <nl> int j = m_dCol [ _i ] ; <nl> c [ IDX2C ( id , j , M ) ] = b [ IDX2C ( id , j , M ) ] * m_dVal [ _i ] ; <nl> __global__ void _isValid ( <nl> } <nl> else <nl> { <nl> - for ( int j = start ; j < end ; j + + ) / / j points to the value <nl> + for ( int j = start ; j < end ; j + + ) / / j points to the value <nl> { <nl> if ( rowIndex [ j ] > = rows ) <nl> { <nl> __global__ void _dense1DConvMultSparseCSCAndWeightedAddToDense ( <nl> const int horizontalSubsample , / / convolution step size <nl> const bool channelwise , / / pixelwise for normal multiplication and channelwise for convolution operation <nl> const ElemType alpha , <nl> - const ElemType * a , / / dense <nl> + const ElemType * a , / / dense <nl> const bool transposeA , <nl> - const ElemType * bnzValues , / / sparse nz values <nl> + const ElemType * bnzValues , / / sparse nz values <nl> const GPUSPARSE_INDEX_TYPE * rowIndex , <nl> const GPUSPARSE_INDEX_TYPE * colCSCIndex , <nl> const ElemType beta , <nl> - ElemType * c / / dense target <nl> + ElemType * c / / dense target <nl> ) <nl> { <nl> CUDA_LONG id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> __global__ void _dense1DConvMultSparseCSCAndWeightedAddToDense ( <nl> int end = colCSCIndex [ colInC + 1 ] ; <nl> <nl> ElemType s = 0 ; <nl> - for ( int j = start ; j < end ; j + + ) / / j points to the value <nl> + for ( int j = start ; j < end ; j + + ) / / j points to the value <nl> { <nl> int i = rowIndex [ j ] - ( horizontalSubsample * numChannels * stepIdx ) ; / / offset row index by the convolution step <nl> <nl> __global__ void _dense1DConvMultSparseCSCTransposeAndAddToDense ( <nl> bool channelwise , / / pixelwise for normal multiplication and channelwise for convolution operation <nl> int rowInB , / / row index of the sparse matrix <nl> ElemType alpha , <nl> - const ElemType * a , / / dense <nl> + const ElemType * a , / / dense <nl> bool transposeA , <nl> - const ElemType * bnzValues , / / sparse nz values <nl> + const ElemType * bnzValues , / / sparse nz values <nl> const GPUSPARSE_INDEX_TYPE * rowIndex , <nl> const GPUSPARSE_INDEX_TYPE * colCSCIndex , <nl> - ElemType * c / / dense target <nl> + ElemType * c / / dense target <nl> ) <nl> { <nl> CUDA_LONG id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> __global__ void _dense1DConvMultSparseCSCTransposeAndAddToDense ( <nl> int end = colCSCIndex [ rowInB + 1 ] ; <nl> <nl> ElemType s = 0 ; <nl> - for ( int j = start ; j < end ; j + + ) / / j points to the value that are in the same row <nl> + for ( int j = start ; j < end ; j + + ) / / j points to the value that are in the same row <nl> { <nl> int colInC = rowIndex [ j ] ; / / the column index because of transpose <nl> <nl> __global__ void _reshape ( <nl> int end = oldColumnIndex [ oldCol + 1 ] ; <nl> bool done = false ; <nl> <nl> - for ( int j = start ; j < end ; j + + ) / / j points to the value <nl> + for ( int j = start ; j < end ; j + + ) / / j points to the value <nl> { <nl> int oldRow = oldRowIndex [ j ] ; <nl> int index = ( oldCol * oldNumRows + oldRow ) ; <nl> __global__ void _findColsWithValues ( <nl> if ( index > = nnz ) <nl> return ; <nl> <nl> - blockIds [ rowIndexes [ index ] ] = 1 ; / / this row has value . <nl> + blockIds [ rowIndexes [ index ] ] = 1 ; / / this row has value . <nl> } <nl> <nl> / / called before _denseMulSparseCSCTransposeToSparseBlockCol and after _findColsWithValuesto determine which columns have values and <nl> __global__ void _denseMulSparseCSCTransposeToSparseBlockCol2 ( <nl> ElemType * resultValues ) <nl> { <nl> const CUDA_LONG index = blockIdx . x * blockDim . x + threadIdx . x ; <nl> - const CUDA_LONG lhsCol = index / numRowsLhs ; / / rhsCol = = lhsCol <nl> + const CUDA_LONG lhsCol = index / numRowsLhs ; / / rhsCol = = lhsCol <nl> if ( lhsCol > = numColsRhs ) <nl> return ; <nl> - const CUDA_LONG lhsRow = index - numRowsLhs * lhsCol ; / / resultRow = = lhsRow <nl> + const CUDA_LONG lhsRow = index - numRowsLhs * lhsCol ; / / resultRow = = lhsRow <nl> <nl> - / / each thread handles one [ row , col ] combination <nl> + / / each thread handles one [ row , col ] combination <nl> ElemType lhsValue = alpha * lhsValues [ IDX2C ( lhsRow , lhsCol , numRowsLhs ) ] ; <nl> <nl> - CUDA_LONG start = rhsCols [ lhsCol ] ; / / rhsCol = = lhsCol <nl> + CUDA_LONG start = rhsCols [ lhsCol ] ; / / rhsCol = = lhsCol <nl> CUDA_LONG end = rhsCols [ lhsCol + 1 ] ; <nl> <nl> for ( CUDA_LONG p = start ; p < end ; p + + ) <nl> { <nl> CUDA_LONG rhsRow = rhsRows [ p ] ; <nl> ElemType rhsVal = rhsNZValues [ p ] ; <nl> - CUDA_LONG resultCol = col2blockIds [ rhsRow ] ; / / resultCol = = rhsRow maps to columnid <nl> + CUDA_LONG resultCol = col2blockIds [ rhsRow ] ; / / resultCol = = rhsRow maps to columnid <nl> <nl> - / / assume resultValues are 0 - initialized <nl> + / / assume resultValues are 0 - initialized <nl> atomicAdd ( & resultValues [ IDX2C ( lhsRow , resultCol , numRowsLhs ) ] , lhsValue * rhsVal ) ; <nl> } <nl> } <nl> __global__ void _denseMulSparseCSCTransposeToSparseBlockCol ( <nl> GPUSPARSE_INDEX_TYPE * resultBlockIds ) <nl> { <nl> const CUDA_LONG index = blockIdx . x * blockDim . x + threadIdx . x ; <nl> - const CUDA_LONG lhsCol = index / numRowsLhs ; / / rhsCol = = lhsCol <nl> + const CUDA_LONG lhsCol = index / numRowsLhs ; / / rhsCol = = lhsCol <nl> if ( lhsCol > = numColsRhs ) <nl> return ; <nl> - const CUDA_LONG lhsRow = index - numRowsLhs * lhsCol ; / / resultRow = = lhsRow <nl> + const CUDA_LONG lhsRow = index - numRowsLhs * lhsCol ; / / resultRow = = lhsRow <nl> <nl> - / / each thread handles one [ row , col ] combination <nl> + / / each thread handles one [ row , col ] combination <nl> ElemType lhsValue = alpha * lhsValues [ IDX2C ( lhsRow , lhsCol , numRowsLhs ) ] ; <nl> <nl> - CUDA_LONG start = rhsCols [ lhsCol ] ; / / rhsCol = = lhsCol <nl> + CUDA_LONG start = rhsCols [ lhsCol ] ; / / rhsCol = = lhsCol <nl> CUDA_LONG end = rhsCols [ lhsCol + 1 ] ; <nl> <nl> for ( CUDA_LONG p = start ; p < end ; p + + ) <nl> { <nl> CUDA_LONG rhsRow = rhsRows [ p ] ; <nl> ElemType rhsVal = rhsNZValues [ p ] ; <nl> - CUDA_LONG resultCol = rhsRowIdx [ p ] ; / / resultCol = = rhsRow maps to columnid <nl> - resultBlockIds [ resultCol ] = rhsRow ; / / indicate which colmn it actually points to <nl> + CUDA_LONG resultCol = rhsRowIdx [ p ] ; / / resultCol = = rhsRow maps to columnid <nl> + resultBlockIds [ resultCol ] = rhsRow ; / / indicate which colmn it actually points to <nl> <nl> - / / assume resultValues are 0 - initialized <nl> + / / assume resultValues are 0 - initialized <nl> atomicAdd ( & resultValues [ IDX2C ( lhsRow , resultCol , numRowsLhs ) ] , lhsValue * rhsVal ) ; <nl> } <nl> } <nl> __global__ void _denseMulSparseCSCTransposeToSparseBlockCol ( <nl> template < class ElemType > <nl> __global__ void _scaleSparseBlockAndAddToDense ( <nl> const ElemType alpha , <nl> - const bool blockCol , / / true if blockRow <nl> + const bool blockCol , / / true if blockRow <nl> const size_t numRows , <nl> const size_t numCols , <nl> const size_t numBlocks , <nl> - const ElemType * lhsValues , / / lhs is blockCol or blockRow <nl> + const ElemType * lhsValues , / / lhs is blockCol or blockRow <nl> const GPUSPARSE_INDEX_TYPE * blockIds , <nl> ElemType * rhs ) <nl> { <nl> __global__ void _computePredictionError ( <nl> return ; <nl> <nl> if ( val [ p ] < 0 ) <nl> - val [ p ] = exp ( val [ p ] ) ; / / negative ; <nl> + val [ p ] = exp ( val [ p ] ) ; / / negative ; <nl> else <nl> - val [ p ] = exp ( - val [ p ] ) - 1 ; / / positive <nl> + val [ p ] = exp ( - val [ p ] ) - 1 ; / / positive <nl> } <nl> <nl> / / compute gradients of input in cross entropy node <nl> __global__ void _computeNceOutput ( <nl> __shared__ ElemType partials [ 512 ] ; <nl> partials [ threadIdx . x ] = 0 ; <nl> <nl> - / / threadIdx . x range from [ 0 ~ 512 ) <nl> - / / blockIdx . x range from [ 0 ~ nnz ) <nl> - / / blockDim . x equal to 512 <nl> - / / gridDim . x equal to nnz <nl> + / / threadIdx . x range from [ 0 ~ 512 ) <nl> + / / blockIdx . x range from [ 0 ~ nnz ) <nl> + / / blockDim . x equal to 512 <nl> + / / gridDim . x equal to nnz <nl> <nl> / / determine the elements to be handled by this block <nl> int total = numRows * sampleCount ; <nl> __global__ void _assignNceDerivative ( <nl> { <nl> ElemType val = - er * b [ IDX2C ( j , wid , width ) ] ; <nl> atomicAdd ( & c [ IDX2C ( j , batchId , width ) ] , val ) ; <nl> - / / c [ IDX2C ( j , batchId , width ) ] + = val ; <nl> - / / c [ IDX2C ( batchId , j , numRows ) ] + = val ; <nl> + / / c [ IDX2C ( j , batchId , width ) ] + = val ; <nl> + / / c [ IDX2C ( batchId , j , numRows ) ] + = val ; <nl> } <nl> } <nl> else if ( inputIndex = = 2 ) / / weight <nl> __global__ void _assignNceDerivative ( <nl> { <nl> ElemType val = - er * a [ IDX2C ( j , batchId , width ) ] ; <nl> atomicAdd ( & c [ IDX2C ( j , wid , width ) ] , val ) ; <nl> - / / c [ IDX2C ( j , wid , width ) ] + = val ; <nl> + / / c [ IDX2C ( j , wid , width ) ] + = val ; <nl> } <nl> } <nl> - else / / bias vector <nl> + else / / bias vector <nl> { <nl> - / / ElemType val = - er ; <nl> + / / ElemType val = - er ; <nl> atomicAdd ( & c [ wid ] , - er ) ; <nl> - / / c [ wid ] - = er ; <nl> + / / c [ wid ] - = er ; <nl> } <nl> } <nl> } <nl> __global__ void _assignNceDerivativeNew ( <nl> { <nl> for ( int i = 0 ; i < width ; i + + ) <nl> { <nl> - int j = ( i + n ) % width ; / / introduce randomization to avoid conflicts <nl> + int j = ( i + n ) % width ; / / introduce randomization to avoid conflicts <nl> ElemType val = - er * b [ IDX2C ( j , wid , width ) ] ; <nl> atomicAdd ( & c [ IDX2C ( j , batchId , width ) ] , val ) ; <nl> } <nl> __global__ void _assignNceDerivativeNew ( <nl> { <nl> for ( int i = 0 ; i < width ; i + + ) <nl> { <nl> - int j = ( i + n ) % width ; / / introduce randomization to avoid conflicts <nl> + int j = ( i + n ) % width ; / / introduce randomization to avoid conflicts <nl> ElemType val = - er * a [ IDX2C ( j , batchId , width ) ] ; <nl> atomicAdd ( & c [ IDX2C ( j , wid , width ) ] , val ) ; <nl> } <nl> __global__ void _computeGradientOfWeight ( <nl> j = mb - 1 ; <nl> } <nl> <nl> - / / figure out blocks <nl> + / / figure out blocks <nl> int bId = i < nv ? 2 * j : 2 * j + 1 ; <nl> int t = labelRow [ bId ] ; <nl> int iStt ; <nl> __global__ void _inplaceSoftThreshold ( <nl> template < class ElemType > <nl> __global__ void _normalGradForSparseBlock ( <nl> const ElemType momentum , <nl> - const bool blockCol , / / true if blockRow <nl> + const bool blockCol , / / true if blockRow <nl> const size_t numRows , <nl> const size_t numCols , <nl> const size_t numBlocks , <nl> - ElemType * lhsValues , / / lhs is blockCol or blockRow <nl> + ElemType * lhsValues , / / lhs is blockCol or blockRow <nl> const GPUSPARSE_INDEX_TYPE * blockIds , <nl> ElemType * rhs ) <nl> { <nl> __global__ void _reductionSum ( <nl> <nl> __shared__ ElemType partialSums [ 1024 ] ; <nl> partialSums [ threadIdx . x ] = 0 ; <nl> - / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> + / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> CUDA_LONG loadPerThread = N / blockDim . x ; <nl> for ( CUDA_LONG i = threadIdx . x * loadPerThread ; i < ( threadIdx . x = = blockDim . x - 1 ? N : ( threadIdx . x + 1 ) * loadPerThread ) ; + + i ) <nl> { <nl> __global__ void _reductionSum ( <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 512 <nl> + / / 512 <nl> if ( threadIdx . x < 512 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 512 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 256 <nl> + / / 256 <nl> if ( threadIdx . x < 256 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 256 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 128 <nl> + / / 128 <nl> if ( threadIdx . x < 128 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 128 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 64 <nl> + / / 64 <nl> if ( threadIdx . x < 64 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 64 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 32 <nl> + / / 32 <nl> if ( threadIdx . x < 32 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 32 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 16 <nl> + / / 16 <nl> if ( threadIdx . x < 16 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 16 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 8 <nl> + / / 8 <nl> if ( threadIdx . x < 8 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 8 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 4 <nl> + / / 4 <nl> if ( threadIdx . x < 4 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 4 ] ; <nl> template < class ElemType > <nl> __global__ void _reductionSumAndAssign ( <nl> ElemType * toAssign , <nl> const ElemType * data , <nl> - CUDA_LONG N , / / length of data <nl> - CUDA_LONG M ) / / length of toAssign <nl> + CUDA_LONG N , / / length of data <nl> + CUDA_LONG M ) / / length of toAssign <nl> { <nl> __shared__ ElemType partialSums [ 1024 ] ; <nl> __shared__ ElemType res ; <nl> partialSums [ threadIdx . x ] = 0 ; <nl> - / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> + / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> CUDA_LONG loadPerThread = N / blockDim . x ; <nl> for ( CUDA_LONG i = threadIdx . x * loadPerThread ; i < ( threadIdx . x = = blockDim . x - 1 ? N : ( threadIdx . x + 1 ) * loadPerThread ) ; + + i ) <nl> { <nl> __global__ void _reductionSumAndAssign ( <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 512 <nl> + / / 512 <nl> if ( threadIdx . x < 512 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 512 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 256 <nl> + / / 256 <nl> if ( threadIdx . x < 256 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 256 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 128 <nl> + / / 128 <nl> if ( threadIdx . x < 128 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 128 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 64 <nl> + / / 64 <nl> if ( threadIdx . x < 64 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 64 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 32 <nl> + / / 32 <nl> if ( threadIdx . x < 32 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 32 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 16 <nl> + / / 16 <nl> if ( threadIdx . x < 16 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 16 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 8 <nl> + / / 8 <nl> if ( threadIdx . x < 8 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 8 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 4 <nl> + / / 4 <nl> if ( threadIdx . x < 4 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 4 ] ; <nl> __global__ void _reductionSum2 ( <nl> <nl> __shared__ ElemType partialSums [ 1024 ] ; <nl> partialSums [ threadIdx . x ] = 0 ; <nl> - / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> + / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> CUDA_LONG loadPerThread = N / blockDim . x ; <nl> for ( CUDA_LONG i = threadIdx . x * loadPerThread ; i < ( threadIdx . x = = blockDim . x - 1 ? N : ( threadIdx . x + 1 ) * loadPerThread ) ; + + i ) <nl> - / / for ( int i = threadIdx . x * loadPerThread ; i < ( threadIdx . x + 1 ) * loadPerThread ; + + i ) <nl> + / / for ( int i = threadIdx . x * loadPerThread ; i < ( threadIdx . x + 1 ) * loadPerThread ; + + i ) <nl> { <nl> partialSums [ threadIdx . x ] + = ( data [ i ] * data [ i ] ) ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 512 <nl> + / / 512 <nl> if ( threadIdx . x < 512 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 512 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 256 <nl> + / / 256 <nl> if ( threadIdx . x < 256 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 256 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 128 <nl> + / / 128 <nl> if ( threadIdx . x < 128 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 128 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 64 <nl> + / / 64 <nl> if ( threadIdx . x < 64 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 64 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 32 <nl> + / / 32 <nl> if ( threadIdx . x < 32 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 32 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 16 <nl> + / / 16 <nl> if ( threadIdx . x < 16 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 16 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 8 <nl> + / / 8 <nl> if ( threadIdx . x < 8 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 8 ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 4 <nl> + / / 4 <nl> if ( threadIdx . x < 4 ) <nl> { <nl> partialSums [ threadIdx . x ] + = partialSums [ threadIdx . x + 4 ] ; <nl> __global__ void _reductionMatrixNormInf ( <nl> <nl> __shared__ ElemType partialSums [ 1024 ] ; <nl> partialSums [ threadIdx . x ] = 0 ; <nl> - / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> + / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> int loadPerThread = N / blockDim . x ; <nl> for ( int i = threadIdx . x * loadPerThread ; i < ( threadIdx . x = = blockDim . x - 1 ? N : ( threadIdx . x + 1 ) * loadPerThread ) ; + + i ) <nl> { <nl> __global__ void _reductionMatrixNormInf ( <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 512 <nl> + / / 512 <nl> if ( threadIdx . x < 512 ) <nl> { <nl> partialSums [ threadIdx . x ] = max ( partialSums [ threadIdx . x + 512 ] , partialSums [ threadIdx . x ] ) ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 256 <nl> + / / 256 <nl> if ( threadIdx . x < 256 ) <nl> { <nl> partialSums [ threadIdx . x ] = max ( partialSums [ threadIdx . x + 256 ] , partialSums [ threadIdx . x ] ) ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 128 <nl> + / / 128 <nl> if ( threadIdx . x < 128 ) <nl> { <nl> partialSums [ threadIdx . x ] = max ( partialSums [ threadIdx . x + 128 ] , partialSums [ threadIdx . x ] ) ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 64 <nl> + / / 64 <nl> if ( threadIdx . x < 64 ) <nl> { <nl> partialSums [ threadIdx . x ] = max ( partialSums [ threadIdx . x + 64 ] , partialSums [ threadIdx . x ] ) ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 32 <nl> + / / 32 <nl> if ( threadIdx . x < 32 ) <nl> { <nl> partialSums [ threadIdx . x ] = max ( partialSums [ threadIdx . x + 32 ] , partialSums [ threadIdx . x ] ) ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 16 <nl> + / / 16 <nl> if ( threadIdx . x < 16 ) <nl> { <nl> partialSums [ threadIdx . x ] = max ( partialSums [ threadIdx . x + 16 ] , partialSums [ threadIdx . x ] ) ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 8 <nl> + / / 8 <nl> if ( threadIdx . x < 8 ) <nl> { <nl> partialSums [ threadIdx . x ] = max ( partialSums [ threadIdx . x + 8 ] , partialSums [ threadIdx . x ] ) ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 4 <nl> + / / 4 <nl> if ( threadIdx . x < 4 ) <nl> { <nl> partialSums [ threadIdx . x ] = max ( partialSums [ threadIdx . x + 4 ] , partialSums [ threadIdx . x ] ) ; <nl> __global__ void _reductionMatrixNorm0 ( <nl> <nl> __shared__ ElemType partialSums [ 1024 ] ; <nl> partialSums [ threadIdx . x ] = 0 ; <nl> - / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> + / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> CUDA_LONG loadPerThread = N / blockDim . x ; <nl> for ( CUDA_LONG i = threadIdx . x * loadPerThread ; i < ( threadIdx . x = = blockDim . x - 1 ? N : ( threadIdx . x + 1 ) * loadPerThread ) ; + + i ) <nl> { <nl> __global__ void _reductionMatrixNorm0 ( <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 512 <nl> + / / 512 <nl> if ( threadIdx . x < 512 ) <nl> { <nl> partialSums [ threadIdx . x ] = partialSums [ threadIdx . x + 512 ] + partialSums [ threadIdx . x ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 256 <nl> + / / 256 <nl> if ( threadIdx . x < 256 ) <nl> { <nl> partialSums [ threadIdx . x ] = partialSums [ threadIdx . x + 256 ] + partialSums [ threadIdx . x ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 128 <nl> + / / 128 <nl> if ( threadIdx . x < 128 ) <nl> { <nl> partialSums [ threadIdx . x ] = partialSums [ threadIdx . x + 128 ] + partialSums [ threadIdx . x ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 64 <nl> + / / 64 <nl> if ( threadIdx . x < 64 ) <nl> { <nl> partialSums [ threadIdx . x ] = partialSums [ threadIdx . x + 64 ] + partialSums [ threadIdx . x ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 32 <nl> + / / 32 <nl> if ( threadIdx . x < 32 ) <nl> { <nl> partialSums [ threadIdx . x ] = partialSums [ threadIdx . x + 32 ] + partialSums [ threadIdx . x ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 16 <nl> + / / 16 <nl> if ( threadIdx . x < 16 ) <nl> { <nl> partialSums [ threadIdx . x ] = partialSums [ threadIdx . x + 16 ] + partialSums [ threadIdx . x ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 8 <nl> + / / 8 <nl> if ( threadIdx . x < 8 ) <nl> { <nl> partialSums [ threadIdx . x ] = partialSums [ threadIdx . x + 8 ] + partialSums [ threadIdx . x ] ; <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 4 <nl> + / / 4 <nl> if ( threadIdx . x < 4 ) <nl> { <nl> partialSums [ threadIdx . x ] = partialSums [ threadIdx . x + 4 ] + partialSums [ threadIdx . x ] ; <nl> __global__ void _getSparseVectorRepresntationForCSCMatrix ( <nl> return ; <nl> int start = m_dRow [ i ] ; <nl> int end = m_dRow [ i + 1 ] ; <nl> - for ( int _i = start ; _i < end ; + + _i ) / / _i is index in m_dVal and m_dCol <nl> + for ( int _i = start ; _i < end ; + + _i ) / / _i is index in m_dVal and m_dCol <nl> { <nl> int j = m_dCol [ _i ] ; <nl> vectArray [ _i ] = i * N + j ; <nl> __global__ void _lrHelper ( <nl> partialSums1 [ threadIdx . x ] = 0 ; <nl> partialSums2 [ threadIdx . x ] = 0 ; <nl> <nl> - / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> + / / int id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> int loadPerThread = N / blockDim . x ; <nl> for ( int i = threadIdx . x * loadPerThread ; i < ( threadIdx . x = = blockDim . x - 1 ? N : ( threadIdx . x + 1 ) * loadPerThread ) ; + + i ) <nl> { <nl> __global__ void _lrHelper ( <nl> __syncthreads ( ) ; <nl> <nl> / * <nl> - / / 512 <nl> + / / 512 <nl> if ( threadIdx . x < 512 ) <nl> { <nl> partialSums1 [ threadIdx . x ] + = partialSums1 [ threadIdx . x + 512 ] ; <nl> __global__ void _lrHelper ( <nl> } <nl> __syncthreads ( ) ; * / <nl> <nl> - / / 256 <nl> + / / 256 <nl> if ( threadIdx . x < 256 ) <nl> { <nl> partialSums1 [ threadIdx . x ] + = partialSums1 [ threadIdx . x + 256 ] ; <nl> __global__ void _lrHelper ( <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 128 <nl> + / / 128 <nl> if ( threadIdx . x < 128 ) <nl> { <nl> partialSums1 [ threadIdx . x ] + = partialSums1 [ threadIdx . x + 128 ] ; <nl> __global__ void _lrHelper ( <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 64 <nl> + / / 64 <nl> if ( threadIdx . x < 64 ) <nl> { <nl> partialSums1 [ threadIdx . x ] + = partialSums1 [ threadIdx . x + 64 ] ; <nl> __global__ void _lrHelper ( <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 32 <nl> + / / 32 <nl> if ( threadIdx . x < 32 ) <nl> { <nl> partialSums1 [ threadIdx . x ] + = partialSums1 [ threadIdx . x + 32 ] ; <nl> __global__ void _lrHelper ( <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 16 <nl> + / / 16 <nl> if ( threadIdx . x < 16 ) <nl> { <nl> partialSums1 [ threadIdx . x ] + = partialSums1 [ threadIdx . x + 16 ] ; <nl> __global__ void _lrHelper ( <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 8 <nl> + / / 8 <nl> if ( threadIdx . x < 8 ) <nl> { <nl> partialSums1 [ threadIdx . x ] + = partialSums1 [ threadIdx . x + 8 ] ; <nl> __global__ void _lrHelper ( <nl> } <nl> __syncthreads ( ) ; <nl> <nl> - / / 4 <nl> + / / 4 <nl> if ( threadIdx . x < 4 ) <nl> { <nl> partialSums1 [ threadIdx . x ] + = partialSums1 [ threadIdx . x + 4 ] ; <nl> __global__ void _innerProductWithShiftNeg ( <nl> ElemType * c , <nl> const ElemType * a , <nl> const ElemType * b , <nl> - const CUDA_LONG N , / / a . GetNumRows ( ) ; <nl> - const CUDA_LONG M , / / a . GetNumCols ( ) ; <nl> + const CUDA_LONG N , / / a . GetNumRows ( ) ; <nl> + const CUDA_LONG M , / / a . GetNumCols ( ) ; <nl> const CUDA_LONG shift , <nl> const CUDA_LONG NTPlusOne ) <nl> { <nl> __global__ void _DropFrame ( <nl> const ElemType * gamma , <nl> const ElemType framedropthreshhold , <nl> const long m_numCols , <nl> - const long m_numRows ) / / ld <nl> + const long m_numRows ) / / ld <nl> { <nl> int col_id = blockDim . x * blockIdx . x + threadIdx . x ; <nl> if ( col_id > = m_numCols ) <nl> __global__ void _DropFrame ( <nl> for ( long i = 0 ; i < m_numRows ; + + i ) <nl> { <nl> int idx = IDX2C ( i , col_id , m_numRows ) ; <nl> - / / printf ( " % u " , idx ) ; <nl> + / / printf ( " % u " , idx ) ; <nl> if ( fabs ( label [ idx ] - 1 . 0 ) < 0 . 1 ) / / we found the 1 in the vector <nl> { <nl> if ( gamma [ idx ] < framedropthreshhold ) <nl> __global__ void _DropFrame ( <nl> <nl> if ( dropframe ) <nl> { <nl> - / / printf ( " frame dropped % u " , col_id ) ; <nl> + / / printf ( " frame dropped % u " , col_id ) ; <nl> for ( long i = 0 ; i < m_numRows ; + + i ) <nl> { <nl> a [ IDX2C ( i , col_id , m_numRows ) ] = 0 . 0 ; <nl> __global__ void _AssignSequenceError ( const ElemType hsmoothingWeight , ElemType * <nl> if ( id > = N ) <nl> return ; <nl> error [ id ] - = alpha * ( label [ id ] - ( 1 . 0 - hsmoothingWeight ) * dnnoutput [ id ] - hsmoothingWeight * gamma [ id ] ) ; <nl> - / / change to ce <nl> - / / error [ id ] - = alpha * ( label [ id ] - dnnoutput [ id ] ) ; <nl> + / / change to ce <nl> + / / error [ id ] - = alpha * ( label [ id ] - dnnoutput [ id ] ) ; <nl> } <nl> <nl> template < class ElemType > <nl> mmm a / Source / Math / GPUSparseMatrix . cu <nl> ppp b / Source / Math / GPUSparseMatrix . cu <nl> void GPUSparseMatrix < ElemType > : : ZeroInit ( const MatrixFormat matrixFormat , const <nl> LogicError ( " GPUSparseMatrix : unsupported sparse matrix format " ) ; <nl> } <nl> <nl> - m_computeDevice = ( computeDevice = = AUTOPLACEMATRIX ) ? GPUMatrix < ElemType > : : GetBestGPUDeviceId ( ) : computeDevice ; / / current GPU device Id <nl> + m_computeDevice = ( computeDevice = = AUTOPLACEMATRIX ) ? GPUMatrix < ElemType > : : GetBestGPUDeviceId ( ) : computeDevice ; / / current GPU device Id <nl> m_computeDevice = EnforceOneGPUOnly ( m_computeDevice ) ; / / see EnforceOneGPUOnly ( ) for comment on what this is <nl> m_numRows = 0 ; <nl> m_numCols = 0 ; <nl> - m_elemSizeAllocated = m_nz = 0 ; / / Number of non - zero elements <nl> + m_elemSizeAllocated = m_nz = 0 ; / / Number of non - zero elements <nl> m_totalBufferSizeAllocated = 0 ; <nl> m_sliceViewOffset = 0 ; <nl> m_format = matrixFormat ; <nl> void GPUSparseMatrix < ElemType > : : DeepCopy ( const GPUSparseMatrix < ElemType > & deepCo <nl> m_externalBuffer = false ; <nl> SetMatrixName ( deepCopy . m_matrixName ) ; <nl> <nl> - / / TODO : to copy other varibles used only for class based LM <nl> + / / TODO : to copy other varibles used only for class based LM <nl> } <nl> <nl> template < class ElemType > <nl> void GPUSparseMatrix < ElemType > : : CopyToCPUSparseMatrix ( CPUSparseMatrix < ElemType > & <nl> <nl> if ( this - > GetFormat ( ) = = matrixFormatSparseCSR ) <nl> { <nl> - / / we need to do conversion because CPUSparseMatrix uses size_t for indexes while GPUSparseMatrix uses int <nl> + / / we need to do conversion because CPUSparseMatrix uses size_t for indexes while GPUSparseMatrix uses int <nl> cpuSparseMatrix . Resize ( GetNumRows ( ) , GetNumCols ( ) , GetNumElemAllocated ( ) , true , false ) ; <nl> cpuSparseMatrix . SetNzCount ( GetNumNZElements ( ) ) ; <nl> <nl> void GPUSparseMatrix < ElemType > : : CopyToCPUSparseMatrix ( CPUSparseMatrix < ElemType > & <nl> } <nl> else if ( this - > GetFormat ( ) = = matrixFormatSparseCSC ) <nl> { <nl> - / / we need to do conversion because CPUSparseMatrix uses size_t for indexes while GPUSparseMatrix uses int <nl> + / / we need to do conversion because CPUSparseMatrix uses size_t for indexes while GPUSparseMatrix uses int <nl> cpuSparseMatrix . Resize ( GetNumRows ( ) , GetNumCols ( ) , GetNumNZElements ( ) , true , false ) ; <nl> cpuSparseMatrix . SetNzCount ( GetNumNZElements ( ) ) ; <nl> <nl> void GPUSparseMatrix < ElemType > : : ChangeDeviceTo ( DEVICEID_TYPE to_id ) <nl> if ( m_computeDevice = = to_id ) <nl> return ; <nl> <nl> - if ( m_totalBufferSizeAllocated = = 0 ) / / nothing to move <nl> + if ( m_totalBufferSizeAllocated = = 0 ) / / nothing to move <nl> { <nl> assert ( m_pArray = = nullptr ) ; <nl> } <nl> void GPUSparseMatrix < ElemType > : : SetValue ( const GPUMatrix < ElemType > & denseMatrix , <nl> cusparseSetMatType ( descr , CUSPARSE_MATRIX_TYPE_GENERAL ) ; <nl> cusparseSetMatIndexBase ( descr , CUSPARSE_INDEX_BASE_ZERO ) ; <nl> <nl> - int numRows = ( int ) denseMatrix . GetNumRows ( ) ; / / m <nl> - int numCols = ( int ) denseMatrix . GetNumCols ( ) ; / / n <nl> + int numRows = ( int ) denseMatrix . GetNumRows ( ) ; / / m <nl> + int numCols = ( int ) denseMatrix . GetNumCols ( ) ; / / n <nl> <nl> int * nnzPerRowOrCol = TracingGPUMemoryAllocator : : Allocate < GPUSPARSE_INDEX_TYPE > ( m_computeDevice , ( ( matrixFormat & matrixFormatRowMajor ) ? numRows : numCols ) ) ; <nl> int nnzTotalDevHostPtr = - 1 ; <nl> GPUSparseMatrix < ElemType > : : GPUSparseMatrix ( GPUSparseMatrix < ElemType > & & moveFrom ) <nl> m_tempHostBuffer = moveFrom . m_tempHostBuffer ; <nl> m_tempHostBufferSize = moveFrom . m_tempHostBufferSize ; <nl> <nl> - moveFrom . ZeroInit ( moveFrom . m_format , moveFrom . m_computeDevice ) ; / / so that memory in moveFrom is not freeed <nl> + moveFrom . ZeroInit ( moveFrom . m_format , moveFrom . m_computeDevice ) ; / / so that memory in moveFrom is not freeed <nl> } <nl> <nl> template < class ElemType > <nl> GPUSparseMatrix < ElemType > & GPUSparseMatrix < ElemType > : : operator = ( GPUSparseMatrix < <nl> if ( this ! = & moveFrom ) <nl> { <nl> if ( OwnBuffer ( ) ) <nl> - ReleaseMemory ( ) ; / / always delete the data pointer since we will use the pointer from moveFrom <nl> + ReleaseMemory ( ) ; / / always delete the data pointer since we will use the pointer from moveFrom <nl> m_computeDevice = moveFrom . m_computeDevice ; <nl> m_numRows = moveFrom . m_numRows ; <nl> m_numCols = moveFrom . m_numCols ; <nl> void GPUSparseMatrix < ElemType > : : Reshape ( const size_t numRows , const size_t numCo <nl> m_numCols = numCols ; <nl> m_totalBufferSizeAllocated = bufferSizeNeeded ; <nl> <nl> - / / following are generated dynamically and no need to save <nl> + / / following are generated dynamically and no need to save <nl> if ( m_rowToId ! = nullptr ) <nl> TracingGPUMemoryAllocator : : Free < GPUSPARSE_INDEX_TYPE > ( m_computeDevice , m_rowToId ) ; <nl> <nl> void GPUSparseMatrix < ElemType > : : Resize ( const size_t numRows , const size_t numCol <nl> <nl> m_pArray = pArray ; <nl> <nl> - / / following are generated dynamically and no need to save <nl> + / / following are generated dynamically and no need to save <nl> if ( m_rowToId ! = nullptr ) <nl> TracingGPUMemoryAllocator : : Free < GPUSPARSE_INDEX_TYPE > ( m_computeDevice , m_rowToId ) ; <nl> <nl> void GPUSparseMatrix < ElemType > : : Resize ( const size_t numRows , const size_t numCol <nl> m_totalBufferSizeAllocated = bufferSizeNeeded ; <nl> m_elemSizeAllocated = numNZElemToReserve ; <nl> } <nl> - else / / if requested size is smaller , keeping original values does not make sense <nl> + else / / if requested size is smaller , keeping original values does not make sense <nl> { <nl> m_elemSizeAllocated = ElemCountFromBufferSize ( numRows , numCols , matrixFormat , m_totalBufferSizeAllocated ) ; <nl> } <nl> void GPUSparseMatrix < ElemType > : : MultiplyAndWeightedAdd ( ElemType alpha , const GPU <nl> int l = transposeB ? ( int ) rhs . GetNumCols ( ) : ( int ) rhs . GetNumRows ( ) ; <nl> int n = transposeB ? ( int ) rhs . GetNumRows ( ) : ( int ) rhs . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & k > 0 & & l > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & k > 0 & & l > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> assert ( k = = l ) ; <nl> if ( k ! = l ) <nl> { <nl> void GPUSparseMatrix < ElemType > : : ConvolveAndWeightedAdd ( ElemType alpha , const GPU <nl> int l = transposeB ? ( int ) rhs . GetNumCols ( ) : ( int ) rhs . GetNumRows ( ) ; <nl> int n = transposeB ? ( int ) rhs . GetNumRows ( ) : ( int ) rhs . GetNumCols ( ) ; <nl> <nl> - assert ( m > 0 & & k > 0 & & l > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> + assert ( m > 0 & & k > 0 & & l > 0 & & n > 0 ) ; / / converting from size_t to int may cause overflow <nl> <nl> int numSteps = 0 ; <nl> if ( padding ) <nl> void GPUSparseMatrix < ElemType > : : ConvolveAndWeightedAdd ( ElemType alpha , const GPU <nl> horizontalSubsample , / / convolution step size <nl> channelwise , / / channelwise or pixelwise multiplication <nl> alpha , <nl> - reinterpret_cast < const ElemType * > ( lhs . BufferPointer ( ) ) , / / dense <nl> + reinterpret_cast < const ElemType * > ( lhs . BufferPointer ( ) ) , / / dense <nl> transposeA , <nl> - reinterpret_cast < const ElemType * > ( rhs . BufferPointer ( ) ) , / / sparse nz values <nl> + reinterpret_cast < const ElemType * > ( rhs . BufferPointer ( ) ) , / / sparse nz values <nl> rhs . RowLocation ( ) , <nl> rhs . ColLocation ( ) , <nl> beta , <nl> - reinterpret_cast < ElemType * > ( c . BufferPointer ( ) ) / / dense target <nl> + reinterpret_cast < ElemType * > ( c . BufferPointer ( ) ) / / dense target <nl> ) ; <nl> <nl> if ( do_sync ) <nl> void GPUSparseMatrix < ElemType > : : ConvolveAndWeightedAdd ( ElemType alpha , const GPU <nl> channelwise , / / channelwise or pixelwise multiplication <nl> rowInB , <nl> alpha , <nl> - reinterpret_cast < const ElemType * > ( lhs . BufferPointer ( ) ) , / / dense <nl> + reinterpret_cast < const ElemType * > ( lhs . BufferPointer ( ) ) , / / dense <nl> transposeA , <nl> - reinterpret_cast < const ElemType * > ( rhs . BufferPointer ( ) ) , / / sparse nz values <nl> + reinterpret_cast < const ElemType * > ( rhs . BufferPointer ( ) ) , / / sparse nz values <nl> rhs . RowLocation ( ) , <nl> rhs . ColLocation ( ) , <nl> - reinterpret_cast < ElemType * > ( c . BufferPointer ( ) ) / / dense target <nl> + reinterpret_cast < ElemType * > ( c . BufferPointer ( ) ) / / dense target <nl> ) ; <nl> } <nl> <nl> void GPUSparseMatrix < ElemType > : : MultiplyAndAdd ( ElemType alpha , const GPUMatrix < E <nl> <nl> assert ( m > 0 & & k > 0 & & l > 0 & & n > 0 ) ; <nl> ( void ) m ; <nl> - ( void ) n ; / / converting from size_t to int may cause overflow <nl> + ( void ) n ; / / converting from size_t to int may cause overflow <nl> assert ( k = = l ) ; <nl> if ( k ! = l ) <nl> { <nl> void GPUSparseMatrix < ElemType > : : MultiplyAndAdd ( ElemType alpha , const GPUMatrix < E <nl> if ( do_sync ) <nl> CUDA_CALL ( cudaEventCreate ( & done ) ) ; <nl> <nl> - / / based on the size of m_nz in rhs and numCols in the resulted matrix we use different approaches <nl> + / / based on the size of m_nz in rhs and numCols in the resulted matrix we use different approaches <nl> if ( n * 10 < GridDim : : maxThreadsPerBlock * rhs . m_nz ) <nl> { <nl> - c . Resize ( m , n , 1 , true , false ) ; / / reserve memory for BlockId2ColOrRow ( ) and ColOrRow2BlockId ( ) <nl> + c . Resize ( m , n , 1 , true , false ) ; / / reserve memory for BlockId2ColOrRow ( ) and ColOrRow2BlockId ( ) <nl> <nl> size_t * blockSize = TracingGPUMemoryAllocator : : Allocate < size_t > ( lhs . GetComputeDeviceId ( ) , 1 ) ; <nl> CUDA_CALL ( cudaMemset ( blockSize , 0 , sizeof ( size_t ) ) ) ; <nl> void GPUSparseMatrix < ElemType > : : MultiplyAndAdd ( ElemType alpha , const GPUMatrix < E <nl> TracingGPUMemoryAllocator : : Free < size_t > ( lhs . GetComputeDeviceId ( ) , blockSize ) ; <nl> <nl> size_t nnz = m * c . m_blockSize ; <nl> - c . Resize ( m , n , nnz , true , true ) ; / / we need to keep the col2blockid and blockid2col info when resizing . <nl> + c . Resize ( m , n , nnz , true , true ) ; / / we need to keep the col2blockid and blockid2col info when resizing . <nl> c . m_nz = nnz ; <nl> CUDA_CALL ( cudaMemset ( c . BufferPointer ( ) , 0 , sizeof ( ElemType ) * ( c . m_elemSizeAllocated ) ) ) ; <nl> <nl> - LONG64 N = ( LONG64 ) lhs . GetNumElements ( ) ; / / here we process for each row in lhs and each column in rhs ( = = columns in lhs ) <nl> + LONG64 N = ( LONG64 ) lhs . GetNumElements ( ) ; / / here we process for each row in lhs and each column in rhs ( = = columns in lhs ) <nl> blocksPerGrid = ( int ) ceil ( ( ( double ) N ) / GridDim : : maxThreadsPerBlock ) ; <nl> _denseMulSparseCSCTransposeToSparseBlockCol2 < ElemType > < < < blocksPerGrid , GridDim : : maxThreadsPerBlock , 0 , t_stream > > > ( <nl> alpha , <nl> void GPUSparseMatrix < ElemType > : : MultiplyAndAdd ( ElemType alpha , const GPUMatrix < E <nl> CUDA_CALL ( cudaMemset ( c . BufferPointer ( ) , 0 , sizeof ( ElemType ) * ( c . m_elemSizeAllocated ) ) ) ; <nl> CUDA_CALL ( cudaMemset ( c . BlockId2ColOrRow ( ) , 0 , sizeof ( GPUSPARSE_INDEX_TYPE ) * ( c . m_blockSize ) ) ) ; <nl> <nl> - LONG64 N = ( LONG64 ) lhs . GetNumElements ( ) ; / / here we process for each row in lhs and each column in rhs ( = = columns in lhs ) <nl> + LONG64 N = ( LONG64 ) lhs . GetNumElements ( ) ; / / here we process for each row in lhs and each column in rhs ( = = columns in lhs ) <nl> blocksPerGrid = ( int ) ceil ( ( ( double ) N ) / GridDim : : maxThreadsPerBlock ) ; <nl> _denseMulSparseCSCTransposeToSparseBlockCol < ElemType > < < < blocksPerGrid , GridDim : : maxThreadsPerBlock , 0 , t_stream > > > ( <nl> alpha , <nl> size_t GPUSparseMatrix < ElemType > : : IdentifyRowsWithValues ( ) const <nl> size_t row = h_Row [ i ] ; <nl> if ( indexer . find ( row ) = = indexer . end ( ) ) <nl> { <nl> - size_t id = indexer . size ( ) ; / / We need to assign size to a temp variable due to difference in Linux and Windows <nl> + size_t id = indexer . size ( ) ; / / We need to assign size to a temp variable due to difference in Linux and Windows <nl> indexer [ row ] = id ; <nl> } <nl> rowToId [ i ] = indexer [ row ] ; <nl> void GPUSparseMatrix < ElemType > : : Multiply ( const GPUSparseMatrix < ElemType > & S1 , bo <nl> cudaEvent_t done = nullptr ; <nl> if ( do_sync ) <nl> CUDA_CALL ( cudaEventCreate ( & done ) ) ; <nl> - / / Step 1 <nl> + / / Step 1 <nl> c . PrepareBuffer ( m , n , false , / / false means we cannot reuse the " c " buffer if it exists for temporaries <nl> [ & ] ( GPUSPARSE_INDEX_TYPE * csrRowPtrC ) - > size_t <nl> { <nl> void GPUSparseMatrix < ElemType > : : Multiply ( const GPUSparseMatrix < ElemType > & S1 , bo <nl> return nnzTotal ; <nl> } ) ; <nl> <nl> - / / Step 2 <nl> + / / Step 2 <nl> if ( sizeof ( float ) = = sizeof ( ElemType ) ) <nl> { <nl> CUSPARSE_CALL ( cusparseScsrgemm ( cusparseHandle , operA , operB , m , n , k , descrA , nnzA , ( const float * ) S1 . BufferPointer ( ) , S1 . RowLocation ( ) , S1 . ColLocation ( ) , <nl> void GPUSparseMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const GPUSparseMatri <nl> cudaEvent_t done = nullptr ; <nl> if ( do_sync ) <nl> CUDA_CALL ( cudaEventCreate ( & done ) ) ; <nl> - / / Step 1 <nl> + / / Step 1 <nl> bool inOutParameter = ( & b = = & c ) ; <nl> c . PrepareBuffer ( m , n , ! inOutParameter , [ & ] ( GPUSPARSE_INDEX_TYPE * csrRowPtrC ) - > size_t <nl> { <nl> void GPUSparseMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const GPUSparseMatri <nl> return nnzTotal ; <nl> } ) ; <nl> <nl> - / / Step 2 <nl> + / / Step 2 <nl> if ( sizeof ( ElemType ) = = sizeof ( float ) ) <nl> { <nl> CUSPARSE_CALL ( cusparseScsrgeam ( cusparseHandle , m , n , reinterpret_cast < const float * > ( & alpha ) , descrA , nnzA , reinterpret_cast < const float * > ( a . BufferPointer ( ) ) , a . RowLocation ( ) , a . ColLocation ( ) , <nl> void GPUSparseMatrix < ElemType > : : ScaleAndAdd ( ElemType alpha , const GPUSparseMatri <nl> if ( a . GetComputeDeviceId ( ) ! = b . GetComputeDeviceId ( ) | | a . GetComputeDeviceId ( ) ! = c . GetComputeDeviceId ( ) ) <nl> RuntimeError ( " ScaleAndAdd : matrices must be on the same device " ) ; <nl> b . PrepareDevice ( ) ; <nl> - / / copy b to c <nl> + / / copy b to c <nl> CUDA_CALL ( cudaMemcpy ( c . BufferPointer ( ) , b . BufferPointer ( ) , sizeof ( ElemType ) * b . GetNumElements ( ) , cudaMemcpyDeviceToDevice ) ) ; <nl> if ( beta ! = 1 ) <nl> { <nl> ElemType GPUSparseMatrix < ElemType > : : InnerProductOfMatrices ( const GPUSparseMatrix <nl> cusparseIndexBase_t idxBase = CUSPARSE_INDEX_BASE_ZERO ; <nl> cusparseHandle_t cusparseHandle = 0 ; <nl> <nl> - if ( a . m_format = = matrixFormatSparseCSR ) / / need to put a in ColumnMajor format <nl> + if ( a . m_format = = matrixFormatSparseCSR ) / / need to put a in ColumnMajor format <nl> { <nl> cscValA = TracingGPUMemoryAllocator : : Allocate < ElemType > ( a . GetComputeDeviceId ( ) , nnz ) ; <nl> cscRowIndA = TracingGPUMemoryAllocator : : Allocate < GPUSPARSE_INDEX_TYPE > ( a . GetComputeDeviceId ( ) , nnz ) ; <nl> ElemType GPUSparseMatrix < ElemType > : : InnerProductOfMatrices ( const GPUSparseMatrix <nl> { <nl> NOT_IMPLEMENTED ; <nl> } <nl> - / / Given sparse matrix in column major format , calculate indices for corresponding sparse vector <nl> + / / Given sparse matrix in column major format , calculate indices for corresponding sparse vector <nl> GPUSPARSE_INDEX_TYPE * vectArray = TracingGPUMemoryAllocator : : Allocate < GPUSPARSE_INDEX_TYPE > ( a . GetComputeDeviceId ( ) , a . m_nz ) ; <nl> CUDA_LONG M = n ; <nl> CUDA_LONG N = m ; <nl> - / / GPUSPARSE_INDEX_TYPE * h_vectArray = new int [ a . m_nz ] ; <nl> + / / GPUSPARSE_INDEX_TYPE * h_vectArray = new int [ a . m_nz ] ; <nl> int blocksPerGrid = ( int ) ceil ( 1 . 0 * M / GridDim : : maxThreadsPerBlock ) ; <nl> if ( do_sync ) <nl> CUDA_CALL ( cudaEventCreate ( & done ) ) ; <nl> ElemType GPUSparseMatrix < ElemType > : : InnerProductOfMatrices ( const GPUSparseMatrix <nl> CUDA_CALL ( cudaEventDestroy ( done ) ) ; <nl> TracingGPUMemoryAllocator : : Free < GPUSPARSE_INDEX_TYPE > ( a . GetComputeDeviceId ( ) , cscRowIndA ) ; <nl> TracingGPUMemoryAllocator : : Free < GPUSPARSE_INDEX_TYPE > ( a . GetComputeDeviceId ( ) , cscColPtrA ) ; <nl> - / / CUDA_CALL ( cudaMemcpy ( h_vectArray , vectArray , sizeof ( GPUSPARSE_INDEX_TYPE ) * a . m_nz , cudaMemcpyDeviceToHost ) ) ; <nl> + / / CUDA_CALL ( cudaMemcpy ( h_vectArray , vectArray , sizeof ( GPUSPARSE_INDEX_TYPE ) * a . m_nz , cudaMemcpyDeviceToHost ) ) ; <nl> <nl> - / / Actual dot product <nl> + / / Actual dot product <nl> ElemType res = 0 ; <nl> if ( sizeof ( ElemType ) = = sizeof ( float ) ) <nl> { <nl> GPUMatrix < ElemType > GPUSparseMatrix < ElemType > : : CopyColumnSliceToDense ( size_t sta <nl> int m = ( int ) GetNumRows ( ) ; <nl> int n = ( int ) GetNumCols ( ) ; <nl> <nl> - / / if ( numCols = = 0 ) <nl> + / / if ( numCols = = 0 ) <nl> / / LogicError ( " The slice cannot have 0 columns . " ) ; <nl> <nl> if ( startColumn + numCols > n ) <nl> ElemType GPUSparseMatrix < ElemType > : : SumOfElements ( ) const <nl> <nl> ElemType * d_sum = TracingGPUMemoryAllocator : : Allocate < ElemType > ( m_computeDevice , 1 ) ; <nl> ElemType h_sum ; <nl> - / / WARNING : THIS kernel is not the most efficient way ! <nl> + / / WARNING : THIS kernel is not the most efficient way ! <nl> _reductionSum < ElemType > < < < 1 , 1024 > > > ( NzValues ( ) , d_sum , ( LONG64 ) GetNumNZElements ( ) ) ; <nl> CUDA_CALL ( cudaMemcpy ( & h_sum , d_sum , sizeof ( ElemType ) , cudaMemcpyDeviceToHost ) ) ; <nl> TracingGPUMemoryAllocator : : Free < ElemType > ( m_computeDevice , d_sum ) ; <nl> ElemType GPUSparseMatrix < ElemType > : : FrobeniusNorm ( ) const <nl> <nl> ElemType * d_sum = TracingGPUMemoryAllocator : : Allocate < ElemType > ( m_computeDevice , 1 ) ; <nl> ElemType h_sum = 0 ; <nl> - / / WARNING : THIS kernel is not the most efficient way ! <nl> + / / WARNING : THIS kernel is not the most efficient way ! <nl> _reductionSum2 < ElemType > < < < 1 , 1024 > > > ( NzValues ( ) , d_sum , ( int ) GetNumNZElements ( ) ) ; <nl> CUDA_CALL ( cudaMemcpy ( & h_sum , d_sum , sizeof ( ElemType ) , cudaMemcpyDeviceToHost ) ) ; <nl> TracingGPUMemoryAllocator : : Free < ElemType > ( m_computeDevice , d_sum ) ; <nl> ElemType GPUSparseMatrix < ElemType > : : MatrixNormInf ( ) const <nl> <nl> ElemType * d_maxAbs = TracingGPUMemoryAllocator : : Allocate < ElemType > ( m_computeDevice , 1 ) ; <nl> ElemType h_maxAbs = 0 ; <nl> - / / WARNING : THIS kernel is not the most efficient way ! <nl> + / / WARNING : THIS kernel is not the most efficient way ! <nl> _reductionMatrixNormInf < ElemType > < < < 1 , 1024 > > > ( NzValues ( ) , d_maxAbs , ( int ) GetNumNZElements ( ) ) ; <nl> CUDA_CALL ( cudaMemcpy ( & h_maxAbs , d_maxAbs , sizeof ( ElemType ) , cudaMemcpyDeviceToHost ) ) ; <nl> TracingGPUMemoryAllocator : : Free < ElemType > ( m_computeDevice , d_maxAbs ) ; <nl> GPUSparseMatrix < ElemType > & GPUSparseMatrix < ElemType > : : AssignTruncateBottomOf ( con <nl> <nl> if ( this ! = & a ) <nl> { <nl> - / / Resize ( a . GetNumRows ( ) , a . GetNumCols ( ) ) ; <nl> + / / Resize ( a . GetNumRows ( ) , a . GetNumCols ( ) ) ; <nl> ResizeAsAndCopyIndexFrom ( a ) ; <nl> } <nl> CUDA_LONG N = ( CUDA_LONG ) GetNumNZElements ( ) ; <nl> void GPUSparseMatrix < ElemType > : : CopyBuffer ( OutType * outBuffer , const InType * inB <nl> outBuffer [ i + 2 ] = inBuffer [ i + 2 ] ; <nl> outBuffer [ i + 3 ] = inBuffer [ i + 3 ] ; <nl> } <nl> - / / handle remaining stuffs <nl> + / / handle remaining stuffs <nl> for ( size_t i = size & ~ 3 ; i < size ; i + + ) <nl> { <nl> outBuffer [ i ] = inBuffer [ i ] ; <nl> mmm a / Source / Math / GPUSparseMatrix . h <nl> ppp b / Source / Math / GPUSparseMatrix . h <nl> class MATH_API GPUSparseMatrix : public BaseMatrix < ElemType > <nl> <nl> GPUSparseMatrix ( const GPUMatrix < ElemType > & , const MatrixFormat matrixFormat = MatrixFormat : : matrixFormatSparseCSR ) ; <nl> <nl> - / / # ifndef __unix__ <nl> + / / # ifndef __unix__ <nl> GPUSparseMatrix ( GPUSparseMatrix < ElemType > & & ) ; <nl> - / / # endif / * LINUX * / <nl> + / / # endif / * LINUX * / <nl> <nl> ~ GPUSparseMatrix ( ) ; <nl> <nl> class MATH_API GPUSparseMatrix : public BaseMatrix < ElemType > <nl> return m_nz ; <nl> } <nl> <nl> - GPUSPARSE_INDEX_TYPE * MajorIndexLocation ( ) const / / row / col ids in CSC / CSR format , blockId2col / blockId2row in BlockCol / BlockRow format <nl> + GPUSPARSE_INDEX_TYPE * MajorIndexLocation ( ) const / / row / col ids in CSC / CSR format , blockId2col / blockId2row in BlockCol / BlockRow format <nl> { <nl> return ( GPUSPARSE_INDEX_TYPE * ) ( m_pArray + m_elemSizeAllocated ) ; <nl> } <nl> class MATH_API GPUSparseMatrix : public BaseMatrix < ElemType > <nl> return sizeof ( GPUSPARSE_INDEX_TYPE ) * MajorIndexCount ( ) ; <nl> } <nl> <nl> - GPUSPARSE_INDEX_TYPE * SecondaryIndexLocation ( ) const / / compressed index , col / row in CSC / CSR format , col2blockId / row2blockId in BlockCol / BlockRow format <nl> + GPUSPARSE_INDEX_TYPE * SecondaryIndexLocation ( ) const / / compressed index , col / row in CSC / CSR format , col2blockId / row2blockId in BlockCol / BlockRow format <nl> { <nl> if ( m_format = = matrixFormatSparseBlockCol ) <nl> return MajorIndexLocation ( ) + m_numCols ; <nl> class MATH_API GPUSparseMatrix : public BaseMatrix < ElemType > <nl> return MajorIndexLocation ( ) + m_numRows ; <nl> else <nl> return MajorIndexLocation ( ) + m_elemSizeAllocated + m_sliceViewOffset ; <nl> - / / return MajorIndexLocation ( ) + m_elemSizeAllocated + m_sliceViewOffset ; <nl> + / / return MajorIndexLocation ( ) + m_elemSizeAllocated + m_sliceViewOffset ; <nl> } <nl> size_t SecondaryIndexCount ( const size_t numRows , const size_t numCols , const size_t numNZReserved , const MatrixFormat format ) const <nl> { <nl> class MATH_API GPUSparseMatrix : public BaseMatrix < ElemType > <nl> / / the column and row locations will swap based on what format we are in . Full index always follows the data array <nl> GPUSPARSE_INDEX_TYPE * RowLocation ( ) const <nl> { <nl> - / / not a valid function for other formats <nl> + / / not a valid function for other formats <nl> assert ( m_format = = matrixFormatSparseCSC | | m_format = = matrixFormatSparseCSR ) ; <nl> <nl> return ( m_format & matrixFormatRowMajor ) ? SecondaryIndexLocation ( ) : MajorIndexLocation ( ) ; <nl> } <nl> size_t RowSize ( ) const / / actual number of bytes in use <nl> { <nl> - / / not a valid function for other formats <nl> + / / not a valid function for other formats <nl> assert ( m_format = = matrixFormatSparseCSC | | m_format = = matrixFormatSparseCSR ) ; <nl> <nl> return ( m_format & matrixFormatRowMajor ) ? SecondaryIndexSize ( ) : MajorIndexSize ( ) ; <nl> } <nl> GPUSPARSE_INDEX_TYPE * ColLocation ( ) const <nl> { <nl> - / / not a valid function for other formats <nl> + / / not a valid function for other formats <nl> assert ( m_format = = matrixFormatSparseCSC | | m_format = = matrixFormatSparseCSR ) ; <nl> <nl> return ( m_format & matrixFormatRowMajor ) ? MajorIndexLocation ( ) : SecondaryIndexLocation ( ) ; <nl> } <nl> size_t ColSize ( ) const / / actual number of bytes in use <nl> { <nl> - / / not a valid function for other formats <nl> + / / not a valid function for other formats <nl> assert ( m_format = = matrixFormatSparseCSC | | m_format = = matrixFormatSparseCSR ) ; <nl> <nl> return ( m_format & matrixFormatRowMajor ) ? MajorIndexSize ( ) : SecondaryIndexSize ( ) ; <nl> class MATH_API GPUSparseMatrix : public BaseMatrix < ElemType > <nl> GPUSPARSE_INDEX_TYPE SecondaryIndexValueAt ( size_t idx ) const ; <nl> GPUSPARSE_INDEX_TYPE * BlockId2ColOrRow ( ) const <nl> { <nl> - / / not a valid function for other formats <nl> + / / not a valid function for other formats <nl> assert ( m_format = = matrixFormatSparseBlockCol | | m_format = = matrixFormatSparseBlockRow ) ; <nl> return MajorIndexLocation ( ) ; <nl> } <nl> GPUSPARSE_INDEX_TYPE * ColOrRow2BlockId ( ) const <nl> { <nl> - / / not a valid function for other formats <nl> + / / not a valid function for other formats <nl> assert ( m_format = = matrixFormatSparseBlockCol | | m_format = = matrixFormatSparseBlockRow ) ; <nl> return SecondaryIndexLocation ( ) ; <nl> } <nl> class MATH_API GPUSparseMatrix : public BaseMatrix < ElemType > <nl> <nl> void Reshape ( const size_t numRows , const size_t numCols ) ; <nl> void ResizeAsAndCopyIndexFrom ( const GPUSparseMatrix < ElemType > & a , const bool growOnly = true ) ; <nl> - void Resize ( const size_t numRows , const size_t numCols , const size_t numNZElemToReserve , const MatrixFormat matrixFormat , const bool growOnly = true , bool keepExistingValues = true ) ; / / matrix format will affect the size to allocate <nl> + void Resize ( const size_t numRows , const size_t numCols , const size_t numNZElemToReserve , const MatrixFormat matrixFormat , const bool growOnly = true , bool keepExistingValues = true ) ; / / matrix format will affect the size to allocate <nl> void Resize ( const size_t numRows , const size_t numCols , const size_t numNZElemToReserve = 10000 , const bool growOnly = true , bool keepExistingValues = false ) ; <nl> <nl> GPUSparseMatrix < ElemType > Transpose ( ) const ; <nl> class MATH_API GPUSparseMatrix : public BaseMatrix < ElemType > <nl> void ChangeDeviceTo ( DEVICEID_TYPE toId ) ; <nl> <nl> GPUSparseMatrix < ElemType > & operator = ( const GPUSparseMatrix < ElemType > & deepCopy ) ; <nl> - / / # ifndef __unix__ <nl> + / / # ifndef __unix__ <nl> GPUSparseMatrix < ElemType > & operator = ( GPUSparseMatrix < ElemType > & & moveFrom ) ; <nl> - / / # endif / * LINUX * / <nl> + / / # endif / * LINUX * / <nl> GPUSparseMatrix < ElemType > operator + ( const GPUSparseMatrix < ElemType > & a ) const ; <nl> GPUSparseMatrix < ElemType > operator - ( const GPUSparseMatrix < ElemType > & a ) const ; <nl> - GPUSparseMatrix < ElemType > & operator ^ = ( const ElemType alpha ) ; / / element - wise power <nl> - GPUSparseMatrix < ElemType > operator ^ ( const ElemType alpha ) const ; / / element - wise power <nl> + GPUSparseMatrix < ElemType > & operator ^ = ( const ElemType alpha ) ; / / element - wise power <nl> + GPUSparseMatrix < ElemType > operator ^ ( const ElemType alpha ) const ; / / element - wise power <nl> GPUSparseMatrix < ElemType > & operator * = ( const ElemType alpha ) ; <nl> GPUSparseMatrix < ElemType > operator * ( const ElemType alpha ) const ; <nl> GPUSparseMatrix < ElemType > & AssignElementPowerOf ( const GPUSparseMatrix < ElemType > & a , const ElemType power ) ; <nl> class MATH_API GPUSparseMatrix : public BaseMatrix < ElemType > <nl> public : <nl> virtual DEVICEID_TYPE GetComputeDeviceId ( void ) const ; <nl> <nl> - / / Sets sparse matrix in CSR format . this acts as deep copy <nl> + / / Sets sparse matrix in CSR format . this acts as deep copy <nl> void SetMatrixFromCSRFormat ( const CPUSPARSE_INDEX_TYPE * h_CSRRow , const CPUSPARSE_INDEX_TYPE * h_Col , const ElemType * h_Val , <nl> const size_t nz , const size_t numRows , const size_t numCols , const bool IsOnDevice = false , const DEVICEID_TYPE devId = - 1 ) ; <nl> void SetMatrixFromCSCFormat ( const CPUSPARSE_INDEX_TYPE * h_CSCCol , const CPUSPARSE_INDEX_TYPE * h_Row , const ElemType * h_Val , <nl> const size_t nz , const size_t numRows , const size_t numCols , const bool IsOnDevice = false , const DEVICEID_TYPE devId = - 1 ) ; <nl> <nl> - / / Gets sparse matrix in CSR format . this acts as deep copy . All passed pointers must be NULL . the function will allocate memory itself . <nl> + / / Gets sparse matrix in CSR format . this acts as deep copy . All passed pointers must be NULL . the function will allocate memory itself . <nl> void GetMatrixFromCSRFormat ( CPUSPARSE_INDEX_TYPE * & h_CSRRow , CPUSPARSE_INDEX_TYPE * & h_Col , ElemType * & h_Val , size_t & numElemAllocated , size_t & nz , size_t & numRows , size_t & numCols ) const ; <nl> <nl> void GetMatrixFromCSCFormat ( CPUSPARSE_INDEX_TYPE * & h_CSCCol , CPUSPARSE_INDEX_TYPE * & h_Row , ElemType * & h_Val , size_t & numElemAllocated , size_t & nz , size_t & numRows , size_t & numCols ) const ; <nl> class MATH_API GPUSparseMatrix : public BaseMatrix < ElemType > <nl> <nl> GPUSparseMatrix < ElemType > & SetToZeroIfAbsLessThan ( const ElemType threshold ) ; <nl> <nl> - ElemType SumOfElements ( ) const ; / / sum of all elements <nl> - ElemType SumOfAbsElements ( ) const ; / / sum of all abs ( elements ) <nl> + ElemType SumOfElements ( ) const ; / / sum of all elements <nl> + ElemType SumOfAbsElements ( ) const ; / / sum of all abs ( elements ) <nl> ElemType FrobeniusNorm ( ) const ; <nl> ElemType MatrixNormInf ( ) const ; <nl> ElemType MatrixNorm1 ( ) const ; <nl> class MATH_API GPUSparseMatrix : public BaseMatrix < ElemType > <nl> } ; <nl> <nl> public : <nl> - / / Performs C = alpha ? op ( S ) ? D + beta ? C ; Where S is sparse and D and C are dense <nl> + / / Performs C = alpha ? op ( S ) ? D + beta ? C ; Where S is sparse and D and C are dense <nl> static void MultiplyAndWeightedAdd ( ElemType alpha , const GPUMatrix < ElemType > & a , const bool transposeA , const GPUSparseMatrix < ElemType > & b , <nl> const bool transposeB , ElemType beta , GPUMatrix < ElemType > & c ) ; <nl> static void MultiplyAndWeightedAdd ( ElemType alpha , const GPUSparseMatrix < ElemType > & S , const bool transposeS , const GPUMatrix < ElemType > & D , <nl> class MATH_API GPUSparseMatrix : public BaseMatrix < ElemType > <nl> static bool AreEqual ( const GPUSparseMatrix < ElemType > & a , const GPUMatrix < ElemType > & b , const ElemType threshold = 1e - 8 ) ; <nl> static bool AreEqual ( const GPUMatrix < ElemType > & a , const GPUSparseMatrix < ElemType > & b , const ElemType threshold = 1e - 8 ) ; <nl> <nl> - / / For these two , I should also add a version which would return GPUSparseMatrix , since Dense . * Sparse = Sparse . * Dense = Sparse <nl> + / / For these two , I should also add a version which would return GPUSparseMatrix , since Dense . * Sparse = Sparse . * Dense = Sparse <nl> static GPUMatrix < ElemType > ElementProductOf ( const GPUSparseMatrix < ElemType > & a , const GPUMatrix < ElemType > & b ) ; <nl> static GPUMatrix < ElemType > ElementProductOf ( const GPUMatrix < ElemType > & a , const GPUSparseMatrix < ElemType > & b ) ; <nl> <nl> class MATH_API GPUSparseMatrix : public BaseMatrix < ElemType > <nl> private : <nl> size_t m_totalBufferSizeAllocated ; <nl> <nl> - / / used by the blockCol and blockRow format <nl> - size_t m_blockSize ; / / block size <nl> - mutable GPUSPARSE_INDEX_TYPE * m_rowToId ; / / the id showing the order row number is observed in the nnz values . <nl> + / / used by the blockCol and blockRow format <nl> + size_t m_blockSize ; / / block size <nl> + mutable GPUSPARSE_INDEX_TYPE * m_rowToId ; / / the id showing the order row number is observed in the nnz values . <nl> <nl> - mutable void * m_tempHostBuffer ; / / used to copy values . <nl> + mutable void * m_tempHostBuffer ; / / used to copy values . <nl> mutable size_t m_tempHostBufferSize ; <nl> <nl> static bool do_sync ; <nl> mmm a / Source / Math / GPUTensor . cu <nl> ppp b / Source / Math / GPUTensor . cu <nl> struct TensorOps <nl> } <nl> static __device__ ElemType Compute ( const FixedArray < ElemType * , 3 > & pointers , ElementWiseOperator op ) <nl> { <nl> - / / const ElemType & a = * ( pointers [ 0 ] ) ; / / const & for opIndex - - costs quite some code bloat <nl> + / / const ElemType & a = * ( pointers [ 0 ] ) ; / / const & for opIndex - - costs quite some code bloat <nl> ElemType a = * ( pointers [ 0 ] ) ; <nl> ElemType b = * ( pointers [ 1 ] ) ; <nl> # define CaseBinaryTensorOp ( oper ) \ <nl> mmm a / Source / Math / GPUWatcher . cu <nl> ppp b / Source / Math / GPUWatcher . cu <nl> size_t GPUWatcher : : GetFreeMemoryOnCUDADevice ( int devId ) <nl> { <nl> return 0 ; <nl> } <nl> - / / get the amount of free memory on the graphics card <nl> + / / get the amount of free memory on the graphics card <nl> size_t free = 0 ; <nl> size_t total = 0 ; <nl> result = cudaMemGetInfo ( & free , & total ) ; <nl> mmm a / Source / Math / Matrix . cpp <nl> ppp b / Source / Math / Matrix . cpp <nl> Matrix < ElemType > : : Matrix ( FILE * f , const char * matrixName , DEVICEID_TYPE deviceId <nl> if ( m_preferredDeviceId = = CPUDEVICE ) <nl> { <nl> NOT_IMPLEMENTED ; <nl> - / / m_CPUSparseMatrix = new CPUSparseMatrix < ElemType > ( f , matrixName ) ; <nl> + / / m_CPUSparseMatrix = new CPUSparseMatrix < ElemType > ( f , matrixName ) ; <nl> SetDataLocation ( CPU , SPARSE ) ; <nl> } <nl> else <nl> { <nl> NOT_IMPLEMENTED ; <nl> - / / m_GPUSparseMatrix = new GPUSparseMatrix < ElemType > ( f , matrixName , m_preferredDeviceId ) ; <nl> + / / m_GPUSparseMatrix = new GPUSparseMatrix < ElemType > ( f , matrixName , m_preferredDeviceId ) ; <nl> SetDataLocation ( GPU , SPARSE ) ; <nl> } <nl> } <nl> Matrix < ElemType > : : Matrix ( const size_t numRows , const size_t numCols , ElemType * p <nl> { <nl> if ( matrixFlags & matrixFormatSparse ) <nl> { <nl> - / / WARNING : matrixFlag is not passed in and externally managed array cannot be passed in <nl> + / / WARNING : matrixFlag is not passed in and externally managed array cannot be passed in <nl> m_CPUSparseMatrix = new CPUSparseMatrix < ElemType > ( matrixFormatSparseCSC , numRows , numCols , nnz ) ; <nl> SetDataLocation ( CPU , SPARSE ) ; <nl> } <nl> Matrix < ElemType > : : Matrix ( const size_t numRows , const size_t numCols , ElemType * p <nl> { <nl> if ( matrixFlags & matrixFormatSparse ) <nl> { <nl> - / / m_GPUSparseMatrix = new GPUSparseMatrix < ElemType > ( numRows , numCols , nnz , pArray , matrixFlags , m_preferredDeviceId ) ; <nl> + / / m_GPUSparseMatrix = new GPUSparseMatrix < ElemType > ( numRows , numCols , nnz , pArray , matrixFlags , m_preferredDeviceId ) ; <nl> m_GPUSparseMatrix = new GPUSparseMatrix < ElemType > ( MatrixFormat ( matrixFlags & MatrixFormat : : matrixFormatMask ) , m_preferredDeviceId ) ; <nl> m_GPUSparseMatrix - > Resize ( numRows , numCols , nnz , true , false ) ; <nl> SetDataLocation ( GPU , SPARSE ) ; <nl> Matrix < ElemType > : : Matrix ( const Matrix < ElemType > & deepCopyFrom , DEVICEID_TYPE dev <nl> { <nl> int origCopyFromDeviceId = deepCopyFrom . GetDeviceId ( ) ; <nl> <nl> - if ( deviceId = = AUTOPLACEMATRIX ) / / use copyFrom ' s device if we have choice <nl> + if ( deviceId = = AUTOPLACEMATRIX ) / / use copyFrom ' s device if we have choice <nl> deviceId = ( DEVICEID_TYPE ) origCopyFromDeviceId ; <nl> <nl> - Init ( deviceId ) ; / / will set m_preferredDeviceId <nl> + Init ( deviceId ) ; / / will set m_preferredDeviceId <nl> <nl> deepCopyFrom . _transferToDevice ( m_preferredDeviceId , true ) ; <nl> <nl> Matrix < ElemType > : : Matrix ( const Matrix < ElemType > & deepCopyFrom , DEVICEID_TYPE dev <nl> m_CPUSparseMatrix = new CPUSparseMatrix < ElemType > ( * ( deepCopyFrom . m_CPUSparseMatrix ) ) , <nl> m_GPUSparseMatrix = new GPUSparseMatrix < ElemType > ( * ( deepCopyFrom . m_GPUSparseMatrix ) ) ) ; <nl> <nl> - / / should we move back ? <nl> + / / should we move back ? <nl> deepCopyFrom . _transferToDevice ( origCopyFromDeviceId , true ) ; <nl> <nl> m_preferredDeviceId = deepCopyFrom . m_preferredDeviceId ; <nl> Matrix < ElemType > : : ~ Matrix ( void ) <nl> template < class ElemType > <nl> Matrix < ElemType > Matrix < ElemType > : : Ones ( const size_t rows , const size_t cols , DEVICEID_TYPE deviceId ) <nl> { <nl> - Matrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> + Matrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> c . SetValue ( 1 ) ; <nl> return c ; <nl> } <nl> Matrix < ElemType > Matrix < ElemType > : : Ones ( const size_t rows , const size_t cols , DE <nl> template < class ElemType > <nl> Matrix < ElemType > Matrix < ElemType > : : Zeros ( const size_t rows , const size_t cols , DEVICEID_TYPE deviceId ) <nl> { <nl> - Matrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> + Matrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> c . SetValue ( 0 ) ; <nl> return c ; <nl> } <nl> Matrix < ElemType > Matrix < ElemType > : : Zeros ( const size_t rows , const size_t cols , D <nl> template < class ElemType > <nl> Matrix < ElemType > Matrix < ElemType > : : Eye ( const size_t rows , DEVICEID_TYPE deviceId ) <nl> { <nl> - Matrix < ElemType > c ( rows , rows , deviceId ) ; / / will initialize to 0 <nl> + Matrix < ElemType > c ( rows , rows , deviceId ) ; / / will initialize to 0 <nl> c . SetDiagonalValue ( 1 ) ; <nl> return c ; <nl> } <nl> Matrix < ElemType > Matrix < ElemType > : : Eye ( const size_t rows , DEVICEID_TYPE deviceId <nl> template < class ElemType > <nl> Matrix < ElemType > Matrix < ElemType > : : RandomUniform ( const size_t rows , const size_t cols , const ElemType low , const ElemType high , unsigned long seed , DEVICEID_TYPE deviceId ) <nl> { <nl> - Matrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> + Matrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> c . SetUniformRandomValue ( low , high , seed ) ; <nl> return c ; <nl> } <nl> Matrix < ElemType > Matrix < ElemType > : : RandomUniform ( const size_t rows , const size_t <nl> template < class ElemType > <nl> Matrix < ElemType > Matrix < ElemType > : : RandomGaussian ( const size_t rows , const size_t cols , const ElemType mean , const ElemType sigma , unsigned long seed , DEVICEID_TYPE deviceId ) <nl> { <nl> - Matrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> + Matrix < ElemType > c ( rows , cols , deviceId ) ; / / will initialize to 0 <nl> c . SetGaussianRandomValue ( mean , sigma , seed ) ; <nl> return c ; <nl> } <nl> void Matrix < ElemType > : : Read ( File & stream ) <nl> { <nl> if ( M . GetDeviceId ( ) < 0 ) <nl> { <nl> - NOT_IMPLEMENTED ; / / You might want to tranfer your matrix to GPU <nl> + NOT_IMPLEMENTED ; / / You might want to tranfer your matrix to GPU <nl> } <nl> else <nl> { <nl> void Matrix < ElemType > : : Write ( File & stream ) const <nl> { <nl> stream < < ' s ' ; <nl> if ( M . GetDeviceId ( ) < 0 ) <nl> - NOT_IMPLEMENTED / / stream < < ( * M . m_CPUMatrix ) ; <nl> + NOT_IMPLEMENTED / / stream < < ( * M . m_CPUMatrix ) ; <nl> else stream <nl> < < ( * M . m_GPUSparseMatrix ) ; <nl> } <nl> Matrix < ElemType > Matrix < ElemType > : : ColumnSlice ( size_t startColumn , size_t numCol <nl> { <nl> int devId = GetDeviceId ( ) ; <nl> <nl> - Matrix < ElemType > slice ( matrixFlagDontOwnBuffer , ( DEVICEID_TYPE ) devId ) ; / / <nl> + Matrix < ElemType > slice ( matrixFlagDontOwnBuffer , ( DEVICEID_TYPE ) devId ) ; / / <nl> <nl> slice . m_preferredDeviceId = m_preferredDeviceId ; <nl> <nl> void Matrix < ElemType > : : SwitchToMatrixType ( MatrixType newMatrixType , MatrixFormat <nl> if ( m_numTimesMatrixTypeChanged = = NUM_MATRIXTYPE_CHANGED_WARN ) <nl> fprintf ( stderr , " WARNING : The same matrix with dim [ % lu , % lu ] has been transferred between different devices for % d times . \ n " , ( unsigned long ) GetNumRows ( ) , ( unsigned long ) GetNumCols ( ) , NUM_MATRIXTYPE_CHANGED_WARN ) ; <nl> <nl> - if ( GetDeviceId ( ) < 0 ) / / CPU <nl> + if ( GetDeviceId ( ) < 0 ) / / CPU <nl> { <nl> if ( newMatrixType = = MatrixType : : SPARSE ) <nl> { <nl> void Matrix < ElemType > : : SwitchToMatrixType ( MatrixType newMatrixType , MatrixFormat <nl> else <nl> LogicError ( " SwitchToMatrixType : Unexpected / invalid new matrix type " ) ; <nl> } <nl> - else / / GPU <nl> + else / / GPU <nl> { <nl> if ( newMatrixType = = MatrixType : : SPARSE ) <nl> { <nl> void Matrix < ElemType > : : SetValue ( const DeviceBoundNumber < ElemType > & db_number ) <nl> { <nl> if ( IsEmpty ( ) ) / / if empty then we are done <nl> return ; <nl> - / / LogicError ( " SetValue : Matrix is empty . " ) ; <nl> + / / LogicError ( " SetValue : Matrix is empty . " ) ; <nl> <nl> DISPATCH_MATRIX_ON_FLAG ( this , <nl> this , <nl> void Matrix < ElemType > : : SetDiagonalValue ( const Matrix < ElemType > & vector ) <nl> <nl> DecideAndMoveToRightDevice ( * this , vector ) ; <nl> <nl> - if ( vector . GetNumElements ( ) = = 1 ) / / reduce to simple form <nl> + if ( vector . GetNumElements ( ) = = 1 ) / / reduce to simple form <nl> { <nl> DISPATCH_MATRIX_ON_FLAG ( & vector , <nl> nullptr , <nl> void Matrix < ElemType > : : SetDiagonalValue ( const Matrix < ElemType > & vector ) <nl> LogicError ( " SetDiagonalValue : input vector ' s dimension does not agree with [ this ] . " ) ; <nl> else <nl> { <nl> - / / WARNING : we use this pointer to decide which function to call . However , vector may be stored in a different matrix type ( DENSE , SPARSE ) <nl> + / / WARNING : we use this pointer to decide which function to call . However , vector may be stored in a different matrix type ( DENSE , SPARSE ) <nl> DISPATCH_MATRIX_ON_FLAG ( this , <nl> this , <nl> assert ( vector . m_CPUMatrix ! = nullptr ) ; <nl> Matrix < ElemType > Matrix < ElemType > : : operator + ( const Matrix < ElemType > & a ) const <nl> } <nl> else <nl> { <nl> - Matrix < ElemType > c ( * this ) ; / / this implementation will introduce a copy overhead . but make resue of the code <nl> + Matrix < ElemType > c ( * this ) ; / / this implementation will introduce a copy overhead . but make resue of the code <nl> c + = a ; <nl> return c ; <nl> } <nl> Matrix < ElemType > & Matrix < ElemType > : : AssignToRowSliceValuesOf ( const Matrix < ElemTy <nl> { <nl> DecideAndMoveToRightDevice ( * this , a ) ; <nl> <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : AddToRowSliceValuesOf ( const Matrix < ElemType > <nl> { <nl> DecideAndMoveToRightDevice ( * this , a ) ; <nl> <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : AddWithRowSliceValuesOf ( const Matrix < ElemTyp <nl> { <nl> DecideAndMoveToRightDevice ( * this , a ) ; <nl> <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : AddWithRowSliceValuesOf ( const Matrix < ElemTyp <nl> } <nl> <nl> # if 0 / / no longer needed , and overkill anyway as it can be implemented as a bunch of calls to AssignRowSliceValuesOf ( ) <nl> - / / stack the columns in inputMatrices ( starting from sliceStartCol for sliceNumCols columns ) and assign it to [ this ] object . <nl> + / / stack the columns in inputMatrices ( starting from sliceStartCol for sliceNumCols columns ) and assign it to [ this ] object . <nl> template < class ElemType > <nl> Matrix < ElemType > & Matrix < ElemType > : : AssignRowStackValuesOf ( const std : : vector < const Matrix < ElemType > * > & inputMatrices , const size_t sliceStartCol , const size_t sliceNumCols ) <nl> { <nl> Matrix < ElemType > & Matrix < ElemType > : : AddWithRowSliceValuesOf ( const Matrix < ElemTyp <nl> const Matrix < ElemType > & a = * inputMatrices [ i ] ; <nl> DecideAndMoveToRightDevice ( * this , a ) ; <nl> <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> } <nl> Matrix < ElemType > & Matrix < ElemType > : : AddWithRowSliceValuesOf ( const Matrix < ElemTyp <nl> { <nl> if ( GetMatrixType ( ) ! = MatrixType : : SPARSE ) <nl> { <nl> - / / GPUDense ; <nl> + / / GPUDense ; <nl> std : : vector < const GPUMatrix < ElemType > * > gpuInputMatrices ; <nl> gpuInputMatrices . resize ( inputMatrices . size ( ) ) ; <nl> for ( int i = 0 ; i < inputMatrices . size ( ) ; i + + ) <nl> Matrix < ElemType > & Matrix < ElemType > : : AddWithRowSliceValuesOf ( const Matrix < ElemTyp <nl> { <nl> if ( GetMatrixType ( ) ! = MatrixType : : SPARSE ) <nl> { <nl> - / / CPUDense ; <nl> + / / CPUDense ; <nl> std : : vector < const CPUMatrix < ElemType > * > cpuInputMatrices ; <nl> cpuInputMatrices . resize ( inputMatrices . size ( ) ) ; <nl> for ( int i = 0 ; i < inputMatrices . size ( ) ; i + + ) <nl> Matrix < ElemType > & Matrix < ElemType > : : AssignRepeatOf ( const Matrix < ElemType > & a , co <nl> { <nl> DecideAndMoveToRightDevice ( * this , a ) ; <nl> <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : AddToRowRepeatValuesOf ( const Matrix < ElemType <nl> { <nl> DecideAndMoveToRightDevice ( * this , a ) ; <nl> <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : AssignPositiveAndShiftedNegSample ( const Matr <nl> { <nl> DecideAndMoveToRightDevice ( * this , a ) ; <nl> <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : AddFoldedPositiveAndShiftedNegSample ( const M <nl> { <nl> DecideAndMoveToRightDevice ( * this , a ) ; <nl> <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : operator - = ( const Matrix < ElemType > & a ) <nl> template < class ElemType > <nl> Matrix < ElemType > Matrix < ElemType > : : operator - ( const Matrix < ElemType > & a ) const <nl> { <nl> - Matrix < ElemType > c ( * this ) ; / / this implementation will introduce a copy overhead . but make resue of the code <nl> + Matrix < ElemType > c ( * this ) ; / / this implementation will introduce a copy overhead . but make resue of the code <nl> ScaleAndAdd ( - 1 , a , c ) ; <nl> return c ; <nl> } <nl> Matrix < ElemType > & Matrix < ElemType > : : AssignElementDivisionOf ( const Matrix < ElemTyp <nl> InvalidArgument ( " The input matrix dimensions do not match . " ) ; <nl> <nl> DecideAndMoveToRightDevice ( a , b , * this ) ; <nl> - / / WARNING : a and b must have same type <nl> + / / WARNING : a and b must have same type <nl> if ( ! ( a . GetMatrixType ( ) = = b . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : ColumnElementMultiplyWith ( const Matrix < ElemT <nl> InvalidArgument ( " ColumnElementMultiplyWith : The input matrix should be a col vector and match [ this ] ' s rows . " ) ; <nl> <nl> DecideAndMoveToRightDevice ( * this , a ) ; <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : RowElementMultiplyWith ( const Matrix < ElemType <nl> if ( ! ( a . GetNumCols ( ) = = GetNumCols ( ) & & a . GetNumRows ( ) = = 1 ) ) <nl> InvalidArgument ( " RowElementMultiplyWith : The input matrix should be a row vector and match [ this ] ' s columns . " ) ; <nl> <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : RowElementDivideBy ( const Matrix < ElemType > & a <nl> if ( ! ( a . GetNumCols ( ) = = GetNumCols ( ) & & a . GetNumRows ( ) = = 1 ) ) <nl> InvalidArgument ( " RowElementDivideBy : The input matrix should be a row vector and match [ this ] ' s columns . " ) ; <nl> <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : ColumnElementDivideBy ( const Matrix < ElemType > <nl> InvalidArgument ( " ColumnElementDivideBy : The input matrix should be a col vector and match [ this ] ' s rows . " ) ; <nl> <nl> DecideAndMoveToRightDevice ( * this , a ) ; <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> template < class ElemType > <nl> Matrix < ElemType > & Matrix < ElemType > : : AssignNumOfDiff ( const Matrix < ElemType > & a , const Matrix < ElemType > & b , bool searchInCol ) <nl> { <nl> DecideAndMoveToRightDevice ( a , b , * this ) ; <nl> - / / WARNING : a and b must have same type <nl> + / / WARNING : a and b must have same type <nl> if ( ! ( a . GetMatrixType ( ) = = b . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : AssignKhatriRaoProductOf ( const Matrix < ElemTy <nl> InvalidArgument ( " AssignKhatriRaoProductOf : The input matrix dimensions do not match . " ) ; <nl> <nl> DecideAndMoveToRightDevice ( a , b , * this ) ; <nl> - / / WARNING : a and b must have same type <nl> + / / WARNING : a and b must have same type <nl> if ( ! ( a . GetMatrixType ( ) = = b . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : AddColumnReshapeProductOf ( const Matrix < ElemT <nl> InvalidArgument ( " AddColumnReshapeProductOf : The input matrix dimensions do not match . " ) ; <nl> <nl> DecideAndMoveToRightDevice ( * this , a , b ) ; <nl> - / / WARNING : a and b must have same type <nl> + / / WARNING : a and b must have same type <nl> if ( ! ( a . GetMatrixType ( ) = = b . GetMatrixType ( ) & & GetMatrixType ( ) = = b . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : AssignFrobeniusNormOf ( const Matrix < ElemType > <nl> <nl> Resize ( 1 , 1 ) ; <nl> <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> Matrix < ElemType > & Matrix < ElemType > : : AssignSignOf ( const Matrix < ElemType > & a ) <nl> LogicError ( " AssignSignOf : Matrix a is empty . " ) ; <nl> <nl> DecideAndMoveToRightDevice ( a , * this ) ; <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> template < class ElemType > <nl> void Matrix < ElemType > : : _transferToDevice ( int to_id , bool ismoved , bool emptyTransfer ) const <nl> { <nl> int from_id = GetDeviceId ( ) ; <nl> - if ( to_id = = from_id ) / / nothing to do <nl> + if ( to_id = = from_id ) / / nothing to do <nl> return ; <nl> <nl> if ( OwnBuffer ( ) ) <nl> void Matrix < ElemType > : : _transferFromDeviceToDevice ( int from_id , int to_id , bool <nl> <nl> if ( m_matrixType = = MatrixType : : SPARSE ) <nl> { <nl> - if ( from_id = = CPUDEVICE ) / / from CPU to GPU <nl> + if ( from_id = = CPUDEVICE ) / / from CPU to GPU <nl> { <nl> if ( m_CPUSparseMatrix = = NULL ) <nl> LogicError ( " Can ' t move from CPU because I ' m not there ! " ) ; <nl> void Matrix < ElemType > : : _transferFromDeviceToDevice ( int from_id , int to_id , bool <nl> SetDataLocation ( BOTH , SPARSE ) ; <nl> } <nl> } <nl> - else / / from GPU <nl> + else / / from GPU <nl> { <nl> if ( m_GPUSparseMatrix = = NULL | | m_GPUSparseMatrix - > GetComputeDeviceId ( ) ! = from_id ) <nl> LogicError ( " This matrix isn ' t on this ( or any ? ) GPU " ) ; <nl> <nl> - if ( to_id < 0 ) / / to CPU <nl> + if ( to_id < 0 ) / / to CPU <nl> { <nl> if ( m_CPUSparseMatrix = = NULL ) <nl> m_CPUSparseMatrix = new CPUSparseMatrix < ElemType > ( m_GPUSparseMatrix - > GetFormat ( ) ) ; <nl> void Matrix < ElemType > : : _transferFromDeviceToDevice ( int from_id , int to_id , bool <nl> SetDataLocation ( BOTH , SPARSE ) ; <nl> } <nl> } <nl> - else / / to another GPU <nl> + else / / to another GPU <nl> { <nl> m_GPUSparseMatrix - > ChangeDeviceTo ( to_id ) ; <nl> } <nl> void Matrix < ElemType > : : _transferFromDeviceToDevice ( int from_id , int to_id , bool <nl> else <nl> # pragma omp critical <nl> { <nl> - if ( from_id = = CPUDEVICE ) / / from CPU to GPU <nl> + if ( from_id = = CPUDEVICE ) / / from CPU to GPU <nl> { <nl> if ( m_CPUMatrix = = NULL ) <nl> LogicError ( " Can ' t move from CPU because I ' m not there ! " ) ; <nl> void Matrix < ElemType > : : _transferFromDeviceToDevice ( int from_id , int to_id , bool <nl> SetDataLocation ( BOTH , DENSE ) ; <nl> } <nl> } <nl> - else / / from GPU <nl> + else / / from GPU <nl> { <nl> if ( m_GPUMatrix = = NULL | | m_GPUMatrix - > GetComputeDeviceId ( ) ! = from_id ) <nl> LogicError ( " This matrix isn ' t on this ( or any ? ) GPU " ) ; <nl> <nl> - if ( to_id < 0 ) / / to CPU <nl> + if ( to_id < 0 ) / / to CPU <nl> { <nl> if ( m_CPUMatrix ! = NULL ) <nl> delete m_CPUMatrix ; <nl> void Matrix < ElemType > : : _transferFromDeviceToDevice ( int from_id , int to_id , bool <nl> SetDataLocation ( BOTH , DENSE ) ; <nl> } <nl> } <nl> - else / / to another GPU <nl> + else / / to another GPU <nl> { <nl> m_GPUMatrix - > ChangeDeviceTo ( to_id ) ; <nl> } <nl> Matrix < ElemType > & Matrix < ElemType > : : AssignSoftmaxSum ( const Matrix < ElemType > & a , <nl> template < class ElemType > <nl> Matrix < ElemType > & Matrix < ElemType > : : AssignNceUnnormalizedEval ( const Matrix < ElemType > & a , const Matrix < ElemType > & b , const Matrix < ElemType > & c , const Matrix < ElemType > & bias ) <nl> { <nl> - / / if ( a . GetMatrixType ( ) ! = MatrixType : : SPARSE ) <nl> + / / if ( a . GetMatrixType ( ) ! = MatrixType : : SPARSE ) <nl> / / NOT_IMPLEMENTED ; <nl> <nl> Resize ( 1 , 1 ) ; <nl> void Matrix < ElemType > : : MultiplyAndWeightedAdd ( ElemType alpha , const Matrix < ElemT <nl> { <nl> DecideAndMoveToRightDevice ( a , b , c ) ; <nl> <nl> - if ( c . GetDeviceId ( ) < 0 ) / / CPU <nl> + if ( c . GetDeviceId ( ) < 0 ) / / CPU <nl> { <nl> if ( a . GetMatrixType ( ) = = MatrixType : : SPARSE ) <nl> NOT_IMPLEMENTED ; <nl> void Matrix < ElemType > : : MultiplyAndWeightedAdd ( ElemType alpha , const Matrix < ElemT <nl> c . SetDataLocation ( CPU , DENSE ) ; <nl> } <nl> } <nl> - else / / GPU operations <nl> + else / / GPU operations <nl> { <nl> - if ( a . m_matrixType = = b . m_matrixType & & b . m_matrixType = = c . m_matrixType & & a . m_matrixType = = MatrixType : : DENSE ) / / All dense <nl> + if ( a . m_matrixType = = b . m_matrixType & & b . m_matrixType = = c . m_matrixType & & a . m_matrixType = = MatrixType : : DENSE ) / / All dense <nl> { <nl> GPUMatrix < ElemType > : : MultiplyAndWeightedAdd ( alpha , * a . m_GPUMatrix , transposeA , * b . m_GPUMatrix , transposeB , beta , * c . m_GPUMatrix ) ; <nl> c . SetDataLocation ( GPU , DENSE ) ; <nl> } <nl> - else if ( a . m_matrixType = = MatrixType : : SPARSE & & b . m_matrixType = = c . m_matrixType & & b . m_matrixType = = MatrixType : : DENSE ) / / Sparse * Dense + Dense <nl> + else if ( a . m_matrixType = = MatrixType : : SPARSE & & b . m_matrixType = = c . m_matrixType & & b . m_matrixType = = MatrixType : : DENSE ) / / Sparse * Dense + Dense <nl> { <nl> GPUMatrix < ElemType > second = transposeB ? b . m_GPUMatrix - > Transpose ( ) : * b . m_GPUMatrix ; <nl> GPUSparseMatrix < ElemType > : : MultiplyAndWeightedAdd ( alpha , * a . m_GPUSparseMatrix , transposeA , second , false , beta , * c . m_GPUMatrix ) ; <nl> c . SetDataLocation ( GPU , DENSE ) ; <nl> } <nl> - else if ( a . m_matrixType = = MatrixType : : DENSE & & b . m_matrixType = = MatrixType : : SPARSE & & c . m_matrixType = = MatrixType : : DENSE ) / / Dense * Sparse + Dense <nl> + else if ( a . m_matrixType = = MatrixType : : DENSE & & b . m_matrixType = = MatrixType : : SPARSE & & c . m_matrixType = = MatrixType : : DENSE ) / / Dense * Sparse + Dense <nl> { <nl> - / / if ( b . m_GPUSparseMatrix - > GetFormat ( ) = = MatrixFormat : : matrixFormatSparseCSR ) <nl> - / / { <nl> + / / if ( b . m_GPUSparseMatrix - > GetFormat ( ) = = MatrixFormat : : matrixFormatSparseCSR ) <nl> + / / { <nl> GPUSparseMatrix < ElemType > : : MultiplyAndWeightedAdd ( alpha , * a . m_GPUMatrix , transposeA , * b . m_GPUSparseMatrix , transposeB , beta , * c . m_GPUMatrix ) ; <nl> - / / } <nl> - / / else <nl> - / / { <nl> + / / } <nl> + / / else <nl> + / / { <nl> / / GPUMatrix < ElemType > firstDummy = transposeA ? a . m_GPUMatrix - > Transpose ( ) * alpha : ( * a . m_GPUMatrix ) * alpha ; <nl> / / GPUMatrix < ElemType > & first = firstDummy ; / / GCC does not support mixing refs and non - refs <nl> / / GPUSparseMatrix < ElemType > secondDummy = transposeB ? b . m_GPUSparseMatrix - > Transpose ( ) : * b . m_GPUSparseMatrix ; <nl> void Matrix < ElemType > : : MultiplyAndWeightedAdd ( ElemType alpha , const Matrix < ElemT <nl> / / GPUSparseMatrix < ElemType > : : Multiply ( first , second , * tmp . m_GPUMatrix ) ; <nl> / / c = tmp + c * beta ; <nl> / / } <nl> - / / } <nl> + / / } <nl> c . SetDataLocation ( GPU , DENSE ) ; <nl> } <nl> else if ( a . m_matrixType = = MatrixType : : DENSE & & b . m_matrixType = = MatrixType : : SPARSE & & c . m_matrixType = = MatrixType : : SPARSE ) / / h - > u0 <nl> Matrix < ElemType > & Matrix < ElemType > : : GetARowByIndex ( const Matrix < ElemType > & a , si <nl> if ( a . IsEmpty ( ) ) <nl> LogicError ( " GetARowByIndex : Matrix is empty . " ) ; <nl> <nl> - / / WARNING : a and this must have same type <nl> + / / WARNING : a and this must have same type <nl> if ( ! ( GetMatrixType ( ) = = a . GetMatrixType ( ) ) ) <nl> NOT_IMPLEMENTED ; <nl> <nl> mmm a / Source / Math / Matrix . h <nl> ppp b / Source / Math / Matrix . h <nl> enum MatrixType <nl> class MATH_API MatrixBase <nl> { <nl> protected : <nl> - / / virtual ~ MatrixBase ( ) { } ; <nl> + / / virtual ~ MatrixBase ( ) { } ; <nl> / / TODO : currently this causes link errors when building DLLs <nl> } ; <nl> <nl> class MATH_API Matrix : public MatrixBase <nl> mutable GPUSparseMatrix < ElemType > * m_GPUSparseMatrix ; <nl> mutable CPUSparseMatrix < ElemType > * m_CPUSparseMatrix ; <nl> mutable MatrixType m_matrixType ; <nl> - mutable CurrentDataLocation m_currentDataLocation ; / / Indicates which matrix is current <nl> + mutable CurrentDataLocation m_currentDataLocation ; / / Indicates which matrix is current <nl> mutable DEVICEID_TYPE m_preferredDeviceId ; <nl> <nl> mutable size_t m_numTimesDeviceChanged ; <nl> mutable size_t m_numTimesMatrixTypeChanged ; <nl> mutable int m_devicesTransferedTo [ 2 ] ; / / TODO : what is this for ? Seems only diagnostics <nl> <nl> - / / Moves matrix from device id_from to device with id_to . This method doesn ' t change preferred device Id <nl> + / / Moves matrix from device id_from to device with id_to . This method doesn ' t change preferred device Id <nl> void _transferFromDeviceToDevice ( int id_from , int id_to , bool ismoved = true , bool emptyTransfer = false ) const ; <nl> - / / Moves matrix from current device to device with id_to . This method doesn ' t change preferred device Id <nl> + / / Moves matrix from current device to device with id_to . This method doesn ' t change preferred device Id <nl> void _transferToDevice ( int id_to , bool ismoved = true , bool emptyTransfer = false ) const ; <nl> static void DecideAndMoveToRightDevice ( const Matrix < ElemType > & a , const Matrix < ElemType > & b ) ; <nl> static void DecideAndMoveToRightDevice ( const Matrix < ElemType > & a , const Matrix < ElemType > & b , const Matrix < ElemType > & c ) ; <nl> class MATH_API Matrix : public MatrixBase <nl> static void CopyElementsFromDenseToSparse ( CPUMatrix < ElemType > & from , CPUSparseMatrix < ElemType > & dest ) ; <nl> <nl> public : <nl> - / / Constructors , destructors and other static matrix builders <nl> - / / Each constructor can take deviceId as parameter . <nl> - / / If deviceId < 0 then the matrix will be based in RAM ( CPUMatrix ) <nl> - / / Elseif deviceId > = 0 and < AUTOPLACEMATRIX , then the matrix will be based on GPU with specified deviceId <nl> - / / Else ( default ) if deviceId = AUTOPLACEMATRIX , the class will try to place itself on the best GPU , if fails it will go to CPU <nl> - / / The default behaiviour should be deviceId = AUTOPLACEMATRIX <nl> + / / Constructors , destructors and other static matrix builders <nl> + / / Each constructor can take deviceId as parameter . <nl> + / / If deviceId < 0 then the matrix will be based in RAM ( CPUMatrix ) <nl> + / / Elseif deviceId > = 0 and < AUTOPLACEMATRIX , then the matrix will be based on GPU with specified deviceId <nl> + / / Else ( default ) if deviceId = AUTOPLACEMATRIX , the class will try to place itself on the best GPU , if fails it will go to CPU <nl> + / / The default behaiviour should be deviceId = AUTOPLACEMATRIX <nl> Matrix ( DEVICEID_TYPE deviceId = AUTOPLACEMATRIX ) ; <nl> Matrix ( BaseMatrix < ElemType > * baseMatrix , ElemType * pArray , DEVICEID_TYPE deviceId ) ; / / constructor for setting Matrix from a base matrix ( externally managed butter pArray ) <nl> - Matrix ( FILE * f , const char * matrixName , DEVICEID_TYPE deviceId = AUTOPLACEMATRIX , const MatrixType matrixType = DENSE ) ; / / matrixName is used to verify that correct matrix is read . <nl> + Matrix ( FILE * f , const char * matrixName , DEVICEID_TYPE deviceId = AUTOPLACEMATRIX , const MatrixType matrixType = DENSE ) ; / / matrixName is used to verify that correct matrix is read . <nl> Matrix ( const size_t numRows , const size_t numCols , DEVICEID_TYPE deviceId = AUTOPLACEMATRIX , const MatrixType matrixType = DENSE , const MatrixFormat matrixFormat = matrixFormatDense ) ; <nl> Matrix ( const size_t numRows , const size_t numCols , ElemType * pArray , const size_t matrixFlags = matrixFlagNormal , DEVICEID_TYPE deviceId = AUTOPLACEMATRIX , const size_t nnz = 0 ) ; <nl> - Matrix ( const Matrix < ElemType > & deepCopyFrom , DEVICEID_TYPE deviceId = AUTOPLACEMATRIX ) ; / / copy constructor , deep copy <nl> - Matrix < ElemType > & operator = ( const Matrix < ElemType > & deepCopyFrom ) ; / / assignment operator , deep copy <nl> - Matrix ( Matrix < ElemType > & & moveFrom ) ; / / move constructor , shallow copy <nl> - Matrix < ElemType > & operator = ( Matrix < ElemType > & & moveFrom ) ; / / move coment operator , shallow copy <nl> + Matrix ( const Matrix < ElemType > & deepCopyFrom , DEVICEID_TYPE deviceId = AUTOPLACEMATRIX ) ; / / copy constructor , deep copy <nl> + Matrix < ElemType > & operator = ( const Matrix < ElemType > & deepCopyFrom ) ; / / assignment operator , deep copy <nl> + Matrix ( Matrix < ElemType > & & moveFrom ) ; / / move constructor , shallow copy <nl> + Matrix < ElemType > & operator = ( Matrix < ElemType > & & moveFrom ) ; / / move coment operator , shallow copy <nl> <nl> static Matrix < ElemType > Ones ( const size_t rows , const size_t cols , DEVICEID_TYPE deviceId = AUTOPLACEMATRIX ) ; <nl> static Matrix < ElemType > Zeros ( const size_t rows , const size_t cols , DEVICEID_TYPE deviceId = AUTOPLACEMATRIX ) ; <nl> class MATH_API Matrix : public MatrixBase <nl> ~ Matrix ( ) ; <nl> <nl> private : <nl> - Matrix ( const MatrixFlags matrixFlags , const MatrixType matrixType , const MatrixFormat matrixFormat , DEVICEID_TYPE deviceID ) ; / / only used internally to initialize a blank matrix <nl> - Matrix ( const MatrixFlags matrixFlags , const MatrixType matrixType , DEVICEID_TYPE deviceID ) ; / / only used internally to initialize a blank matrix <nl> - Matrix ( const MatrixFlags matrixFlags , DEVICEID_TYPE deviceID ) ; / / only used internally to initialize a blank matrix <nl> - void Init ( DEVICEID_TYPE deviceID ) ; / / only used internally to initialize a blank matrix <nl> + Matrix ( const MatrixFlags matrixFlags , const MatrixType matrixType , const MatrixFormat matrixFormat , DEVICEID_TYPE deviceID ) ; / / only used internally to initialize a blank matrix <nl> + Matrix ( const MatrixFlags matrixFlags , const MatrixType matrixType , DEVICEID_TYPE deviceID ) ; / / only used internally to initialize a blank matrix <nl> + Matrix ( const MatrixFlags matrixFlags , DEVICEID_TYPE deviceID ) ; / / only used internally to initialize a blank matrix <nl> + void Init ( DEVICEID_TYPE deviceID ) ; / / only used internally to initialize a blank matrix <nl> void SetDataLocation ( CurrentDataLocation location , MatrixType type = UNDETERMINED ) const ; <nl> <nl> public : <nl> class MATH_API Matrix : public MatrixBase <nl> { <nl> return m_baseMatrix - > OwnBuffer ( ) ; <nl> } <nl> - int GetDeviceId ( ) const ; / / - 1 if CPU , otherwise GPU CUDA device id <nl> + int GetDeviceId ( ) const ; / / - 1 if CPU , otherwise GPU CUDA device id <nl> DEVICEID_TYPE GetPreferredDeviceId ( ) const <nl> { <nl> return m_preferredDeviceId ; <nl> - } ; / / - 1 if CPU , otherwise GPU CUDA device id <nl> + } ; / / - 1 if CPU , otherwise GPU CUDA device id <nl> void SetPreferredDeviceId ( DEVICEID_TYPE preferredDeviceId ) <nl> { <nl> m_preferredDeviceId = preferredDeviceId ; <nl> } <nl> - / / Moves matrix from device id_from to device with id_to . <nl> - / / If emptyTransfer = true , then no data is ever moved , just corresponding GPU / CPU matrices are deleted and then created using empty constructor <nl> + / / Moves matrix from device id_from to device with id_to . <nl> + / / If emptyTransfer = true , then no data is ever moved , just corresponding GPU / CPU matrices are deleted and then created using empty constructor <nl> void TransferFromDeviceToDevice ( int id_from , int id_to , bool ismoved = false , / * if false then keep source and set location to BOTH * / bool emptyTransfer = false , bool updatePreferredDevice = true ) const ; <nl> - / / Same as TransferFromDeviceToDevice ( ) but moves only if it is currently not on the target device <nl> + / / Same as TransferFromDeviceToDevice ( ) but moves only if it is currently not on the target device <nl> void TransferToDeviceIfNotThere ( int id_to , bool ismoved = false , bool emptyTransfer = false , bool updatePreferredDevice = true ) const ; <nl> void TransferToDeviceIfNotThereAndNotAutoPlace ( int id_to , bool ismoved = false , bool emptyTransfer = false , bool updatePreferredDevice = true ) const ; <nl> CurrentDataLocation GetCurrentMatrixLocation ( ) const <nl> { <nl> return m_currentDataLocation ; <nl> } ; <nl> - void SwitchToMatrixType ( MatrixType newMatrixType , MatrixFormat newMatrixFormat , bool keepValues ) ; / / sets matrix type between dense and sparse <nl> + void SwitchToMatrixType ( MatrixType newMatrixType , MatrixFormat newMatrixFormat , bool keepValues ) ; / / sets matrix type between dense and sparse <nl> size_t GetNumRows ( ) const ; <nl> size_t GetNumCols ( ) const ; <nl> size_t GetNumElements ( ) const ; <nl> class MATH_API Matrix : public MatrixBase <nl> ElemType * BufferPointer ( ) const ; <nl> size_t NzCount ( ) const ; <nl> <nl> - ElemType * CopyToArray ( ) const ; / / allocated by the callee but need to be deleted by the caller <nl> - size_t CopyToArray ( ElemType * & arrayCopyTo , size_t & currentArraySize ) const ; / / allocated by the callee but need to be deleted by the caller <nl> + ElemType * CopyToArray ( ) const ; / / allocated by the callee but need to be deleted by the caller <nl> + size_t CopyToArray ( ElemType * & arrayCopyTo , size_t & currentArraySize ) const ; / / allocated by the callee but need to be deleted by the caller <nl> / / colStride specifies leading dimension of dst . <nl> / / REVIEW alexeyk : GPU version copies from device to host only , implement all versions ( device < - > host ) . <nl> void CopySection ( size_t numRows , size_t numCols , ElemType * dst , size_t colStride ) const ; <nl> class MATH_API Matrix : public MatrixBase <nl> void FSAdagrad ( size_t mbSize , Matrix < ElemType > & gradients , Matrix < ElemType > & functionValues , const ElemType learnRatePerSample , const ElemType momentum ) ; <nl> ElemType RmsProp ( Matrix < ElemType > & gradients , ElemType RMS_GAMMA , ElemType RMS_WGT_INC , ElemType RMS_WGT_MAX , ElemType RMS_WGT_DEC , ElemType RMS_WGT_MIN , const bool needAveMultiplier ) ; <nl> <nl> - void Resize ( const size_t numRows , const size_t numCols , const size_t numNZElemToReserve = 10000 , bool growOnly = true ) ; / / by default we only reallocate if need to grow <nl> + void Resize ( const size_t numRows , const size_t numCols , const size_t numNZElemToReserve = 10000 , bool growOnly = true ) ; / / by default we only reallocate if need to grow <nl> void Resize ( const Matrix < ElemType > & other ) <nl> { <nl> Resize ( other . GetNumRows ( ) , other . GetNumCols ( ) ) ; <nl> class MATH_API Matrix : public MatrixBase <nl> Matrix < ElemType > & operator / = ( ElemType alpha ) ; <nl> Matrix < ElemType > operator / ( ElemType alpha ) const ; <nl> <nl> - Matrix < ElemType > & operator ^ = ( ElemType alpha ) ; / / element - wise power <nl> - Matrix < ElemType > operator ^ ( ElemType alpha ) const ; / / element - wise power <nl> + Matrix < ElemType > & operator ^ = ( ElemType alpha ) ; / / element - wise power <nl> + Matrix < ElemType > operator ^ ( ElemType alpha ) const ; / / element - wise power <nl> Matrix < ElemType > & AssignElementPowerOf ( const Matrix < ElemType > & a , const ElemType power ) ; <nl> <nl> Matrix < ElemType > & ElementMultiplyWith ( const Matrix < ElemType > & a ) ; <nl> class MATH_API Matrix : public MatrixBase <nl> Matrix < ElemType > & InplaceHardmax ( const bool isColWise ) ; <nl> Matrix < ElemType > & AssignHardmaxOf ( const Matrix < ElemType > & a , const bool isColWise ) ; <nl> <nl> - / / sequence training <nl> + / / sequence training <nl> Matrix < ElemType > & DropFrame ( const Matrix < ElemType > & label , const Matrix < ElemType > & gamma , const ElemType & threshhold ) ; <nl> Matrix < ElemType > & AssignSequenceError ( const ElemType hsmoothingWeight , const Matrix < ElemType > & label , const Matrix < ElemType > & dnnoutput , const Matrix < ElemType > & gamma , ElemType alpha ) ; <nl> Matrix < ElemType > & InplaceSqrt ( ) ; <nl> class MATH_API Matrix : public MatrixBase <nl> Matrix < ElemType > & SetToZeroIfAbsLessThan ( const ElemType threshold ) ; <nl> <nl> DeviceBoundNumber < ElemType > Sum_AsDeviceBoundNum ( ) const ; <nl> - ElemType SumOfAbsElements ( ) const ; / / sum of all abs ( elements ) <nl> - ElemType SumOfElements ( ) const ; / / sum of all elements <nl> + ElemType SumOfAbsElements ( ) const ; / / sum of all abs ( elements ) <nl> + ElemType SumOfElements ( ) const ; / / sum of all elements <nl> Matrix < ElemType > & AssignSumOfElements ( const Matrix < ElemType > & a ) ; <nl> <nl> ElemType LogAddSumOfElements ( ) const ; <nl> class MATH_API Matrix : public MatrixBase <nl> Matrix < ElemType > & AssignRowSliceValuesOf ( const Matrix < ElemType > & a , const size_t startIndex , const size_t numRows ) ; <nl> Matrix < ElemType > & AddToRowSliceValuesOf ( const Matrix < ElemType > & a , const size_t startIndex , const size_t numRows ) ; <nl> Matrix < ElemType > & AddWithRowSliceValuesOf ( const Matrix < ElemType > & a , const size_t startIndex , const size_t numRows ) ; <nl> - / / Matrix < ElemType > & AssignRowStackValuesOf ( const std : : vector < const Matrix < ElemType > * > & inputMatrices , const size_t sliceStartCol , const size_t sliceNumCols ) ; <nl> + / / Matrix < ElemType > & AssignRowStackValuesOf ( const std : : vector < const Matrix < ElemType > * > & inputMatrices , const size_t sliceStartCol , const size_t sliceNumCols ) ; <nl> <nl> Matrix < ElemType > & AssignRepeatOf ( const Matrix < ElemType > & a , const size_t numRowRepeats , const size_t numColRepeats ) ; <nl> Matrix < ElemType > & AddToRowRepeatValuesOf ( const Matrix < ElemType > & a , const size_t numRepeats ) ; <nl> class MATH_API Matrix : public MatrixBase <nl> <nl> ElemType MatrixNormInf ( ) const ; <nl> ElemType MatrixNorm1 ( ) const ; <nl> - ElemType MatrixNorm0 ( ) const ; / / number of non - zero elemets <nl> + ElemType MatrixNorm0 ( ) const ; / / number of non - zero elemets <nl> Matrix < ElemType > & AssignSignOf ( const Matrix < ElemType > & a ) ; <nl> Matrix < ElemType > & AddSignOf ( const Matrix < ElemType > & a ) ; <nl> void VectorMax ( Matrix < ElemType > & maxIndexes , Matrix < ElemType > & maxValues , const bool isColWise ) const ; <nl> class MATH_API Matrix : public MatrixBase <nl> <nl> Matrix < ElemType > & AssignNumOfDiff ( const Matrix < ElemType > & a , const Matrix < ElemType > & b , bool searchInCol = false ) ; <nl> <nl> - Matrix < ElemType > & AssignInnerProductOfMatrices ( const Matrix < ElemType > & a , const Matrix < ElemType > & b ) ; / / this method will resize ( 1 , 1 ) first <nl> + Matrix < ElemType > & AssignInnerProductOfMatrices ( const Matrix < ElemType > & a , const Matrix < ElemType > & b ) ; / / this method will resize ( 1 , 1 ) first <nl> <nl> bool HasNan ( const char * name ) const ; <nl> size_t CountNanInf ( ) const ; <nl> <nl> void Print ( const char * matrixName , size_t rowFirst , size_t rowLast , size_t colFirst , size_t colLast ) const ; <nl> - void Print ( const char * matrixName = nullptr ) const ; / / print whole matrix . can be expensive <nl> + void Print ( const char * matrixName = nullptr ) const ; / / print whole matrix . can be expensive <nl> <nl> Matrix < ElemType > & AssignPackedConvolutionInput ( const Matrix < ElemType > & inputSubBatch , <nl> const size_t inputWidth , const size_t inputHeight , const size_t inputChannels , <nl> class MATH_API Matrix : public MatrixBase <nl> public : <nl> static DEVICEID_TYPE GetBestGPUDeviceId ( ) ; <nl> <nl> - / / static BLAS functions <nl> + / / static BLAS functions <nl> <nl> / / singular value decomposition of A as A = U * SIGMA * VT <nl> static void SVD ( const Matrix < ElemType > & A , Matrix < ElemType > & SIGMA , Matrix < ElemType > & U , Matrix < ElemType > & VT , Matrix < ElemType > & W ) ; <nl> class MATH_API Matrix : public MatrixBase <nl> static void AssignScaledDifference ( const Matrix < ElemType > & alpha , const Matrix < ElemType > & a , const Matrix < ElemType > & b , Matrix < ElemType > & c ) ; <nl> <nl> static void AddElementToElement ( const Matrix < ElemType > & a , const size_t ai , const size_t aj , Matrix < ElemType > & c , const size_t ci , const size_t cj ) ; <nl> - / / static void AddLogElementToElement ( const Matrix < ElemType > & a , const size_t ai , const size_t aj , Matrix < ElemType > & c , const size_t ci , const size_t cj ) ; <nl> + / / static void AddLogElementToElement ( const Matrix < ElemType > & a , const size_t ai , const size_t aj , Matrix < ElemType > & c , const size_t ci , const size_t cj ) ; <nl> static void AssignElementToElement ( const Matrix < ElemType > & a , const size_t ai , const size_t aj , Matrix < ElemType > & c , const size_t ci , const size_t cj ) ; <nl> static void MinusOneAt ( Matrix < ElemType > & c , const size_t position ) ; <nl> <nl> static void Scale ( ElemType alpha , Matrix < ElemType > & a ) ; <nl> - static void Scale ( const Matrix < ElemType > & alpha , Matrix < ElemType > & a ) ; / / In this case Matrix alpha must be 1x1 <nl> + static void Scale ( const Matrix < ElemType > & alpha , Matrix < ElemType > & a ) ; / / In this case Matrix alpha must be 1x1 <nl> static void Scale ( ElemType alpha , const Matrix < ElemType > & a , Matrix < ElemType > & c ) ; <nl> static void InnerProduct ( const Matrix < ElemType > & a , const Matrix < ElemType > & b , Matrix < ElemType > & c , const bool isColWise ) ; <nl> static ElemType InnerProductOfMatrices ( const Matrix < ElemType > & a , const Matrix < ElemType > & b ) ; <nl> mmm a / Source / Math / MatrixQuantizerGPU . cu <nl> ppp b / Source / Math / MatrixQuantizerGPU . cu <nl> void MatrixQuantizerGPU < ElemType > : : UnquantizeAsync ( QuantizedMatrix < ElemType > & in <nl> SyncAssignCompleteEvent ( GetComputeStream ( ) ) ; <nl> } <nl> <nl> - / / do the actually unquantization <nl> + / / do the actually unquantization <nl> _UnquantizeMatrix ( inQMatrixGPU . GetArray ( ) , inQMatrixGPU . GetSize ( ) , <nl> outMatrix . BufferPointer ( ) , outMatrix . GetNumRows ( ) , outMatrix . GetNumCols ( ) , <nl> nBits , add , GetComputeStream ( ) ) ; <nl> mmm a / Source / Math / MatrixQuantizerGPU . h <nl> ppp b / Source / Math / MatrixQuantizerGPU . h <nl> class MatrixQuantizerGPU : public MatrixQuantizerImpl < ElemType > <nl> / / wait for the assign stream operations , scheduled so far , to finish <nl> void SyncAssignCompleteEvent ( cudaStream_t computestream ) const ; <nl> <nl> - / / for concurrent computation and memcpy <nl> + / / for concurrent computation and memcpy <nl> / / - assign to GPU : CPU - to - GPU , started by CPU when data read ; flags assigncomplete <nl> / / - GPU - side operation - - waits for assigncomplete ; flags quantizecomplete <nl> / / - fetch from GPU - - waits for quantizecomplete ; flags fetchcomplete <nl> class MatrixQuantizerGPU : public MatrixQuantizerImpl < ElemType > <nl> static cudaStream_t GetAssignStream ( ) ; <nl> <nl> private : <nl> - / / helper functions for gpus <nl> + / / helper functions for gpus <nl> static void Sync ( ) ; <nl> static void SyncStream ( cudaStream_t stream ) ; <nl> static void SyncEvent ( cudaEvent_t ev ) ; <nl> mmm a / Source / Math / MatrixQuantizer_kernel . cu <nl> ppp b / Source / Math / MatrixQuantizer_kernel . cu <nl> __global__ void _QuantizeStripjOneQWord ( <nl> / / get data pointers to the quantized column <nl> auto & qCol = * ( Microsoft : : MSR : : CNTK : : QuantizedColumn < ElemType > * ) & qMat [ qColSize * j ] ; <nl> <nl> - / / and quantizer <nl> + / / and quantizer <nl> const Microsoft : : MSR : : CNTK : : ColumnQuantizer < ElemType > q ( ldNbits , qCol . lower , qCol . upper ) ; <nl> <nl> / / quantize one QWord to qCol [ iQWord ] <nl> void _QuantizeMatrix ( <nl> dim3 mvgriddim , mvblockdim ; <nl> / / using specialized CUDA code ( not shared with CPU ) for collated memory access <nl> / / each thread column computes ' warpsize ' elements <nl> - mvgriddim = ( unsigned int ) nCol ; / / column number <nl> + mvgriddim = ( unsigned int ) nCol ; / / column number <nl> mvblockdim = REDUCTION_BLOCK_SIZE ; <nl> <nl> if ( zeroThresholdFor1Bit ) <nl> mmm a / Source / Math / NoGPU . cpp <nl> ppp b / Source / Math / NoGPU . cpp <nl> void GPUSparseMatrix < ElemType > : : ResizeAsAndCopyIndexFrom ( const GPUSparseMatrix < E <nl> template < class ElemType > <nl> void GPUSparseMatrix < ElemType > : : Resize ( const size_t numRows , const size_t numCols , const size_t numNZElemToReserve , const MatrixFormat matrixFormat , const bool growOnly , bool keepExistingValues ) <nl> { <nl> - } / / matrix format will affect the size to allocate <nl> + } / / matrix format will affect the size to allocate <nl> template < class ElemType > <nl> void GPUSparseMatrix < ElemType > : : Resize ( const size_t numRows , const size_t numCols , const size_t numNZElemToReserve , const bool growOnly , bool keepExistingValues ) <nl> { <nl> void GPUMatrix < ElemType > : : SetDevice ( DEVICEID_TYPE deviceId ) { } ; <nl> / / GetBestGPUDeviceId - Get the best GPU DeviceId , based on cuda information <nl> / / TODO : should be replaced by BestGpu class instead , it ' s much better <nl> template < class ElemType > <nl> - int GPUMatrix < ElemType > : : GetBestGPUDeviceId ( ) / / returns - 1 if no GPUs can be used <nl> + int GPUMatrix < ElemType > : : GetBestGPUDeviceId ( ) / / returns - 1 if no GPUs can be used <nl> { <nl> return EnforceOneGPUOnly ( - 1 ) ; / / CPU <nl> } <nl> void GPUMatrix < ElemType > : : SetValue ( const ElemType v ) <nl> } <nl> <nl> template < class ElemType > <nl> - void GPUMatrix < ElemType > : : SetValue ( const ElemType * d_v ) / / d_v is pointer to the the value in GPU memory <nl> + void GPUMatrix < ElemType > : : SetValue ( const ElemType * d_v ) / / d_v is pointer to the the value in GPU memory <nl> { <nl> } <nl> <nl> void GPUMatrix < ElemType > : : Scale ( GPUMatrix < ElemType > & / * alpha * / , GPUMatrix < ElemTy <nl> { <nl> } <nl> <nl> - template < class ElemType > / / c = alpha * a <nl> + template < class ElemType > / / c = alpha * a <nl> void GPUMatrix < ElemType > : : Scale ( ElemType alpha , const GPUMatrix < ElemType > & / * a * / , GPUMatrix < ElemType > & c ) <nl> { <nl> } <nl> mmm a / Source / Math / QuantizedMatrix . h <nl> ppp b / Source / Math / QuantizedMatrix . h <nl> class MATH_API QuantizedMatrix <nl> size_t m_numCols ; <nl> size_t m_numBits ; <nl> <nl> - / / number of bytes in a quantized column <nl> + / / number of bytes in a quantized column <nl> size_t m_qColSize ; <nl> <nl> template < typename T > <nl> mmm a / Source / Math / TensorView . cpp <nl> ppp b / Source / Math / TensorView . cpp <nl> static void PrepareTensorOperands ( array < TensorShape , N > shapes , array < size_t , N > <nl> / / flatten consecutive dimensions <nl> / / Dimensions must be consecutive in memory , and either non - broadcasting or all - broadcasting , across all dimensions . <nl> / / After this , as , bs , and cs no longer match the TensorShape objects . <nl> - / / fprintf ( stderr , " Pre - flatten : Op % d : % s op % s - > % s via % s \ n " , ( int ) op , string ( shapes [ 0 ] ) . c_str ( ) , string ( shapes [ 1 ] ) . c_str ( ) , string ( shapes [ 2 ] ) . c_str ( ) , string ( TensorShape ( opDims ) ) . c_str ( ) ) ; <nl> + / / fprintf ( stderr , " Pre - flatten : Op % d : % s op % s - > % s via % s \ n " , ( int ) op , string ( shapes [ 0 ] ) . c_str ( ) , string ( shapes [ 1 ] ) . c_str ( ) , string ( shapes [ 2 ] ) . c_str ( ) , string ( TensorShape ( opDims ) ) . c_str ( ) ) ; <nl> for ( size_t k = 1 ; k < dims ; k + + ) <nl> { <nl> for ( size_t i = 0 ; i < N ; i + + ) <nl> static void PrepareTensorOperands ( array < TensorShape , N > shapes , array < size_t , N > <nl> opDims = TensorShape ( opDims ) . FlattenInPlace ( k ) . GetDims ( ) ; / / ( ugh ) <nl> nope : ; <nl> } <nl> - / / fprintf ( stderr , " Post - flatten : Op % d : % s op % s - > % s via % s \ n " , ( int ) op , string ( shapes [ 0 ] ) . c_str ( ) , string ( shapes [ 1 ] ) . c_str ( ) , string ( shapes [ 2 ] ) . c_str ( ) , string ( TensorShape ( opDims ) ) . c_str ( ) ) ; <nl> + / / fprintf ( stderr , " Post - flatten : Op % d : % s op % s - > % s via % s \ n " , ( int ) op , string ( shapes [ 0 ] ) . c_str ( ) , string ( shapes [ 1 ] ) . c_str ( ) , string ( shapes [ 2 ] ) . c_str ( ) , string ( TensorShape ( opDims ) ) . c_str ( ) ) ; <nl> <nl> / / remove singleton dimensions <nl> SmallVector < bool > toDrop ( dims , false ) ; <nl> static void PrepareTensorOperands ( array < TensorShape , N > shapes , array < size_t , N > <nl> for ( size_t i = 0 ; i < N ; i + + ) <nl> assert ( dims = = shapes [ i ] . size ( ) ) ; <nl> / / note : if op is a scalar , then we end up with 0 dimensions here , which is allowed <nl> - / / fprintf ( stderr , " Post - drop : Op % d : % s op % s - > % s via % s \ n " , ( int ) op , string ( shapes [ 0 ] ) . c_str ( ) , string ( shapes [ 1 ] ) . c_str ( ) , string ( shapes [ 2 ] ) . c_str ( ) , string ( TensorShape ( opDims ) ) . c_str ( ) ) ; <nl> + / / fprintf ( stderr , " Post - drop : Op % d : % s op % s - > % s via % s \ n " , ( int ) op , string ( shapes [ 0 ] ) . c_str ( ) , string ( shapes [ 1 ] ) . c_str ( ) , string ( shapes [ 2 ] ) . c_str ( ) , string ( TensorShape ( opDims ) ) . c_str ( ) ) ; <nl> <nl> / / determine broadcasting ; that is , set strides to 0 for 1 - dimensions <nl> / / To be more precise , we should only set actually broadcasting dimensions to 0 . <nl> static void PrepareTensorOperands ( array < TensorShape , N > shapes , array < size_t , N > <nl> break ; <nl> } <nl> <nl> - / / fprintf ( stderr , " % s op % s - > % s via % s \ n " , string ( shapes [ 0 ] ) . c_str ( ) , string ( shapes [ 1 ] ) . c_str ( ) , string ( shapes [ 2 ] ) . c_str ( ) , string ( TensorShape ( opDims ) ) . c_str ( ) ) ; <nl> + / / fprintf ( stderr , " % s op % s - > % s via % s \ n " , string ( shapes [ 0 ] ) . c_str ( ) , string ( shapes [ 1 ] ) . c_str ( ) , string ( shapes [ 2 ] ) . c_str ( ) , string ( TensorShape ( opDims ) ) . c_str ( ) ) ; <nl> <nl> / / determine inverse broadcasting dimensions <nl> / / Inverse broadcasting dims are actual for loops in the kernel , whereas broadcasting input dims are handled by the thread index . <nl> static bool CheckDifferentObject ( const TensorView < ElemType > & a , const TensorView <nl> template < class ElemType > <nl> void TensorView < ElemType > : : DoUnaryOpOf ( ElemType beta , const TensorView & a , ElemType alpha , ElementWiseOperator op ) <nl> { <nl> - / / static int cc = 0 ; if ( cc + + = = 0 ) <nl> + / / static int cc = 0 ; if ( cc + + = = 0 ) <nl> / / fprintf ( stderr , " Tensor Op : Op % d : % s - > % s \ n " , ( int ) op , string ( a . GetShape ( ) ) . c_str ( ) , string ( GetShape ( ) ) . c_str ( ) ) ; <nl> <nl> / / prepare all tensor descriptor information as needed for execution <nl> void TensorView < ElemType > : : DoUnaryOpOf ( ElemType beta , const TensorView & a , ElemT <nl> template < class ElemType > <nl> void TensorView < ElemType > : : DoBinaryOpOf ( ElemType beta , const TensorView & a , const TensorView & b , ElemType alpha , ElementWiseOperator op ) <nl> { <nl> - / / static int cc = 0 ; if ( cc + + = = 0 ) <nl> + / / static int cc = 0 ; if ( cc + + = = 0 ) <nl> / / fprintf ( stderr , " Tensor Op : Op % d : % s op % s - > % s \ n " , ( int ) op , string ( a . GetShape ( ) ) . c_str ( ) , string ( b . GetShape ( ) ) . c_str ( ) , string ( GetShape ( ) ) . c_str ( ) ) ; <nl> <nl> array < size_t , 3 > offsets ; <nl> void TensorView < ElemType > : : DoBinaryOpOf ( ElemType beta , const TensorView & a , cons <nl> template < class ElemType > <nl> void TensorView < ElemType > : : DoTernaryOpOf ( ElemType beta , const TensorView & a , const TensorView & b , const TensorView & c , ElemType alpha , ElementWiseOperator op ) <nl> { <nl> - / / static int cc = 0 ; if ( cc + + = = 0 ) <nl> + / / static int cc = 0 ; if ( cc + + = = 0 ) <nl> / / fprintf ( stderr , " Tensor Op : Op % d : % s , % s , % s - > % s \ n " , ( int ) op , string ( a . GetShape ( ) ) . c_str ( ) , string ( b . GetShape ( ) ) . c_str ( ) , string ( c . GetShape ( ) ) . c_str ( ) , string ( GetShape ( ) ) . c_str ( ) ) ; <nl> <nl> array < size_t , 4 > offsets ; <nl> mmm a / Source / Math / ValueQuantizer . h <nl> ppp b / Source / Math / ValueQuantizer . h <nl> class ValueQuantizer <nl> return u ? val1 : val0 ; <nl> } <nl> <nl> - / / how many bits we are quanatizing to <nl> + / / how many bits we are quanatizing to <nl> cudasharedcode size_t NBits ( ) const <nl> { <nl> return Nbits ; <nl> } <nl> <nl> - / / max value of quantize value ; 2 ^ Nbits <nl> + / / max value of quantize value ; 2 ^ Nbits <nl> cudasharedcode QWordVal QuanRangeEnd ( ) const <nl> { <nl> return rangeend ; <nl> mmm a / Source / Math / cudalatticeops . cu . h <nl> ppp b / Source / Math / cudalatticeops . cu . h <nl> void latticefunctionsops : : edgealignment ( const vectorref < lrhmmdef > & hmms , const v <nl> dim3 t ( 32 , 8 ) ; <nl> const size_t tpb = t . x * t . y ; <nl> dim3 b ( ( unsigned int ) ( ( numedges + tpb - 1 ) / tpb ) ) ; <nl> - / / cudaarrayref < float > logLLsarray ; / / TODO : pass this in , of course <nl> - / / passtextureref texref ( logLLstex , logLLsarray ) ; / / use the same name as that global texref one , so it will match the name inside the kernel <nl> + / / cudaarrayref < float > logLLsarray ; / / TODO : pass this in , of course <nl> + / / passtextureref texref ( logLLstex , logLLsarray ) ; / / use the same name as that global texref one , so it will match the name inside the kernel <nl> edgealignmentj < < < b , t , 0 , / * GetCurrentStream ( ) * / cudaStreamDefault > > > ( hmms , transPs , spalignunitid , silalignunitid , logLLs , nodes , edges , aligns , alignoffsets , backptrstorage , backptroffsets , alignresult , edgeacscores ) ; <nl> checklaunch ( " edgealignment " ) ; <nl> } <nl> mmm a / Source / Math / cudalib . cpp <nl> ppp b / Source / Math / cudalib . cpp <nl> void * mallocbytes ( size_t nelem , size_t sz ) <nl> { <nl> try <nl> { <nl> - / / fprintf ( stderr , " mallocbytes : allocating % d elements of size % d , % d bytes \ n " , ( int ) nelem , ( int ) sz , ( int ) ( nelem * sz ) ) ; / / comment out by [ v - hansu ] to get rid out annoying output <nl> + / / fprintf ( stderr , " mallocbytes : allocating % d elements of size % d , % d bytes \ n " , ( int ) nelem , ( int ) sz , ( int ) ( nelem * sz ) ) ; / / comment out by [ v - hansu ] to get rid out annoying output <nl> void * p ; <nl> cudaMalloc ( & p , nelem * sz ) | | " cudaMalloc failed " ; <nl> return p ; <nl> mmm a / Source / Math / latticefunctionskernels . h <nl> ppp b / Source / Math / latticefunctionskernels . h <nl> struct latticefunctionskernels <nl> return bitsasfloat ( old ) ; <nl> } <nl> # else / / this code does not work because ( assumed ! = old ) will not compare correctly in case of NaNs <nl> - / / same pattern as atomicAdd ( ) , but performing the log - add operation instead <nl> + / / same pattern as atomicAdd ( ) , but performing the log - add operation instead <nl> template < typename FLOAT > <nl> static __device__ FLOAT atomicLogAdd ( FLOAT * address , FLOAT val ) <nl> { <nl> struct latticefunctionskernels <nl> thisvector [ j ] = value ; <nl> } <nl> <nl> - / / zhaorui <nl> + / / zhaorui <nl> static inline __device__ float getlogtransp ( lr3transP transP , int from , int to ) <nl> { <nl> / * if ( from < - 1 | | from > = transP . MAXSTATES | | to > transP . MAXSTATES ) <nl> { <nl> - / / printf ( " from : % d to : % d \ n " , from , to ) ; <nl> + / / printf ( " from : % d to : % d \ n " , from , to ) ; <nl> return LOGZERO ; <nl> } * / <nl> return transP . loga [ from + 1 ] [ to ] ; <nl> struct latticefunctionskernels <nl> const size_t te = ts + numframes ; / / end time of current unit <nl> <nl> size_t state1step0to1 = te ; / / inflection point from state 0 to 1 , record in state 1 <nl> - / / size_t state1stepm1to1 = te ; <nl> + / / size_t state1stepm1to1 = te ; <nl> size_t state2step0to1 = te ; / / inflection point from state 0 to 1 , record in state 2 <nl> - / / size_t state2stepm1to1 = te ; / / inflection point from state 0 to 1 , record in state 2 <nl> + / / size_t state2stepm1to1 = te ; / / inflection point from state 0 to 1 , record in state 2 <nl> size_t state2step1to2 = te ; / / inflection point from state 1 to 2 , record in state 2 <nl> size_t state2step0to2 = te ; <nl> <nl> - / / now we only support transition from - 1 to 0 or 2 for sil <nl> + / / now we only support transition from - 1 to 0 or 2 for sil <nl> float pathscore0 = fwscore ; / / log pp in state 0 <nl> float pathscore1 = fwscore ; / / log pp in state 1 <nl> float pathscore2 = fwscore ; / / log pp in state 2 <nl> struct latticefunctionskernels <nl> / / first frame <nl> if ( ts ! = te ) / / for t = ts , initialization <nl> { <nl> - / * if ( isSil ) / / for sil , - 1 to 2 and - 1 to 0 is permitted <nl> + / * if ( isSil ) / / for sil , - 1 to 2 and - 1 to 0 is permitted <nl> { <nl> pathscore0 + = getlogtransp ( transP , - 1 , 0 ) + logLLs ( senoneid0 , ts ) ; <nl> pathscore2 + = getlogtransp ( transP , - 1 , 2 ) + logLLs ( senoneid2 , ts ) ; <nl> } <nl> - else / / for others , only - 1 to 0 is permitted <nl> + else / / for others , only - 1 to 0 is permitted <nl> { <nl> pathscore0 + = getlogtransp ( transP , - 1 , 0 ) + logLLs ( senoneid0 , ts ) ; <nl> pathscore1 + = getlogtransp ( transP , - 1 , 1 ) + logLLs ( senoneid1 , ts ) ; <nl> struct latticefunctionskernels <nl> } * / <nl> pathscore2 + = getlogtransp ( transP , - 1 , 2 ) + logLLs ( senoneid2 , ts ) ; <nl> pathscore1 + = getlogtransp ( transP , - 1 , 1 ) + logLLs ( senoneid1 , ts ) ; <nl> - / / state1stepm1to1 = ts ; <nl> + / / state1stepm1to1 = ts ; <nl> pathscore0 + = getlogtransp ( transP , - 1 , 0 ) + logLLs ( senoneid0 , ts ) ; <nl> } <nl> <nl> struct latticefunctionskernels <nl> size_t backptroffset = backptroffsets [ j ] ; / / we make use of backptrstorage in backptroffsets [ j ] for viterbi of ergodic model ( silence ) <nl> <nl> bpmatrixref backptrmatrix ( & backptrstorage [ backptroffset ] , hmm . MAXSTATES , numframes ) ; <nl> - / / subsequent frames <nl> + / / subsequent frames <nl> for ( size_t t = ts + 1 ; t < te ; t + + ) <nl> { <nl> if ( ! isSp ) <nl> struct latticefunctionskernels <nl> { <nl> pathscore2 = pathscore12 ; <nl> state2step0to1 = state1step0to1 ; / / record the inflection point <nl> - / / state2stepm1to1 = state1stepm1to1 ; <nl> + / / state2stepm1to1 = state1stepm1to1 ; <nl> state2step1to2 = t ; / / record the inflection point <nl> state2step0to2 = te ; <nl> if ( isSil ) <nl> backptrmatrix ( 2 , t - ts - 1 ) = 1 ; <nl> } <nl> - / / if ( isSil ) / / only silence have path from 0 to 2 <nl> + / / if ( isSil ) / / only silence have path from 0 to 2 <nl> { <nl> const float pathscore02 = pathscore0 + getlogtransp ( transP , 0 , 2 ) ; / / log pp from state 0 to 2 <nl> if ( pathscore02 > = pathscore2 ) / / if state 0 - > 2 <nl> struct latticefunctionskernels <nl> { <nl> pathscore1 = pathscore01 ; <nl> state1step0to1 = t ; / / record the inflection point <nl> - / / state1stepm1to1 = te ; <nl> + / / state1stepm1to1 = te ; <nl> if ( isSil ) <nl> backptrmatrix ( 1 , t - ts - 1 ) = 0 ; <nl> } <nl> struct latticefunctionskernels <nl> else if ( isSp ) <nl> { <nl> pathscore2 = pathscore0 + getlogtransp ( transP , 0 , 1 ) ; / / sp model , from 0 to 1 <nl> - / / printf ( " sp , % f \ n " , pathscore2 ) ; <nl> + / / printf ( " sp , % f \ n " , pathscore2 ) ; <nl> } <nl> <nl> - else if ( isSil ) / / for sil , the exit state can be 0 or 2 . <nl> + else if ( isSil ) / / for sil , the exit state can be 0 or 2 . <nl> { <nl> const float pathscore03 = pathscore0 + getlogtransp ( transP , 0 , 3 ) ; <nl> pathscore2 + = getlogtransp ( transP , 2 , 3 ) ; <nl> struct latticefunctionskernels <nl> <nl> if ( ! isSil ) <nl> { <nl> - if ( state2step0to2 < te ) / / from 0 to 2 <nl> + if ( state2step0to2 < te ) / / from 0 to 2 <nl> { <nl> state2step0to2 + = alignindex - ts ; <nl> for ( size_t t = alignindex ; t < alignindex + numframes ; t + + ) / / set the final alignment <nl> struct latticefunctionskernels <nl> alignresult [ t ] = ( unsigned short ) senoneid ; <nl> } <nl> } <nl> - else / / from 1 to 2 <nl> + else / / from 1 to 2 <nl> { <nl> state2step0to1 + = alignindex - ts ; / / convert to align measure <nl> state2step1to2 + = alignindex - ts ; <nl> struct latticefunctionskernels <nl> { <nl> size_t lastpointer = 2 ; <nl> const float pathscore03 = pathscore0 + getlogtransp ( transP , 0 , 3 ) ; <nl> - if ( pathscore03 > = pathscore2 ) / / exit state is 0 <nl> + if ( pathscore03 > = pathscore2 ) / / exit state is 0 <nl> { <nl> alignresult [ alignindex + numframes - 1 ] = ( unsigned short ) senoneid0 ; <nl> lastpointer = 0 ; <nl> } <nl> - else / / exit state is 2 <nl> + else / / exit state is 2 <nl> alignresult [ alignindex + numframes - 1 ] = ( unsigned short ) senoneid2 ; <nl> <nl> for ( size_t t = alignindex + numframes - 2 ; ( t + 1 ) > alignindex ; t - - ) / / set the final alignment <nl> struct latticefunctionskernels <nl> / / edge info <nl> const edgeinfowithscores & e = edges [ j ] ; <nl> double edgescore = ( e . l * lmf + wp + edgeacscores [ j ] ) / amf ; / / note : edgeacscores [ j ] = = LOGZERO if edge was pruned <nl> - / / zhaorui to deal with the abnormal score for sent start . <nl> + / / zhaorui to deal with the abnormal score for sent start . <nl> if ( e . l < - 200 . 0f ) <nl> edgescore = ( 0 . 0 * lmf + wp + edgeacscores [ j ] ) / amf ; <nl> const bool boostmmi = ( boostingfactor ! = 0 . 0f ) ; <nl> struct latticefunctionskernels <nl> / / edge info <nl> const edgeinfowithscores & e = edges [ j ] ; <nl> double edgescore = ( e . l * lmf + wp + edgeacscores [ j ] ) / amf ; <nl> - / / zhaorui to deal with the abnormal score for sent start . <nl> + / / zhaorui to deal with the abnormal score for sent start . <nl> if ( e . l < - 200 . 0f ) <nl> edgescore = ( 0 . 0 * lmf + wp + edgeacscores [ j ] ) / amf ; <nl> if ( boostmmi ) <nl> mmm a / Source / Readers / BinaryReader / BinaryFile . cpp <nl> ppp b / Source / Readers / BinaryReader / BinaryFile . cpp <nl> BinaryFile : : BinaryFile ( std : : wstring fileName , FileOptions options , size_t size ) <nl> } <nl> <nl> / / code to detect type of file ( network / local ) <nl> - / / std : : wstring path ; <nl> - / / auto found = fileName . find_last_of ( L " \ \ / " ) ; <nl> - / / if ( found = = npos ) <nl> + / / std : : wstring path ; <nl> + / / auto found = fileName . find_last_of ( L " \ \ / " ) ; <nl> + / / if ( found = = npos ) <nl> / / path = fileName + L " \ \ " ; <nl> - / / else <nl> + / / else <nl> / / path = fileName . substr ( 0 , found ) ; <nl> - / / auto driveType = GetDriveType ( path . c_str ( ) ) ; <nl> + / / auto driveType = GetDriveType ( path . c_str ( ) ) ; <nl> <nl> / / get the actual size of the file <nl> if ( size = = 0 ) <nl> bool Section : : ValidateHeader ( bool writing ) const <nl> valid & = ( m_sectionHeader - > dataSections < ( m_sectionHeader - > sizeHeader - offset ( SectionHeader , sectionFilePosition ) ) / sizeof ( size_t ) ) ; / / number of data sub - sections ( for nesting ) <nl> valid & = ( m_sectionHeader - > sectionType < sectionTypeMax * 2 ) ; / / what is the type of the data in this section <nl> valid & = ( m_sectionHeader - > sectionData < sectionDataMax * 2 ) ; / / type of section ( SectionData enum ) <nl> - / / m_sectionHeader - > bytesPerElement = elementSize ; / / number of bytes per element , ( 0 means variable ) <nl> + / / m_sectionHeader - > bytesPerElement = elementSize ; / / number of bytes per element , ( 0 means variable ) <nl> valid & = ( m_sectionHeader - > customStructureID < customStructureMax * 2 ) ; / / ID for custom structure <nl> - / / m_sectionHeader - > elementsPerRecord = 0 ; / / number of elements per Record <nl> + / / m_sectionHeader - > elementsPerRecord = 0 ; / / number of elements per Record <nl> valid & = ( m_sectionHeader - > flags < flagMax * 2 ) ; / / bit flags , dependent on sectionType <nl> - / / m_sectionHeader - > elementsCount = 0 ; / / number of total elements stored <nl> - / / strcpy_s ( m_sectionHeader - > nameDescription , description . c_str ( ) ) ; / / name and description of section contents in this format ( name : description ) ( string , with extra bytes zeroed out , at least one null terminator required ) <nl> + / / m_sectionHeader - > elementsCount = 0 ; / / number of total elements stored <nl> + / / strcpy_s ( m_sectionHeader - > nameDescription , description . c_str ( ) ) ; / / name and description of section contents in this format ( name : description ) ( string , with extra bytes zeroed out , at least one null terminator required ) <nl> <nl> / / the size of the section must at least accomidate the header and all it ' s elements <nl> valid & = ( m_sectionHeader - > size > = m_sectionHeader - > sizeHeader + m_sectionHeader - > elementsCount * m_sectionHeader - > bytesPerElement ) ; / / size of this section ( including header and all sub - sections ) <nl> char * Section : : GetElementBuffer ( size_t element , size_t windowSize ) <nl> m_mappedElementSize = 0 ; / / only used for element window mapping <nl> <nl> / / save off the header size so we can reestablish pointers if necessary <nl> - / / size_t headerSize = m_sectionHeader - > sizeHeader ; <nl> - / / assert ( ( char * ) m_elementBuffer - ( char * ) m_sectionHeader ) ; <nl> - / / void * elementBuffer = <nl> + / / size_t headerSize = m_sectionHeader - > sizeHeader ; <nl> + / / assert ( ( char * ) m_elementBuffer - ( char * ) m_sectionHeader ) ; <nl> + / / void * elementBuffer = <nl> EnsureMapped ( m_elementBuffer , windowSize ) ; <nl> <nl> / / check to see if the mapping changed , if so update pointers <nl> - / / if ( elementBuffer ! = m_elementBuffer ) <nl> - / / { <nl> + / / if ( elementBuffer ! = m_elementBuffer ) <nl> + / / { <nl> / / m_elementBuffer = elementBuffer ; <nl> / / m_sectionHeader - = headerSize ; <nl> - / / } <nl> + / / } <nl> <nl> return ( char * ) m_elementBuffer ; <nl> } <nl> bool Section : : SaveData ( size_t recordStart , const std : : map < std : : wstring , void * , n <nl> } <nl> <nl> char * data = section - > EnsureElements ( index , size ) ; <nl> - / / void * data = section - > GetElement ( index ) ; <nl> + / / void * data = section - > GetElement ( index ) ; <nl> memcpy_s ( data , size , dataSource , size ) ; <nl> return recordStart + numRecords < GetRecordCount ( ) ; <nl> } <nl> mmm a / Source / Readers / BinaryReader / BinaryReader . cpp <nl> ppp b / Source / Readers / BinaryReader / BinaryReader . cpp <nl> bool BinaryReader < ElemType > : : GetMinibatch ( std : : map < std : : wstring , Matrix < ElemType <nl> size_t size = rows * dataSize * actualmbsize ; <nl> size_t index = epochStartSample * section - > GetElementsPerRecord ( ) ; <nl> ElemType * data = ( ElemType * ) section - > EnsureElements ( index , size ) ; <nl> - / / ElemType * data = section - > GetElement < ElemType > ( epochStartSample * section - > GetElementsPerRecord ( ) ) ; <nl> - / / data = ( ElemType * ) section - > EnsureMapped ( data , size ) ; <nl> + / / ElemType * data = section - > GetElement < ElemType > ( epochStartSample * section - > GetElementsPerRecord ( ) ) ; <nl> + / / data = ( ElemType * ) section - > EnsureMapped ( data , size ) ; <nl> <nl> / / make sure that the data is as expected <nl> if ( ! ! ( section - > GetFlags ( ) & flagAuxilarySection ) | | section - > GetElementSize ( ) ! = sizeof ( ElemType ) ) <nl> mmm a / Source / Readers / BinaryReader / BinaryReader . h <nl> ppp b / Source / Readers / BinaryReader / BinaryReader . h <nl> struct SectionHeader <nl> WORD writtenID ; / / unique ID so files written at the same time can be identified <nl> WORD unusedWords [ 5 ] ; <nl> size_t elementsCount ; / / number of total elements stored <nl> - / / * section specific data goes below here * / / <nl> + / / * section specific data goes below here * / / <nl> WORD labelKind ; / / kind of label ( LabelKind type ) <nl> WORD labelDim ; / / number of possible states for labels ( category type ) <nl> char unused [ descriptionSize - 18 * sizeof ( WORD ) - sizeof ( size_t ) ] ; / / space for future expansion ( zero out in current versions ) <nl> mmm a / Source / Readers / DSSMReader / DSSMReader . cpp <nl> ppp b / Source / Readers / DSSMReader / DSSMReader . cpp <nl> std : : string ws2s ( const std : : wstring & wstr ) <nl> template < class ElemType > <nl> size_t DSSMReader < ElemType > : : RandomizeSweep ( size_t mbStartSample ) <nl> { <nl> - / / size_t randomRangePerEpoch = ( m_epochSize + m_randomizeRange - 1 ) / m_randomizeRange ; <nl> - / / return m_epoch * randomRangePerEpoch + epochSample / m_randomizeRange ; <nl> + / / size_t randomRangePerEpoch = ( m_epochSize + m_randomizeRange - 1 ) / m_randomizeRange ; <nl> + / / return m_epoch * randomRangePerEpoch + epochSample / m_randomizeRange ; <nl> return mbStartSample / m_randomizeRange ; <nl> } <nl> <nl> bool DSSMReader < ElemType > : : GetMinibatch ( std : : map < std : : wstring , Matrix < ElemType > * <nl> featuresD . Resize ( dssm_docInput . numRows , actualMBSize ) ; <nl> * / <nl> <nl> - / / fprintf ( stderr , " featuresQ \ n " ) ; <nl> + / / fprintf ( stderr , " featuresQ \ n " ) ; <nl> dssm_queryInput . Next_Batch ( featuresQ , m_readNextSample , actualMBSize , read_order ) ; <nl> - / / fprintf ( stderr , " \ n \ n \ nfeaturesD \ n " ) ; <nl> + / / fprintf ( stderr , " \ n \ n \ nfeaturesD \ n " ) ; <nl> dssm_docInput . Next_Batch ( featuresD , m_readNextSample , actualMBSize , read_order ) ; <nl> - / / fprintf ( stderr , " \ n \ n \ n \ n \ n " ) ; <nl> + / / fprintf ( stderr , " \ n \ n \ n \ n \ n " ) ; <nl> m_readNextSample + = actualMBSize ; <nl> / * <nl> featuresQ . Print ( " featuresQ " ) ; <nl> bool DSSMReader < ElemType > : : DataEnd ( EndDataType endDataType ) <nl> assert ( false ) ; <nl> break ; <nl> case endDataEpoch : <nl> - / / ret = ( m_mbStartSample / m_epochSize < m_epoch ) ; <nl> + / / ret = ( m_mbStartSample / m_epochSize < m_epoch ) ; <nl> ret = ( m_readNextSample > = m_totalSamples ) ; <nl> break ; <nl> case endDataSet : <nl> void DSSM_BinaryInput < ElemType > : : Init ( wstring fileName , size_t dim ) <nl> LODWORD ( 0 ) , <nl> sizeof ( int64_t ) * 2 + sizeof ( int32_t ) ) ; <nl> <nl> - / / cout < < " After mapviewoffile " < < endl ; <nl> + / / cout < < " After mapviewoffile " < < endl ; <nl> <nl> memcpy ( & numRows , header_buffer , sizeof ( int64_t ) ) ; <nl> memcpy ( & numCols , ( char * ) header_buffer + sizeof ( int64_t ) , sizeof ( int32_t ) ) ; <nl> memcpy ( & totalNNz , ( char * ) header_buffer + sizeof ( int64_t ) + sizeof ( int32_t ) , sizeof ( int64_t ) ) ; <nl> <nl> - / / cout < < " After gotvalues " < < endl ; <nl> + / / cout < < " After gotvalues " < < endl ; <nl> int64_t base_offset = sizeof ( int64_t ) * 2 + sizeof ( int32_t ) ; <nl> <nl> int64_t offsets_padding = base_offset % sysGran ; <nl> bool DSSM_BinaryInput < ElemType > : : SetupEpoch ( size_t minibatchSize ) <nl> values = ( ElemType * ) malloc ( sizeof ( ElemType ) * MAX_BUFFER * minibatchSize ) ; <nl> colIndices = ( int32_t * ) malloc ( sizeof ( int32_t ) * ( minibatchSize + 1 ) ) ; <nl> rowIndices = ( int32_t * ) malloc ( sizeof ( int32_t ) * MAX_BUFFER * minibatchSize ) ; <nl> - / / fprintf ( stderr , " values size : % d " , sizeof ( ElemType ) * MAX_BUFFER * minibatchSize ) ; <nl> - / / fprintf ( stderr , " colindi size : % d " , sizeof ( int32_t ) * MAX_BUFFER * ( 1 + minibatchSize ) ) ; <nl> - / / fprintf ( stderr , " rowindi size : % d " , sizeof ( int32_t ) * MAX_BUFFER * minibatchSize ) ; <nl> + / / fprintf ( stderr , " values size : % d " , sizeof ( ElemType ) * MAX_BUFFER * minibatchSize ) ; <nl> + / / fprintf ( stderr , " colindi size : % d " , sizeof ( int32_t ) * MAX_BUFFER * ( 1 + minibatchSize ) ) ; <nl> + / / fprintf ( stderr , " rowindi size : % d " , sizeof ( int32_t ) * MAX_BUFFER * minibatchSize ) ; <nl> } <nl> if ( minibatchSize > mbSize ) <nl> { <nl> bool DSSM_BinaryInput < ElemType > : : Next_Batch ( Matrix < ElemType > & matrices , size_t c <nl> <nl> for ( int c = 0 ; c < numToRead ; c + + , cur + + ) <nl> { <nl> - / / int64_t cur_offset = offsets [ ordering [ cur ] ] ; <nl> + / / int64_t cur_offset = offsets [ ordering [ cur ] ] ; <nl> int64_t cur_offset = offsets [ cur ] ; <nl> - / / int64_t cur_offset = offsets [ ordering [ c ] ] ; <nl> - / / int32_t nnz ; <nl> + / / int64_t cur_offset = offsets [ ordering [ c ] ] ; <nl> + / / int32_t nnz ; <nl> colIndices [ c ] = cur_index ; <nl> int32_t nnz = * ( int32_t * ) ( ( char * ) data_buffer + cur_offset ) ; <nl> - / / memcpy ( & nnz , ( char * ) data_buffer + cur_offset , sizeof ( int32_t ) ) ; <nl> + / / memcpy ( & nnz , ( char * ) data_buffer + cur_offset , sizeof ( int32_t ) ) ; <nl> memcpy ( values + cur_index , ( char * ) data_buffer + cur_offset + sizeof ( int32_t ) , sizeof ( ElemType ) * nnz ) ; <nl> memcpy ( rowIndices + cur_index , ( char * ) data_buffer + cur_offset + sizeof ( int32_t ) + sizeof ( ElemType ) * nnz , sizeof ( int32_t ) * nnz ) ; <nl> / * * <nl> bool DSSM_BinaryInput < ElemType > : : Next_Batch ( Matrix < ElemType > & matrices , size_t c <nl> for ( int i = 0 ; i < nnz ; i + + ) <nl> { <nl> fprintf ( stderr , " % d : % . f " , rowIndices [ cur_index + i ] , values [ cur_index + i ] ) ; <nl> - / / matrices . SetValue ( rowIndices [ cur_index + i ] , c , values [ cur_index + i ] ) ; <nl> + / / matrices . SetValue ( rowIndices [ cur_index + i ] , c , values [ cur_index + i ] ) ; <nl> } <nl> fprintf ( stderr , " \ n " ) ; <nl> * * / <nl> bool DSSM_BinaryInput < ElemType > : : Next_Batch ( Matrix < ElemType > & matrices , size_t c <nl> * / <nl> <nl> matrices . SetMatrixFromCSCFormat ( colIndices , rowIndices , values , cur_index , m_dim , numToRead ) ; <nl> - / / matrices . Print ( " actual values " ) ; <nl> - / / exit ( 1 ) ; <nl> + / / matrices . Print ( " actual values " ) ; <nl> + / / exit ( 1 ) ; <nl> / * <nl> matrices . SwitchToMatrixType ( MatrixType : : DENSE , MatrixFormat : : matrixFormatDense ) ; <nl> matrices . Print ( " featuresQ " ) ; <nl> mmm a / Source / Readers / DSSMReader / DSSMReader . h <nl> ppp b / Source / Readers / DSSMReader / DSSMReader . h <nl> class DSSM_BinaryInput <nl> HANDLE m_offsets ; <nl> HANDLE m_data ; <nl> <nl> - / / void * header_orig ; / / Don ' t need this since the header is at the start of the file <nl> + / / void * header_orig ; / / Don ' t need this since the header is at the start of the file <nl> void * offsets_orig ; <nl> void * data_orig ; <nl> <nl> class DSSM_BinaryInput <nl> template < class ElemType > <nl> class DSSMReader : public IDataReader < ElemType > <nl> { <nl> - / / public : <nl> + / / public : <nl> / / typedef std : : string LabelType ; <nl> / / typedef unsigned LabelIdType ; <nl> private : <nl> class DSSMReader : public IDataReader < ElemType > <nl> ConfigParameters m_readerConfig ; <nl> <nl> size_t RandomizeSweep ( size_t epochSample ) ; <nl> - / / bool Randomize ( ) { return m_randomizeRange ! = randomizeNone ; } <nl> + / / bool Randomize ( ) { return m_randomizeRange ! = randomizeNone ; } <nl> bool Randomize ( ) <nl> { <nl> return false ; <nl> mmm a / Source / Readers / HTKMLFReader / HTKMLFReader . cpp <nl> ppp b / Source / Readers / HTKMLFReader / HTKMLFReader . cpp <nl> void HTKMLFReader < ElemType > : : InitFromConfig ( const ConfigRecordType & readerConfig <nl> <nl> m_noData = false ; <nl> <nl> - wstring command ( readerConfig ( L " action " , L " " ) ) ; / / look up in the config for the master command to determine whether we ' re writing output ( inputs only ) or training / evaluating ( inputs and outputs ) <nl> + wstring command ( readerConfig ( L " action " , L " " ) ) ; / / look up in the config for the master command to determine whether we ' re writing output ( inputs only ) or training / evaluating ( inputs and outputs ) <nl> <nl> if ( readerConfig . Exists ( L " legacyMode " ) ) <nl> RuntimeError ( " legacy mode has been deprecated \ n " ) ; <nl> void HTKMLFReader < ElemType > : : PrepareForTrainingOrTesting ( const ConfigRecordType & <nl> vector < vector < wstring > > infilesmulti ; <nl> size_t numFiles ; <nl> wstring unigrampath ( L " " ) ; <nl> - / / wstring statelistpath ( L " " ) ; <nl> + / / wstring statelistpath ( L " " ) ; <nl> size_t randomize = randomizeAuto ; <nl> size_t iFeat , iLabel ; <nl> iFeat = iLabel = 0 ; <nl> void HTKMLFReader < ElemType > : : PrepareForTrainingOrTesting ( const ConfigRecordType & <nl> InvalidArgument ( " network needs at least 1 input and 1 output specified ! " ) ; <nl> } <nl> <nl> - / / load data for all real - valued inputs ( features ) <nl> + / / load data for all real - valued inputs ( features ) <nl> foreach_index ( i , featureNames ) <nl> { <nl> const ConfigRecordType & thisFeature = readerConfig ( featureNames [ i ] ) ; <nl> void HTKMLFReader < ElemType > : : PrepareForTrainingOrTesting ( const ConfigRecordType & <nl> } <nl> } <nl> <nl> - / / get lattice toc file names <nl> + / / get lattice toc file names <nl> std : : pair < std : : vector < wstring > , std : : vector < wstring > > latticetocs ; <nl> - foreach_index ( i , latticeNames ) / / only support one set of lattice now <nl> + foreach_index ( i , latticeNames ) / / only support one set of lattice now <nl> { <nl> const ConfigRecordType & thisLattice = readerConfig ( latticeNames [ i ] ) ; <nl> <nl> void HTKMLFReader < ElemType > : : PrepareForTrainingOrTesting ( const ConfigRecordType & <nl> RootPathInLatticeTocs = ( wstring ) thisLattice ( L " prefixPathInToc " , L " " ) ; <nl> } <nl> <nl> - / / get HMM related file names <nl> + / / get HMM related file names <nl> vector < wstring > cdphonetyingpaths , transPspaths ; <nl> foreach_index ( i , hmmNames ) <nl> { <nl> void HTKMLFReader < ElemType > : : PrepareForTrainingOrTesting ( const ConfigRecordType & <nl> } <nl> <nl> / / mmf files <nl> - / / only support one set now <nl> + / / only support one set now <nl> if ( cdphonetyingpaths . size ( ) > 0 & & statelistpaths . size ( ) > 0 & & transPspaths . size ( ) > 0 ) <nl> m_hset . loadfromfile ( cdphonetyingpaths [ 0 ] , statelistpaths [ 0 ] , transPspaths [ 0 ] ) ; <nl> if ( iFeat ! = scriptpaths . size ( ) | | iLabel ! = mlfpathsmulti . size ( ) ) <nl> void HTKMLFReader < ElemType > : : PrepareForTrainingOrTesting ( const ConfigRecordType & <nl> . . . / file2 . feat <nl> etc . <nl> the features will be read from <nl> - / / aaa / bbb / ccc / file1 . feat <nl> - / / aaa / bbb / ccc / file2 . feat <nl> + / / aaa / bbb / ccc / file1 . feat <nl> + / / aaa / bbb / ccc / file2 . feat <nl> etc . <nl> This works well if you store the scp file with the features but <nl> do not want different scp files everytime you move or create new features <nl> void HTKMLFReader < ElemType > : : PrepareForTrainingOrTesting ( const ConfigRecordType & <nl> } <nl> / / get labels <nl> <nl> - / / if ( readerConfig . Exists ( L " statelist " ) ) <nl> + / / if ( readerConfig . Exists ( L " statelist " ) ) <nl> / / statelistpath = readerConfig ( L " statelist " ) ; <nl> <nl> double htktimetoframe = 100000 . 0 ; / / default is 10ms <nl> - / / std : : vector < msra : : asr : : htkmlfreader < msra : : asr : : htkmlfentry , msra : : lattices : : lattice : : htkmlfwordsequence > > labelsmulti ; <nl> + / / std : : vector < msra : : asr : : htkmlfreader < msra : : asr : : htkmlfentry , msra : : lattices : : lattice : : htkmlfwordsequence > > labelsmulti ; <nl> std : : vector < std : : map < std : : wstring , std : : vector < msra : : asr : : htkmlfentry > > > labelsmulti ; <nl> - / / std : : vector < std : : wstring > pagepath ; <nl> + / / std : : vector < std : : wstring > pagepath ; <nl> foreach_index ( i , mlfpathsmulti ) <nl> { <nl> const msra : : lm : : CSymbolSet * wordmap = unigram ? & unigramsymbols : NULL ; <nl> void HTKMLFReader < ElemType > : : PrepareForWriting ( const ConfigRecordType & readerCon <nl> <nl> std : : vector < std : : wstring > featureNames ; <nl> std : : vector < std : : wstring > labelNames ; <nl> - / / lattice and hmm <nl> + / / lattice and hmm <nl> std : : vector < std : : wstring > hmmNames ; <nl> std : : vector < std : : wstring > latticeNames ; <nl> <nl> bool HTKMLFReader < ElemType > : : GetMinibatchToTrainOrTest ( std : : map < std : : wstring , Ma <nl> m_extraLabelsIDBufferMultiUtt . clear ( ) ; <nl> m_extraPhoneboundaryIDBufferMultiUtt . clear ( ) ; <nl> m_extraSeqsPerMB . clear ( ) ; <nl> - if ( m_noData & & m_numFramesToProcess [ 0 ] = = 0 ) / / no data left for the first channel of this minibatch , <nl> + if ( m_noData & & m_numFramesToProcess [ 0 ] = = 0 ) / / no data left for the first channel of this minibatch , <nl> { <nl> return false ; <nl> } <nl> bool HTKMLFReader < ElemType > : : GetMinibatchToTrainOrTest ( std : : map < std : : wstring , Ma <nl> m_processedFrame [ i ] + = ( endFr - startFr ) ; / / advance the cursor <nl> assert ( m_processedFrame [ i ] = = m_numFramesToProcess [ i ] ) ; / / we must be at the end <nl> m_switchFrame [ i ] = actualmbsize [ i ] ; <nl> - / / if ( actualmbsize [ i ] ! = 0 ) <nl> + / / if ( actualmbsize [ i ] ! = 0 ) <nl> / / m_pMBLayout - > Set ( i , actualmbsize [ i ] - 1 , MinibatchPackingFlags : : SequenceEnd ) ; / / NOTE : this ORs , while original code overwrote in matrix but ORed into vector <nl> / / at this point , we completed an utterance - - fill the rest with the next utterance <nl> <nl> bool HTKMLFReader < ElemType > : : GetMinibatchToTrainOrTest ( std : : map < std : : wstring , Ma <nl> { <nl> / / dereference matrix that corresponds to key ( input / output name ) and <nl> / / populate based on whether its a feature or a label <nl> - / / Matrix < ElemType > & data = * matrices [ iter - > first ] ; / / can be features or labels <nl> + / / Matrix < ElemType > & data = * matrices [ iter - > first ] ; / / can be features or labels <nl> <nl> if ( m_nameToTypeMap [ iter - > first ] = = InputOutputTypes : : real ) <nl> { <nl> bool HTKMLFReader < ElemType > : : GetMinibatchToWrite ( std : : map < std : : wstring , Matrix < E <nl> { <nl> m_pMBLayout - > Init ( 1 , feat . cols ( ) ) ; <nl> m_pMBLayout - > AddSequence ( NEW_SEQUENCE_ID , 0 , 0 , feat . cols ( ) ) ; / / feat . cols ( ) = = number of time steps here since we only have one parallel sequence <nl> - / / m_pMBLayout - > Set ( 0 , 0 , MinibatchPackingFlags : : SequenceStart ) ; <nl> - / / m_pMBLayout - > SetWithoutOr ( 0 , feat . cols ( ) - 1 , MinibatchPackingFlags : : SequenceEnd ) ; / / BUGBUG : using SetWithoutOr ( ) because original code did ; but that seems inconsistent <nl> + / / m_pMBLayout - > Set ( 0 , 0 , MinibatchPackingFlags : : SequenceStart ) ; <nl> + / / m_pMBLayout - > SetWithoutOr ( 0 , feat . cols ( ) - 1 , MinibatchPackingFlags : : SequenceEnd ) ; / / BUGBUG : using SetWithoutOr ( ) because original code did ; but that seems inconsistent <nl> first = false ; <nl> } <nl> <nl> bool HTKMLFReader < ElemType > : : ReNewBufferForMultiIO ( size_t i ) <nl> } <nl> } <nl> } <nl> - / / lattice <nl> + / / lattice <nl> if ( m_latticeBufferMultiUtt [ i ] ! = NULL ) <nl> { <nl> m_latticeBufferMultiUtt [ i ] . reset ( ) ; <nl> mmm a / Source / Readers / HTKMLFReader / HTKMLFReader . h <nl> ppp b / Source / Readers / HTKMLFReader / HTKMLFReader . h <nl> class HTKMLFReader : public IDataReader < ElemType > <nl> std : : vector < std : : shared_ptr < ElemType > > m_labelsBufferMultiIO ; <nl> std : : vector < size_t > m_labelsBufferAllocatedMultiIO ; <nl> <nl> - / / for lattice uids and phoneboundaries <nl> + / / for lattice uids and phoneboundaries <nl> std : : vector < shared_ptr < const msra : : dbn : : latticepair > > m_latticeBufferMultiUtt ; <nl> std : : vector < std : : vector < size_t > > m_labelsIDBufferMultiUtt ; <nl> std : : vector < std : : vector < size_t > > m_phoneboundaryIDBufferMultiUtt ; <nl> class HTKMLFReader : public IDataReader < ElemType > <nl> std : : vector < std : : vector < size_t > > m_extraLabelsIDBufferMultiUtt ; <nl> std : : vector < std : : vector < size_t > > m_extraPhoneboundaryIDBufferMultiUtt ; <nl> <nl> - / / hmm <nl> + / / hmm <nl> msra : : asr : : simplesenonehmm m_hset ; <nl> <nl> std : : map < std : : wstring , size_t > m_featureNameToIdMap ; <nl> mmm a / Source / Readers / HTKMLFReader / HTKMLFWriter . cpp <nl> ppp b / Source / Readers / HTKMLFReader / HTKMLFWriter . cpp <nl> template < class ElemType > <nl> bool HTKMLFWriter < ElemType > : : SaveData ( size_t / * recordStart * / , const std : : map < std : : wstring , void * , nocase_compare > & matrices , size_t / * numRecords * / , size_t / * datasetSize * / , size_t / * byteVariableSized * / ) <nl> { <nl> <nl> - / / std : : map < std : : wstring , void * , nocase_compare > : : iterator iter ; <nl> + / / std : : map < std : : wstring , void * , nocase_compare > : : iterator iter ; <nl> if ( outputFileIndex > = outputFiles [ 0 ] . size ( ) ) <nl> RuntimeError ( " index for output scp file out of range . . . " ) ; <nl> <nl> mmm a / Source / Readers / HTKMLFReader / basetypes . h <nl> ppp b / Source / Readers / HTKMLFReader / basetypes . h <nl> class fixed_vector <nl> # endif <nl> } <nl> / / . . . TODO : when I make this public , LinearTransform . h acts totally up but I cannot see where it comes from . <nl> - / / fixed_vector ( const fixed_vector & other ) : n ( 0 ) , p ( NULL ) { * this = other ; } <nl> + / / fixed_vector ( const fixed_vector & other ) : n ( 0 ) , p ( NULL ) { * this = other ; } <nl> public : <nl> fixed_vector ( ) <nl> : n ( 0 ) , p ( NULL ) <nl> mmm a / Source / Readers / HTKMLFReader / chunkevalsource . h <nl> ppp b / Source / Readers / HTKMLFReader / chunkevalsource . h <nl> class chunkevalsourcemulti / / : public numamodelmanager <nl> <nl> frames . reserve ( chunksize * 2 ) ; <nl> framesmulti . push_back ( frames ) ; <nl> - / / framesmulti [ i ] . reserve ( chunksize * 2 ) ; <nl> + / / framesmulti [ i ] . reserve ( chunksize * 2 ) ; <nl> <nl> thisfeat . resize ( vdims [ i ] , chunksize ) ; <nl> feat . push_back ( thisfeat ) ; <nl> <nl> outpaths . push_back ( std : : vector < std : : wstring > ( ) ) ; <nl> sampperiods . push_back ( std : : vector < unsigned int > ( ) ) ; <nl> - / / feat [ i ] . resize ( vdims [ i ] , chunksize ) ; / / initialize to size chunksize <nl> + / / feat [ i ] . resize ( vdims [ i ] , chunksize ) ; / / initialize to size chunksize <nl> } <nl> } <nl> <nl> class FileEvalSource / / : public numamodelmanager <nl> <nl> frames . reserve ( chunksize * 2 ) ; <nl> framesMulti . push_back ( frames ) ; <nl> - / / framesmulti [ i ] . reserve ( chunksize * 2 ) ; <nl> + / / framesmulti [ i ] . reserve ( chunksize * 2 ) ; <nl> <nl> thisfeat . resize ( vdims [ i ] , chunksize ) ; <nl> feat . push_back ( thisfeat ) ; <nl> <nl> sampPeriods . push_back ( std : : vector < unsigned int > ( ) ) ; <nl> - / / feat [ i ] . resize ( vdims [ i ] , chunksize ) ; / / initialize to size chunksize <nl> + / / feat [ i ] . resize ( vdims [ i ] , chunksize ) ; / / initialize to size chunksize <nl> } <nl> } <nl> <nl> class FileEvalSource / / : public numamodelmanager <nl> rightextent = rightcontext [ i ] ; <nl> } <nl> <nl> - / / msra : : dbn : : augmentneighbors ( framesMulti [ i ] , boundaryFlags , 0 , leftcontext [ i ] , rightcontext [ i ] , ) <nl> + / / msra : : dbn : : augmentneighbors ( framesMulti [ i ] , boundaryFlags , 0 , leftcontext [ i ] , rightcontext [ i ] , ) <nl> msra : : dbn : : augmentneighbors ( framesMulti [ i ] , boundaryFlags , leftextent , rightextent , 0 , framesInBlock , feat [ i ] ) ; <nl> } <nl> minibatchReady = true ; <nl> mmm a / Source / Readers / HTKMLFReader / htkfeatio . h <nl> ppp b / Source / Readers / HTKMLFReader / htkfeatio . h <nl> class htkfeatio <nl> RuntimeError ( " reading idx feature cache header : invalid magic " ) ; <nl> nsamples = swapint ( fgetint ( f ) ) ; <nl> sampperiod = 0 ; <nl> - sampkind = ( short ) 9 ; / / user type <nl> + sampkind = ( short ) 9 ; / / user type <nl> int nRows = swapint ( fgetint ( f ) ) ; <nl> int nCols = swapint ( fgetint ( f ) ) ; <nl> sampsize = ( short ) ( nRows * nCols ) ; / / features are stored as bytes ; <nl> class htkfeatreader : protected htkfeatio <nl> / / information on current file <nl> / / File handle and feature type information is stored in the underlying htkfeatio object . <nl> size_t physicalframes ; / / total number of frames in physical file <nl> - / / TODO make this nicer <nl> + / / TODO make this nicer <nl> bool isidxformat ; / / support reading of features in idxformat as well ( it ' s a hack , but different format ' s are not supported yet ) <nl> uint64_t physicaldatastart ; / / byte offset of first data byte <nl> size_t vecbytesize ; / / size of one vector in bytes <nl> class htkfeatreader : protected htkfeatio <nl> void openphysical ( const parsedpath & ppath ) <nl> { <nl> wstring physpath = ppath . physicallocation ( ) ; <nl> - / / auto_file_ptr f = fopenOrDie ( physpath , L " rbS " ) ; <nl> + / / auto_file_ptr f = fopenOrDie ( physpath , L " rbS " ) ; <nl> auto_file_ptr f ( fopenOrDie ( physpath , L " rb " ) ) ; / / removed ' S ' for now , as we mostly run local anyway , and this will speed up debugging <nl> <nl> / / read the header ( 12 bytes for htk feature files ) <nl> struct htkmlfentry <nl> RuntimeError ( " htkmlfentry : state % s not found in statelist " , toks [ 2 ] ) ; <nl> const size_t uid = iter - > second ; / / get state index <nl> setdata ( ts , te , uid ) ; <nl> - / / phone boundary <nl> + / / phone boundary <nl> if ( hmmnamehash . size ( ) > 0 ) <nl> { <nl> if ( toks . size ( ) > 4 ) <nl> class htkmlfreader : public map < wstring , vector < ENTRY > > / / [ key ] [ i ] the data <nl> if ( sentend > = 0 & & wordseqbuffer . back ( ) . wordindex = = ( size_t ) silence ) <nl> wordseqbuffer . back ( ) . wordindex = sentend ; <nl> } <nl> - / / if ( sentstart < 0 | | sentend < 0 | | silence < 0 ) <nl> + / / if ( sentstart < 0 | | sentend < 0 | | silence < 0 ) <nl> / / LogicError ( " parseentry : word map must contain ! silence , ! sent_start , and ! sent_end " ) ; <nl> / / implant <nl> auto & wordsequence = wordsequences [ key ] ; / / this creates the map entry <nl> class htkmlfreader : public map < wstring , vector < ENTRY > > / / [ key ] [ i ] the data <nl> read ( paths [ i ] , restricttokeys , wordmap , unitmap , htkTimeToFrame ) ; <nl> } <nl> <nl> - / / phone boundary <nl> + / / phone boundary <nl> template < typename WORDSYMBOLTABLE , typename UNITSYMBOLTABLE > <nl> htkmlfreader ( const vector < wstring > & paths , const set < wstring > & restricttokeys , const wstring & stateListPath , const WORDSYMBOLTABLE * wordmap , const UNITSYMBOLTABLE * unitmap , <nl> const double htkTimeToFrame , const msra : : asr : : simplesenonehmm & hset ) <nl> mmm a / Source / Readers / HTKMLFReader / latticearchive . cpp <nl> ppp b / Source / Readers / HTKMLFReader / latticearchive . cpp <nl> void lattice : : dedup ( ) <nl> L . merge ( L2 , hset ) ; <nl> / / note : we are left with dups due to true unigram merging ( HTK lattices cannot represent true unigram lattices since id is on the nodes ) <nl> } <nl> - / / L . removefinalnull ( ) ; <nl> - / / L . determinenodecontexts ( hset ) ; <nl> + / / L . removefinalnull ( ) ; <nl> + / / L . determinenodecontexts ( hset ) ; <nl> <nl> / / convert it - - TODO : once we permanently use the new format , do this in fread ( ) for V1 <nl> / / Note : Merging may have left this in unsorted format ; we need to be robust against that . <nl> void lattice : : fromhtklattice ( const wstring & path , const std : : unordered_map < std : : <nl> if ( it = = unitmap . end ( ) ) <nl> RuntimeError ( " lattice : unit in alignment that is not in model : % s " , label . c_str ( ) ) ; <nl> const size_t unitid = it - > second ; <nl> - / / const size_t unitid = unitmap . insert ( make_pair ( label , unitmap . size ( ) ) ) . first - > second ; / / may create a new entry with index = # entries <nl> + / / const size_t unitid = unitmap . insert ( make_pair ( label , unitmap . size ( ) ) ) . first - > second ; / / may create a new entry with index = # entries <nl> align . push_back ( aligninfo ( unitid , frames ) ) ; <nl> edgeframes + = frames ; <nl> } <nl> mmm a / Source / Readers / HTKMLFReader / minibatchsourcehelpers . h <nl> ppp b / Source / Readers / HTKMLFReader / minibatchsourcehelpers . h <nl> class randomordering / / note : NOT thread - safe at all <nl> } <nl> <nl> / / this returns the map directly ( read - only ) and will lazily initialize it for a given seed <nl> - const std : : vector < INDEXTYPE > & operator ( ) ( size_t seed ) / / throw ( ) <nl> + const std : : vector < INDEXTYPE > & operator ( ) ( size_t seed ) / / throw ( ) <nl> { <nl> / / if wrong seed then lazily recache the sequence <nl> if ( seed ! = currentseed ) <nl> mmm a / Source / Readers / HTKMLFReader / msra_mgram . h <nl> ppp b / Source / Readers / HTKMLFReader / msra_mgram . h <nl> class int24_vector : std : : vector < unsigned char > <nl> class mgram_map <nl> { <nl> typedef unsigned int index_t ; / / ( - > size_t when we really need it ) <nl> - / / typedef size_t index_t ; / / ( tested once , seems to work ) <nl> + / / typedef size_t index_t ; / / ( tested once , seems to work ) <nl> static const index_t nindex ; / / invalid index <nl> / / entry [ m ] [ i ] is first index of children in level m + 1 , entry [ m ] [ i + 1 ] the end . <nl> int M ; / / order , e . g . M = 3 for trigram <nl> class mgram_map <nl> { <nl> int w = k [ n - 1 ] ; / / may be - 1 for unknown word <nl> int id = map ( w ) ; / / may still be - 1 <nl> - / / const char * sym = idToSymbol ( id ) ; sym ; / / ( debugging ) <nl> + / / const char * sym = idToSymbol ( id ) ; sym ; / / ( debugging ) <nl> i = find_child ( n - 1 , i , id ) ; <nl> if ( i = = nindex ) / / unknown history : fall back <nl> return foundcoord ( - 1 ) ; / / indicates failure <nl> class CMGramLMEstimator : public CMGramLM <nl> / / Establish w - > id mapping - - mapping is identical ( w = id ) during estimation . <nl> std : : vector < int > w2id ( mmap . maxid ( ) + 1 ) ; <nl> foreach_index ( i , w2id ) w2id [ i ] = i ; <nl> - / / std : : vector < int > w2id ( mmap . identical_map ( ) ) ; <nl> + / / std : : vector < int > w2id ( mmap . identical_map ( ) ) ; <nl> <nl> / / close down creation of new tokens , so we can random - access <nl> mmap . created ( w2id ) ; <nl> class CMGramLMEstimator : public CMGramLM <nl> dropWord . push_back ( true ) ; / / filtering but no < UNK > : <nl> assert ( ! filterVocabulary | | unkId ! = - 1 | | dropWord [ dropId ] ) ; <nl> <nl> - / / std : : vector < unsigned int > minObs ( 2 , 0 ) ; <nl> - / / std : : vector < unsigned int > iMinObs ( 3 , 0 ) ; <nl> - / / iMinObs [ 1 ] = 3 ; / / remove singleton 2 + - grams <nl> - / / iMinObs [ 2 ] = 3 ; / / remove singleton 3 + - grams <nl> + / / std : : vector < unsigned int > minObs ( 2 , 0 ) ; <nl> + / / std : : vector < unsigned int > iMinObs ( 3 , 0 ) ; <nl> + / / iMinObs [ 1 ] = 3 ; / / remove singleton 2 + - grams <nl> + / / iMinObs [ 2 ] = 3 ; / / remove singleton 3 + - grams <nl> <nl> - / / / / set prune value to 0 3 3 <nl> - / / setMinObs ( iMinObs ) ; <nl> + / / / / set prune value to 0 3 3 <nl> + / / setMinObs ( iMinObs ) ; <nl> <nl> / / TODO : Re - enable when MESSAGE definition is provided ( printf ? ) <nl> / / for ( size_t i = 0 ; i < minObs . size ( ) ; i + + ) <nl> class CMGramLMEstimator : public CMGramLM <nl> / / Establish w - > id mapping - - mapping is identical ( w = id ) during estimation . <nl> std : : vector < int > w2id ( map . maxid ( ) + 1 ) ; <nl> foreach_index ( i , w2id ) w2id [ i ] = i ; <nl> - / / std : : vector < int > w2id ( map . identical_map ( ) ) ; <nl> + / / std : : vector < int > w2id ( map . identical_map ( ) ) ; <nl> <nl> / / close down creation of new tokens , so we can random - access <nl> map . created ( w2id ) ; <nl> class CMGramLMEstimator : public CMGramLM <nl> { <nl> if ( n1 [ m ] = = 0 ) RuntimeError ( msra : : strfun : : strprintf ( " estimate : error estimating discounting values : n1 [ % d ] = = 0 " , m ) ) ; <nl> if ( n2 [ m ] = = 0 ) RuntimeError ( msra : : strfun : : strprintf ( " estimate : error estimating discounting values : n2 [ % d ] = = 0 " , m ) ) ; <nl> - / / if ( n3 [ m ] = = 0 ) RuntimeError ( " estimate : error estimating discounting values : n3 [ % d ] = = 0 " , m ) ; <nl> + / / if ( n3 [ m ] = = 0 ) RuntimeError ( " estimate : error estimating discounting values : n3 [ % d ] = = 0 " , m ) ; <nl> double Y = n1 [ m ] / ( n1 [ m ] + 2 . 0 * n2 [ m ] ) ; <nl> if ( n3 [ m ] = = 0 | | n4 [ m ] = = 0 ) <nl> { <nl> class CMGramLMEstimator : public CMGramLM <nl> mgram_map : : coord j = histCoord [ m - 1 ] ; / / parent <nl> if ( counts [ j ] = = 0 ) <nl> RuntimeError ( " estimate : invalid pruning : a parent m - gram got pruned away " ) ; <nl> - / / RuntimeError ( " estimate : invalid pruning : a parent m - gram got pruned away " ) ; <nl> + / / RuntimeError ( " estimate : invalid pruning : a parent m - gram got pruned away " ) ; <nl> numMGrams [ m ] + + ; <nl> } <nl> } <nl> class CMGramLMEstimator : public CMGramLM <nl> / / get history ' s count <nl> const mgram_map : : coord j = histCoord [ m - 1 ] ; / / index of parent entry <nl> double histCount = counts [ j ] ; / / parent count - - before pruning <nl> - / / double histCount = succCount [ j ] ; / / parent count - - actuals after pruning <nl> + / / double histCount = succCount [ j ] ; / / parent count - - actuals after pruning <nl> <nl> / / estimate probability for this M - gram <nl> unsigned int count = counts [ iter ] ; <nl> skippruned : ; / / m - gram was pruned <nl> / / the only items used below are P and Pmap . <nl> w2id . resize ( Pmap . maxid ( ) + 1 ) ; <nl> foreach_index ( i , w2id ) w2id [ i ] = i ; <nl> - / / std : : vector < int > w2id ( Pmap . identical_map ( ) ) ; <nl> + / / std : : vector < int > w2id ( Pmap . identical_map ( ) ) ; <nl> Pmap . created ( w2id ) ; / / finalize and establish mapping for read access <nl> map . swap ( Pmap ) ; / / install the new map in our m - gram <nl> Pmap . clear ( ) ; / / no longer using the old one <nl> mmm a / Source / Readers / HTKMLFReader / rollingwindowsource . h <nl> ppp b / Source / Readers / HTKMLFReader / rollingwindowsource . h <nl> class minibatchframesource : public minibatchsource <nl> / / for single input / output set size to be 1 and run old getbatch <nl> feat . resize ( 1 ) ; <nl> uids . resize ( 1 ) ; <nl> - / / transcripts . resize ( 1 ) ; <nl> - / / latticepairs . resize ( 1 ) ; <nl> + / / transcripts . resize ( 1 ) ; <nl> + / / latticepairs . resize ( 1 ) ; <nl> sentendmark . resize ( 1 ) ; <nl> phoneboundaries . resize ( 1 ) ; <nl> return getbatch ( globalts , framesrequested , feat [ 0 ] , uids [ 0 ] , transcripts , latticepairs ) ; <nl> class minibatchframesourcemulti : public minibatchsource <nl> size_t featdim ; <nl> size_t maxvdim ; <nl> / / cache <nl> - / / std : : vector < biggrowablevectorarray > frames ; <nl> + / / std : : vector < biggrowablevectorarray > frames ; <nl> std : : vector < unique_ptr < biggrowablevectorarray > > pframes ; / / [ t ] [ i ] all features concatenated <nl> std : : vector < char > boundaryflags ; / / [ t ] - 1 for first and + 1 for last frame , 0 else ( for augmentneighbors ( ) ) <nl> std : : vector < std : : vector < CLASSIDTYPE > > classids ; / / [ t ] the state that the frame belongs to <nl> mmm a / Source / Readers / HTKMLFReader / utterancesourcemulti . h <nl> ppp b / Source / Readers / HTKMLFReader / utterancesourcemulti . h <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> std : : vector < std : : vector < size_t > > counts ; / / [ s ] occurence count for all states ( used for priors ) <nl> int verbosity ; <nl> / / lattice reader <nl> - / / const std : : vector < unique_ptr < latticesource > > & lattices ; <nl> + / / const std : : vector < unique_ptr < latticesource > > & lattices ; <nl> const latticesource & lattices ; <nl> <nl> - / / std : : vector < latticesource > lattices ; <nl> + / / std : : vector < latticesource > lattices ; <nl> / / word - level transcripts ( for MMI mode when adding best path to lattices ) <nl> const map < wstring , msra : : lattices : : lattice : : htkmlfwordsequence > & allwordtranscripts ; / / ( used for getting word - level transcripts ) <nl> - / / std : : vector < map < wstring , msra : : lattices : : lattice : : htkmlfwordsequence > > allwordtranscripts ; <nl> + / / std : : vector < map < wstring , msra : : lattices : : lattice : : htkmlfwordsequence > > allwordtranscripts ; <nl> / / data store ( incl . paging in / out of features and lattices ) <nl> struct utterancedesc / / data descriptor for one utterance <nl> { <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> lattices . resize ( utteranceset . size ( ) ) ; <nl> foreach_index ( i , utteranceset ) <nl> { <nl> - / / fprintf ( stderr , " . " ) ; <nl> + / / fprintf ( stderr , " . " ) ; <nl> / / read features for this file <nl> auto uttframes = getutteranceframes ( i ) ; / / matrix stripe for this utterance ( currently unfilled ) <nl> reader . read ( utteranceset [ i ] . parsedpath , ( const string & ) featkind , sampperiod , uttframes ) ; / / note : file info here used for checkuing only <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> if ( ! latticesource . empty ( ) ) <nl> latticesource . getlattices ( utteranceset [ i ] . key ( ) , lattices [ i ] , uttframes . cols ( ) ) ; <nl> } <nl> - / / fprintf ( stderr , " \ n " ) ; <nl> + / / fprintf ( stderr , " \ n " ) ; <nl> if ( verbosity ) <nl> fprintf ( stderr , " requiredata : % d utterances read \ n " , ( int ) utteranceset . size ( ) ) ; <nl> } <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> size_t numutts = 0 ; <nl> <nl> std : : vector < bool > uttisvalid ; / / boolean flag to check that utterance is valid . valid means number of <nl> - / / frames is consistent across all feature and label streams <nl> + / / frames is consistent across all feature and label streams <nl> std : : vector < size_t > uttduration ; / / track utterance durations to determine utterance validity <nl> <nl> std : : vector < size_t > classidsbegin ; <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> { <nl> classids . push_back ( unique_ptr < biggrowablevector < CLASSIDTYPE > > ( new biggrowablevector < CLASSIDTYPE > ( ) ) ) ; <nl> phoneboundaries . push_back ( unique_ptr < biggrowablevector < HMMIDTYPE > > ( new biggrowablevector < HMMIDTYPE > ( ) ) ) ; <nl> - / / std : : pair < std : : vector < wstring > , std : : vector < wstring > > latticetocs ; <nl> - / / std : : unordered_map < std : : string , size_t > modelsymmap ; <nl> - / / lattices . push_back ( shared_ptr < latticesource > ( new latticesource ( latticetocs , modelsymmap ) ) ) ; <nl> + / / std : : pair < std : : vector < wstring > , std : : vector < wstring > > latticetocs ; <nl> + / / std : : unordered_map < std : : string , size_t > modelsymmap ; <nl> + / / lattices . push_back ( shared_ptr < latticesource > ( new latticesource ( latticetocs , modelsymmap ) ) ) ; <nl> } <nl> <nl> / / first check consistency across feature streams <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> <nl> foreach_index ( i , infiles [ m ] ) <nl> { <nl> - utterancedesc utterance ( msra : : asr : : htkfeatreader : : parsedpath ( infiles [ m ] [ i ] ) , 0 ) ; / / mseltzer - is this foolproof for multiio ? is classids always non - empty ? <nl> + utterancedesc utterance ( msra : : asr : : htkfeatreader : : parsedpath ( infiles [ m ] [ i ] ) , 0 ) ; / / mseltzer - is this foolproof for multiio ? is classids always non - empty ? <nl> const size_t uttframes = utterance . numframes ( ) ; / / will throw if frame bounds not given - - required to be given in this mode <nl> / / we need at least 2 frames for boundary markers to work <nl> if ( uttframes < 2 ) <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> { <nl> std : : vector < utterancedesc > utteranceset ; / / read all utterances to here first ; at the end , distribute to chunks <nl> utteranceset . reserve ( infiles [ m ] . size ( ) ) ; <nl> - / / if ( m = = 0 ) <nl> + / / if ( m = = 0 ) <nl> / / numutts = infiles [ m ] . size ( ) ; <nl> - / / else <nl> + / / else <nl> / / if ( infiles [ m ] . size ( ) ! = numutts ) <nl> / / RuntimeError ( " minibatchutterancesourcemulti : all feature files must have same number of utterances \ n " ) ; <nl> if ( m = = 0 ) <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> <nl> if ( uttisvalid [ i ] ) <nl> { <nl> - utterancedesc utterance ( msra : : asr : : htkfeatreader : : parsedpath ( infiles [ m ] [ i ] ) , labels . empty ( ) ? 0 : classidsbegin [ i ] ) ; / / mseltzer - is this foolproof for multiio ? is classids always non - empty ? <nl> + utterancedesc utterance ( msra : : asr : : htkfeatreader : : parsedpath ( infiles [ m ] [ i ] ) , labels . empty ( ) ? 0 : classidsbegin [ i ] ) ; / / mseltzer - is this foolproof for multiio ? is classids always non - empty ? <nl> const size_t uttframes = utterance . numframes ( ) ; / / will throw if frame bounds not given - - required to be given in this mode <nl> assert ( uttframes = = uttduration [ i ] ) ; / / ensure nothing funky happened <nl> / / already performed these checks above <nl> / / we need at least 2 frames for boundary markers to work <nl> - / / if ( uttframes < 2 ) <nl> + / / if ( uttframes < 2 ) <nl> / / RuntimeError ( " minibatchutterancesource : utterances < 2 frames not supported " ) ; <nl> - / / if ( uttframes > frameref : : maxframesperutterance ) <nl> - / / { <nl> + / / if ( uttframes > frameref : : maxframesperutterance ) <nl> + / / { <nl> / / fprintf ( stderr , " minibatchutterancesource : skipping % d - th file ( % d frames ) because it exceeds max . frames ( % d ) for frameref bit field : % ls " , i , uttframes , frameref : : maxframesperutterance , key . c_str ( ) ) ; <nl> / / continue ; <nl> - / / } <nl> + / / } <nl> <nl> / / check whether we have the ref transcript <nl> - / / auto labelsiter = labels [ 0 ] . end ( ) ; <nl> + / / auto labelsiter = labels [ 0 ] . end ( ) ; <nl> bool lacksmlf = true ; <nl> if ( ! labels . empty ( ) ) / / empty means unsupervised mode ( don ' t load any ) <nl> { <nl> key = utterance . key ( ) ; <nl> / / check if labels are available ( if not , it normally means that no path was found in realignment ) <nl> auto labelsiter = labels [ 0 ] . find ( key ) ; <nl> - / / const bool lacksmlf = ( labelsiter = = labels [ 0 ] . end ( ) ) ; <nl> + / / const bool lacksmlf = ( labelsiter = = labels [ 0 ] . end ( ) ) ; <nl> lacksmlf = ( labelsiter = = labels [ 0 ] . end ( ) ) ; <nl> if ( lacksmlf ) <nl> if ( nomlf + + < 5 ) <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> if ( m = = 0 ) <nl> { <nl> if ( ! labels . empty ( ) & & ! lacksmlf ) <nl> - / / if ( ! labels . empty ( ) & & labelsiter ! = labels [ 0 ] . end ( ) ) <nl> + / / if ( ! labels . empty ( ) & & labelsiter ! = labels [ 0 ] . end ( ) ) <nl> { <nl> / / first verify that all the label files have the proper duration <nl> foreach_index ( j , labels ) <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> fprintf ( stderr , " [ duration mismatch ( % d in label vs . % d in feat file ) , skipping % ls ] " , ( int ) labframes , ( int ) uttframes , key . c_str ( ) ) ; <nl> nomlf + + ; <nl> uttisvalid [ i ] = false ; <nl> - / / continue ; / / skip this utterance at all <nl> + / / continue ; / / skip this utterance at all <nl> break ; <nl> } <nl> } <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> biggrowablevector < CLASSIDTYPE > & cid = * classids [ j ] ; <nl> foreach_index ( i , utteranceset ) <nl> { <nl> - / / if ( ( * classids [ j ] ) [ utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ] ! = ( CLASSIDTYPE ) - 1 ) <nl> - / / printf ( " index = % d \ n " , utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ) ; <nl> - / / printf ( " cid [ index ] = % d \ n " , cid [ utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ] ) ; <nl> - / / printf ( " CLASSIDTYPE ( - 1 ) = % d \ n " , ( CLASSIDTYPE ) - 1 ) ; <nl> + / / if ( ( * classids [ j ] ) [ utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ] ! = ( CLASSIDTYPE ) - 1 ) <nl> + / / printf ( " index = % d \ n " , utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ) ; <nl> + / / printf ( " cid [ index ] = % d \ n " , cid [ utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ] ) ; <nl> + / / printf ( " CLASSIDTYPE ( - 1 ) = % d \ n " , ( CLASSIDTYPE ) - 1 ) ; <nl> if ( cid [ utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ] ! = ( CLASSIDTYPE ) - 1 ) <nl> LogicError ( " minibatchutterancesource : classids [ ] out of sync " ) ; <nl> } <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> } <nl> } <nl> } <nl> - # endif / / 0 <nl> + # endif / / 0 <nl> static void checkoverflow ( size_t fieldval , size_t targetval , const char * fieldname ) <nl> { <nl> if ( fieldval ! = targetval ) <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> <nl> size_t chunkforframepos ( const size_t t ) const / / find chunk for a given frame position <nl> { <nl> - / / inspect chunk of first feature stream only <nl> + / / inspect chunk of first feature stream only <nl> auto iter = std : : lower_bound ( randomizedchunks [ 0 ] . begin ( ) , randomizedchunks [ 0 ] . end ( ) , t , [ & ] ( const chunk & chunk , size_t t ) <nl> { <nl> return chunk . globalte ( ) < = t ; <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> rightextent = rightcontext [ i ] ; <nl> } <nl> augmentneighbors ( uttframevectors , noboundaryflags , t , leftextent , rightextent , feat [ i ] , t + tspos ) ; <nl> - / / augmentneighbors ( uttframevectors , noboundaryflags , t , feat [ i ] , t + tspos ) ; <nl> + / / augmentneighbors ( uttframevectors , noboundaryflags , t , feat [ i ] , t + tspos ) ; <nl> } <nl> <nl> / / copy the frames and class labels <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> RuntimeError ( " minibatchframesourcemulti : getbatch ( ) being called for single input feature and single output feature , should use minibatchutterancesource instead \ n " ) ; <nl> <nl> / / for single input / output set size to be 1 and run old getbatch <nl> - / / feat . resize ( 1 ) ; <nl> - / / uids . resize ( 1 ) ; <nl> - / / return getbatch ( globalts , framesrequested , feat [ 0 ] , uids [ 0 ] , transcripts , latticepairs ) ; <nl> + / / feat . resize ( 1 ) ; <nl> + / / uids . resize ( 1 ) ; <nl> + / / return getbatch ( globalts , framesrequested , feat [ 0 ] , uids [ 0 ] , transcripts , latticepairs ) ; <nl> } <nl> <nl> size_t totalframes ( ) const <nl> mmm a / Source / Readers / ImageReader / ImageReader . cpp <nl> ppp b / Source / Readers / ImageReader / ImageReader . cpp <nl> class ITransform <nl> { <nl> public : <nl> virtual void Init ( const ConfigParameters & config ) = 0 ; <nl> - / / virtual void Init ( const ScriptableObjects : : IConfigRecord & config ) = 0 ; <nl> + / / virtual void Init ( const ScriptableObjects : : IConfigRecord & config ) = 0 ; <nl> virtual void Apply ( cv : : Mat & mat ) = 0 ; <nl> <nl> ITransform ( ) { } ; <nl> class CropTransform : public ITransform <nl> { <nl> InitFromConfig ( config ) ; <nl> } <nl> - / / virtual void Init ( const ScriptableObjects : : IConfigRecord & config ) override { InitFromConfig ( config ) ; } <nl> + / / virtual void Init ( const ScriptableObjects : : IConfigRecord & config ) override { InitFromConfig ( config ) ; } <nl> <nl> void Apply ( cv : : Mat & mat ) <nl> { <nl> class ScaleTransform : public ITransform <nl> { <nl> InitFromConfig ( config ) ; <nl> } <nl> - / / virtual void Init ( const ScriptableObjects : : IConfigRecord & config ) override { InitFromConfig ( config ) ; } <nl> + / / virtual void Init ( const ScriptableObjects : : IConfigRecord & config ) override { InitFromConfig ( config ) ; } <nl> <nl> void Apply ( cv : : Mat & mat ) <nl> { <nl> class MeanTransform : public ITransform <nl> { <nl> InitFromConfig ( config ) ; <nl> } <nl> - / / virtual void Init ( const ScriptableObjects : : IConfigRecord & config ) override { InitFromConfig ( config ) ; } <nl> + / / virtual void Init ( const ScriptableObjects : : IConfigRecord & config ) override { InitFromConfig ( config ) ; } <nl> <nl> void Apply ( cv : : Mat & mat ) <nl> { <nl> mmm a / Source / Readers / Kaldi2Reader / HTKMLFReader . cpp <nl> ppp b / Source / Readers / Kaldi2Reader / HTKMLFReader . cpp <nl> void HTKMLFReader < ElemType > : : PrepareForSequenceTraining ( const ConfigRecordType & <nl> / / to training criterion node through " readerDeriv " and feed objective <nl> / / through " readerObj " . <nl> bool hasDrive = false , hasObj = false ; <nl> - / / for ( auto iter = readerConfig . begin ( ) ; iter ! = readerConfig . end ( ) ; + + iter ) <nl> + / / for ( auto iter = readerConfig . begin ( ) ; iter ! = readerConfig . end ( ) ; + + iter ) <nl> for ( const auto & id : readerConfig . GetMemberIds ( ) ) <nl> { <nl> const ConfigRecordType & temp = readerConfig ( id ) ; <nl> void HTKMLFReader < ElemType > : : PrepareForTrainingOrTesting ( const ConfigRecordType & <nl> # endif <nl> # ifdef __unix__ <nl> char * tempFile ; <nl> - / / GetTempFileName ( pageFilePath . c_str ( ) , L " CNTK " , 0 , tempFile ) ; <nl> + / / GetTempFileName ( pageFilePath . c_str ( ) , L " CNTK " , 0 , tempFile ) ; <nl> tempFile = ( char * ) pageFilePath . c_str ( ) ; <nl> int fid = mkstemp ( tempFile ) ; <nl> unlink ( tempFile ) ; <nl> void HTKMLFReader < ElemType > : : PrepareForTrainingOrTesting ( const ConfigRecordType & <nl> const bool mayhavenoframe = false ; <nl> int addEnergy = 0 ; <nl> <nl> - / / m_frameSourceMultiIO = new msra : : dbn : : minibatchframesourcemulti ( infilesmulti , labelsmulti , m_featDims , m_labelDims , randomize , pagepath , mayhavenoframe , addEnergy ) ; <nl> - / / m_frameSourceMultiIO - > setverbosity ( verbosity ) ; <nl> + / / m_frameSourceMultiIO = new msra : : dbn : : minibatchframesourcemulti ( infilesmulti , labelsmulti , m_featDims , m_labelDims , randomize , pagepath , mayhavenoframe , addEnergy ) ; <nl> + / / m_frameSourceMultiIO - > setverbosity ( verbosity ) ; <nl> int verbosity = readerConfig ( L " verbosity " , 2 ) ; <nl> m_frameSource = new msra : : dbn : : minibatchframesourcemulti ( scriptpaths , infilesmulti , labelsmulti , m_featDims , m_labelDims , numContextLeft , numContextRight , randomize , pagePaths , mayhavenoframe , addEnergy ) ; <nl> m_frameSource - > setverbosity ( verbosity ) ; <nl> void HTKMLFReader < ElemType > : : StartMinibatchLoopToWrite ( size_t mbSize , size_t / * e <nl> { <nl> m_fileEvalSource - > Reset ( ) ; <nl> m_fileEvalSource - > SetMinibatchSize ( mbSize ) ; <nl> - / / m_chunkEvalSourceMultiIO - > reset ( ) ; <nl> + / / m_chunkEvalSourceMultiIO - > reset ( ) ; <nl> m_inputFileIndex = 0 ; <nl> <nl> foreach_index ( i , m_featuresBufferMultiIO ) <nl> bool HTKMLFReader < ElemType > : : GetOneMinibatchToTrainOrTestDataBuffer ( <nl> m_pMBLayout - > AddSequence ( NEW_SEQUENCE_ID , i , - ( ptrdiff_t ) startFrame , m_toProcess [ i ] - startFrame ) ; <nl> } <nl> } <nl> - / / m_pMBLayout - > Set ( i , 0 , MinibatchPackingFlags : : SequenceStart ) ; <nl> + / / m_pMBLayout - > Set ( i , 0 , MinibatchPackingFlags : : SequenceStart ) ; <nl> <nl> if ( ( startFrame + m_currentMBSize ) < m_toProcess [ i ] ) <nl> { <nl> bool HTKMLFReader < ElemType > : : GetOneMinibatchToTrainOrTestDataBuffer ( <nl> m_pMBLayout - > AddGap ( i , 0 , m_currentMBSize ) ; <nl> for ( size_t k = 0 ; k < m_currentMBSize ; k + + ) <nl> { <nl> - / / m_pMBLayout - > Set ( i , k , MinibatchPackingFlags : : NoInput ) ; <nl> + / / m_pMBLayout - > Set ( i , k , MinibatchPackingFlags : : NoInput ) ; <nl> <nl> / / Populates < NO_INPUT > with real features , the <nl> / / following implementation is not efficient . . . <nl> bool HTKMLFReader < ElemType > : : GetOneMinibatchToTrainOrTestDataBuffer ( <nl> / / Sets the utterance boundary . <nl> assert ( currentMBFilled + m_toProcess [ i ] < = m_pMBLayout - > GetNumTimeSteps ( ) ) ; <nl> m_pMBLayout - > AddSequence ( NEW_SEQUENCE_ID , i , currentMBFilled , currentMBFilled + m_toProcess [ i ] ) ; <nl> - / / m_pMBLayout - > Set ( i , currentMBFilled , MinibatchPackingFlags : : SequenceStart ) ; <nl> - / / m_pMBLayout - > Set ( i , currentMBFilled + m_toProcess [ i ] - 1 , MinibatchPackingFlags : : SequenceEnd ) ; <nl> + / / m_pMBLayout - > Set ( i , currentMBFilled , MinibatchPackingFlags : : SequenceStart ) ; <nl> + / / m_pMBLayout - > Set ( i , currentMBFilled + m_toProcess [ i ] - 1 , MinibatchPackingFlags : : SequenceEnd ) ; <nl> populateSucc = PopulateUtteranceInMinibatch ( matrices , i , 0 , m_toProcess [ i ] , m_currentMBSize , currentMBFilled ) ; <nl> if ( m_doMinibatchBuffering & & populateSucc ) <nl> { <nl> bool HTKMLFReader < ElemType > : : GetOneMinibatchToTrainOrTestDataBuffer ( <nl> if ( currentMBFilled < m_currentMBSize ) <nl> { <nl> m_pMBLayout - > AddSequence ( NEW_SEQUENCE_ID , i , currentMBFilled , currentMBFilled + m_toProcess [ i ] ) ; <nl> - / / m_pMBLayout - > Set ( i , currentMBFilled , MinibatchPackingFlags : : SequenceStart ) ; <nl> + / / m_pMBLayout - > Set ( i , currentMBFilled , MinibatchPackingFlags : : SequenceStart ) ; <nl> } <nl> } <nl> else <nl> bool HTKMLFReader < ElemType > : : GetOneMinibatchToTrainOrTestDataBuffer ( <nl> m_pMBLayout - > AddGap ( i , currentMBFilled , m_currentMBSize ) ; <nl> for ( size_t k = currentMBFilled ; k < m_currentMBSize ; k + + ) <nl> { <nl> - / / m_pMBLayout - > Set ( i , k , MinibatchPackingFlags : : NoInput ) ; <nl> + / / m_pMBLayout - > Set ( i , k , MinibatchPackingFlags : : NoInput ) ; <nl> <nl> / / Populates < NO_INPUT > with real features , the <nl> / / following implementation is not efficient . . . <nl> void HTKMLFReader < ElemType > : : CopyMinibatchToBuffer ( ) <nl> ( startIndex + currentMBSize < = originalMBSize ) ? currentMBSize : ( originalMBSize - startIndex ) ; <nl> <nl> / / Sets MBLayout . <nl> - / / currentMinibatch . pMBLayout - > CopyFromRange ( m_pMBLayout , startIndex , numFrames ) ; <nl> + / / currentMinibatch . pMBLayout - > CopyFromRange ( m_pMBLayout , startIndex , numFrames ) ; <nl> currentMinibatch . pMBLayout - > Init ( m_pMBLayout - > GetNumParallelSequences ( ) , numFrames ) ; <nl> const auto & sequences = m_pMBLayout - > GetAllSequences ( ) ; <nl> for ( const auto & seq : sequences ) <nl> bool HTKMLFReader < ElemType > : : GetMinibatchToWrite ( std : : map < std : : wstring , Matrix < E <nl> { <nl> m_pMBLayout - > Init ( 1 , feat . cols ( ) ) ; <nl> m_pMBLayout - > AddSequence ( NEW_SEQUENCE_ID , 0 , 0 , feat . cols ( ) ) ; <nl> - / / m_pMBLayout - > SetWithoutOr ( 0 , feat . cols ( ) - 1 , MinibatchPackingFlags : : SequenceEnd ) ; <nl> + / / m_pMBLayout - > SetWithoutOr ( 0 , feat . cols ( ) - 1 , MinibatchPackingFlags : : SequenceEnd ) ; <nl> first = false ; <nl> } <nl> <nl> bool HTKMLFReader < ElemType > : : GetMinibatchToWrite ( std : : map < std : : wstring , Matrix < E <nl> m_featuresBufferMultiIO [ id ] = new ElemType [ feat . rows ( ) * feat . cols ( ) ] ; <nl> m_featuresBufferAllocatedMultiIO [ id ] = feat . rows ( ) * feat . cols ( ) ; <nl> } <nl> - else if ( m_featuresBufferAllocatedMultiIO [ id ] < feat . rows ( ) * feat . cols ( ) ) / / buffer size changed . can be partial minibatch <nl> + else if ( m_featuresBufferAllocatedMultiIO [ id ] < feat . rows ( ) * feat . cols ( ) ) / / buffer size changed . can be partial minibatch <nl> { <nl> delete [ ] m_featuresBufferMultiIO [ id ] ; <nl> m_featuresBufferMultiIO [ id ] = new ElemType [ feat . rows ( ) * feat . cols ( ) ] ; <nl> m_featuresBufferAllocatedMultiIO [ id ] = feat . rows ( ) * feat . cols ( ) ; <nl> } <nl> / / shouldn ' t need this since we fill up the entire buffer below <nl> - / / memset ( m_featuresBufferMultiIO [ id ] , 0 , sizeof ( ElemType ) * feat . rows ( ) * feat . cols ( ) ) ; <nl> + / / memset ( m_featuresBufferMultiIO [ id ] , 0 , sizeof ( ElemType ) * feat . rows ( ) * feat . cols ( ) ) ; <nl> <nl> if ( sizeof ( ElemType ) = = sizeof ( float ) ) <nl> { <nl> bool HTKMLFReader < ElemType > : : ReNewBufferForMultiIO ( size_t i ) <nl> m_featuresBufferMultiUtt [ i ] = new ElemType [ totalFeatNum ] ; <nl> m_featuresBufferAllocatedMultiUtt [ i ] = totalFeatNum ; <nl> } <nl> - else if ( m_featuresBufferAllocatedMultiUtt [ i ] < totalFeatNum ) / / buffer size changed . can be partial minibatch <nl> + else if ( m_featuresBufferAllocatedMultiUtt [ i ] < totalFeatNum ) / / buffer size changed . can be partial minibatch <nl> { <nl> delete [ ] m_featuresBufferMultiUtt [ i ] ; <nl> m_featuresBufferMultiUtt [ i ] = new ElemType [ totalFeatNum ] ; <nl> bool HTKMLFReader < ElemType > : : ReNewBufferForMultiIO ( size_t i ) <nl> for ( int k = 0 ; k < actualmbsizeOri ; k + + ) <nl> { <nl> assert ( uids [ k ] < dim ) ; <nl> - / / labels ( uids [ i ] , i ) = ( ElemType ) 1 ; <nl> + / / labels ( uids [ i ] , i ) = ( ElemType ) 1 ; <nl> m_labelsBufferMultiUtt [ i ] [ k * dim + uids [ k ] + m_labelsStartIndexMultiUtt [ id + i * numOfLabel ] ] = ( ElemType ) 1 ; <nl> } <nl> } <nl> mmm a / Source / Readers / Kaldi2Reader / HTKMLFReader . h <nl> ppp b / Source / Readers / Kaldi2Reader / HTKMLFReader . h <nl> class HTKMLFReader : public IDataReader < ElemType > <nl> msra : : dbn : : minibatchiterator * m_mbiter ; <nl> msra : : dbn : : minibatchsource * m_frameSource ; <nl> vector < msra : : asr : : FeatureSection * > m_trainingOrTestingFeatureSections ; <nl> - / / msra : : dbn : : minibatchreadaheadsource * m_readAheadSource ; <nl> + / / msra : : dbn : : minibatchreadaheadsource * m_readAheadSource ; <nl> msra : : dbn : : FileEvalSource * m_fileEvalSource ; <nl> vector < msra : : asr : : FeatureSection * > m_writingFeatureSections ; <nl> msra : : dbn : : latticesource * m_lattices ; <nl> mmm a / Source / Readers / Kaldi2Reader / HTKMLFWriter . cpp <nl> ppp b / Source / Readers / Kaldi2Reader / HTKMLFWriter . cpp <nl> void HTKMLFWriter < ElemType > : : InitFromConfig ( const ConfigRecordType & writerConfig <nl> wstringstream ss ( line ) ; <nl> std : : wstring first_col ; <nl> ss > > first_col ; <nl> - filelist . push_back ( first_col ) ; / / LEOTODO <nl> + filelist . push_back ( first_col ) ; / / LEOTODO <nl> n + + ; <nl> } <nl> <nl> bool HTKMLFWriter < ElemType > : : SaveData ( size_t / * recordStart * / , const std : : map < std <nl> <nl> if ( kaldicmd . size ( ) = = 0 ) <nl> { <nl> - / / std : : map < std : : wstring , void * , nocase_compare > : : iterator iter ; <nl> + / / std : : map < std : : wstring , void * , nocase_compare > : : iterator iter ; <nl> if ( outputFileIndex > = outputFiles [ 0 ] . size ( ) ) <nl> RuntimeError ( " index for output scp file out of range . . . " ) ; <nl> <nl> bool HTKMLFWriter < ElemType > : : SaveData ( size_t / * recordStart * / , const std : : map < std <nl> wstring outFile = outputFiles [ id ] [ outputFileIndex ] ; <nl> string wfea = " ark : " + msra : : strfun : : utf8 ( outFile ) ; <nl> <nl> - / / wfea = msra : : strfun : : utf8 ( kaldicmd [ i ] ) ; <nl> - / / feature_writer [ i ] . Open ( wfea ) ; <nl> + / / wfea = msra : : strfun : : utf8 ( kaldicmd [ i ] ) ; <nl> + / / feature_writer [ i ] . Open ( wfea ) ; <nl> kaldi : : Matrix < kaldi : : BaseFloat > nnet_out_host ; <nl> <nl> assert ( outputData . GetNumRows ( ) = = dim ) ; <nl> mmm a / Source / Readers / Kaldi2Reader / basetypes . h <nl> ppp b / Source / Readers / Kaldi2Reader / basetypes . h <nl> static inline std : : string basename ( std : : string const & pathname ) <nl> <nl> static inline std : : string removeExtension ( std : : string const & filename ) <nl> { <nl> - / / std : : string : : const_reverse_iterator pivot = std : : find ( filename . rbegin ( ) , filename . rend ( ) , ' . ' ) ; <nl> - / / return pivot = = filename . rend ( ) ? filename : std : : string ( filename . begin ( ) , pivot . base ( ) - 1 ) ; <nl> + / / std : : string : : const_reverse_iterator pivot = std : : find ( filename . rbegin ( ) , filename . rend ( ) , ' . ' ) ; <nl> + / / return pivot = = filename . rend ( ) ? filename : std : : string ( filename . begin ( ) , pivot . base ( ) - 1 ) ; <nl> int lastindex = filename . find_first_of ( " . " ) ; <nl> return filename . substr ( 0 , lastindex ) ; <nl> } <nl> static inline std : : wstring basename ( std : : wstring const & pathname ) <nl> <nl> static inline std : : wstring removeExtension ( std : : wstring const & filename ) <nl> { <nl> - / / std : : wstring : : const_reverse_iterator pivot = std : : find ( filename . rbegin ( ) , filename . rend ( ) , ' . ' ) ; <nl> - / / return pivot = = filename . rend ( ) ? filename : std : : wstring ( filename . begin ( ) , pivot . base ( ) - 1 ) ; <nl> + / / std : : wstring : : const_reverse_iterator pivot = std : : find ( filename . rbegin ( ) , filename . rend ( ) , ' . ' ) ; <nl> + / / return pivot = = filename . rend ( ) ? filename : std : : wstring ( filename . begin ( ) , pivot . base ( ) - 1 ) ; <nl> int lastindex = filename . find_first_of ( L " . " ) ; <nl> return filename . substr ( 0 , lastindex ) ; <nl> } <nl> class fixed_vector <nl> # endif <nl> } <nl> / / . . . TODO : when I make this public , LinearTransform . h acts totally up but I cannot see where it comes from . <nl> - / / fixed_vector ( const fixed_vector & other ) : n ( 0 ) , p ( NULL ) { * this = other ; } <nl> + / / fixed_vector ( const fixed_vector & other ) : n ( 0 ) , p ( NULL ) { * this = other ; } <nl> public : <nl> fixed_vector ( ) <nl> : n ( 0 ) , p ( NULL ) <nl> mmm a / Source / Readers / Kaldi2Reader / chunkevalsource . h <nl> ppp b / Source / Readers / Kaldi2Reader / chunkevalsource . h <nl> class chunkevalsourcemulti / / : public numamodelmanager <nl> <nl> frames . reserve ( chunksize * 2 ) ; <nl> framesmulti . push_back ( frames ) ; <nl> - / / framesmulti [ i ] . reserve ( chunksize * 2 ) ; <nl> + / / framesmulti [ i ] . reserve ( chunksize * 2 ) ; <nl> <nl> thisfeat . resize ( vdims [ i ] , chunksize ) ; <nl> feat . push_back ( thisfeat ) ; <nl> <nl> outpaths . push_back ( std : : vector < std : : wstring > ( ) ) ; <nl> sampperiods . push_back ( std : : vector < unsigned int > ( ) ) ; <nl> - / / feat [ i ] . resize ( vdims [ i ] , chunksize ) ; / / initialize to size chunksize <nl> + / / feat [ i ] . resize ( vdims [ i ] , chunksize ) ; / / initialize to size chunksize <nl> } <nl> } <nl> <nl> class FileEvalSource / / : public numamodelmanager <nl> <nl> frames . reserve ( chunksize * 2 ) ; <nl> framesMulti . push_back ( frames ) ; <nl> - / / framesmulti [ i ] . reserve ( chunksize * 2 ) ; <nl> + / / framesmulti [ i ] . reserve ( chunksize * 2 ) ; <nl> <nl> thisfeat . resize ( vdims [ i ] , chunksize ) ; <nl> feat . push_back ( thisfeat ) ; <nl> <nl> sampPeriods . push_back ( std : : vector < unsigned int > ( ) ) ; <nl> - / / feat [ i ] . resize ( vdims [ i ] , chunksize ) ; / / initialize to size chunksize <nl> + / / feat [ i ] . resize ( vdims [ i ] , chunksize ) ; / / initialize to size chunksize <nl> } <nl> } <nl> <nl> class FileEvalSource / / : public numamodelmanager <nl> rightextent = rightcontext [ i ] ; <nl> } <nl> <nl> - / / msra : : dbn : : augmentneighbors ( framesMulti [ i ] , boundaryFlags , 0 , leftcontext [ i ] , rightcontext [ i ] , ) <nl> + / / msra : : dbn : : augmentneighbors ( framesMulti [ i ] , boundaryFlags , 0 , leftcontext [ i ] , rightcontext [ i ] , ) <nl> msra : : dbn : : augmentneighbors ( framesMulti [ i ] , boundaryFlags , leftextent , rightextent , 0 , framesInBlock , feat [ i ] ) ; <nl> } <nl> minibatchReady = true ; <nl> mmm a / Source / Readers / Kaldi2Reader / htkfeatio . h <nl> ppp b / Source / Readers / Kaldi2Reader / htkfeatio . h <nl> class FeatureSection <nl> <nl> feature_reader = new kaldi : : RandomAccessBaseFloatMatrixReader ( rx ) ; <nl> <nl> - / / std : : wcout < < " Kaldi2Reader : created feature reader " < < feature_reader < < " [ " < < rx . c_str ( ) < < " ] " < < std : : endl ; <nl> + / / std : : wcout < < " Kaldi2Reader : created feature reader " < < feature_reader < < " [ " < < rx . c_str ( ) < < " ] " < < std : : endl ; <nl> <nl> if ( this - > feature_transform = = " NO_FEATURE_TRANSFORM " ) <nl> { <nl> class FeatureSection <nl> <nl> ~ FeatureSection ( ) <nl> { <nl> - / / std : : wcout < < " Kaldi2Reader : deleted feature reader " < < feature_reader < < std : : endl ; <nl> + / / std : : wcout < < " Kaldi2Reader : deleted feature reader " < < feature_reader < < std : : endl ; <nl> <nl> delete feature_reader ; <nl> } <nl> class htkfeatwriter : protected htkfeatio <nl> template < class MATRIX > <nl> static void write ( const wstring & path , const string & kindstr , unsigned int period , const MATRIX & feat ) <nl> { <nl> - / / std : : wcout < < __FILE__ < < " : " < < __FUNCTION__ < < " not implemented " < < std : : endl ; <nl> + / / std : : wcout < < __FILE__ < < " : " < < __FUNCTION__ < < " not implemented " < < std : : endl ; <nl> exit ( 1 ) ; <nl> } <nl> template < class T > <nl> class htkfeatwriter : protected htkfeatio <nl> os . put ( ' \ 0 ' ) ; <nl> os . put ( ' B ' ) ; <nl> std : : string my_token = ( precision = = 4 ? " FM " : " DM " ) ; <nl> - / / WriteToken ( os , binary , my_token ) ; <nl> + / / WriteToken ( os , binary , my_token ) ; <nl> os < < my_token < < " " ; <nl> { <nl> int32 rows = numframes ; <nl> class htkfeatreader : protected htkfeatio <nl> { <nl> / / information on current file <nl> / / File handle and feature type information is stored in the underlying htkfeatio object . <nl> - / / TODO make this nicer <nl> + / / TODO make this nicer <nl> <nl> public : <nl> / / parser for complex a = b [ s , e ] syntax <nl> struct htkmlfentry <nl> { <nl> unsigned int firstframe ; / / range [ firstframe , firstframe + numframes ) <nl> unsigned short numframes ; <nl> - / / unsigned short classid ; / / numeric state id <nl> + / / unsigned short classid ; / / numeric state id <nl> unsigned int classid ; / / numeric state id - mseltzer changed from ushort to uint for untied cd phones > 2 ^ 16 <nl> <nl> public : <nl> mmm a / Source / Readers / Kaldi2Reader / latticearchive . cpp <nl> ppp b / Source / Readers / Kaldi2Reader / latticearchive . cpp <nl> void lattice : : dedup ( ) <nl> L . merge ( L2 , hset ) ; <nl> / / note : we are left with dups due to true unigram merging ( HTK lattices cannot represent true unigram lattices since id is on the nodes ) <nl> } <nl> - / / L . removefinalnull ( ) ; <nl> - / / L . determinenodecontexts ( hset ) ; <nl> + / / L . removefinalnull ( ) ; <nl> + / / L . determinenodecontexts ( hset ) ; <nl> <nl> / / convert it - - TODO : once we permanently use the new format , do this in fread ( ) for V1 <nl> / / Note : Merging may have left this in unsorted format ; we need to be robust against that . <nl> void lattice : : fromhtklattice ( const wstring & path , const std : : unordered_map < std : : <nl> if ( it = = unitmap . end ( ) ) <nl> throw std : : runtime_error ( " lattice : unit in alignment that is not in model : " + label ) ; <nl> const size_t unitid = it - > second ; <nl> - / / const size_t unitid = unitmap . insert ( make_pair ( label , unitmap . size ( ) ) ) . first - > second ; / / may create a new entry with index = # entries <nl> + / / const size_t unitid = unitmap . insert ( make_pair ( label , unitmap . size ( ) ) ) . first - > second ; / / may create a new entry with index = # entries <nl> align . push_back ( aligninfo ( unitid , frames ) ) ; <nl> edgeframes + = frames ; <nl> } <nl> mmm a / Source / Readers / Kaldi2Reader / minibatchiterator . h <nl> ppp b / Source / Readers / Kaldi2Reader / minibatchiterator . h <nl> class minibatchsource <nl> / / - lattices are returned as a shared_ptr <nl> / / Thus , getbatch ( ) can be called in a thread - safe fashion , allowing for a ' minibatchsource ' implementation that wraps another with a read - ahead thread . <nl> / / Return value is ' true ' if it did read anything from disk , and ' false ' if data came only from RAM cache . This is used for controlling the read - ahead thread . <nl> - / / <nl> + / / <nl> / / This version introduces < utteranceinfo > , which contains the utterance ID <nl> / / information for each frame in the minibatch . Ideally we would like to <nl> / / call it as < uids > , but that is already taken by the labels . . . If the <nl> mmm a / Source / Readers / Kaldi2Reader / minibatchsourcehelpers . h <nl> ppp b / Source / Readers / Kaldi2Reader / minibatchsourcehelpers . h <nl> class RandomOrdering / / note : NOT thread - safe at all <nl> } <nl> <nl> / / this returns the map directly ( read - only ) and will lazily initialize it for a given seed <nl> - const std : : vector < INDEXTYPE > & operator ( ) ( size_t seed ) / / throw ( ) <nl> + const std : : vector < INDEXTYPE > & operator ( ) ( size_t seed ) / / throw ( ) <nl> { <nl> / / if wrong seed then lazily recache the sequence <nl> if ( seed ! = currentseed ) <nl> class RandomOrdering / / note : NOT thread - safe at all <nl> } ; <nl> <nl> / / typedef unsigned short CLASSIDTYPE ; / / type to store state ids ; don ' t use size_t - - saves HUGE amounts of RAM <nl> - typedef unsigned int CLASSIDTYPE ; / / mseltzer - change to unsigned int for untied context - dependent phones <nl> + typedef unsigned int CLASSIDTYPE ; / / mseltzer - change to unsigned int for untied context - dependent phones <nl> } ; <nl> } ; <nl> mmm a / Source / Readers / Kaldi2Reader / msra_mgram . h <nl> ppp b / Source / Readers / Kaldi2Reader / msra_mgram . h <nl> class int24_vector : std : : vector < unsigned char > <nl> class mgram_map <nl> { <nl> typedef unsigned int index_t ; / / ( - > size_t when we really need it ) <nl> - / / typedef size_t index_t ; / / ( tested once , seems to work ) <nl> + / / typedef size_t index_t ; / / ( tested once , seems to work ) <nl> static const index_t nindex = ( index_t ) - 1 ; / / invalid index <nl> / / entry [ m ] [ i ] is first index of children in level m + 1 , entry [ m ] [ i + 1 ] the end . <nl> int M ; / / order , e . g . M = 3 for trigram <nl> class mgram_map <nl> { <nl> int w = k [ n - 1 ] ; / / may be - 1 for unknown word <nl> int id = map ( w ) ; / / may still be - 1 <nl> - / / const char * sym = idToSymbol ( id ) ; sym ; / / ( debugging ) <nl> + / / const char * sym = idToSymbol ( id ) ; sym ; / / ( debugging ) <nl> i = find_child ( n - 1 , i , id ) ; <nl> if ( i = = nindex ) / / unknown history : fall back <nl> return foundcoord ( - 1 ) ; / / indicates failure <nl> class CMGramLMEstimator : public CMGramLM <nl> std : : vector < int > w2id ( mmap . maxid ( ) + 1 ) ; <nl> foreach_index ( i , w2id ) <nl> w2id [ i ] = i ; <nl> - / / std : : vector < int > w2id ( mmap . identical_map ( ) ) ; <nl> + / / std : : vector < int > w2id ( mmap . identical_map ( ) ) ; <nl> <nl> / / close down creation of new tokens , so we can random - access <nl> mmap . created ( w2id ) ; <nl> class CMGramLMEstimator : public CMGramLM <nl> dropWord . push_back ( true ) ; / / filtering but no < UNK > : <nl> assert ( ! filterVocabulary | | unkId ! = - 1 | | dropWord [ dropId ] ) ; <nl> <nl> - / / std : : vector < unsigned int > minObs ( 2 , 0 ) ; <nl> - / / std : : vector < unsigned int > iMinObs ( 3 , 0 ) ; <nl> - / / iMinObs [ 1 ] = 3 ; / / remove singleton 2 + - grams <nl> - / / iMinObs [ 2 ] = 3 ; / / remove singleton 3 + - grams <nl> + / / std : : vector < unsigned int > minObs ( 2 , 0 ) ; <nl> + / / std : : vector < unsigned int > iMinObs ( 3 , 0 ) ; <nl> + / / iMinObs [ 1 ] = 3 ; / / remove singleton 2 + - grams <nl> + / / iMinObs [ 2 ] = 3 ; / / remove singleton 3 + - grams <nl> <nl> - / / / / set prune value to 0 3 3 <nl> - / / setMinObs ( iMinObs ) ; <nl> + / / / / set prune value to 0 3 3 <nl> + / / setMinObs ( iMinObs ) ; <nl> <nl> for ( size_t i = 0 ; i < minObs . size ( ) ; i + + ) <nl> { <nl> class CMGramLMEstimator : public CMGramLM <nl> std : : vector < int > w2id ( map . maxid ( ) + 1 ) ; <nl> foreach_index ( i , w2id ) <nl> w2id [ i ] = i ; <nl> - / / std : : vector < int > w2id ( map . identical_map ( ) ) ; <nl> + / / std : : vector < int > w2id ( map . identical_map ( ) ) ; <nl> <nl> / / close down creation of new tokens , so we can random - access <nl> map . created ( w2id ) ; <nl> class CMGramLMEstimator : public CMGramLM <nl> throw runtime_error ( msra : : strfun : : strprintf ( " estimate : error estimating discounting values : n1 [ % d ] = = 0 " , m ) ) ; <nl> if ( n2 [ m ] = = 0 ) <nl> throw runtime_error ( msra : : strfun : : strprintf ( " estimate : error estimating discounting values : n2 [ % d ] = = 0 " , m ) ) ; <nl> - / / if ( n3 [ m ] = = 0 ) RuntimeError ( " estimate : error estimating discounting values : n3 [ % d ] = = 0 " , m ) ; <nl> + / / if ( n3 [ m ] = = 0 ) RuntimeError ( " estimate : error estimating discounting values : n3 [ % d ] = = 0 " , m ) ; <nl> double Y = n1 [ m ] / ( n1 [ m ] + 2 . 0 * n2 [ m ] ) ; <nl> if ( n3 [ m ] = = 0 | | n4 [ m ] = = 0 ) <nl> { <nl> class CMGramLMEstimator : public CMGramLM <nl> mgram_map : : coord j = histCoord [ m - 1 ] ; / / parent <nl> if ( counts [ j ] = = 0 ) <nl> RuntimeError ( " estimate : invalid pruning : a parent m - gram got pruned away " ) ; <nl> - / / throw runtime_error ( " estimate : invalid pruning : a parent m - gram got pruned away " ) ; <nl> + / / throw runtime_error ( " estimate : invalid pruning : a parent m - gram got pruned away " ) ; <nl> numMGrams [ m ] + + ; <nl> } <nl> } <nl> class CMGramLMEstimator : public CMGramLM <nl> / / get history ' s count <nl> const mgram_map : : coord j = histCoord [ m - 1 ] ; / / index of parent entry <nl> double histCount = counts [ j ] ; / / parent count - - before pruning <nl> - / / double histCount = succCount [ j ] ; / / parent count - - actuals after pruning <nl> + / / double histCount = succCount [ j ] ; / / parent count - - actuals after pruning <nl> <nl> / / estimate probability for this M - gram <nl> unsigned int count = counts [ iter ] ; <nl> class CMGramLMEstimator : public CMGramLM <nl> w2id . resize ( Pmap . maxid ( ) + 1 ) ; <nl> foreach_index ( i , w2id ) <nl> w2id [ i ] = i ; <nl> - / / std : : vector < int > w2id ( Pmap . identical_map ( ) ) ; <nl> + / / std : : vector < int > w2id ( Pmap . identical_map ( ) ) ; <nl> Pmap . created ( w2id ) ; / / finalize and establish mapping for read access <nl> map . swap ( Pmap ) ; / / install the new map in our m - gram <nl> Pmap . clear ( ) ; / / no longer using the old one <nl> class CMGramLMClone : public CMGramLM <nl> { <nl> int w = key [ i ] ; <nl> if ( dropWord [ w ] ) <nl> - goto skipMGram ; / / skipMGram <nl> + goto skipMGram ; / / skipMGram <nl> } <nl> } <nl> / / local block for get rid of : warning C4533 : initialization of ' c ' is skipped by ' goto skipMGram ' <nl> class OldCMGramLM : public ILM <nl> unknownLogP = entries_1 [ i ] . logP ; <nl> } <nl> entries [ 0 ] [ 0 ] . logP = unknownLogP ; ; <nl> - / / = ( float ) - log ( ( double ) lmSymbols . size ( ) ) ; / / zerogram score <nl> + / / = ( float ) - log ( ( double ) lmSymbols . size ( ) ) ; / / zerogram score <nl> <nl> / / establish mapping of word ids from user to LM space <nl> userToLMSymMap . resize ( userSymMap . size ( ) ) ; <nl> mmm a / Source / Readers / Kaldi2Reader / notes . txt <nl> ppp b / Source / Readers / Kaldi2Reader / notes . txt <nl> GetMinibatchToWrite <nl> const auto path = reader . parse ( m_inputFilesMultiIO [ i ] [ m_inputFileIndex ] ) ; <nl> reader . read ( path , featkind , sampperiod , feat ) ; <nl> <nl> - m_fileEvalSource - > AddFile ( feat , featkind , sampperiod , i ) ; / / sampPeriods not used , featkind not used <nl> + m_fileEvalSource - > AddFile ( feat , featkind , sampperiod , i ) ; / / sampPeriods not used , featkind not used <nl> m_fileEvalSource - > CreateEvalMinibatch ( ) ; <nl> m_fileEvalSource - > ChunkOfFrames ( id ) ; <nl> \ No newline at end of file <nl> mmm a / Source / Readers / Kaldi2Reader / numahelpers . h <nl> ppp b / Source / Readers / Kaldi2Reader / numahelpers . h <nl> void parallel_for_on_each_numa_node ( bool multistep , const FUNCTION & body ) <nl> for ( size_t k = 0 ; k < nodes ; k + + ) <nl> nextstepcounters [ k ] = 0 ; <nl> overridenode ( ) ; <nl> - / / unsigned int totalloops = 0 ; / / for debugging only , can be removed later <nl> + / / unsigned int totalloops = 0 ; / / for debugging only , can be removed later <nl> msra : : parallel : : parallel_for ( 0 , nodes * steps / * execute each step on each NUMA node * / , 1 , [ & ] ( size_t / * dummy * / ) <nl> { <nl> const size_t numanodeid = getcurrentnode ( ) ; <nl> void parallel_for_on_each_numa_node ( bool multistep , const FUNCTION & body ) <nl> continue ; / / so try next NUMA node <nl> / / found one : execute and terminate loop <nl> body ( node , step , steps ) ; <nl> - / / InterlockedIncrement ( & totalloops ) ; <nl> + / / InterlockedIncrement ( & totalloops ) ; <nl> return ; / / done <nl> } <nl> / / oops ? ? <nl> throw std : : logic_error ( " parallel_for_on_each_numa_node : no left - over block found - - should not get here ! ! " ) ; <nl> } ) ; <nl> - / / assert ( totalloops = = nodes * steps ) ; <nl> + / / assert ( totalloops = = nodes * steps ) ; <nl> } <nl> <nl> / / execute a passed function once for each NUMA node <nl> mmm a / Source / Readers / Kaldi2Reader / pplhelpers . h <nl> ppp b / Source / Readers / Kaldi2Reader / pplhelpers . h <nl> void parallel_for ( size_t begin , size_t end , size_t step , const FUNCTION & f ) <nl> const size_t cores = ppl_cores ; <nl> if ( cores > 1 ) / / parallel computation ( regular ) <nl> { <nl> - / / fprintf ( stderr , " foreach_index_block : computing % d blocks of % d frames on % d cores \ n " , nblocks , nfwd , determine_num_cores ( ) ) ; <nl> + / / fprintf ( stderr , " foreach_index_block : computing % d blocks of % d frames on % d cores \ n " , nblocks , nfwd , determine_num_cores ( ) ) ; <nl> Concurrency : : parallel_for ( begin , end , step , f ) ; <nl> } <nl> else / / for comparison : single - threaded ( this also documents what the above means ) <nl> { <nl> - / / fprintf ( stderr , " foreach_index_block : computing % d blocks of % d frames on a single thread \ n " , nblocks , nfwd ) ; <nl> + / / fprintf ( stderr , " foreach_index_block : computing % d blocks of % d frames on a single thread \ n " , nblocks , nfwd ) ; <nl> for ( size_t j0 = begin ; j0 < end ; j0 + = step ) <nl> f ( j0 ) ; <nl> } <nl> mmm a / Source / Readers / Kaldi2Reader / readaheadsource . h <nl> ppp b / Source / Readers / Kaldi2Reader / readaheadsource . h <nl> class minibatchreadaheadsource : public minibatchsource / * the interface we imple <nl> <nl> feat . resize ( 1 ) ; <nl> uids . resize ( 1 ) ; <nl> - / / transcripts . resize ( 1 ) ; <nl> - / / lattices . resize ( 1 ) ; <nl> + / / transcripts . resize ( 1 ) ; <nl> + / / lattices . resize ( 1 ) ; <nl> return getbatch ( globalts , framesrequested , feat [ 0 ] , uids [ 0 ] , transcripts , lattices ) ; <nl> } <nl> <nl> mmm a / Source / Readers / Kaldi2Reader / rollingwindowsource . h <nl> ppp b / Source / Readers / Kaldi2Reader / rollingwindowsource . h <nl> class biggrowablevectorarray : public growablevectorbase < msra : : dbn : : matrix > <nl> msra : : dbn : : matrix * newblock ( ) const <nl> { <nl> / / we stripe the data across NUMA nodes as to not fill up one node with the feature data <nl> - / / msra : : numa : : overridenode ( ( int ) msra : : numa : : getmostspaciousnumanode ( ) ) ; <nl> + / / msra : : numa : : overridenode ( ( int ) msra : : numa : : getmostspaciousnumanode ( ) ) ; <nl> msra : : dbn : : matrix * res = new msra : : dbn : : matrix ( m , elementsperblock ) ; <nl> - / / msra : : numa : : overridenode ( - 1 ) ; / / note : we really should reset it also in case of failure <nl> + / / msra : : numa : : overridenode ( - 1 ) ; / / note : we really should reset it also in case of failure <nl> return res ; <nl> } <nl> <nl> class minibatchframesourcemulti : public minibatchsource <nl> size_t featdim ; <nl> size_t maxvdim ; <nl> / / cache <nl> - / / std : : vector < biggrowablevectorarray > frames ; <nl> + / / std : : vector < biggrowablevectorarray > frames ; <nl> std : : vector < unique_ptr < biggrowablevectorarray > > pframes ; / / [ t ] [ i ] all features concatenated <nl> std : : vector < char > boundaryflags ; / / [ t ] - 1 for first and + 1 for last frame , 0 else ( for augmentneighbors ( ) ) <nl> std : : vector < std : : vector < CLASSIDTYPE > > classids ; / / [ t ] the state that the frame belongs to <nl> mmm a / Source / Readers / Kaldi2Reader / simplethread . h <nl> ppp b / Source / Readers / Kaldi2Reader / simplethread . h <nl> class simplethread : CCritSec <nl> exceptionptr = badallocexceptionptr ; <nl> } <nl> } <nl> - / / void join ( ) <nl> - / / { <nl> + / / void join ( ) <nl> + / / { <nl> / / check ( ) ; <nl> / / wait ( ) ; <nl> / / check_for_exception ( ) ; / / ( check ( ) not sufficient because it would fail since thread is gone ) <nl> - / / } <nl> + / / } <nl> ~ simplethread ( ) throw ( ) <nl> { <nl> / / wait until it shuts down <nl> mmm a / Source / Readers / Kaldi2Reader / ssefloat4 . h <nl> ppp b / Source / Readers / Kaldi2Reader / ssefloat4 . h <nl> class float4 <nl> : v ( _mm_load1_ps ( & f ) ) <nl> { <nl> } <nl> - / / float4 ( float f ) : v ( _mm_set_ss ( f ) ) { } / / code seems more complex than _mm_load1_ps ( ) <nl> + / / float4 ( float f ) : v ( _mm_set_ss ( f ) ) { } / / code seems more complex than _mm_load1_ps ( ) <nl> <nl> / / basic math <nl> float4 operator - ( ) const <nl> class float4 <nl> / / save a float4 to RAM bypassing the cache ( ' without polluting the cache ' ) <nl> void storewithoutcache ( float4 & r4 ) const <nl> { <nl> - / / _mm_stream_ps ( ( float * ) & r4 , v ) ; <nl> + / / _mm_stream_ps ( ( float * ) & r4 , v ) ; <nl> r4 = v ; <nl> } <nl> <nl> class float4 <nl> / / save a float4 to RAM bypassing the cache ( ' without polluting the cache ' ) <nl> void storewithoutcache ( float4 * p4 ) const <nl> { <nl> - / / _mm_stream_ps ( ( float * ) p4 , v ) ; <nl> + / / _mm_stream_ps ( ( float * ) p4 , v ) ; <nl> * p4 = v ; <nl> } <nl> <nl> mmm a / Source / Readers / Kaldi2Reader / ssematrix . h <nl> ppp b / Source / Readers / Kaldi2Reader / ssematrix . h <nl> class ssematrixbase <nl> <nl> / / operations - - add as we go <nl> <nl> - / / both m1 and m2 are passed in normal form ( i . e . , not transposed ) <nl> + / / both m1 and m2 are passed in normal form ( i . e . , not transposed ) <nl> void KhatriRaoProduct ( const ssematrixbase & m1 , const ssematrixbase & m2 ) <nl> { <nl> auto & us = * this ; <nl> class ssematrixbase <nl> <nl> if ( isehtransposed ) <nl> { <nl> - / / find nrows and ncols of the reshpaed eh <nl> + / / find nrows and ncols of the reshpaed eh <nl> size_t nrows = h . rows ( ) ; <nl> size_t ncols = eh . rows ( ) / nrows ; <nl> assert ( eh . rows ( ) % nrows = = 0 ) ; <nl> class ssematrixbase <nl> / / dot - product of vectors in matrix format ( matrix type , but only one column ) <nl> float dotprod ( const ssematrixbase & other ) const <nl> { <nl> - / / assert ( other . cols ( ) = = 1 ) ; <nl> - / / assert ( cols ( ) = = 1 ) ; <nl> + / / assert ( other . cols ( ) = = 1 ) ; <nl> + / / assert ( cols ( ) = = 1 ) ; <nl> assert ( rows ( ) = = other . rows ( ) ) ; <nl> assert ( cols ( ) = = other . cols ( ) ) ; <nl> float result = 0 . 0f ; <nl> class ssematrixbase <nl> assert ( ( 15 & ( long ) & row [ 0 ] ) = = 0 ) ; <nl> assert ( ( 15 & ( long ) & cols4 [ 0 ] ) = = 0 ) ; <nl> assert ( ( 15 & ( long ) & cols4 [ cols4stride ] ) = = 0 ) ; <nl> - / / assert ( cols4stride * 4 = = cols4 . size ( ) ) ; / / ( passed in one vector with 4 columns stacked on top of each other ) <nl> - / / assert ( row . size ( ) * 4 = = cols4 . size ( ) ) ; / / this assert is no longer appropriate because of further breaking into blocks <nl> + / / assert ( cols4stride * 4 = = cols4 . size ( ) ) ; / / ( passed in one vector with 4 columns stacked on top of each other ) <nl> + / / assert ( row . size ( ) * 4 = = cols4 . size ( ) ) ; / / this assert is no longer appropriate because of further breaking into blocks <nl> <nl> / / perform multiple columns in parallel <nl> const size_t nlong = ( row . size ( ) + 3 ) / 4 ; / / number of SSE elements <nl> class ssematrixbase <nl> acc3 + = prow [ m ] * pcol3 [ m ] ; <nl> } <nl> # else <nl> - const size_t prefetch = 1 ; / / 128 / sizeof ( acc0 ) ; <nl> + const size_t prefetch = 1 ; / / 128 / sizeof ( acc0 ) ; <nl> size_t m ; <nl> for ( m = 1 ; m < nlong - prefetch ; m + + ) <nl> { <nl> class ssematrixbase <nl> / / is loaded once into cache . Each row of M is loaded into cache once per stripe of V , <nl> / / in the example every 195 columns . <nl> const size_t cacheablerowsV = 512 ; / / at most <nl> - const size_t cacheablecolsV = 16 ; / / V . cacheablecols ( ) ; / / don ' t get more than this of V per row of M <nl> + const size_t cacheablecolsV = 16 ; / / V . cacheablecols ( ) ; / / don ' t get more than this of V per row of M <nl> / / 512 * 16 - > 32 KB <nl> <nl> const size_t colstripewV = cacheablecolsV ; / / width of col stripe of V <nl> class ssematrixbase <nl> { <nl> const size_t k1 = min ( k0 + dotprodstep , V . rows ( ) ) ; <nl> const bool first = k0 = = 0 ; <nl> - / / const bool last = k0 + dotprodstep > = V . rows ( ) ; <nl> + / / const bool last = k0 + dotprodstep > = V . rows ( ) ; <nl> <nl> / / loop over requested rows [ beginrow , endrow ) of result ( = rows of M ( = cols of Mt ) ) <nl> for ( size_t i = i0 ; i < i1 ; i + + ) / / remember that cols of Mt are the rows of M <nl> class ssematrixbase <nl> array_ref < float > usij ( & us ( i , j ) , 4 * us . colstride - i + 1 ) ; <nl> array_ref < float > patchij ( & patch ( i - i0 , j - j0 ) , 4 * patch . colstride - ( i - i0 ) + 1 ) ; <nl> <nl> - / / dotprod4 ( row , cols4 , V . colstride , usij , us . colstride ) ; <nl> + / / dotprod4 ( row , cols4 , V . colstride , usij , us . colstride ) ; <nl> if ( first ) <nl> dotprod4 ( row , cols4 , V . colstride , patchij , patch . colstride ) ; <nl> else <nl> class ssematrixbase <nl> / / dotprod ( Mt . col ( i ) , V . col ( j + 3 ) , us ( i , j + 3 ) ) ; <nl> } <nl> for ( size_t j = j14 ; j < j1 ; j + + ) / / remainder not grouped <nl> - / / dotprod ( Mt . col ( i ) , V . col ( j ) , us ( i , j ) ) ; <nl> + / / dotprod ( Mt . col ( i ) , V . col ( j ) , us ( i , j ) ) ; <nl> if ( first ) / / do it in one big step ignoring the cache issue <nl> dotprod ( Mt . col ( i ) , V . col ( j ) , patch ( i - i0 , j - j0 ) ) ; <nl> } <nl> class ssematrixbase <nl> assert ( us . rows ( ) = = A . rows ( ) ) ; <nl> assert ( us . cols ( ) = = Bt . rows ( ) ) ; / / Bt . rows ( ) = = B . cols ( ) <nl> assert ( A . cols ( ) = = Bt . cols ( ) ) ; / / Bt . cols ( ) = = B . rows ( ) <nl> - / / fprintf ( stderr , " 0x % x ( % d , % d ) x 0x % x ( % d , % d ) ' - > 0x % x ( % d , % d ) \ n " , A . p , A . rows ( ) , A . cols ( ) , Bt . p , Bt . rows ( ) , Bt . cols ( ) , us . p , us . rows ( ) , us . cols ( ) ) ; <nl> + / / fprintf ( stderr , " 0x % x ( % d , % d ) x 0x % x ( % d , % d ) ' - > 0x % x ( % d , % d ) \ n " , A . p , A . rows ( ) , A . cols ( ) , Bt . p , Bt . rows ( ) , Bt . cols ( ) , us . p , us . rows ( ) , us . cols ( ) ) ; <nl> <nl> foreach_coord ( i , j , us ) <nl> { <nl> class ssematrixbase <nl> assert ( us . cols ( ) = = V . cols ( ) ) ; <nl> assert ( i0 < i1 & & i1 < = Mt . cols ( ) ) ; / / remember that cols of Mt are the rows of M <nl> <nl> - / / for ( size_t i = 0 ; i < Mt . cols ( ) ; i + + ) / / remember that cols of Mt are the rows of M <nl> + / / for ( size_t i = 0 ; i < Mt . cols ( ) ; i + + ) / / remember that cols of Mt are the rows of M <nl> for ( size_t i = i0 ; i < i1 ; i + + ) / / remember that cols of Mt are the rows of M <nl> { <nl> size_t j0 = V . cols ( ) & ~ 3 ; <nl> class ssematrix : public ssematrixbase <nl> return ; / / no resize needed <nl> const size_t newcolstride = ( n + 3 ) & ~ 3 ; / / pad to multiples of four floats ( required SSE alignment ) <nl> const size_t totalelem = newcolstride * m ; <nl> - / / fprintf ( stderr , " resize ( % d , % d ) allocating % d elements \ n " , n , m , totalelem ) ; <nl> + / / fprintf ( stderr , " resize ( % d , % d ) allocating % d elements \ n " , n , m , totalelem ) ; <nl> float * pnew = totalelem > 0 ? new_sse < float > ( totalelem ) : NULL ; <nl> : : swap ( this - > p , pnew ) ; <nl> delete_sse ( pnew ) ; / / pnew is now the old p <nl> class ssematrix : public ssematrixbase <nl> this - > colstride = newcolstride ; <nl> / / touch the memory to ensure the page is created <nl> for ( size_t offset = 0 ; offset < totalelem ; offset + = 4096 / sizeof ( float ) ) <nl> - this - > p [ offset ] = 0 . 0f ; / / nan ; <nl> + this - > p [ offset ] = 0 . 0f ; / / nan ; <nl> / / clear padding elements ( numrows < = i < colstride ) to 0 . 0 for SSE optimization <nl> for ( size_t j = 0 ; j < this - > numcols ; j + + ) <nl> for ( size_t i = this - > numrows ; i < this - > colstride ; i + + ) <nl> pair < unsigned int , unsigned int > printmatvaluedistributionf ( const char * name , co <nl> unsigned int numzeros = 0 ; <nl> foreach_coord ( i , j , m ) <nl> { <nl> - vals [ k ] = abs ( m ( i , j ) ) ; / / this is slower than memcpy but without assumption on how values are stored . <nl> + vals [ k ] = abs ( m ( i , j ) ) ; / / this is slower than memcpy but without assumption on how values are stored . <nl> numzeros + = ( vals [ k + + ] < 1e - 10f ) ; <nl> } <nl> <nl> mmm a / Source / Readers / Kaldi2Reader / utterancesourcemulti . h <nl> ppp b / Source / Readers / Kaldi2Reader / utterancesourcemulti . h <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> std : : vector < std : : vector < size_t > > counts ; / / [ s ] occurence count for all states ( used for priors ) <nl> int verbosity ; <nl> / / lattice reader <nl> - / / const std : : vector < unique_ptr < latticesource > > & lattices ; <nl> + / / const std : : vector < unique_ptr < latticesource > > & lattices ; <nl> const latticesource & lattices ; <nl> <nl> - / / std : : vector < latticesource > lattices ; <nl> + / / std : : vector < latticesource > lattices ; <nl> / / word - level transcripts ( for MMI mode when adding best path to lattices ) <nl> const map < wstring , msra : : lattices : : lattice : : htkmlfwordsequence > & allwordtranscripts ; / / ( used for getting word - level transcripts ) <nl> - / / std : : vector < map < wstring , msra : : lattices : : lattice : : htkmlfwordsequence > > allwordtranscripts ; <nl> + / / std : : vector < map < wstring , msra : : lattices : : lattice : : htkmlfwordsequence > > allwordtranscripts ; <nl> / / data store ( incl . paging in / out of features and lattices ) <nl> struct utterancedesc / / data descriptor for one utterance <nl> { <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> : totalframes ( 0 ) <nl> { <nl> } <nl> - / / utterancechunkdata ( const utterancechunkdata & other ) : utteranceset ( other . utteranceset ) , firstframes ( other . firstframes ) , frames ( other . frames ) , totalframes ( other . totalframes ) , lattices ( other . lattices ) { } ; <nl> + / / utterancechunkdata ( const utterancechunkdata & other ) : utteranceset ( other . utteranceset ) , firstframes ( other . firstframes ) , frames ( other . frames ) , totalframes ( other . totalframes ) , lattices ( other . lattices ) { } ; <nl> void push_back ( utterancedesc & & / * destructive * / utt ) <nl> { <nl> - / / printf ( " start push % d % d \ n " , frames . rows ( ) , frames . cols ( ) ) ; <nl> + / / printf ( " start push % d % d \ n " , frames . rows ( ) , frames . cols ( ) ) ; <nl> <nl> if ( isinram ( ) ) <nl> { <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> lattices . resize ( utteranceset . size ( ) ) ; <nl> foreach_index ( i , utteranceset ) <nl> { <nl> - / / fprintf ( stderr , " . " ) ; <nl> + / / fprintf ( stderr , " . " ) ; <nl> / / read features for this file <nl> auto uttframes = getutteranceframes ( i ) ; / / matrix stripe for this utterance ( currently unfilled ) <nl> reader . readNoAlloc ( utteranceset [ i ] . parsedpath , ( const string & ) featkind , sampperiod , uttframes ) ; / / note : file info here used for checkuing only <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> if ( ! latticesource . empty ( ) ) <nl> latticesource . getlattices ( utteranceset [ i ] . key ( ) , lattices [ i ] , uttframes . cols ( ) ) ; <nl> } <nl> - / / fprintf ( stderr , " \ n " ) ; <nl> + / / fprintf ( stderr , " \ n " ) ; <nl> if ( verbosity ) <nl> { <nl> fprintf ( stderr , " requiredata : % zu utterances read \ n " , utteranceset . size ( ) ) ; <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> size_t numutts = 0 ; <nl> <nl> std : : vector < bool > uttisvalid ; / / boolean flag to check that utterance is valid . valid means number of <nl> - / / frames is consistent across all feature and label streams <nl> + / / frames is consistent across all feature and label streams <nl> std : : vector < size_t > uttduration ; / / track utterance durations to determine utterance validity <nl> <nl> std : : vector < size_t > classidsbegin ; <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> foreach_index ( i , labels ) <nl> { <nl> classids . push_back ( unique_ptr < biggrowablevector < CLASSIDTYPE > > ( new biggrowablevector < CLASSIDTYPE > ( ) ) ) ; <nl> - / / std : : pair < std : : vector < wstring > , std : : vector < wstring > > latticetocs ; <nl> - / / std : : unordered_map < std : : string , size_t > modelsymmap ; <nl> - / / lattices . push_back ( shared_ptr < latticesource > ( new latticesource ( latticetocs , modelsymmap ) ) ) ; <nl> + / / std : : pair < std : : vector < wstring > , std : : vector < wstring > > latticetocs ; <nl> + / / std : : unordered_map < std : : string , size_t > modelsymmap ; <nl> + / / lattices . push_back ( shared_ptr < latticesource > ( new latticesource ( latticetocs , modelsymmap ) ) ) ; <nl> } <nl> <nl> / / first check consistency across feature streams <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> <nl> foreach_index ( i , infiles [ m ] ) <nl> { <nl> - utterancedesc utterance ( msra : : asr : : htkfeatreader : : parsedpath ( infiles [ m ] [ i ] , featuresections [ m ] ) , 0 ) ; / / mseltzer - is this foolproof for multiio ? is classids always non - empty ? <nl> + utterancedesc utterance ( msra : : asr : : htkfeatreader : : parsedpath ( infiles [ m ] [ i ] , featuresections [ m ] ) , 0 ) ; / / mseltzer - is this foolproof for multiio ? is classids always non - empty ? <nl> const size_t uttframes = utterance . numframes ( ) ; / / will throw if frame bounds not given - - required to be given in this mode <nl> / / we need at least 2 frames for boundary markers to work <nl> if ( uttframes < 2 ) <nl> { <nl> - / / throw std : : runtime_error ( " minibatchutterancesource : utterances < 2 frames not supported " ) ; <nl> + / / throw std : : runtime_error ( " minibatchutterancesource : utterances < 2 frames not supported " ) ; <nl> fprintf ( stderr , " minibatchutterancesource : skipping % d - th file ( % zd frames ) because it less than % d frames for frameref bit field : % S \ n " , <nl> i , uttframes , 2 , key . c_str ( ) ) ; <nl> uttduration [ i ] = 0 ; <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> foreach_index ( m , infiles ) <nl> { <nl> utteranceset . clear ( ) ; <nl> - / / if ( m = = 0 ) <nl> + / / if ( m = = 0 ) <nl> / / numutts = infiles [ m ] . size ( ) ; <nl> - / / else <nl> + / / else <nl> / / if ( infiles [ m ] . size ( ) ! = numutts ) <nl> / / throw std : : runtime_error ( " minibatchutterancesourcemulti : all feature files must have same number of utterances \ n " ) ; <nl> if ( m = = 0 ) <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> <nl> if ( uttisvalid [ i ] ) <nl> { <nl> - utterancedesc utterance ( msra : : asr : : htkfeatreader : : parsedpath ( infiles [ m ] [ i ] , featuresections [ m ] ) , labels . empty ( ) ? 0 : classidsbegin [ i ] ) ; / / mseltzer - is this foolproof for multiio ? is classids always non - empty ? <nl> + utterancedesc utterance ( msra : : asr : : htkfeatreader : : parsedpath ( infiles [ m ] [ i ] , featuresections [ m ] ) , labels . empty ( ) ? 0 : classidsbegin [ i ] ) ; / / mseltzer - is this foolproof for multiio ? is classids always non - empty ? <nl> const size_t uttframes = utterance . numframes ( ) ; / / will throw if frame bounds not given - - required to be given in this mode <nl> assert ( uttframes = = uttduration [ i ] ) ; / / ensure nothing funky happened <nl> <nl> / / already performed these checks above <nl> / / we need at least 2 frames for boundary markers to work <nl> - / / if ( uttframes < 2 ) <nl> + / / if ( uttframes < 2 ) <nl> / / throw std : : runtime_error ( " minibatchutterancesource : utterances < 2 frames not supported " ) ; <nl> - / / if ( uttframes > frameref : : maxframesperutterance ) <nl> - / / { <nl> + / / if ( uttframes > frameref : : maxframesperutterance ) <nl> + / / { <nl> / / fprintf ( stderr , " minibatchutterancesource : skipping % d - th file ( % d frames ) because it exceeds max . frames ( % d ) for frameref bit field : % S " , i , uttframes , frameref : : maxframesperutterance , key . c_str ( ) ) ; <nl> / / continue ; <nl> - / / } <nl> + / / } <nl> <nl> / / check whether we have the ref transcript <nl> - / / auto labelsiter = labels [ 0 ] . end ( ) ; <nl> + / / auto labelsiter = labels [ 0 ] . end ( ) ; <nl> bool lacksmlf = true ; <nl> if ( ! labels . empty ( ) ) / / empty means unsupervised mode ( don ' t load any ) <nl> { <nl> key = utterance . key ( ) ; <nl> / / check if labels are available ( if not , it normally means that no path was found in realignment ) <nl> auto labelsiter = labels [ 0 ] . find ( key ) ; <nl> - / / const bool lacksmlf = ( labelsiter = = labels [ 0 ] . end ( ) ) ; <nl> + / / const bool lacksmlf = ( labelsiter = = labels [ 0 ] . end ( ) ) ; <nl> lacksmlf = ( labelsiter = = labels [ 0 ] . end ( ) ) ; <nl> if ( lacksmlf ) <nl> if ( nomlf + + < 5 ) <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> if ( m = = 0 ) <nl> { <nl> if ( ! labels . empty ( ) & & ! lacksmlf ) <nl> - / / if ( ! labels . empty ( ) & & labelsiter ! = labels [ 0 ] . end ( ) ) <nl> + / / if ( ! labels . empty ( ) & & labelsiter ! = labels [ 0 ] . end ( ) ) <nl> { <nl> / / first verify that all the label files have the proper duration <nl> foreach_index ( j , labels ) <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> biggrowablevector < CLASSIDTYPE > & cid = * classids [ j ] ; <nl> foreach_index ( i , utteranceset ) <nl> { <nl> - / / if ( ( * classids [ j ] ) [ utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ] ! = ( CLASSIDTYPE ) - 1 ) <nl> - / / printf ( " index = % d \ n " , utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ) ; <nl> - / / printf ( " cid [ index ] = % d \ n " , cid [ utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ] ) ; <nl> - / / printf ( " CLASSIDTYPE ( - 1 ) = % d \ n " , ( CLASSIDTYPE ) - 1 ) ; <nl> + / / if ( ( * classids [ j ] ) [ utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ] ! = ( CLASSIDTYPE ) - 1 ) <nl> + / / printf ( " index = % d \ n " , utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ) ; <nl> + / / printf ( " cid [ index ] = % d \ n " , cid [ utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ] ) ; <nl> + / / printf ( " CLASSIDTYPE ( - 1 ) = % d \ n " , ( CLASSIDTYPE ) - 1 ) ; <nl> if ( cid [ utteranceset [ i ] . classidsbegin + utteranceset [ i ] . numframes ( ) ] ! = ( CLASSIDTYPE ) - 1 ) <nl> throw std : : logic_error ( " minibatchutterancesource : classids [ ] out of sync " ) ; <nl> } <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> / / Loading an initial 24 - hour range will involve 96 disk seeks , acceptable . <nl> / / When paging chunk by chunk , chunk size ~ 14 MB . <nl> std : : vector < utterancechunkdata > & thisallchunks = allchunks [ m ] ; <nl> - / / std : : vector < utterancechunkdata > thisallchunks ; <nl> + / / std : : vector < utterancechunkdata > thisallchunks ; <nl> <nl> thisallchunks . resize ( 0 ) ; <nl> thisallchunks . reserve ( _totalframes / chunkframes ) ; <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> } <nl> } <nl> } <nl> - # endif / / 0 <nl> + # endif / / 0 <nl> static void checkoverflow ( size_t fieldval , size_t targetval , const char * fieldname ) <nl> { <nl> if ( fieldval ! = targetval ) <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> <nl> size_t chunkforframepos ( const size_t t ) const / / find chunk for a given frame position <nl> { <nl> - / / inspect chunk of first feature stream only <nl> + / / inspect chunk of first feature stream only <nl> auto iter = std : : lower_bound ( randomizedchunks [ 0 ] . begin ( ) , randomizedchunks [ 0 ] . end ( ) , t , [ & ] ( const chunk & chunk , size_t t ) <nl> { <nl> return chunk . globalte ( ) < = t ; <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> / / We specify the utterance by its global start time ( in a space of a infinitely repeated training set ) . <nl> / / This is efficient since getbatch ( ) is called with sequential ' globalts ' except at epoch start . <nl> / / Note that the start of an epoch does not necessarily fall onto an utterance boundary . The caller must use firstvalidglobalts ( ) to find the first valid globalts at or after a given time . <nl> - / / <nl> - / / <nl> + / / <nl> + / / <nl> / * implement * / bool getbatch ( const size_t globalts , const size_t framesrequested , std : : vector < msra : : dbn : : matrix > & feat , <nl> std : : vector < std : : vector < size_t > > & uids , std : : vector < std : : pair < wstring , size_t > > & utteranceinfo , <nl> std : : vector < const_array_ref < msra : : lattices : : lattice : : htkmlfwordsequence : : word > > & transcripts , <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> } <nl> } <nl> / / return these utterances <nl> - / / fprintf ( stderr , " getbatch : getting utterances % d . . % d ( % d frames out of % d requested ) in sweep % d \ n " , spos , epos - 1 , mbframes , framesrequested , sweep ) ; <nl> + / / fprintf ( stderr , " getbatch : getting utterances % d . . % d ( % d frames out of % d requested ) in sweep % d \ n " , spos , epos - 1 , mbframes , framesrequested , sweep ) ; <nl> size_t tspos = 0 ; / / relative start of utterance ' pos ' within the returned minibatch <nl> for ( size_t pos = spos ; pos < epos ; pos + + ) <nl> { <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> rightextent = rightcontext [ i ] ; <nl> } <nl> augmentneighbors ( uttframevectors , noboundaryflags , t , leftextent , rightextent , feat [ i ] , t + tspos ) ; <nl> - / / augmentneighbors ( uttframevectors , noboundaryflags , t , feat [ i ] , t + tspos ) ; <nl> + / / augmentneighbors ( uttframevectors , noboundaryflags , t , feat [ i ] , t + tspos ) ; <nl> } <nl> <nl> / / copy the frames and class labels <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> } <nl> assert ( tspos = = mbframes ) ; <nl> } <nl> - else / / / / debug mode returning randomized frames again , to see whether convergence is better ( we don ' t ensure non - repetition at this point ) <nl> + else / / / / debug mode returning randomized frames again , to see whether convergence is better ( we don ' t ensure non - repetition at this point ) <nl> { <nl> const size_t sweepts = sweep * _totalframes ; / / first global frame index for this sweep <nl> const size_t sweepte = sweepts + _totalframes ; / / and its end <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> } <nl> augmentneighbors ( uttframevectors , noboundaryflags , t , leftextent , rightextent , feat [ i ] , j ) ; <nl> <nl> - / / augmentneighbors ( uttframevectors , noboundaryflags , t , feat [ i ] , j ) ; <nl> + / / augmentneighbors ( uttframevectors , noboundaryflags , t , feat [ i ] , j ) ; <nl> if ( issupervised ( ) & & i = = 0 ) <nl> { <nl> auto frameclassids = getclassids ( frameref ) ; <nl> class minibatchutterancesourcemulti : public minibatchsource <nl> throw runtime_error ( " minibatchframesourcemulti : getbatch ( ) being called for single input feature and single output feature , should use minibatchutterancesource instead \ n " ) ; <nl> <nl> / / for single input / output set size to be 1 and run old getbatch <nl> - / / feat . resize ( 1 ) ; <nl> - / / uids . resize ( 1 ) ; <nl> - / / return getbatch ( globalts , framesrequested , feat [ 0 ] , uids [ 0 ] , transcripts , latticepairs ) ; <nl> + / / feat . resize ( 1 ) ; <nl> + / / uids . resize ( 1 ) ; <nl> + / / return getbatch ( globalts , framesrequested , feat [ 0 ] , uids [ 0 ] , transcripts , latticepairs ) ; <nl> } <nl> size_t totalframes ( ) const <nl> { <nl> mmm a / Source / Readers / LMSequenceReader / SequenceParser . cpp <nl> ppp b / Source / Readers / LMSequenceReader / SequenceParser . cpp <nl> void SequenceParser < NumType , LabelType > : : SetStateRange ( int value1 , int value2 , P <nl> template < typename NumType , typename LabelType > <nl> void SequenceParser < NumType , LabelType > : : SetupStateTables ( ) <nl> { <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = WHITESPACE <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , Whitespace , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , Whitespace , WholeNumber ) ; <nl> void SequenceParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' : ' , Whitespace , Whitespace ) ; / / intepret ' : ' as white space because it ' s a divider <nl> SetState ( ' \ n ' , Whitespace , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = NEGATIVE_SIGN <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , Sign , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , Sign , WholeNumber ) ; <nl> void SequenceParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ r ' , Sign , Whitespace ) ; <nl> SetState ( ' \ n ' , Sign , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = NUMBER <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , WholeNumber , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , WholeNumber , WholeNumber ) ; <nl> void SequenceParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' : ' , WholeNumber , Whitespace ) ; / / Add for 1234 : 0 . 9 usage in Sequences <nl> SetState ( ' \ n ' , WholeNumber , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = PERIOD <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , Period , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , Period , Remainder ) ; <nl> void SequenceParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ r ' , Period , Whitespace ) ; <nl> SetState ( ' \ n ' , Period , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = REMAINDER <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , Remainder , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , Remainder , Remainder ) ; <nl> void SequenceParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' : ' , Remainder , Whitespace ) ; / / Add for 1234 : 0 . 9 usage in Sequences <nl> SetState ( ' \ n ' , Remainder , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = THE_LETTER_E <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , TheLetterE , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , TheLetterE , Exponent ) ; <nl> void SequenceParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ r ' , TheLetterE , Whitespace ) ; <nl> SetState ( ' \ n ' , TheLetterE , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = EXPONENT_NEGATIVE_SIGN <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , ExponentSign , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , ExponentSign , Exponent ) ; <nl> void SequenceParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ r ' , ExponentSign , Whitespace ) ; <nl> SetState ( ' \ n ' , ExponentSign , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = EXPONENT <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , Exponent , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , Exponent , Exponent ) ; <nl> void SequenceParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' : ' , Exponent , Whitespace ) ; <nl> SetState ( ' \ n ' , Exponent , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = END_OF_LINE <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> SetStateRange ( 0 , 255 , EndOfLine , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , EndOfLine , WholeNumber ) ; <nl> SetState ( ' - ' , EndOfLine , Sign ) ; <nl> void SequenceParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ t ' , EndOfLine , Whitespace ) ; <nl> SetState ( ' \ r ' , EndOfLine , Whitespace ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = LABEL <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> SetStateRange ( 0 , 255 , Label , Label ) ; <nl> SetState ( ' \ n ' , Label , EndOfLine ) ; <nl> / / whitespace <nl> void SequenceParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ r ' , Label , Whitespace ) ; <nl> SetState ( ' : ' , Label , Whitespace ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = LINE_COUNT_EOL <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> SetStateRange ( 0 , 255 , LineCountEOL , LineCountOther ) ; <nl> SetState ( ' \ n ' , LineCountEOL , LineCountEOL ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = LINE_COUNT_OTHER <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> SetStateRange ( 0 , 255 , LineCountOther , LineCountOther ) ; <nl> SetState ( ' \ n ' , LineCountOther , LineCountEOL ) ; <nl> } <nl> void SequenceParser < NumType , LabelType > : : DoneWithValue ( ) <nl> <nl> / / TODO : In sequence reader we probably don ' t need to store numbers in labels ( we ' ll see ) <nl> / / if it ' s a label , store in label location instead of number location <nl> - / / int index = m_elementsConvertedThisLine ; <nl> - / / if ( m_startLabels < = index & & index < m_startLabels + m_dimLabels ) <nl> - / / { <nl> + / / int index = m_elementsConvertedThisLine ; <nl> + / / if ( m_startLabels < = index & & index < m_startLabels + m_dimLabels ) <nl> + / / { <nl> / / StoreLabel ( FinalResult ) ; <nl> - / / } <nl> - / / if ( m_startFeatures < = index & & index < m_startFeatures + m_dimFeatures ) <nl> + / / } <nl> + / / if ( m_startFeatures < = index & & index < m_startFeatures + m_dimFeatures ) <nl> { <nl> m_numbers - > push_back ( FinalResult ) ; <nl> m_totalNumbersConverted + + ; <nl> int wmain ( int argc , wchar_t * argv [ ] ) <nl> std : : vector < int > labels ; <nl> labels . reserve ( 60000 ) ; <nl> parser . ParseInit ( L " c : \ \ speech \ \ mnist \ \ mnist_train . txt " , LabelFirst ) ; <nl> - / / parser . ParseInit ( " c : \ \ speech \ \ parseTest . txt " , LabelNone ) ; <nl> + / / parser . ParseInit ( " c : \ \ speech \ \ parseTest . txt " , LabelNone ) ; <nl> int records = 0 ; <nl> do <nl> { <nl> mmm a / Source / Readers / LMSequenceReader / SequenceParser . h <nl> ppp b / Source / Readers / LMSequenceReader / SequenceParser . h <nl> class SequenceParser <nl> case Whitespace : <nl> m_spaceDelimitedMax = m_byteCounter ; <nl> / / hit whitespace and nobody processed anything , so add as label <nl> - / / if ( m_elementsConvertedThisLine = = elementsProcessed ) <nl> + / / if ( m_elementsConvertedThisLine = = elementsProcessed ) <nl> / / DoneWithLabel ( ) ; <nl> break ; <nl> case EndOfLine : <nl> class SequenceParser <nl> { <nl> m_spaceDelimitedMax = m_byteCounter ; <nl> / / hit whitespace and nobody processed anything , so add as label <nl> - / / if ( m_elementsConvertedThisLine = = elementsProcessed ) <nl> + / / if ( m_elementsConvertedThisLine = = elementsProcessed ) <nl> / / DoneWithLabel ( ) ; <nl> } <nl> / / process the label at the end of a line <nl> - / / if ( m_labelMode = = LabelLast & & m_labels ! = NULL ) <nl> - / / { <nl> + / / if ( m_labelMode = = LabelLast & & m_labels ! = NULL ) <nl> + / / { <nl> / / StoreLastLabel ( ) ; <nl> - / / } <nl> + / / } <nl> / / intentional fall - through <nl> case LineCountEOL : <nl> lineCount + + ; / / done with another record <nl> mmm a / Source / Readers / LMSequenceReader / SequenceReader . cpp <nl> ppp b / Source / Readers / LMSequenceReader / SequenceReader . cpp <nl> bool SequenceReader < ElemType > : : EnsureDataAvailable ( size_t mbStartSample , bool / * <nl> } <nl> LabelInfo & labelInfo = m_labelInfo [ nextWord ? labelInfoIn : labelInfoOut ] ; <nl> <nl> - / / if ( m_labelIdData . size ( ) > epochSample ) <nl> - / / { <nl> + / / if ( m_labelIdData . size ( ) > epochSample ) <nl> + / / { <nl> / / m_labelIdData . resize ( epochSample ) ; <nl> / / m_labelData . resize ( epochSample * labelInfo . dim ) ; <nl> - / / } <nl> + / / } <nl> <nl> / / see how many we already read <nl> int sequencesRead = 0 ; <nl> bool SequenceReader < ElemType > : : EnsureDataAvailable ( size_t mbStartSample , bool / * <nl> m_sequence . push_back ( epochSample ) ; <nl> if ( ( m_sequence . size ( ) = = 1 ? epochSample : epochSample - m_sequence [ m_sequence . size ( ) - 2 ] ) > m_mbSize ) <nl> { <nl> - / / fprintf ( stderr , " read sentence length is longer than the minibatch size . should be smaller . increase the minibatch size to at least % d " , epochSample ) ; <nl> + / / fprintf ( stderr , " read sentence length is longer than the minibatch size . should be smaller . increase the minibatch size to at least % d " , epochSample ) ; <nl> <nl> std : : wcerr < < " read sentence length is longer than the minibatch size . should be smaller . increase the minibatch size to at least " < < epochSample < < endl ; <nl> RuntimeError ( " read sentence length is longer than the minibatch size . should be smaller . increase the minibatch size to at least % d " , ( int ) epochSample ) ; <nl> void SequenceReader < ElemType > : : WriteLabelFile ( ) <nl> } <nl> else if ( ! m_cachingWriter ) <nl> { <nl> - / / fprintf ( stderr , " WARNING : file % ls NOT written to disk , label files only written when starting at epoch zero ! " , labelInfo . fileToWrite . c_str ( ) ) ; <nl> + / / fprintf ( stderr , " WARNING : file % ls NOT written to disk , label files only written when starting at epoch zero ! " , labelInfo . fileToWrite . c_str ( ) ) ; <nl> std : : wcerr < < " WARNING : file " < < labelInfo . fileToWrite . c_str ( ) < < " NOT written to disk , label files only written when starting at epoch zero ! " < < endl ; <nl> } <nl> } <nl> void SequenceReader < ElemType > : : InitFromConfig ( const ConfigRecordType & readerConf <nl> / / NOTE : probably want to re - enable at some point <nl> <nl> / / initialize the cache <nl> - / / InitCache ( readerConfig ) ; <nl> - / / m_readerConfig = readerConfig ; <nl> + / / InitCache ( readerConfig ) ; <nl> + / / m_readerConfig = readerConfig ; <nl> <nl> - / / / / if we have a cache , no need to parse the test files . . . <nl> - / / if ( m_cachingReader ) <nl> + / / / / if we have a cache , no need to parse the test files . . . <nl> + / / if ( m_cachingReader ) <nl> / / return ; <nl> <nl> std : : vector < std : : wstring > features ; <nl> void SequenceReader < ElemType > : : InitFromConfig ( const ConfigRecordType & readerConf <nl> if ( m_traceLevel > 0 ) <nl> { <nl> fprintf ( stderr , " reading sequence file % ls \ n " , m_file . c_str ( ) ) ; <nl> - / / std : : wcerr < < " reading sequence file " < < m_file . c_str ( ) < < endl ; <nl> + / / std : : wcerr < < " reading sequence file " < < m_file . c_str ( ) < < endl ; <nl> } <nl> <nl> const LabelInfo & labelIn = m_labelInfo [ labelInfoIn ] ; <nl> void SequenceReader < ElemType > : : ReadWord ( char * word , FILE * fin ) <nl> <nl> if ( a > = MAX_STRING ) <nl> { <nl> - / / printf ( " Too long word found ! \ n " ) ; / / truncate too long words <nl> + / / printf ( " Too long word found ! \ n " ) ; / / truncate too long words <nl> a - - ; <nl> } <nl> } <nl> void SequenceReader < ElemType > : : GetInputProb ( std : : map < std : : wstring , Matrix < ElemTy <nl> m_id2Prob - > SwitchToMatrixType ( MatrixType : : DENSE , matrixFormatDense , false ) ; <nl> m_id2Prob - > Resize ( nwords , 1 , false ) ; <nl> <nl> - / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> + / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> int curDevId = m_id2Prob - > GetDeviceId ( ) ; <nl> m_id2Prob - > TransferFromDeviceToDevice ( curDevId , CPUDEVICE , true , false , false ) ; <nl> for ( size_t j = 0 ; j < nwords ; j + + ) <nl> void SequenceReader < ElemType > : : GetInputToClass ( std : : map < std : : wstring , Matrix < Ele <nl> m_id2classLocal - > SwitchToMatrixType ( MatrixType : : DENSE , matrixFormatDense , false ) ; <nl> m_id2classLocal - > Resize ( nwords , 1 , false ) ; <nl> <nl> - / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> + / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> int curDevId = m_id2classLocal - > GetDeviceId ( ) ; <nl> m_id2classLocal - > TransferFromDeviceToDevice ( curDevId , CPUDEVICE , true , false , false ) ; <nl> for ( size_t j = 0 ; j < nwords ; j + + ) <nl> void SequenceReader < ElemType > : : GetClassInfo ( ) <nl> m_classInfoLocal - > SwitchToMatrixType ( MatrixType : : DENSE , matrixFormatDense , false ) ; <nl> m_classInfoLocal - > Resize ( 2 , class_size ) ; <nl> <nl> - / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> + / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> int curDevId = m_classInfoLocal - > GetDeviceId ( ) ; <nl> m_classInfoLocal - > TransferFromDeviceToDevice ( curDevId , CPUDEVICE , true , false , false ) ; <nl> <nl> void BatchSequenceReader < ElemType > : : InitFromConfig ( const ConfigRecordType & reade <nl> / / NOTE : probably want to re - enable at some point <nl> <nl> / / initialize the cache <nl> - / / InitCache ( readerConfig ) ; <nl> - / / m_readerConfig = readerConfig ; <nl> + / / InitCache ( readerConfig ) ; <nl> + / / m_readerConfig = readerConfig ; <nl> <nl> - / / / / if we have a cache , no need to parse the test files . . . <nl> - / / if ( m_cachingReader ) <nl> + / / / / if we have a cache , no need to parse the test files . . . <nl> + / / if ( m_cachingReader ) <nl> / / return ; <nl> <nl> std : : vector < std : : wstring > features ; <nl> void BatchSequenceReader < ElemType > : : InitFromConfig ( const ConfigRecordType & reade <nl> RuntimeError ( " two label definitions ( in and out ) required for Sequence Reader " ) ; <nl> <nl> const ConfigRecordType & featureConfig = readerConfig ( m_featuresName . c_str ( ) , ConfigRecordType : : Record ( ) ) ; <nl> - wstring mode = featureConfig ( L " mode " , L " class " ) ; / / class , softmax , nce <nl> + wstring mode = featureConfig ( L " mode " , L " class " ) ; / / class , softmax , nce <nl> std : : transform ( mode . begin ( ) , mode . end ( ) , mode . begin ( ) , : : tolower ) ; <nl> <nl> if ( mode = = L " nce " ) <nl> void BatchSequenceReader < ElemType > : : InitFromConfig ( const ConfigRecordType & reade <nl> } <nl> else <nl> { <nl> - ; / / readerConfig ( L " randomize " ) ; <nl> + ; / / readerConfig ( L " randomize " ) ; <nl> } <nl> } <nl> else <nl> { <nl> - ; / / randomizeAuto ; <nl> + ; / / randomizeAuto ; <nl> } <nl> <nl> / / The input data is a combination of the label Data and extra feature dims together <nl> void BatchSequenceReader < ElemType > : : InitFromConfig ( const ConfigRecordType & reade <nl> if ( m_traceLevel > 0 ) <nl> { <nl> fwprintf ( stderr , L " reading sequence file % s \ n " , m_file . c_str ( ) ) ; <nl> - / / std : : wcerr < < " reading sequence file " < < m_file . c_str ( ) < < endl ; <nl> + / / std : : wcerr < < " reading sequence file " < < m_file . c_str ( ) < < endl ; <nl> } <nl> <nl> const LabelInfo & labelIn = m_labelInfo [ labelInfoIn ] ; <nl> bool BatchSequenceReader < ElemType > : : GetMinibatch ( std : : map < std : : wstring , Matrix < E <nl> <nl> if ( actualmbsize > 0 ) <nl> { <nl> - / / loop through all the samples <nl> + / / loop through all the samples <nl> Matrix < ElemType > & features = * matrices [ m_featuresName ] ; <nl> <nl> / / create MBLayout <nl> bool BatchSequenceReader < ElemType > : : GetMinibatch ( std : : map < std : : wstring , Matrix < E <nl> features . SetValue ( idx , j , ( ElemType ) 1 ) ; <nl> <nl> / / actual time position <nl> - / / size_t timeIdx = ( size_t ) j / mToProcess . size ( ) ; <nl> - / / size_t uttIdx = ( size_t ) fmod ( j , mToProcess . size ( ) ) ; / / parallel - sequence index <nl> + / / size_t timeIdx = ( size_t ) j / mToProcess . size ( ) ; <nl> + / / size_t uttIdx = ( size_t ) fmod ( j , mToProcess . size ( ) ) ; / / parallel - sequence index <nl> } <nl> <nl> features . TransferFromDeviceToDevice ( CPUDEVICE , featureDeviceId , false , false , false ) ; <nl> void BatchSequenceReader < ElemType > : : SetSentenceBegin ( int wrd , int uttPos , int ti <nl> / / BUGBUG : This is currently not functional . Nothing in here marks gaps , nor sets any end flags . <nl> uttPos ; <nl> LogicError ( " BatchSequenceReader : : SetSentenceBegin ( ) : Disabled because this implementation seems out of date w . r . t . setting end and gap flags . " ) ; <nl> - / / m_pMBLayout - > SetWithoutOr ( uttPos , timePos , MinibatchPackingFlags : : SequenceStart ) ; / / TODO : can we use Set ( ) ( with OR ) ? <nl> + / / m_pMBLayout - > SetWithoutOr ( uttPos , timePos , MinibatchPackingFlags : : SequenceStart ) ; / / TODO : can we use Set ( ) ( with OR ) ? <nl> } <nl> } <nl> } <nl> void BatchSequenceReader < ElemType > : : GetLabelOutput ( std : : map < std : : wstring , <nl> else <nl> labels - > Resize ( 1 , actualmbsize , false ) ; <nl> <nl> - / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> + / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> int curDevId = labels - > GetDeviceId ( ) ; <nl> labels - > TransferFromDeviceToDevice ( curDevId , CPUDEVICE , true , false , false ) ; <nl> ElemType epsilon = ( ElemType ) 1e - 6 ; / / avoid all zero , although this is almost impossible . <nl> mmm a / Source / Readers / LMSequenceReader / SequenceReader . h <nl> ppp b / Source / Readers / LMSequenceReader / SequenceReader . h <nl> class SequenceReader : public IDataReader < ElemType > <nl> virtual void StartMinibatchLoop ( size_t mbSize , size_t epoch , size_t requestedEpochSamples = requestDataSize ) ; <nl> virtual bool GetMinibatch ( std : : map < std : : wstring , Matrix < ElemType > * > & matrices ) ; <nl> <nl> - / / void SetSentenceSegBatch ( std : : vector < size_t > & / * sentenceEnd * / ) { } ; <nl> + / / void SetSentenceSegBatch ( std : : vector < size_t > & / * sentenceEnd * / ) { } ; <nl> / / TODO : ^ ^ should this be void CopyMBLayoutTo ( MBLayoutPtr pMBLayout ) ; <nl> virtual const std : : map < LabelIdType , LabelType > & GetLabelMapping ( const std : : wstring & sectionName ) ; <nl> virtual void SetLabelMapping ( const std : : wstring & sectionName , const std : : map < LabelIdType , LabelType > & labelMapping ) ; <nl> mmm a / Source / Readers / LUSequenceReader / LUSequenceReader . cpp <nl> ppp b / Source / Readers / LUSequenceReader / LUSequenceReader . cpp <nl> void BatchLUSequenceReader < ElemType > : : GetClassInfo ( LabelInfo & lblInfo ) <nl> lblInfo . m_classInfoLocal - > Resize ( 2 , lblInfo . mNbrClasses ) ; <nl> lblInfo . m_classInfoLocal - > SetValue ( 0 ) ; / / TODO : needed ? ( left - over of refactoring ) <nl> <nl> - / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> + / / move to CPU since element - wise operation is expensive and can go wrong in GPU <nl> / / TODO : Can it ever be not on the CPU ? We allocate it ourselves abovew <nl> int curDevId = lblInfo . m_classInfoLocal - > GetDeviceId ( ) ; <nl> lblInfo . m_classInfoLocal - > TransferFromDeviceToDevice ( curDevId , CPUDEVICE , true , false , false ) ; <nl> void BatchLUSequenceReader < ElemType > : : InitFromConfig ( const ConfigRecordType & rea <nl> else <nl> RuntimeError ( " two label definitions ( in and out ) required for Sequence Reader " ) ; <nl> <nl> - / / const ConfigRecordType & featureConfig = readerConfig ( m_featuresName . c_str ( ) , ConfigRecordType : : Record ( ) ) ; <nl> + / / const ConfigRecordType & featureConfig = readerConfig ( m_featuresName . c_str ( ) , ConfigRecordType : : Record ( ) ) ; <nl> <nl> for ( int index = labelInfoMin ; index < labelInfoMax ; + + index ) <nl> { <nl> void BatchLUSequenceReader < ElemType > : : InitFromConfig ( const ConfigRecordType & rea <nl> / / if we have labels , we need a label Mapping file , it will be a file with one label per line <nl> if ( m_labelInfo [ index ] . type ! = labelNone ) <nl> { <nl> - wstring mode = labelConfig ( L " mode " , L " plain " ) ; / / plain , class <nl> + wstring mode = labelConfig ( L " mode " , L " plain " ) ; / / plain , class <nl> <nl> m_labelInfo [ index ] . m_classInfoLocal = nullptr ; <nl> m_labelInfo [ index ] . m_id2classLocal = nullptr ; <nl> void BatchLUSequenceReader < ElemType > : : StartMinibatchLoop ( size_t mbSize , size_t e <nl> { <nl> const LabelInfo & labelInfo = m_labelInfo [ ( m_labelInfo [ labelInfoOut ] . type = = labelNextWord ) ? labelInfoIn : labelInfoOut ] ; <nl> m_featuresBuffer = new ElemType [ mbSize * labelInfo . dim ] ( ) ; <nl> - / / memset ( m_featuresBuffer , 0 , sizeof ( ElemType ) * mbSize * labelInfo . dim ) ; <nl> + / / memset ( m_featuresBuffer , 0 , sizeof ( ElemType ) * mbSize * labelInfo . dim ) ; <nl> } <nl> <nl> if ( m_labelsBuffer = = NULL ) <nl> void BatchLUSequenceReader < ElemType > : : StartMinibatchLoop ( size_t mbSize , size_t e <nl> if ( labelInfo . type = = labelCategory ) <nl> { <nl> m_labelsBuffer = new ElemType [ labelInfo . dim * mbSize ] ( ) ; <nl> - / / memset ( m_labelsBuffer , 0 , sizeof ( ElemType ) * labelInfo . dim * mbSize ) ; <nl> + / / memset ( m_labelsBuffer , 0 , sizeof ( ElemType ) * labelInfo . dim * mbSize ) ; <nl> m_labelsIdBuffer = new long [ mbSize ] ( ) ; <nl> - / / memset ( m_labelsIdBuffer , 0 , sizeof ( long ) * mbSize ) ; <nl> + / / memset ( m_labelsIdBuffer , 0 , sizeof ( long ) * mbSize ) ; <nl> } <nl> else if ( labelInfo . type ! = labelNone ) <nl> { <nl> m_labelsBuffer = new ElemType [ mbSize ] ( ) ; <nl> - / / memset ( m_labelsBuffer , 0 , sizeof ( ElemType ) * mbSize ) ; <nl> + / / memset ( m_labelsBuffer , 0 , sizeof ( ElemType ) * mbSize ) ; <nl> m_labelsIdBuffer = NULL ; <nl> } <nl> } <nl> bool BatchLUSequenceReader < ElemType > : : EnsureDataAvailable ( size_t / * mbStartSample <nl> <nl> m_labelIdData . push_back ( ( LabelIdType ) NULLLABEL ) ; <nl> <nl> - / / m_pMBLayout - > Set ( k , j , MinibatchPackingFlags : : NoInput ) ; <nl> + / / m_pMBLayout - > Set ( k , j , MinibatchPackingFlags : : NoInput ) ; <nl> } <nl> } <nl> } <nl> bool BatchLUSequenceReader < ElemType > : : GetMinibatch ( std : : map < std : : wstring , Matrix <nl> if ( t > mSentenceEndAt [ s ] | | idx > = featInfo . dim ) <nl> { <nl> assert ( idx = = ( LabelIdType ) NULLLABEL ) ; / / TODO : what other conditions ? <nl> - / / if ( ! m_pMBLayout - > IsGap ( s , t ) ) / / verify that these are marked as NoInput <nl> + / / if ( ! m_pMBLayout - > IsGap ( s , t ) ) / / verify that these are marked as NoInput <nl> / / LogicError ( " BatchLUSequenceReader : : GetMinibatch observation is larger than its dimension but no_labels sign is not used to indicate that this observation has no labels . Possible reason is a bug in EnsureDataAvailable or a bug here . " ) ; <nl> continue ; <nl> } <nl> <nl> - / / if ( m_pMBLayout - > IsGap ( s , t ) ) / / verify that these are marked as NoInput <nl> + / / if ( m_pMBLayout - > IsGap ( s , t ) ) / / verify that these are marked as NoInput <nl> / / LogicError ( " BatchLUSequenceReader : : GetMinibatch : Inconsistent NoInput flag " ) ; <nl> <nl> locObs . SetValue ( idx + jj * featInfo . dim , j , ( ElemType ) 1 ) ; <nl> bool BatchLUSequenceReader < ElemType > : : GetFrame ( std : : map < std : : wstring , Matrix < Ele <nl> { <nl> const LabelInfo & featInfo = m_labelInfo [ labelInfoIn ] ; <nl> <nl> - / / loop through all the samples <nl> + / / loop through all the samples <nl> Matrix < ElemType > & features = * matrices [ m_featuresName ] ; <nl> Matrix < ElemType > locObs ( CPUDEVICE ) ; <nl> locObs . SwitchToMatrixType ( SPARSE , matrixFormatSparseCSC , false ) ; <nl> mmm a / Source / Readers / LibSVMBinaryReader / LibSVMBinaryReader . cpp <nl> ppp b / Source / Readers / LibSVMBinaryReader / LibSVMBinaryReader . cpp <nl> template < class ElemType > <nl> DenseBinaryMatrix < ElemType > : : DenseBinaryMatrix ( wstring name , int deviceID , size_t numRows , size_t numCols ) <nl> : BinaryMatrix < ElemType > ( name , deviceID , numRows , numCols ) <nl> { <nl> - / / this - > m_values = ( ElemType * ) malloc ( sizeof ( ElemType ) * numRows * numCols ) ; <nl> + / / this - > m_values = ( ElemType * ) malloc ( sizeof ( ElemType ) * numRows * numCols ) ; <nl> this - > m_values = ( ElemType * ) CUDAPageLockedMemAllocator : : Malloc ( sizeof ( ElemType ) * numRows * numCols , deviceID ) ; <nl> } <nl> <nl> void DenseBinaryMatrix < ElemType > : : Dispose ( ) <nl> { <nl> if ( this - > m_values ! = nullptr ) <nl> { <nl> - / / free ( this - > m_values ) ; <nl> + / / free ( this - > m_values ) ; <nl> CUDAPageLockedMemAllocator : : Free ( this - > m_values , this - > m_deviceID ) ; <nl> } <nl> this - > m_values = nullptr ; <nl> void DenseBinaryMatrix < ElemType > : : SetMaxRows ( size_t maxRows ) <nl> { <nl> if ( maxRows > this - > m_maxNumRows ) <nl> { <nl> - / / ElemType * values = ( ElemType * ) malloc ( sizeof ( ElemType ) * this - > m_maxNumCols * maxRows ) ; <nl> + / / ElemType * values = ( ElemType * ) malloc ( sizeof ( ElemType ) * this - > m_maxNumCols * maxRows ) ; <nl> ElemType * values = ( ElemType * ) CUDAPageLockedMemAllocator : : Malloc ( sizeof ( ElemType ) * this - > m_maxNumCols * maxRows , this - > m_deviceID ) ; <nl> if ( this - > m_values ! = nullptr ) <nl> { <nl> void DenseBinaryMatrix < ElemType > : : SetMaxRows ( size_t maxRows ) <nl> { <nl> memcpy ( values , this - > m_values , sizeof ( ElemType ) * this - > m_numRows * this - > m_maxNumCols ) ; <nl> } <nl> - / / free ( this - > m_values ) ; <nl> + / / free ( this - > m_values ) ; <nl> CUDAPageLockedMemAllocator : : Free ( this - > m_values , this - > m_deviceID ) ; <nl> } <nl> this - > m_values = values ; <nl> template < class ElemType > <nl> SparseBinaryMatrix < ElemType > : : SparseBinaryMatrix ( wstring name , int deviceId , size_t numRows , size_t numCols ) <nl> : BinaryMatrix < ElemType > ( name , deviceId , numRows , numCols ) , m_rowIndices ( nullptr ) , m_colIndices ( nullptr ) , m_nnz ( 0 ) , m_maxNNz ( 0 ) <nl> { <nl> - / / m_colIndices = ( int32_t * ) malloc ( sizeof ( int32_t ) * ( numRows + 1 ) ) ; <nl> + / / m_colIndices = ( int32_t * ) malloc ( sizeof ( int32_t ) * ( numRows + 1 ) ) ; <nl> m_colIndices = ( int32_t * ) CUDAPageLockedMemAllocator : : Malloc ( sizeof ( int32_t ) * ( numRows + 1 ) , deviceId ) ; <nl> m_colIndices [ 0 ] = 0 ; <nl> } <nl> void SparseBinaryMatrix < ElemType > : : Dispose ( ) <nl> { <nl> if ( this - > m_values ! = nullptr ) <nl> { <nl> - / / free ( this - > m_values ) ; <nl> + / / free ( this - > m_values ) ; <nl> CUDAPageLockedMemAllocator : : Free ( this - > m_values , this - > m_deviceID ) ; <nl> } <nl> this - > m_values = nullptr ; <nl> if ( m_colIndices ! = nullptr ) <nl> { <nl> - / / free ( m_colIndices ) ; <nl> + / / free ( m_colIndices ) ; <nl> CUDAPageLockedMemAllocator : : Free ( this - > m_colIndices , this - > m_deviceID ) ; <nl> } <nl> m_colIndices = nullptr ; <nl> if ( m_rowIndices ! = nullptr ) <nl> { <nl> - / / free ( m_rowIndices ) ; <nl> + / / free ( m_rowIndices ) ; <nl> CUDAPageLockedMemAllocator : : Free ( this - > m_rowIndices , this - > m_deviceID ) ; <nl> } <nl> m_rowIndices = nullptr ; <nl> void SparseBinaryMatrix < ElemType > : : SetMaxRows ( size_t maxRows ) <nl> { <nl> if ( maxRows > this - > m_maxNumRows ) <nl> { <nl> - / / int32_t * colIndices = ( int32_t * ) malloc ( sizeof ( int32_t ) * ( maxRows + 1 ) ) ; <nl> + / / int32_t * colIndices = ( int32_t * ) malloc ( sizeof ( int32_t ) * ( maxRows + 1 ) ) ; <nl> int32_t * colIndices = ( int32_t * ) CUDAPageLockedMemAllocator : : Malloc ( sizeof ( int32_t ) * ( maxRows + 1 ) , this - > m_deviceID ) ; <nl> if ( this - > m_colIndices ! = nullptr ) <nl> { <nl> void SparseBinaryMatrix < ElemType > : : SetMaxRows ( size_t maxRows ) <nl> { <nl> memcpy ( colIndices , m_colIndices , sizeof ( int32_t ) * ( this - > m_numRows + 1 ) ) ; <nl> } <nl> - / / free ( this - > m_colIndices ) ; <nl> + / / free ( this - > m_colIndices ) ; <nl> CUDAPageLockedMemAllocator : : Free ( this - > m_colIndices , this - > m_deviceID ) ; <nl> } <nl> this - > m_colIndices = colIndices ; <nl> void SparseBinaryMatrix < ElemType > : : ResizeArrays ( size_t newNNz ) <nl> return ; <nl> } <nl> size_t newMaxNNz = ( size_t ) ( ( newNNz + m_nnz ) * 1 . 3 ) ; <nl> - / / int32_t * rowIndices = ( int32_t * ) malloc ( sizeof ( int32_t ) * newMaxNNz ) ; <nl> - / / ElemType * values = ( ElemType * ) malloc ( sizeof ( ElemType ) * newMaxNNz ) ; <nl> + / / int32_t * rowIndices = ( int32_t * ) malloc ( sizeof ( int32_t ) * newMaxNNz ) ; <nl> + / / ElemType * values = ( ElemType * ) malloc ( sizeof ( ElemType ) * newMaxNNz ) ; <nl> int32_t * rowIndices = ( int32_t * ) CUDAPageLockedMemAllocator : : Malloc ( sizeof ( int32_t ) * newMaxNNz , this - > m_deviceID ) ; <nl> ElemType * values = ( ElemType * ) CUDAPageLockedMemAllocator : : Malloc ( sizeof ( ElemType ) * newMaxNNz , this - > m_deviceID ) ; <nl> <nl> void SparseBinaryMatrix < ElemType > : : ResizeArrays ( size_t newNNz ) <nl> <nl> if ( m_rowIndices ! = nullptr ) <nl> { <nl> - / / free ( m_rowIndices ) ; <nl> + / / free ( m_rowIndices ) ; <nl> CUDAPageLockedMemAllocator : : Free ( this - > m_rowIndices , this - > m_deviceID ) ; <nl> } <nl> if ( this - > m_values ! = nullptr ) <nl> { <nl> - / / free ( this - > m_values ) ; <nl> + / / free ( this - > m_values ) ; <nl> CUDAPageLockedMemAllocator : : Free ( this - > m_values , this - > m_deviceID ) ; <nl> } <nl> <nl> void SparseBinaryInput < ElemType > : : Init ( std : : map < std : : wstring , std : : wstring > rena <nl> <nl> m_inFile . read ( ( char * ) tempName , len ) ; <nl> tempName [ len ] = ' \ 0 ' ; <nl> - / / std : : string name ( ( char * ) header_buffer + base_offset , len ) ; <nl> + / / std : : string name ( ( char * ) header_buffer + base_offset , len ) ; <nl> std : : wstring wname = msra : : strfun : : utf16 ( tempName ) ; <nl> if ( rename . find ( wname ) = = rename . end ( ) ) <nl> { <nl> void SparseBinaryInput < ElemType > : : Init ( std : : map < std : : wstring , std : : wstring > rena <nl> base_offset + = sizeof ( int8_t ) * len ; <nl> <nl> m_inFile . read ( ( char * ) & numCols , sizeof ( numCols ) ) ; <nl> - / / numCols = * ( int32_t * ) ( ( char * ) header_buffer + base_offset ) ; <nl> + / / numCols = * ( int32_t * ) ( ( char * ) header_buffer + base_offset ) ; <nl> base_offset + = sizeof ( int32_t ) ; <nl> <nl> m_mappedNumCols [ m_features . back ( ) ] = numCols ; <nl> void SparseBinaryInput < ElemType > : : Init ( std : : map < std : : wstring , std : : wstring > rena <nl> } <nl> base_offset + = sizeof ( int32_t ) ; <nl> <nl> - / / std : : string name ( ( char * ) header_buffer + base_offset , len ) ; <nl> + / / std : : string name ( ( char * ) header_buffer + base_offset , len ) ; <nl> m_inFile . read ( ( char * ) tempName , len ) ; <nl> tempName [ len ] = ' \ 0 ' ; <nl> std : : wstring wname = msra : : strfun : : utf16 ( tempName ) ; <nl> void SparseBinaryInput < ElemType > : : Init ( std : : map < std : : wstring , std : : wstring > rena <nl> } <nl> else <nl> { <nl> - / / m_features . emplace_back ( rename [ wname ] ) ; <nl> + / / m_features . emplace_back ( rename [ wname ] ) ; <nl> m_labels . emplace_back ( rename [ wname ] ) ; <nl> } <nl> base_offset + = sizeof ( int8_t ) * len ; <nl> <nl> - / / numCols = * ( int32_t * ) ( ( char * ) header_buffer + base_offset ) ; <nl> + / / numCols = * ( int32_t * ) ( ( char * ) header_buffer + base_offset ) ; <nl> m_inFile . read ( ( char * ) & numCols , sizeof ( numCols ) ) ; <nl> base_offset + = sizeof ( int32_t ) ; <nl> m_mappedNumCols [ m_labels . back ( ) ] = numCols ; <nl> void SparseBinaryInput < ElemType > : : StartDistributedMinibatchLoop ( size_t mbSize , s <nl> for ( size_t c = 0 ; c < m_windowSize ; c + + ) <nl> { <nl> m_maxMBSize = max ( m_maxMBSize , ( size_t ) ( m_offsets [ c + 1 ] - m_offsets [ c ] ) ) ; <nl> - / / fprintf ( stderr , " m_offsets [ % lu ] = % lu \ n " , c , m_offsets [ c ] ) ; <nl> + / / fprintf ( stderr , " m_offsets [ % lu ] = % lu \ n " , c , m_offsets [ c ] ) ; <nl> } <nl> - / / fprintf ( stderr , " max mb size : % ld \ n " , m_maxMBSize ) ; <nl> + / / fprintf ( stderr , " max mb size : % ld \ n " , m_maxMBSize ) ; <nl> size_t maxMem = 1024 * 1024 * 1024 ; / / 1GB <nl> size_t maxPointers = maxMem / m_maxMBSize ; <nl> for ( size_t c = 0 ; c < maxPointers ; c + + ) <nl> shared_ptr < BinaryMatrix < ElemType > > SparseBinaryInput < ElemType > : : CreateMatrix ( std <nl> { <nl> shared_ptr < BinaryMatrix < ElemType > > retVal ; / / = nullptr ; <nl> <nl> - / / if ( m_features . find ( matName ) ! = m_features . end ( ) ) { <nl> + / / if ( m_features . find ( matName ) ! = m_features . end ( ) ) { <nl> if ( std : : find ( m_features . begin ( ) , m_features . end ( ) , matName ) ! = m_features . end ( ) ) <nl> { <nl> retVal = make_shared < SparseBinaryMatrix < ElemType > > ( matName , deviceId , m_mbSize , m_mappedNumCols [ matName ] ) ; <nl> } <nl> - / / else if ( m_labels . find ( matName ) ! = m_labels . end ( ) ) { <nl> + / / else if ( m_labels . find ( matName ) ! = m_labels . end ( ) ) { <nl> else if ( std : : find ( m_labels . begin ( ) , m_labels . end ( ) , matName ) ! = m_labels . end ( ) ) <nl> { <nl> retVal = make_shared < DenseBinaryMatrix < ElemType > > ( matName , deviceId , m_mbSize , m_mappedNumCols [ matName ] ) ; <nl> void SparseBinaryInput < ElemType > : : ReadMinibatches ( size_t * read_order , size_t num <nl> { <nl> # if DEBUG <nl> marker_series series ( L " Read Minibatches " ) ; <nl> - / / diagnostic : : span span ( series , L " Reading Data " ) ; <nl> + / / diagnostic : : span span ( series , L " Reading Data " ) ; <nl> span * read_span ; <nl> # endif <nl> for ( size_t c = 0 ; c < numToRead ; c + + ) <nl> void SparseBinaryInput < ElemType > : : ReadMinibatches ( size_t * read_order , size_t num <nl> # if DEBUG <nl> read_span = new span ( series , 1 , L " Getting Buffer % ld \ n " , c ) ; <nl> # endif <nl> - / / fprintf ( stderr , " start reading data % ld \ n " , c ) ; <nl> + / / fprintf ( stderr , " start reading data % ld \ n " , c ) ; <nl> size_t readSize = m_offsets [ read_order [ c ] + 1 ] - m_offsets [ read_order [ c ] ] ; <nl> / / void * data_buffer = GetTempDataPointer ( readSize ) ; <nl> # if DEBUG <nl> template < class ElemType > <nl> size_t SparseBinaryInput < ElemType > : : ReadMinibatch ( void * data_buffer , std : : map < std : : wstring , shared_ptr < BinaryMatrix < ElemType > > > & matrices ) <nl> { <nl> <nl> - / / fprintf ( stderr , " start read minibatch . \ n " ) ; <nl> + / / fprintf ( stderr , " start read minibatch . \ n " ) ; <nl> / * <nl> size_t readSize = m_offsets [ cur_batch + 1 ] - m_offsets [ cur_batch ] ; <nl> void * data_buffer = GetTempDataPointer ( readSize ) ; <nl> size_t SparseBinaryInput < ElemType > : : ReadMinibatch ( void * data_buffer , std : : map < st <nl> <nl> for ( int32_t c = 0 ; c < m_features . size ( ) ; c + + ) <nl> { <nl> - / / fprintf ( stderr , " read features % d . \ n " , c ) ; <nl> + / / fprintf ( stderr , " read features % d . \ n " , c ) ; <nl> nnz = * ( int32_t * ) ( ( char * ) data_buffer + buffer_offset ) ; <nl> buffer_offset + = sizeof ( int32_t ) ; <nl> <nl> size_t SparseBinaryInput < ElemType > : : ReadMinibatch ( void * data_buffer , std : : map < st <nl> <nl> for ( int32_t c = 0 ; c < m_labels . size ( ) ; c + + ) <nl> { <nl> - / / fprintf ( stderr , " read labels % d . \ n " , c ) ; <nl> + / / fprintf ( stderr , " read labels % d . \ n " , c ) ; <nl> int32_t numCols = m_mappedNumCols [ m_labels [ c ] ] ; <nl> <nl> ElemType * vals = ( ElemType * ) ( ( char * ) data_buffer + buffer_offset ) ; <nl> template < class ElemType > <nl> size_t SparseBinaryInput < ElemType > : : FillMatrices ( std : : map < std : : wstring , shared_ptr < BinaryMatrix < ElemType > > > & matrices ) <nl> { <nl> <nl> - / / fprintf ( stderr , " start fill matrices \ n " ) ; <nl> + / / fprintf ( stderr , " start fill matrices \ n " ) ; <nl> size_t curSize = 0 ; <nl> for ( auto mat : matrices ) <nl> { <nl> size_t SparseBinaryInput < ElemType > : : FillMatrices ( std : : map < std : : wstring , shared_p <nl> mat . second - > Clear ( ) ; <nl> } <nl> void * data_buffer ; <nl> - / / fprintf ( stderr , " start while \ n " ) ; <nl> - / / clock_t start_w = clock ( ) ; <nl> - / / while ( curSize + m_microBatchSize < = m_mbSize & & ( data_buffer = m_dataToConsume . pop ( ) ) ! = nullptr ) { <nl> + / / fprintf ( stderr , " start while \ n " ) ; <nl> + / / clock_t start_w = clock ( ) ; <nl> + / / while ( curSize + m_microBatchSize < = m_mbSize & & ( data_buffer = m_dataToConsume . pop ( ) ) ! = nullptr ) { <nl> while ( curSize + m_microBatchSize < = m_mbSize & & m_nextMB < m_epochSize ) <nl> { <nl> data_buffer = m_dataToConsume . pop ( ) ; <nl> - / / clock_t in_w = clock ( ) ; <nl> - / / start_w = in_w - start_w ; <nl> - / / fprintf ( stderr , " start read mb \ tIt took me % d clicks ( % f seconds ) . \ n " , start_w , ( ( float ) start_w ) / CLOCKS_PER_SEC ) ; <nl> - / / start_w = in_w ; <nl> - / / fprintf ( stderr , " start read mb \ n " ) ; <nl> + / / clock_t in_w = clock ( ) ; <nl> + / / start_w = in_w - start_w ; <nl> + / / fprintf ( stderr , " start read mb \ tIt took me % d clicks ( % f seconds ) . \ n " , start_w , ( ( float ) start_w ) / CLOCKS_PER_SEC ) ; <nl> + / / start_w = in_w ; <nl> + / / fprintf ( stderr , " start read mb \ n " ) ; <nl> curSize + = ReadMinibatch ( data_buffer , matrices ) ; <nl> - / / fprintf ( stderr , " end read mb \ n " ) ; <nl> + / / fprintf ( stderr , " end read mb \ n " ) ; <nl> m_nextMB + + ; <nl> m_dataToProduce . push ( data_buffer ) ; <nl> } <nl> - / / fprintf ( stderr , " end fill matrices \ n " ) ; <nl> + / / fprintf ( stderr , " end fill matrices \ n " ) ; <nl> return curSize ; <nl> } <nl> <nl> void LibSVMBinaryReader < ElemType > : : DoDSSMMatrix ( Matrix < ElemType > & mat , size_t ac <nl> { <nl> if ( DSSMLabels ! = nullptr ) <nl> { <nl> - / / free ( DSSMLabels ) ; <nl> + / / free ( DSSMLabels ) ; <nl> CUDAPageLockedMemAllocator : : Free ( DSSMLabels , mat . GetDeviceId ( ) ) ; <nl> } <nl> DSSMCols = actualMBSize ; <nl> - / / DSSMLabels = ( ElemType * ) malloc ( sizeof ( ElemType ) * numRows * actualMBSize ) ; <nl> + / / DSSMLabels = ( ElemType * ) malloc ( sizeof ( ElemType ) * numRows * actualMBSize ) ; <nl> DSSMLabels = ( ElemType * ) CUDAPageLockedMemAllocator : : Malloc ( sizeof ( ElemType ) * numRows * actualMBSize , mat . GetDeviceId ( ) ) ; <nl> memset ( DSSMLabels , 0 , sizeof ( ElemType ) * numRows * actualMBSize ) ; <nl> for ( size_t c = 0 ; c < numRows * actualMBSize ; c + = numRows ) <nl> bool LibSVMBinaryReader < ElemType > : : GetMinibatch ( std : : map < std : : wstring , Matrix < El <nl> { <nl> if ( ! m_pendingAsyncGetMinibatch . valid ( ) ) <nl> { <nl> - / / fprintf ( stderr , " not valid \ n " ) ; <nl> + / / fprintf ( stderr , " not valid \ n " ) ; <nl> CheckDataMatrices ( matrices ) ; <nl> m_pendingAsyncGetMinibatch = std : : async ( std : : launch : : async , [ this ] ( ) <nl> { <nl> bool LibSVMBinaryReader < ElemType > : : GetMinibatch ( std : : map < std : : wstring , Matrix < El <nl> # if DEBUG <nl> reader_series - > write_flag ( _T ( " after get . " ) ) ; <nl> # endif <nl> - / / timer = clock ( ) - timer ; <nl> - / / fprintf ( stderr , " done get \ tIt took me % d clicks ( % f seconds ) . \ n " , timer , ( ( float ) timer ) / CLOCKS_PER_SEC ) ; <nl> + / / timer = clock ( ) - timer ; <nl> + / / fprintf ( stderr , " done get \ tIt took me % d clicks ( % f seconds ) . \ n " , timer , ( ( float ) timer ) / CLOCKS_PER_SEC ) ; <nl> <nl> if ( actualMBSize = = 0 ) <nl> { <nl> bool LibSVMBinaryReader < ElemType > : : GetMinibatch ( std : : map < std : : wstring , Matrix < El <nl> } <nl> m_pendingAsyncGetMinibatch = std : : async ( std : : launch : : async , [ this ] ( ) <nl> { <nl> - / / CheckDataMatrices ( matrices ) ; <nl> + / / CheckDataMatrices ( matrices ) ; <nl> return m_dataInput - > FillMatrices ( m_dataMatrices ) ; <nl> } ) ; <nl> } <nl> bool LibSVMBinaryReader < ElemType > : : GetMinibatch ( std : : map < std : : wstring , Matrix < El <nl> timer = clock ( ) - timer ; <nl> fprintf ( stderr , " It took me % d clicks ( % f seconds ) . \ n " , timer , ( ( float ) timer ) / CLOCKS_PER_SEC ) ; <nl> * / <nl> - / / fprintf ( stderr , " done \ n " ) ; <nl> + / / fprintf ( stderr , " done \ n " ) ; <nl> return true ; <nl> } <nl> <nl> mmm a / Source / Readers / LibSVMBinaryReader / LibSVMBinaryReader . h <nl> ppp b / Source / Readers / LibSVMBinaryReader / LibSVMBinaryReader . h <nl> class BinaryMatrix <nl> public : <nl> BinaryMatrix ( wstring name , int deviceID , size_t numRows , size_t numCols ) <nl> : m_matrixName ( name ) , m_deviceID ( deviceID ) , m_maxNumRows ( numRows ) , m_numRows ( 0 ) , m_maxNumCols ( numCols ) , m_values ( nullptr ) { } ; <nl> - / / BinaryMatrix ( wstring name , size_t numRows , size_t numCols ) : m_matrixName ( name ) , m_maxNumRows ( numRows ) , m_numRows ( 0 ) , m_maxNumCols ( numCols ) , m_values ( nullptr ) { } ; <nl> + / / BinaryMatrix ( wstring name , size_t numRows , size_t numCols ) : m_matrixName ( name ) , m_maxNumRows ( numRows ) , m_numRows ( 0 ) , m_maxNumCols ( numCols ) , m_values ( nullptr ) { } ; <nl> virtual void Clear ( ) = 0 ; <nl> virtual void Dispose ( ) = 0 ; <nl> virtual void Fill ( Matrix < ElemType > * ) = 0 ; <nl> class DenseBinaryMatrix : public BinaryMatrix < ElemType > <nl> { <nl> public : <nl> DenseBinaryMatrix ( wstring name , int deviceID , size_t numRows , size_t numCols ) ; <nl> - / / DenseBinaryMatrix ( wstring name , size_t numRows , size_t numCols ) ; <nl> + / / DenseBinaryMatrix ( wstring name , size_t numRows , size_t numCols ) ; <nl> virtual void Clear ( ) ; <nl> virtual void Dispose ( ) ; <nl> virtual void Fill ( Matrix < ElemType > * matrix ) override ; <nl> class SparseBinaryMatrix : public BinaryMatrix < ElemType > <nl> { <nl> public : <nl> SparseBinaryMatrix ( wstring name , int deviceID , size_t numRows , size_t numCols ) ; <nl> - / / SparseBinaryMatrix ( wstring name , size_t numRows , size_t numCols ) ; <nl> + / / SparseBinaryMatrix ( wstring name , size_t numRows , size_t numCols ) ; <nl> virtual void Clear ( ) ; <nl> virtual void Dispose ( ) ; <nl> virtual void Fill ( Matrix < ElemType > * matrix ) override ; <nl> class SparseBinaryInput <nl> void StartDistributedMinibatchLoop ( size_t mbSize , size_t subsetNum , size_t numSubsets ) ; <nl> void ReadMinibatches ( size_t * read_order , size_t numToRead ) ; <nl> size_t ReadMinibatch ( void * data_buffer , std : : map < std : : wstring , shared_ptr < BinaryMatrix < ElemType > > > & matrices ) ; <nl> - / / void GetMinibatch ( std : : map < std : : wstring , Matrix < ElemType > * > & matrices ) ; <nl> + / / void GetMinibatch ( std : : map < std : : wstring , Matrix < ElemType > * > & matrices ) ; <nl> size_t FillMatrices ( std : : map < std : : wstring , shared_ptr < BinaryMatrix < ElemType > > > & matrices ) ; <nl> size_t GetMBSize ( ) <nl> { <nl> class SparseBinaryInput <nl> } <nl> void Shuffle ( ) ; <nl> shared_ptr < BinaryMatrix < ElemType > > CreateMatrix ( std : : wstring matName , int deviceId ) ; <nl> - / / shared_ptr < BinaryMatrix < ElemType > > CreateMatrix ( std : : wstring matName ) ; <nl> + / / shared_ptr < BinaryMatrix < ElemType > > CreateMatrix ( std : : wstring matName ) ; <nl> virtual bool DataEnd ( EndDataType endDataType ) ; <nl> <nl> private : <nl> class LibSVMBinaryReader : public IDataReader < ElemType > <nl> pMBLayout - > CopyFrom ( m_pMBLayout ) ; <nl> } ; <nl> <nl> - / / virtual bool DataEnd ( EndDataType endDataType ) ; <nl> + / / virtual bool DataEnd ( EndDataType endDataType ) ; <nl> <nl> size_t NumberSlicesInEachRecurrentIter ( ) <nl> { <nl> mmm a / Source / Readers / UCIFastReader / UCIFastReader . cpp <nl> ppp b / Source / Readers / UCIFastReader / UCIFastReader . cpp <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> template < class ElemType > <nl> size_t UCIFastReader < ElemType > : : RandomizeSweep ( size_t mbStartSample ) <nl> { <nl> - / / size_t randomRangePerEpoch = ( m_epochSize + m_randomizeRange - 1 ) / m_randomizeRange ; <nl> - / / return m_epoch * randomRangePerEpoch + epochSample / m_randomizeRange ; <nl> + / / size_t randomRangePerEpoch = ( m_epochSize + m_randomizeRange - 1 ) / m_randomizeRange ; <nl> + / / return m_epoch * randomRangePerEpoch + epochSample / m_randomizeRange ; <nl> return mbStartSample / m_randomizeRange ; <nl> } <nl> <nl> void UCIFastReader < ElemType > : : InitFromConfig ( const ConfigRecordType & readerConfi <nl> RuntimeError ( " features and label files must be the same file , use separate readers to define single use files " ) ; <nl> <nl> size_t vdim = configFeatures ( L " dim " ) ; <nl> - / / string name = configFeatures . Name ( ) ; / / TODO : Aaargh ! ! ! <nl> + / / string name = configFeatures . Name ( ) ; / / TODO : Aaargh ! ! ! <nl> size_t udim = configLabels ( L " labelDim " , ( size_t ) 0 ) ; <nl> <nl> / / initialize all the variables <nl> void UCIFastReader < ElemType > : : InitFromConfig ( const ConfigRecordType & readerConfi <nl> else <nl> labelType = ( wstring ) configLabels ( L " labelType " , L " category " ) ; <nl> <nl> - / / convert to lower case for case insensitive comparison <nl> + / / convert to lower case for case insensitive comparison <nl> if ( ! _wcsicmp ( labelType . c_str ( ) , L " category " ) ) <nl> { <nl> m_labelType = labelCategory ; <nl> bool UCIFastReader < ElemType > : : GetMinibatchImpl ( std : : map < std : : wstring , Matrix < Ele <nl> <nl> / / figure which sweep of the randomization we are on <nl> size_t epochSample = m_mbStartSample % m_epochSize ; / / where the minibatch starts in this epoch <nl> - / / size_t samplesExtra = m_totalSamples % m_epochSize ; / / extra samples at the end of an epoch <nl> - / / size_t epochsDS = ( m_totalSamples + m_epochSize - 1 ) / m_epochSize ; / / how many epochs per dataset <nl> + / / size_t samplesExtra = m_totalSamples % m_epochSize ; / / extra samples at the end of an epoch <nl> + / / size_t epochsDS = ( m_totalSamples + m_epochSize - 1 ) / m_epochSize ; / / how many epochs per dataset <nl> size_t randomizeSet = randomize ? RandomizeSweep ( m_mbStartSample ) : 0 ; <nl> const auto & tmap = m_randomordering ( randomizeSet ) ; <nl> size_t epochEnd = m_epochSize ; <nl> bool UCIFastReader < ElemType > : : GetMinibatchImpl ( std : : map < std : : wstring , Matrix < Ele <nl> if ( randomize ) <nl> randBase = epochSample - epochSample % m_randomizeRange ; <nl> <nl> - / / loop through all the samples <nl> + / / loop through all the samples <nl> for ( size_t jSample = m_mbStartSample ; j < actualmbsize ; + + j , + + jSample ) <nl> { <nl> / / pick the right sample with randomization if desired <nl> mmm a / Source / Readers / UCIFastReader / UCIFastReader . h <nl> ppp b / Source / Readers / UCIFastReader / UCIFastReader . h <nl> class UCIFastReader : public IDataReader < ElemType > <nl> using LabelType = typename IDataReader < ElemType > : : LabelType ; <nl> using LabelIdType = typename IDataReader < ElemType > : : LabelIdType ; <nl> using IDataReader < ElemType > : : mRequestedNumParallelSequences ; <nl> - / / typedef std : : string LabelType ; <nl> - / / typedef unsigned LabelIdType ; <nl> + / / typedef std : : string LabelType ; <nl> + / / typedef unsigned LabelIdType ; <nl> private : <nl> UCIParser < ElemType , LabelType > m_parser ; <nl> size_t m_mbSize ; / / size of minibatch requested <nl> mmm a / Source / Readers / UCIFastReader / UCIParser . cpp <nl> ppp b / Source / Readers / UCIFastReader / UCIParser . cpp <nl> void UCIParser < NumType , LabelType > : : SetStateRange ( int value1 , int value2 , ParseS <nl> template < typename NumType , typename LabelType > <nl> void UCIParser < NumType , LabelType > : : SetupStateTables ( ) <nl> { <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = WHITESPACE <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , Whitespace , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , Whitespace , WholeNumber ) ; <nl> void UCIParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ r ' , Whitespace , Whitespace ) ; <nl> SetState ( ' \ n ' , Whitespace , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = NEGATIVE_SIGN <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , Sign , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , Sign , WholeNumber ) ; <nl> void UCIParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ r ' , Sign , Whitespace ) ; <nl> SetState ( ' \ n ' , Sign , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = NUMBER <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , WholeNumber , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , WholeNumber , WholeNumber ) ; <nl> void UCIParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ r ' , WholeNumber , Whitespace ) ; <nl> SetState ( ' \ n ' , WholeNumber , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = PERIOD <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , Period , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , Period , Remainder ) ; <nl> void UCIParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ r ' , Period , Whitespace ) ; <nl> SetState ( ' \ n ' , Period , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = REMAINDER <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , Remainder , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , Remainder , Remainder ) ; <nl> void UCIParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ r ' , Remainder , Whitespace ) ; <nl> SetState ( ' \ n ' , Remainder , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = THE_LETTER_E <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , TheLetterE , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , TheLetterE , Exponent ) ; <nl> void UCIParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ r ' , TheLetterE , Whitespace ) ; <nl> SetState ( ' \ n ' , TheLetterE , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = EXPONENT_NEGATIVE_SIGN <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , ExponentSign , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , ExponentSign , Exponent ) ; <nl> void UCIParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ r ' , ExponentSign , Whitespace ) ; <nl> SetState ( ' \ n ' , ExponentSign , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = EXPONENT <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> SetStateRange ( 0 , 255 , Exponent , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , Exponent , Exponent ) ; <nl> void UCIParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ r ' , Exponent , Whitespace ) ; <nl> SetState ( ' \ n ' , Exponent , EndOfLine ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = END_OF_LINE <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> SetStateRange ( 0 , 255 , EndOfLine , Label ) ; <nl> SetStateRange ( ' 0 ' , ' 9 ' , EndOfLine , WholeNumber ) ; <nl> SetState ( ' - ' , EndOfLine , Sign ) ; <nl> void UCIParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ t ' , EndOfLine , Whitespace ) ; <nl> SetState ( ' \ r ' , EndOfLine , Whitespace ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = LABEL <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> SetStateRange ( 0 , 255 , Label , Label ) ; <nl> SetState ( ' \ n ' , Label , EndOfLine ) ; <nl> / / whitespace <nl> void UCIParser < NumType , LabelType > : : SetupStateTables ( ) <nl> SetState ( ' \ t ' , Label , Whitespace ) ; <nl> SetState ( ' \ r ' , Label , Whitespace ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = LINE_COUNT_EOL <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> SetStateRange ( 0 , 255 , LineCountEOL , LineCountOther ) ; <nl> SetState ( ' \ n ' , LineCountEOL , LineCountEOL ) ; <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / STATE = LINE_COUNT_OTHER <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = <nl> SetStateRange ( 0 , 255 , LineCountOther , LineCountOther ) ; <nl> SetState ( ' \ n ' , LineCountOther , LineCountEOL ) ; <nl> } <nl> long UCIParser < NumType , LabelType > : : Parse ( size_t recordsRequested , std : : vector < N <nl> case Whitespace : <nl> m_spaceDelimitedMax = m_byteCounter ; <nl> / / hit whitespace and nobody processed anything , so add as label <nl> - / / if ( m_elementsConvertedThisLine = = elementsProcessed ) <nl> + / / if ( m_elementsConvertedThisLine = = elementsProcessed ) <nl> / / DoneWithLabel ( ) ; <nl> break ; <nl> case EndOfLine : <nl> long UCIParser < NumType , LabelType > : : Parse ( size_t recordsRequested , std : : vector < N <nl> { <nl> m_spaceDelimitedMax = m_byteCounter ; <nl> / / hit whitespace and nobody processed anything , so add as label <nl> - / / if ( m_elementsConvertedThisLine = = elementsProcessed ) <nl> + / / if ( m_elementsConvertedThisLine = = elementsProcessed ) <nl> / / DoneWithLabel ( ) ; <nl> } <nl> / / process the label at the end of a line <nl> - / / if ( m_labelMode = = LabelLast & & m_labels ! = NULL ) <nl> - / / { <nl> + / / if ( m_labelMode = = LabelLast & & m_labels ! = NULL ) <nl> + / / { <nl> / / StoreLastLabel ( ) ; <nl> - / / } <nl> + / / } <nl> / / intentional fall - through <nl> case LineCountEOL : <nl> recordCount + + ; / / done with another record <nl> int wmain ( int argc , wchar_t * argv [ ] ) <nl> std : : vector < int > labels ; <nl> labels . reserve ( 60000 ) ; <nl> parser . ParseInit ( L " c : \ \ speech \ \ mnist \ \ mnist_train . txt " , LabelFirst ) ; <nl> - / / parser . ParseInit ( " c : \ \ speech \ \ parseTest . txt " , LabelNone ) ; <nl> + / / parser . ParseInit ( " c : \ \ speech \ \ parseTest . txt " , LabelNone ) ; <nl> int records = 0 ; <nl> do <nl> { <nl> mmm a / Source / SGDLib / DataReaderHelpers . h <nl> ppp b / Source / SGDLib / DataReaderHelpers . h <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> seqRange ) ; <nl> } <nl> <nl> - / / m_NetInputMatrixPtr = decimatedMatrices ; <nl> + / / m_NetInputMatrixPtr = decimatedMatrices ; <nl> for ( auto & x : decimatedMatrices ) <nl> { <nl> wstring name = x . first ; <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> / / also revert net . m_MBLayoutPtr <nl> m_NetMBLayoutPtr - > CopyFrom ( m_MBLayoutCache ) ; <nl> <nl> - / / m_NetCriterionNodes [ 0 ] - > Value ( ) . SetValue ( ( ElemType ) 0 ) ; <nl> + / / m_NetCriterionNodes [ 0 ] - > Value ( ) . SetValue ( ( ElemType ) 0 ) ; <nl> Matrix < ElemType > : : AddElementToElement ( * m_NetCriterionAccumulator , 0 , 0 , <nl> m_NetCriterionNodes [ 0 ] - > Value ( ) , 0 , 0 ) ; <nl> m_NetCriterionAccumulator - > SetValue ( ( ElemType ) 0 ) ; <nl> <nl> for ( size_t i = 0 ; i < m_NetEvaluationNodes . size ( ) ; i + + ) <nl> { <nl> - / / m_NetEvaluationNodes [ i ] - > Value ( ) . SetValue ( ( ElemType ) 0 ) ; <nl> + / / m_NetEvaluationNodes [ i ] - > Value ( ) . SetValue ( ( ElemType ) 0 ) ; <nl> Matrix < ElemType > : : AddElementToElement ( * m_NetEvaluationAccumulator , 0 , i , <nl> m_NetEvaluationNodes [ i ] - > Value ( ) , 0 , 0 ) ; <nl> } <nl> mmm a / Source / SGDLib / DistGradHeader . h <nl> ppp b / Source / SGDLib / DistGradHeader . h <nl> struct DistGradHeader <nl> delete [ ] ( ( char * ) header ) ; <nl> } <nl> <nl> - / / aggregate header information <nl> + / / aggregate header information <nl> void Aggregate ( DistGradHeader * other , bool add = false ) <nl> { <nl> if ( other - > numEvalNode ! = numEvalNode ) <nl> mmm a / Source / SGDLib / SGD . cpp <nl> ppp b / Source / SGDLib / SGD . cpp <nl> void SGD < ElemType > : : TrainOrAdaptModel ( int startEpoch , ComputationNetworkPtr net , <nl> } <nl> } <nl> <nl> - / / get hmm file for sequence training <nl> + / / get hmm file for sequence training <nl> bool isSequenceTrainingCriterion = ( criterionNodes [ 0 ] - > OperationName ( ) = = L " SequenceWithSoftmax " ) ; <nl> if ( isSequenceTrainingCriterion ) <nl> { <nl> - / / SequenceWithSoftmaxNode < ElemType > * node = static_cast < SequenceWithSoftmaxNode < ElemType > * > ( criterionNodes [ 0 ] ) ; <nl> + / / SequenceWithSoftmaxNode < ElemType > * node = static_cast < SequenceWithSoftmaxNode < ElemType > * > ( criterionNodes [ 0 ] ) ; <nl> auto node = dynamic_pointer_cast < SequenceWithSoftmaxNode < ElemType > > ( criterionNodes [ 0 ] ) ; <nl> auto hmm = node - > gethmm ( ) ; <nl> trainSetDataReader - > GetHmmData ( hmm ) ; <nl> void SGD < ElemType > : : TrainOrAdaptModel ( int startEpoch , ComputationNetworkPtr net , <nl> { <nl> InitDistGradAgg ( evaluationNodes . size ( ) , m_traceLevel ) ; <nl> } <nl> - / / precompute mean and invStdDev nodes and save initial model <nl> + / / precompute mean and invStdDev nodes and save initial model <nl> if ( PreCompute ( net , trainSetDataReader , featureNodes , labelNodes , inputMatrices ) | | startEpoch = = 0 ) <nl> { <nl> / / Synchronize all ranks before writing the model to ensure that <nl> bool SGD < ElemType > : : PreCompute ( ComputationNetworkPtr net , <nl> fprintf ( stderr , " \ tNodeName : % ls \ n " , ( node - > NodeName ( ) ) . c_str ( ) ) ; <nl> } <nl> <nl> - / / compute <nl> - / / trainSetDataReader - > StartMinibatchLoop ( m_mbSize [ 0 ] , 0 , requestDataSize ) ; <nl> + / / compute <nl> + / / trainSetDataReader - > StartMinibatchLoop ( m_mbSize [ 0 ] , 0 , requestDataSize ) ; <nl> / / trainSetDataReader - > StartMinibatchLoop ( m_mbSize [ 0 ] , 0 , m_epochSize ) ; / / only based on one epoch <nl> / / [ 1 / 12 / 2015 erw ] to support large dataset , we usually partition whole dataset into several epoch ' s , <nl> / / so we need to use all the data to do precomputing <nl> double SGD < ElemType > : : SearchForBestLearnRate ( ComputationNetworkPtr net , <nl> <nl> bestLearnRatePerSample = learnRatePerSample ; <nl> <nl> - / / grid search for the first m_numBestSearchEpoch epochs <nl> + / / grid search for the first m_numBestSearchEpoch epochs <nl> if ( epochNumber < m_numBestSearchEpoch ) <nl> { <nl> double leftLearnRatePerSample = 0 . 01 / m_mbSize [ epochNumber ] ; <nl> void SGD < ElemType > : : AttemptUtteranceDerivativeFeatures ( ComputationNetworkPtr net <nl> if ( outputNodes . empty ( ) ) <nl> LogicError ( " no output node was found . " ) ; <nl> <nl> - / / net - > SetActualMiniBatchSizeFromFeatures ( ) ; <nl> + / / net - > SetActualMiniBatchSizeFromFeatures ( ) ; <nl> trainSetDataReader - > CopyMBLayoutTo ( net - > GetMBLayoutPtr ( ) ) ; <nl> net - > VerifyActualNumParallelSequences ( trainSetDataReader - > GetNumParallelSequences ( ) ) ; <nl> net - > ForwardProp ( outputNodes [ 0 ] ) ; / / Only evaluate the first output <nl> template < class ElemType > <nl> bool SGD < ElemType > : : ModelAveragingProcessing ( size_t nSamplesSinceLastSync , const std : : list < ComputationNodeBasePtr > & learnableNodes , size_t & nProcessedFrames , <nl> float & SecondsSinceLastSyncFinished , float & SecondsSpentOnSync ) <nl> { <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / the current strategy is that after each minibatch , we will sync between processors <nl> / / to decide whether a sync need to be performed . This is definitely not optimal , <nl> / / which we will fix it later . <nl> <nl> / / TODO : the way we handle timer is not very good <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> static bool first = true ; <nl> static Timer MAtimer ; <nl> if ( first ) <nl> size_t SGD < ElemType > : : ModelAveragingSync ( int nSamplesSinceLastSync , const std : : l <nl> return nSamplesSinceLastSync ; <nl> } <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / Sec . 1 calculate factor <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> float factor = 0 ; <nl> int nTotalSamples = nSamplesSinceLastSync ; <nl> g_mpi - > AllReduce ( & nTotalSamples , 1 ) ; <nl> size_t SGD < ElemType > : : ModelAveragingSync ( int nSamplesSinceLastSync , const std : : l <nl> factor = ( nSamplesSinceLastSync + 0 . 0f ) / nTotalSamples ; <nl> } <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / Sec . 2 sync models based on factor <nl> / / Note : this is suboptimal at the moment : <nl> / / we do the averaging for each node in a sequence manner , i . e . , <nl> size_t SGD < ElemType > : : ModelAveragingSync ( int nSamplesSinceLastSync , const std : : l <nl> / / ( node1 ) GPU - > CPU - > MPI_AllReduce <nl> / / ( node2 ) GPU - > CPU - > MPI_AllReduce <nl> / / ( node3 ) GPU - > CPU - > MPI_AllReduce <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> for ( auto iter = learnableNodes . begin ( ) ; iter ! = learnableNodes . end ( ) ; iter + + ) <nl> { <nl> ComputationNodeBasePtr pNode = * iter ; <nl> template < class ElemType > <nl> / / make actualMBSize is a valid value <nl> assert ( actualMBSize > 0 ) ; <nl> <nl> - / / clipping gradients to prevent outliers <nl> + / / clipping gradients to prevent outliers <nl> sgd - > ClipGradient ( gradientValues , actualMBSize ) ; <nl> <nl> GradientsUpdateType adpType = sgd - > GradUpdateType ( ) ; <nl> template < class ElemType > <nl> ( adpType = = GradientsUpdateType : : RmsProp & & gradientValues . GetMatrixType ( ) = = MatrixType : : SPARSE ) | | <nl> ( adpType = = GradientsUpdateType : : FSAdaGrad & & gradientValues . GetMatrixType ( ) = = MatrixType : : SPARSE ) ) <nl> { <nl> - / / rmsprop for sparse is not implemented yet , delegate it with adagrad <nl> + / / rmsprop for sparse is not implemented yet , delegate it with adagrad <nl> <nl> double aveMultiplier = smoothedGradient . Adagrad ( gradientValues , needAveMultiplier ) ; <nl> Matrix < ElemType > : : ScaleAndAdd ( ( ElemType ) ( - learnRatePerSample / aveMultiplier ) , gradientValues , functionValues ) ; <nl> bool SGD < ElemType > : : GradientCheck ( ComputationNetworkPtr net , <nl> break ; <nl> } <nl> <nl> - / / double mbEvalCri = <nl> - / / criterionNode should be a scalar <nl> + / / double mbEvalCri = <nl> + / / criterionNode should be a scalar <nl> / / TODO : why is this value not used ? <nl> criterionNodes [ npos ] - > Get00Element ( ) ; <nl> double eGradErr = node - > Gradient ( ) ( irow , icol ) ; <nl> bool SGD < ElemType > : : GradientCheck ( ComputationNetworkPtr net , <nl> <nl> node - > BumpEvalTimeStamp ( ) ; <nl> net - > ForwardProp ( criterionNodes [ npos ] ) ; <nl> - / / criterionNode should be a scalar <nl> + / / criterionNode should be a scalar <nl> <nl> double mbEvalCriPos = criterionNodes [ npos ] - > Get00Element ( ) ; / / TODO : make Get00Element ( ) a function of ComputationNodeBase <nl> <nl> SGDParams : : SGDParams ( const ConfigRecordType & configSGD , size_t sizeofElemType ) <nl> m_reduceLearnRateIfImproveLessThan = configAALR ( L " reduceLearnRateIfImproveLessThan " , 0 . 0 ) ; <nl> m_continueReduce = configAALR ( L " continueReduce " , false ) ; <nl> m_learnRateAdjustInterval = configAALR ( L " learnRateAdjustInterval " , ( size_t ) 1 ) ; <nl> - m_learnRateAdjustInterval = max ( ( size_t ) 1 , m_learnRateAdjustInterval ) ; / / minimum interval is 1 epoch <nl> + m_learnRateAdjustInterval = max ( ( size_t ) 1 , m_learnRateAdjustInterval ) ; / / minimum interval is 1 epoch <nl> m_learnRateDecreaseFactor = configAALR ( L " learnRateDecreaseFactor " , 0 . 618 ) ; <nl> m_increaseLearnRateIfImproveMoreThan = configAALR ( L " increaseLearnRateIfImproveMoreThan " , numeric_limits < double > : : infinity ( ) ) ; <nl> m_learnRateIncreaseFactor = configAALR ( L " learnRateIncreaseFactor " , 1 . 382 ) ; <nl> mmm a / Source / SGDLib / SGD . h <nl> ppp b / Source / SGDLib / SGD . h <nl> struct SGDParams : public ScriptableObjects : : Object <nl> <nl> SGDParams ( const ScriptableObjects : : IConfigRecordPtr configp ) ; <nl> <nl> - / / SGDParams ( SGDParams & & ) = default ; / / ( does not compile in VS 2013 ; not critical ) <nl> + / / SGDParams ( SGDParams & & ) = default ; / / ( does not compile in VS 2013 ; not critical ) <nl> <nl> protected : <nl> / / learning rate per sample provided outside <nl> struct SGDParams : public ScriptableObjects : : Object <nl> } <nl> <nl> / / only true when the user specify LearningRatePerMB and the number of parallel utterances in Reader > 1 <nl> - / / bool m_needToNormalizeLRByParallUtterance ; / / TODO : should go away <nl> - / / bool m_needToNormalizeMomentumByParallUtterance ; <nl> + / / bool m_needToNormalizeLRByParallUtterance ; / / TODO : should go away <nl> + / / bool m_needToNormalizeMomentumByParallUtterance ; <nl> <nl> intargvector m_mbSize ; <nl> bool m_truncated ; / / do BPTT <nl> struct SGDParams : public ScriptableObjects : : Object <nl> double m_L2RegWeight ; <nl> double m_L1RegWeight ; <nl> <nl> - / / sequence training <nl> + / / sequence training <nl> double m_hSmoothingWeight ; <nl> double m_frameDropThresh ; <nl> bool m_doReferenceAlign ; <nl> class SGD : public SGDParams <nl> / / TODO : The next few do not belong into SGD any more than the network or reader we operate on . Either move network and reader in here , or move these out . <nl> m_modelPath ( ( const wstring & ) configSGD ( L " modelPath " ) ) , <nl> m_keepCheckPointFiles ( configSGD ( L " keepCheckPointFiles " , false ) ) , <nl> - / / m_validateAfterModelReloading ( configSGD ( L " validateAfterModelReloading " , true ) ) , <nl> + / / m_validateAfterModelReloading ( configSGD ( L " validateAfterModelReloading " , true ) ) , <nl> m_trainCriterionNodeName ( ( const wstring & ) configSGD ( L " trainCriterionNodeName " , L " " ) ) , <nl> m_evalCriterionNodeName ( ( const wstring & ) configSGD ( L " evalCriterionNodeName " , L " " ) ) , <nl> m_prevChosenMinibatchSize ( 0 ) , <nl> class SGD : public SGDParams <nl> protected : <nl> wstring m_modelPath ; <nl> bool m_keepCheckPointFiles ; <nl> - / / bool m_validateAfterModelReloading ; / / TODO : remove this . Why would one not validate a model ? <nl> + / / bool m_validateAfterModelReloading ; / / TODO : remove this . Why would one not validate a model ? <nl> <nl> wstring m_trainCriterionNodeName ; <nl> wstring m_evalCriterionNodeName ; <nl> mmm a / Source / SGDLib / SimpleEvaluator . h <nl> ppp b / Source / SGDLib / SimpleEvaluator . h <nl> class SimpleEvaluator <nl> size_t numMBsRun = 0 ; <nl> size_t actualMBSize = 0 ; <nl> size_t numSamplesLastMBs = 0 ; <nl> - size_t lastMBsRun = 0 ; / / MBs run before this display <nl> + size_t lastMBsRun = 0 ; / / MBs run before this display <nl> <nl> std : : vector < double > evalResultsLastMBs ; <nl> for ( int i = 0 ; i < evalResults . size ( ) ; i + + ) <nl> class SimpleEvaluator <nl> DisplayEvalStatistics ( lastMBsRun + 1 , numMBsRun , numSamplesLastMBs , evalNodes , evalResults , evalResultsLastMBs ) ; <nl> } <nl> <nl> - / / final statistics <nl> + / / final statistics <nl> for ( int i = 0 ; i < evalResultsLastMBs . size ( ) ; i + + ) <nl> { <nl> evalResultsLastMBs [ i ] = 0 ; <nl> class SimpleEvaluator <nl> <nl> if ( displayConvertedValue ) <nl> { <nl> - / / display Perplexity as well for crossEntropy values <nl> + / / display Perplexity as well for crossEntropy values <nl> if ( evalNodes [ i ] - > OperationName ( ) = = OperationNameOf ( CrossEntropyWithSoftmaxNode ) | | <nl> evalNodes [ i ] - > OperationName ( ) = = OperationNameOf ( CrossEntropyNode ) | | <nl> evalNodes [ i ] - > OperationName ( ) = = OperationNameOf ( ClassBasedCrossEntropyWithSoftmaxNode ) | | <nl> mmm a / Source / SGDLib / SimpleOutputWriter . h <nl> ppp b / Source / SGDLib / SimpleOutputWriter . h <nl> class SimpleOutputWriter <nl> void WriteOutput ( IDataReader < ElemType > & dataReader , size_t mbSize , IDataWriter < ElemType > & dataWriter , const std : : vector < std : : wstring > & outputNodeNames , size_t numOutputSamples = requestDataSize , bool doUnitTest = false ) <nl> { <nl> <nl> - / / specify output nodes and files <nl> + / / specify output nodes and files <nl> std : : vector < ComputationNodeBasePtr > outputNodes ; <nl> if ( outputNodeNames . size ( ) = = 0 ) <nl> { <nl> class SimpleOutputWriter <nl> / / allocate memory for forward computation <nl> m_net - > AllocateAllMatrices ( { } , outputNodes , nullptr ) ; <nl> <nl> - / / specify feature value nodes <nl> + / / specify feature value nodes <nl> std : : vector < ComputationNodeBasePtr > & featureNodes = m_net - > FeatureNodes ( ) ; <nl> std : : vector < ComputationNodeBasePtr > & labelNodes = m_net - > LabelNodes ( ) ; <nl> std : : map < std : : wstring , Matrix < ElemType > * > inputMatrices ; <nl> class SimpleOutputWriter <nl> inputMatrices [ featureNodes [ i ] - > NodeName ( ) ] = & dynamic_pointer_cast < ComputationNode < ElemType > > ( featureNodes [ i ] ) - > Value ( ) ; <nl> for ( size_t i = 0 ; i < labelNodes . size ( ) ; i + + ) <nl> inputMatrices [ labelNodes [ i ] - > NodeName ( ) ] = & dynamic_pointer_cast < ComputationNode < ElemType > > ( labelNodes [ i ] ) - > Value ( ) ; <nl> - / / Matrix < ElemType > endOfFile = Matrix < ElemType > ( ( size_t ) 1 , ( size_t ) 1 ) ; <nl> - / / endOfFile ( 0 , 0 ) = 0 ; <nl> + / / Matrix < ElemType > endOfFile = Matrix < ElemType > ( ( size_t ) 1 , ( size_t ) 1 ) ; <nl> + / / endOfFile ( 0 , 0 ) = 0 ; <nl> <nl> / / evaluate with minibatches <nl> dataReader . StartMinibatchLoop ( mbSize , 0 , numOutputSamples ) ; <nl> class SimpleOutputWriter <nl> ComputationNetwork : : BumpEvalTimeStamp ( featureNodes ) ; <nl> ComputationNetwork : : BumpEvalTimeStamp ( labelNodes ) ; <nl> <nl> - / / size_t actualMBSize = m_net - > SetActualMiniBatchSizeFromFeatures ( ) ; <nl> - / / dataReader . CopyMBLayoutTo ( m_net - > GetMBLayoutPtr ( ) ) ; <nl> - / / m_net - > VerifyActualNumParallelSequences ( dataReader . GetNumParallelSequences ( ) ) ; <nl> + / / size_t actualMBSize = m_net - > SetActualMiniBatchSizeFromFeatures ( ) ; <nl> + / / dataReader . CopyMBLayoutTo ( m_net - > GetMBLayoutPtr ( ) ) ; <nl> + / / m_net - > VerifyActualNumParallelSequences ( dataReader . GetNumParallelSequences ( ) ) ; <nl> <nl> for ( int i = 0 ; i < outputNodes . size ( ) ; i + + ) <nl> { <nl> class SimpleOutputWriter <nl> if ( m_verbosity > 0 ) <nl> fprintf ( stderr , " Total Samples Evaluated = % lu \ n " , totalEpochSamples ) ; <nl> <nl> - / / clean up <nl> + / / clean up <nl> } <nl> <nl> void WriteOutput ( IDataReader < ElemType > & dataReader , size_t mbSize , std : : wstring outputPath , const std : : vector < std : : wstring > & outputNodeNames , size_t numOutputSamples = requestDataSize ) <nl> { <nl> msra : : files : : make_intermediate_dirs ( outputPath ) ; <nl> <nl> - / / specify output nodes and files <nl> + / / specify output nodes and files <nl> std : : vector < ComputationNodeBasePtr > outputNodes ; <nl> if ( outputNodeNames . size ( ) = = 0 ) <nl> { <nl> class SimpleOutputWriter <nl> / / allocate memory for forward computation <nl> m_net - > AllocateAllMatrices ( { } , outputNodes , nullptr ) ; <nl> <nl> - / / specify feature value nodes <nl> + / / specify feature value nodes <nl> auto & featureNodes = m_net - > FeatureNodes ( ) ; <nl> std : : map < std : : wstring , Matrix < ElemType > * > inputMatrices ; <nl> for ( size_t i = 0 ; i < featureNodes . size ( ) ; i + + ) <nl> class SimpleOutputWriter <nl> <nl> fprintf ( stderr , " Total Samples Evaluated = % lu \ n " , totalEpochSamples ) ; <nl> <nl> - / / clean up <nl> + / / clean up <nl> for ( int i = 0 ; i < outputStreams . size ( ) ; i + + ) <nl> { <nl> outputStreams [ i ] - > close ( ) ; <nl> mmm a / Source / SequenceTrainingLib / gammacalculation . h <nl> ppp b / Source / SequenceTrainingLib / gammacalculation . h <nl> class GammaCalculation <nl> { <nl> } <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / Sec . 1 init functions <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> void init ( msra : : asr : : simplesenonehmm hset , int DeviceId ) <nl> { <nl> m_deviceid = DeviceId ; <nl> class GammaCalculation <nl> } <nl> } <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / Sec . 2 set functions <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> void SetGammarCalculationParams ( const SeqGammarCalParam & gammarParam ) <nl> { <nl> lmf = ( float ) gammarParam . lmf ; <nl> class GammaCalculation <nl> boostmmifactor = ( float ) gammarParam . bMMIfactor ; <nl> } <nl> <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / Sec . 3 calculation functions <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> void calgammaformb ( Microsoft : : MSR : : CNTK : : Matrix < ElemType > & functionValues , <nl> std : : vector < shared_ptr < const msra : : dbn : : latticepair > > & lattices , <nl> const Microsoft : : MSR : : CNTK : : Matrix < ElemType > & loglikelihood , <nl> class GammaCalculation <nl> std : : vector < size_t > & extrauttmap , <nl> bool doreferencealign ) <nl> { <nl> - / / check total frame number to be added ? <nl> - / / int deviceid = loglikelihood . GetDeviceId ( ) ; <nl> + / / check total frame number to be added ? <nl> + / / int deviceid = loglikelihood . GetDeviceId ( ) ; <nl> size_t boundaryframenum ; <nl> std : : vector < size_t > validframes ; / / [ s ] cursor pointing to next utterance begin within a single parallel sequence [ s ] <nl> validframes . assign ( samplesInRecurrentStep , 0 ) ; <nl> ElemType objectValue = 0 . 0 ; <nl> - / / convert from Microsoft : : MSR : : CNTK : : Matrix to msra : : math : : ssematrixbase <nl> + / / convert from Microsoft : : MSR : : CNTK : : Matrix to msra : : math : : ssematrixbase <nl> size_t numrows = loglikelihood . GetNumRows ( ) ; <nl> size_t numcols = loglikelihood . GetNumCols ( ) ; <nl> Microsoft : : MSR : : CNTK : : Matrix < ElemType > tempmatrix ( m_deviceid ) ; <nl> <nl> - / / copy loglikelihood to pred <nl> + / / copy loglikelihood to pred <nl> if ( numcols > pred . cols ( ) ) <nl> { <nl> pred . resize ( numrows , numcols ) ; <nl> class GammaCalculation <nl> if ( samplesInRecurrentStep = = 1 ) / / no sequence parallelism <nl> { <nl> tempmatrix = loglikelihood . ColumnSlice ( ts , numframes ) ; <nl> - / / if ( m_deviceid = = CPUDEVICE ) <nl> + / / if ( m_deviceid = = CPUDEVICE ) <nl> { <nl> CopyFromCNTKMatrixToSSEMatrix ( tempmatrix , numframes , predstripe ) ; <nl> } <nl> class GammaCalculation <nl> Microsoft : : MSR : : CNTK : : Matrix < ElemType > loglikelihoodForCurrentParallelUtterance = loglikelihood . ColumnSlice ( mapi + ( validframes [ mapi ] * samplesInRecurrentStep ) , ( ( numframes - 1 ) * samplesInRecurrentStep ) + 1 ) ; <nl> tempmatrix . CopyColumnsStrided ( loglikelihoodForCurrentParallelUtterance , numframes , samplesInRecurrentStep , 1 ) ; <nl> <nl> - / / if ( doreferencealign | | m_deviceid = = CPUDEVICE ) <nl> + / / if ( doreferencealign | | m_deviceid = = CPUDEVICE ) <nl> { <nl> CopyFromCNTKMatrixToSSEMatrix ( tempmatrix , numframes , predstripe ) ; <nl> } <nl> class GammaCalculation <nl> } <nl> numavlogp / = numframes ; <nl> <nl> - / / auto_timer dengammatimer ; <nl> + / / auto_timer dengammatimer ; <nl> double denavlogp = lattices [ i ] - > second . forwardbackward ( parallellattice , <nl> ( const msra : : math : : ssematrixbase & ) predstripe , ( const msra : : asr : : simplesenonehmm & ) m_hset , <nl> ( msra : : math : : ssematrixbase & ) dengammasstripe , ( msra : : math : : ssematrixbase & ) gammasbuffer / * empty , not used * / , <nl> class GammaCalculation <nl> tempmatrix = gammafromlattice . ColumnSlice ( ts , numframes ) ; <nl> } <nl> <nl> - / / copy gamma to tempmatrix <nl> + / / copy gamma to tempmatrix <nl> if ( m_deviceid = = CPUDEVICE ) <nl> { <nl> CopyFromSSEMatrixToCNTKMatrix ( dengammas , numrows , numframes , tempmatrix , gammafromlattice . GetDeviceId ( ) ) ; <nl> class GammaCalculation <nl> bool initialmark ; <nl> msra : : dbn : : matrix dengammas ; <nl> msra : : dbn : : matrix pred ; <nl> - int m_deviceid ; / / - 1 : cpu <nl> + int m_deviceid ; / / - 1 : cpu <nl> size_t m_maxframenum ; <nl> float lmf ; / / Note that 9 was best for Fisher - - these should best be configurable <nl> float wp ; <nl> mmm a / Source / SequenceTrainingLib / latticeforwardbackward . cpp <nl> ppp b / Source / SequenceTrainingLib / latticeforwardbackward . cpp <nl> static bool islogzero ( FLOAT v ) <nl> LogicError ( " invalid backpointer resulting in state index out of range " ) ; <nl> <nl> int bp = ( int ) backpointers ( j , t ) ; / / save the backpointer before overwriting it ( gammas and backpointers are aliases of each other ) <nl> - / / thisedgealignmentsj [ t ] = ( unsigned short ) hmm . getsenoneid ( j - js ) ; <nl> + / / thisedgealignmentsj [ t ] = ( unsigned short ) hmm . getsenoneid ( j - js ) ; <nl> if ( ! returnsenoneids ) / / return binary gammas ( for MMI ; this mode is compatible with softalignmode ) <nl> for ( size_t i = js ; i < je ; i + + ) <nl> loggammas ( i , t ) = ( ( int ) i = = j ) ? 0 . 0f : LOGZERO ; <nl> void lattice : : forwardbackwardalign ( parallelstate & parallelstate , <nl> if ( parallelstate . enabled ( ) ) <nl> parallelforwardbackwardalign ( parallelstate , hset , logLLs , edgeacscores , thisedgealignments , thisbackpointers ) ; <nl> <nl> - / / zhaorui align to reference mlf <nl> + / / zhaorui align to reference mlf <nl> if ( bounds . size ( ) > 0 ) <nl> { <nl> size_t framenum = bounds . size ( ) ; <nl> void lattice : : forwardbackwardalign ( parallelstate & parallelstate , <nl> t + + ; <nl> te = t ; <nl> <nl> - / / make one phone unit <nl> + / / make one phone unit <nl> size_t phoneid = bounds [ ts ] - 1 ; <nl> refunits [ 0 ] . unit = phoneid ; <nl> refunits [ 0 ] . frames = te - ts ; <nl> void lattice : : forwardbackwardalign ( parallelstate & parallelstate , <nl> littlematrixheap refmatrixheap ( 1 ) ; / / for abcs <nl> refabcs = & refmatrixheap . newmatrix ( edgestates , te - ts + 2 ) ; <nl> const auto edgeLLs = msra : : math : : ssematrixstriperef < msra : : math : : ssematrixbase > ( const_cast < msra : : math : : ssematrixbase & > ( logLLs ) , ts , te - ts ) ; <nl> - / / do alignment <nl> + / / do alignment <nl> alignedge ( ( const_array_ref < aligninfo > ) refunits , hset , edgeLLs , * refabcs , 0 , true , refedgealignmentsj ) ; <nl> <nl> for ( t = ts ; t < te ; t + + ) <nl> void lattice : : forwardbackwardalign ( parallelstate & parallelstate , <nl> <nl> / / Phase 4 : alignment or forwardbackward on CPU for non parallel mode or verification <nl> <nl> - if ( ! parallelstate . enabled ( ) | | cpuverification ) / / non parallel mode or verification <nl> + if ( ! parallelstate . enabled ( ) | | cpuverification ) / / non parallel mode or verification <nl> { <nl> edgeacscores . resize ( edges . size ( ) ) ; <nl> std : : vector < float > edgeacscoresgpu ; <nl> void lattice : : mmierrorsignal ( parallelstate & parallelstate , double minlogpp , cons <nl> auto & loggammas = * abcs [ j ] ; <nl> <nl> const float edgelogP = ( float ) logpps [ j ] ; <nl> - / / if ( islogzero ( edgelogP ) ) / / we had a 0 prob <nl> + / / if ( islogzero ( edgelogP ) ) / / we had a 0 prob <nl> / / continue ; <nl> <nl> / / accumulate this edge ' s gamma matrix into target posteriors <nl> void lattice : : mmierrorsignal ( parallelstate & parallelstate , double minlogpp , cons <nl> for ( size_t t = ts ; t < te ; t + + ) <nl> { <nl> const size_t tutt = t + tedge ; / / time index w . r . t . utterance <nl> - / / double logsum = LOGZERO ; / / [ v - hansu ] check code for mmi ; search this comment to see all related codes <nl> + / / double logsum = LOGZERO ; / / [ v - hansu ] check code for mmi ; search this comment to see all related codes <nl> for ( size_t i = 0 ; i < n ; i + + ) <nl> { <nl> const size_t j = js + i ; / / state index for this unit in matrix <nl> double lattice : : forwardbackward ( parallelstate & parallelstate , const msra : : math : : <nl> / / allocate alpha / beta / gamma matrices ( all are sharing the same memory in - place ) <nl> std : : vector < msra : : math : : ssematrixbase * > abcs ; <nl> std : : vector < float > edgeacscores ; / / [ edge index ] acoustic scores <nl> - / / funcation call for forwardbackward on edge level <nl> + / / funcation call for forwardbackward on edge level <nl> forwardbackwardalign ( parallelstate , hset , softalignstates , minlogpp , origlogpps , abcs , matrixheap , sMBRmode / * returnsenoneids * / , edgeacscores , logLLs , thisedgealignments , thisbackpointers , uids , bounds ) ; <nl> <nl> / / PHASE 2 : lattice - level forward backward <nl> double lattice : : forwardbackward ( parallelstate & parallelstate , const msra : : math : : <nl> totalfwscore = forwardbackwardlattice ( edgeacscores , parallelstate , logpps , logalphas , logbetas , lmf , wp , amf , boostingfactor , returnEframescorrect , ( const_array_ref < size_t > & ) uids , thisedgealignments , logEframescorrect , Eframescorrectbuf , logEframescorrecttotal ) ; <nl> if ( sMBRmode & & ! returnEframescorrect ) <nl> logEframescorrecttotal = forwardbackwardlatticesMBR ( edgeacscores , hset , logalphas , logbetas , lmf , wp , amf , ( const_array_ref < size_t > & ) uids , thisedgealignments , Eframescorrectbuf ) ; <nl> - / / ^ ^ BUGBUG not tested <nl> + / / ^ ^ BUGBUG not tested <nl> } <nl> else <nl> totalfwscore = bestpathlattice ( edgeacscores , logpps , lmf , wp , amf ) ; <nl> double lattice : : forwardbackward ( parallelstate & parallelstate , const msra : : math : : <nl> <nl> const size_t numframes = logLLs . cols ( ) ; <nl> assert ( numframes = = info . numframes ) ; <nl> - / / fprintf ( stderr , " forwardbackward : total forward score % . 6f ( % d frames ) \ n " , totalfwscore , ( int ) numframes ) ; / / for now - - while we are debugging the GPU port <nl> + / / fprintf ( stderr , " forwardbackward : total forward score % . 6f ( % d frames ) \ n " , totalfwscore , ( int ) numframes ) ; / / for now - - while we are debugging the GPU port <nl> <nl> / / MMI mode <nl> if ( ! sMBRmode ) <nl> mmm a / Source / SequenceTrainingLib / parallelforwardbackward . cpp <nl> ppp b / Source / SequenceTrainingLib / parallelforwardbackward . cpp <nl> static double emulateforwardbackwardlattice ( const size_t * batchsizeforward , cons <nl> if ( returnEframescorrect ) <nl> logEframescorrecttotal = logaccbetas . front ( ) - totalbwscore ; <nl> <nl> - # if 1 / / check for matching <nl> + # if 1 / / check for matching <nl> double difffwbw = totalfwscore - totalbwscore ; <nl> double absdifffwbw = difffwbw > 0 ? difffwbw : 0 - difffwbw ; <nl> <nl> struct parallelstateimpl <nl> # endif <nl> <nl> / / LLs <nl> - / / zhaorui <nl> + / / zhaorui <nl> / * cudalogLLs - > allocate ( logLLs . rows ( ) , logLLs . cols ( ) ) ; <nl> cudalogLLs - > assign ( 0 , logLLs . rows ( ) , 0 , logLLs . cols ( ) , & logLLs ( 0 , 0 ) , logLLs . getcolstride ( ) , true ) ; / / doing this last with ' true ' so we can measure time better ; maybe remove later * / <nl> } <nl> - / / template < class ElemType > <nl> + / / template < class ElemType > <nl> void setloglls ( const Microsoft : : MSR : : CNTK : : Matrix < float > & loglls ) <nl> { <nl> * cudalogLLs = loglls ; <nl> lattice : : parallelstate : : ~ parallelstate ( ) <nl> void lattice : : parallelstate : : entercomputation ( const msra : : asr : : simplesenonehmm & hset , const mbrclassdefinition mbrclassdef ) <nl> { <nl> pimpl - > cachehset ( hset , mbrclassdef ) ; <nl> - } / / pass models in ( to GPU ) / / TODO : rethink the naming of this function <nl> + } / / pass models in ( to GPU ) / / TODO : rethink the naming of this function <nl> void lattice : : parallelstate : : copyalignments ( edgealignments & edgealignments ) <nl> { <nl> pimpl - > copyalignments ( edgealignments ) ; <nl> double lattice : : parallelforwardbackwardlattice ( parallelstate & parallelstate , con <nl> std : : vector < double > & logalphas , std : : vector < double > & logbetas , const bool returnEframescorrect , <nl> const_array_ref < size_t > & uids , std : : vector < double > & logEframescorrect , <nl> std : : vector < double > & Eframescorrectbuf , double & logEframescorrecttotal ) const <nl> - { / / ^ ^ TODO : remove this <nl> + { / / ^ ^ TODO : remove this <nl> vector < size_t > batchsizeforward ; / / record the batch size that exclude the data dependency for forward <nl> vector < size_t > batchsizebackward ; / / record the batch size that exclude the data dependency for backward <nl> <nl> void lattice : : parallelmmierrorsignal ( parallelstate & parallelstate , const edgeali <nl> latticefunctions - > mmierrorsignal ( * parallelstate - > alignresult . get ( ) , * parallelstate - > alignoffsetsgpu . get ( ) , * parallelstate - > edgesgpu . get ( ) , <nl> * parallelstate - > nodesgpu . get ( ) , * parallelstate - > logppsgpu . get ( ) , * parallelstate - > errorsignalgpu . get ( ) ) ; <nl> <nl> - / / parallelstate - > errorsignalgpu - > fetch ( 0 , errorsignal . rows ( ) , 0 , errorsignal . cols ( ) , & errorsignal ( 0 , 0 ) , errorsignal . getcolstride ( ) , true ) ; <nl> + / / parallelstate - > errorsignalgpu - > fetch ( 0 , errorsignal . rows ( ) , 0 , errorsignal . cols ( ) , & errorsignal ( 0 , 0 ) , errorsignal . getcolstride ( ) , true ) ; <nl> } <nl> else <nl> { <nl> mmm a / Tests / EndToEndTests / Image / QuickE2E / cntk . config <nl> ppp b / Tests / EndToEndTests / Image / QuickE2E / cntk . config <nl> train = [ <nl> out = Sigmoid ( z ) <nl> ] <nl> <nl> - DNNLayer ( inDim , outDim , x , parmScale ) = [ / / no non - linearity , as input for SoftMax <nl> + DNNLayer ( inDim , outDim , x , parmScale ) = [ / / no non - linearity , as input for SoftMax <nl> W = Parameter ( outDim , inDim , init = " uniform " , initValueScale = parmScale , initOnCPUOnly = false ) <nl> b = Parameter ( outDim , 1 , init = " uniform " , initValueScale = parmScale , initOnCPUOnly = false ) <nl> t = Times ( W , x ) <nl> mmm a / Tests / UnitTests / EvalTest / CNTKEvalTest . cpp <nl> ppp b / Tests / UnitTests / EvalTest / CNTKEvalTest . cpp <nl> void DoCommand ( const ConfigParameters & configRoot ) <nl> <nl> ConfigArray minibatchSize = config ( " minibatchSize " , " 256 " ) ; <nl> intargvector mbSizeArr = minibatchSize ; <nl> - size_t mbSize = 20000 ; / / mbSizeArr [ 0 ] ; <nl> + size_t mbSize = 20000 ; / / mbSizeArr [ 0 ] ; <nl> size_t epochSize = config ( " epochSize " , " 0 " ) ; <nl> if ( epochSize = = 0 ) <nl> { <nl> int wmain ( int argc , wchar_t * argv [ ] ) <nl> wstring logpath = config ( " stderr " , L " " ) ; <nl> ConfigArray command = config ( " command " , " train " ) ; <nl> <nl> - / / dump config info <nl> + / / dump config info <nl> fprintf ( stderr , " command : " ) ; <nl> for ( int i = 0 ; i < command . size ( ) ; i + + ) <nl> { <nl> fprintf ( stderr , " % s " , command [ i ] . c_str ( ) ) ; <nl> } <nl> <nl> - / / run commands <nl> + / / run commands <nl> std : : string type = config ( " precision " , " float " ) ; <nl> / / accept old precision key for backward compatibility <nl> if ( config . Exists ( " type " ) ) <nl> mmm a / Tests / UnitTests / MathPerformanceTests / MathPerformanceTests . cpp <nl> ppp b / Tests / UnitTests / MathPerformanceTests / MathPerformanceTests . cpp <nl> void AddMultiplyAndInplaceSigmoidTest ( int n , int k , int m ) <nl> CPUMatrix < ElemType > C ( n , m ) ; <nl> auto t_start = clock ( ) ; <nl> C = A * B + D ; <nl> - / / C . InplaceSigmoid ( ) ; <nl> + / / C . InplaceSigmoid ( ) ; <nl> auto t_end = clock ( ) ; <nl> std : : cout < < " CPU Matrix in : " < < 1 . 0 * ( t_end - t_start ) / CLOCKS_PER_SEC < < " seconds " < < endl ; <nl> std : : cout < < n < < " " < < k < < " " < < m < < endl ; <nl> void AddMultiplyAndInplaceSigmoidTest ( int n , int k , int m ) <nl> Matrix < ElemType > CG ( ( size_t ) n , ( size_t ) m ) ; <nl> auto t_startG = clock ( ) ; <nl> CG = AG * BG + DG ; <nl> - / / CG . InplaceSigmoid ( ) ; <nl> + / / CG . InplaceSigmoid ( ) ; <nl> auto t_endG = clock ( ) ; <nl> std : : cout < < " Matrix in : " < < 1 . 0 * ( t_endG - t_startG ) / CLOCKS_PER_SEC < < " seconds " < < endl ; <nl> } <nl> void MandSTest ( int count , int devId ) <nl> auto t_startG = clock ( ) ; <nl> for ( int i = 0 ; i < count ; + + i ) <nl> { <nl> - / / Matrix < ElemType > : : MultiplyAndWeightedAdd ( arr [ i ] , A , false , B , false , 3 . 2 * arr [ i ] , C ) ; <nl> + / / Matrix < ElemType > : : MultiplyAndWeightedAdd ( arr [ i ] , A , false , B , false , 3 . 2 * arr [ i ] , C ) ; <nl> C + = ( A * arr [ i ] ) * ( B * ( arr [ i ] * 2 . 3 ) ) ; <nl> } <nl> auto t_endG = clock ( ) ; <nl> void MandSTest ( int count , int devId ) <nl> for ( int i = 0 ; i < count ; + + i ) <nl> { <nl> CPUMatrix < ElemType > : : MultiplyAndWeightedAdd ( arr [ i ] , AC , false , BC , false , 3 . 2 * arr [ i ] , CC ) ; <nl> - / / CC + = ( arr [ i ] * AC ) * ( ( arr [ i ] * 2 . 3 ) * BC ) ; <nl> + / / CC + = ( arr [ i ] * AC ) * ( ( arr [ i ] * 2 . 3 ) * BC ) ; <nl> } <nl> auto t_endC = clock ( ) ; <nl> double valMC = 1 . 0 * ( t_endC - t_startC ) / ( CLOCKS_PER_SEC * count ) ; <nl> int wmain ( ) <nl> <nl> TestOldRnnForwardPropSRP < float > ( ) ; <nl> <nl> - / / MandSTest < float > ( 100 , 2 ) ; <nl> + / / MandSTest < float > ( 100 , 2 ) ; <nl> <nl> / * cout < < endl < < " * * * * * * * * * * * * * * * * * * * * Matrix SquareMultiplyAndWeightedAdd10TimesAvg TEST * * * * * * * * * * * * * * * * * * * * " < < endl ; <nl> SquareMultiplyAndAdd10TimesAvgTest < float > ( 4096 , 10 ) ; <nl> mmm a / Tests / UnitTests / MathTests / MatrixBlasTests . cpp <nl> ppp b / Tests / UnitTests / MathTests / MatrixBlasTests . cpp <nl> BOOST_AUTO_TEST_SUITE ( CPUMatrixSuite ) <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixMultiplyTest , RandomSeedFixture ) <nl> { <nl> - / / Part 1 : Multiply with identity matrix <nl> + / / Part 1 : Multiply with identity matrix <nl> SingleMatrix matrixA = SingleMatrix : : RandomGaussian ( 64 , 23 , 0 , 2 , IncrementCounter ( ) ) ; <nl> SingleMatrix matrixB = SingleMatrix : : Eye ( 23 ) ; <nl> SingleMatrix matrixC = matrixA * matrixB ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixMultiplyTest , RandomSeedFixture ) <nl> matrix0 ( 2 , 1 ) = 8 ; <nl> matrix0 ( 2 , 2 ) = 9 ; <nl> <nl> - / / Part 2 : Compare with Octave on toy example <nl> + / / Part 2 : Compare with Octave on toy example <nl> SingleMatrix matrix1 ( 3 , 4 , AUTOPLACEMATRIX ) ; <nl> matrix1 ( 0 , 0 ) = 8 ; <nl> matrix1 ( 0 , 1 ) = 9 ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixMultiplyTest , RandomSeedFixture ) <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixMultiplyAndPlusAndMinus , RandomSeedFixture ) <nl> { <nl> - / / Part 1 : Multiply with identity matrix <nl> + / / Part 1 : Multiply with identity matrix <nl> SingleMatrix matrixA = SingleMatrix : : RandomGaussian ( 64 , 23 , 0 , 2 , IncrementCounter ( ) ) ; <nl> SingleMatrix matrixB = SingleMatrix : : Eye ( 23 ) ; <nl> SingleMatrix matrixB1 = SingleMatrix : : RandomUniform ( 64 , 23 , - 95 . 23f , 43 . 5f , IncrementCounter ( ) ) ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixMultiplyAndPlusAndMinus , RandomSeedFixture ) <nl> BOOST_CHECK_EQUAL ( matrixA ( i , j ) + matrixB1 ( i , j ) - matrixB2 ( i , j ) , C ( i , j ) ) ; <nl> } <nl> <nl> - / / Part 3 : compare with CPUMatrix results <nl> + / / Part 3 : compare with CPUMatrix results <nl> / / TODO : Split into separate test case WI # 82 <nl> CPUMatrix < float > cpuMatrix1 = CPUMatrix < float > : : RandomUniform ( 429 , 1024 , - 1 , 1 , IncrementCounter ( ) ) ; <nl> CPUMatrix < float > cpuMatrix2 = CPUMatrix < float > : : RandomUniform ( 429 , 1024 , - 2 , 2 , IncrementCounter ( ) ) ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixScaleAndAdd_double , RandomSeedFixture ) <nl> BOOST_CHECK ( fabsf ( static_cast < float > ( matrixC ( i , j ) - ( alpha * matrixA ( i , j ) + matrixB ( i , j ) ) ) ) < c_epsilonDoubleE11 ) ; <nl> } <nl> <nl> - / / Test 2 <nl> + / / Test 2 <nl> / / TODO : Split into separate test case WI # 82 <nl> DoubleMatrix matrixA1 = DoubleMatrix : : RandomUniform ( 1024 , 512 , - 12 . 34f , 55 . 2312f , seed + 2 , 0 ) ; <nl> DoubleMatrix matrixB1 = DoubleMatrix : : RandomUniform ( 1024 , 512 , - 12 . 34f , 55 . 2312f , seed + 3 , 0 ) ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixScaleAndAdd_double , RandomSeedFixture ) <nl> BOOST_CHECK ( fabsf ( static_cast < float > ( matrixC1 ( i , j ) - ( alpha * matrixA1 ( i , j ) + beta * matrixB1 ( i , j ) ) ) ) < c_epsilonDoubleE11 ) ; <nl> } <nl> <nl> - / / Test 3 - columnwise <nl> + / / Test 3 - columnwise <nl> / / TODO : Split into separate test case WI # 82 <nl> DoubleMatrix matrixA2 = DoubleMatrix : : RandomUniform ( 1024 , 1 , - 12 . 34 , 55 . 2312 , seed + 4 , 0 ) ; <nl> DoubleMatrix matrixB2 = DoubleMatrix : : RandomUniform ( 1024 , 512 , - 12 . 34 , 55 . 2312 , seed + 5 , 0 ) ; / / Column <nl> mmm a / Tests / UnitTests / MathTests / MatrixFileWriteReadTests . cpp <nl> ppp b / Tests / UnitTests / MathTests / MatrixFileWriteReadTests . cpp <nl> BOOST_FIXTURE_TEST_CASE ( CPUMatrixFileWriteRead , RandomSeedFixture ) <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixFileWriteRead , RandomSeedFixture ) <nl> { <nl> - / / Test Matrix in Dense mode <nl> + / / Test Matrix in Dense mode <nl> Matrix < float > matrix = Matrix < float > : : RandomUniform ( 43 , 10 , - 26 . 3f , 30 . 2f , IncrementCounter ( ) ) ; <nl> Matrix < float > matrixCopy = matrix ; <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixFileWriteRead , RandomSeedFixture ) <nl> <nl> BOOST_CHECK ( matrixRead . IsEqualTo ( matrixCopy , c_epsilonFloatE5 ) ) ; <nl> <nl> - / / Test Matrix in Sparse mode <nl> + / / Test Matrix in Sparse mode <nl> Matrix < float > matrixSparse = Matrix < float > : : RandomUniform ( 43 , 10 , - 26 . 3f , 30 . 2f , IncrementCounter ( ) ) ; <nl> Matrix < float > matrixSparseCopy = matrixSparse ; <nl> <nl> mmm a / Tests / UnitTests / MathTests / MatrixSparseDenseInteractionsTests . cpp <nl> ppp b / Tests / UnitTests / MathTests / MatrixSparseDenseInteractionsTests . cpp <nl> BOOST_AUTO_TEST_SUITE ( GPUMatrixSuite ) <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixChangeModesBetweenDenseAndSparse , RandomSeedFixture ) <nl> { <nl> - / / This test should fail if you don ' t have CUDA GPU <nl> + / / This test should fail if you don ' t have CUDA GPU <nl> Matrix < float > mA ; <nl> mA . AssignTruncateBottomOf ( Matrix < float > : : RandomUniform ( dim1 , dim2 , - 3 . 0f , 0 . 1f , IncrementCounter ( ) ) , 0 ) ; <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixChangeModesBetweenDenseAndSparse , RandomSeedFixtur <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixSparseTimesDense , RandomSeedFixture ) <nl> { <nl> - / / DENSE <nl> + / / DENSE <nl> Matrix < float > mAdense ; <nl> mAdense . AssignTruncateBottomOf ( Matrix < float > : : RandomUniform ( dim1 , dim2 , - 3 . 0f , 0 . 1f , IncrementCounter ( ) ) , 0 ) ; <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixSparseTimesDense , RandomSeedFixture ) <nl> Matrix < float > mAsparse ( mAdense ) ; <nl> mAsparse . SwitchToMatrixType ( MatrixType : : SPARSE , matrixFormatSparseCSR , true ) ; <nl> <nl> - / / DENSE <nl> + / / DENSE <nl> Matrix < float > mB = Matrix < float > : : RandomGaussian ( dim2 , dim3 , 1 . 0f , 4 . 0f , IncrementCounter ( ) ) ; <nl> Matrix < float > mC = Matrix < float > : : RandomGaussian ( dim1 , dim3 , 1 . 0f , 2 . 0f , IncrementCounter ( ) ) ; <nl> Matrix < float > mD ( mC ) ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixSparseTimesSparse , RandomSeedFixture ) <nl> BOOST_CHECK ( mCsparse . IsEqualTo ( mCdense , c_epsilonFloatE4 ) ) ; <nl> <nl> / / TODO : as soon as beta ! = 0 . 0 the ' MultiplyAndWeightedAdd ' fails with stack overflow ( also in the first test 5 lines above ) <nl> - / / alpha = 2 . 4f ; <nl> - / / beta = 3 . 4f ; <nl> - / / mCsparse . SwitchToMatrixType ( MatrixType : : SPARSE , matrixFormatSparseCSR , true ) ; <nl> - / / Matrix < float > : : MultiplyAndWeightedAdd ( alpha , mAdense , transposeA , mBdense , transposeB , beta , mCdense ) ; <nl> - / / Matrix < float > : : MultiplyAndWeightedAdd ( alpha , mAsparse , transposeA , mBsparse , transposeB , beta , mCsparse ) ; <nl> - / / mCsparse . SwitchToMatrixType ( MatrixType : : DENSE , matrixFormatDense , true ) ; <nl> - / / BOOST_CHECK ( mCsparse . IsEqualTo ( mCdense , c_epsilonFloatE4 ) ) ; <nl> + / / alpha = 2 . 4f ; <nl> + / / beta = 3 . 4f ; <nl> + / / mCsparse . SwitchToMatrixType ( MatrixType : : SPARSE , matrixFormatSparseCSR , true ) ; <nl> + / / Matrix < float > : : MultiplyAndWeightedAdd ( alpha , mAdense , transposeA , mBdense , transposeB , beta , mCdense ) ; <nl> + / / Matrix < float > : : MultiplyAndWeightedAdd ( alpha , mAsparse , transposeA , mBsparse , transposeB , beta , mCsparse ) ; <nl> + / / mCsparse . SwitchToMatrixType ( MatrixType : : DENSE , matrixFormatDense , true ) ; <nl> + / / BOOST_CHECK ( mCsparse . IsEqualTo ( mCdense , c_epsilonFloatE4 ) ) ; <nl> } <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixSparsePlusSparse , RandomSeedFixture ) <nl> mmm a / Tests / UnitTests / MathTests / MatrixTests . cpp <nl> ppp b / Tests / UnitTests / MathTests / MatrixTests . cpp <nl> BOOST_FIXTURE_TEST_CASE ( MatrixConstructors , RandomSeedFixture ) <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixMoveTest1 , RandomSeedFixture ) <nl> { <nl> - / / no moves required <nl> + / / no moves required <nl> SingleMatrix a ; <nl> SingleMatrix b ; <nl> b . Resize ( 50 , 100 ) ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixMoveTest1 , RandomSeedFixture ) <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixMoveTest2 , RandomSeedFixture ) <nl> { <nl> - / / potentially a move is required <nl> + / / potentially a move is required <nl> SingleMatrix a ; <nl> SingleMatrix b ; <nl> b . Resize ( 50 , 100 ) ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixMoveTest2 , RandomSeedFixture ) <nl> BOOST_CHECK_EQUAL ( a . GetDeviceId ( ) , 0 ) ; <nl> BOOST_CHECK_EQUAL ( b . GetDeviceId ( ) , 0 ) ; <nl> <nl> - b ( 12 , 13 ) = 14 ; / / this will move whole matrix B from GPU to CPU <nl> + b ( 12 , 13 ) = 14 ; / / this will move whole matrix B from GPU to CPU <nl> BOOST_CHECK_EQUAL ( b . GetDeviceId ( ) , - 1 ) ; <nl> <nl> std : : swap ( a , b ) ; / / this will not only swap A and B but will put them to their preferred device ( GPU if present ) <nl> BOOST_FIXTURE_TEST_CASE ( MatrixMoveTest2 , RandomSeedFixture ) <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixDeepCopy , RandomSeedFixture ) <nl> { <nl> - / / This is deep copy , not move <nl> + / / This is deep copy , not move <nl> SingleMatrix a ; <nl> SingleMatrix b ; <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixInitRandomUniformSeed , RandomSeedFixture ) <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixSetValueMethods , RandomSeedFixture ) <nl> { <nl> - / / void SetValue ( const ElemType v ) ; <nl> + / / void SetValue ( const ElemType v ) ; <nl> SingleMatrix a ( 32 , 12 , AUTOPLACEMATRIX ) ; <nl> BOOST_CHECK_EQUAL ( 32 , a . GetNumRows ( ) ) ; <nl> BOOST_CHECK_EQUAL ( 12 , a . GetNumCols ( ) ) ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixSetValueMethods , RandomSeedFixture ) <nl> BOOST_CHECK_EQUAL ( v , a ( i , j ) ) ; <nl> } <nl> <nl> - / / void SetValue ( const Matrix < ElemType > & deepCopyFrom ) ; <nl> + / / void SetValue ( const Matrix < ElemType > & deepCopyFrom ) ; <nl> SingleMatrix b ; <nl> b . SetValue ( a ) ; <nl> foreach_coord ( i , j , b ) <nl> BOOST_FIXTURE_TEST_CASE ( MatrixSetValueMethods , RandomSeedFixture ) <nl> BOOST_CHECK_EQUAL ( v , b ( i , j ) ) ; <nl> } <nl> <nl> - / / void SetValue ( const size_t numRows , const size_t numCols , ElemType * pArray , const bool srcIsColMajor ) ; <nl> + / / void SetValue ( const size_t numRows , const size_t numCols , ElemType * pArray , const bool srcIsColMajor ) ; <nl> std : : array < float , 7 > arrVector = { 123 . 0f , 0 . 23f , - 22 . 0f , 63 . 0f , 43 . 42f , 324 . 3f , 99912 . 0f } ; <nl> <nl> float * arr = arrVector . data ( ) ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixSetValueMethods , RandomSeedFixture ) <nl> BOOST_CHECK_EQUAL ( arr [ i ] , bbbb ( i , 3 ) ) ; <nl> } <nl> <nl> - / / void SetDiagonalValue ( const ElemType v ) ; <nl> + / / void SetDiagonalValue ( const ElemType v ) ; <nl> SingleMatrix c ( 4 , 4 , AUTOPLACEMATRIX ) ; <nl> const float val = - 0 . 00332f ; <nl> c . SetDiagonalValue ( val ) ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixSetValueMethods , RandomSeedFixture ) <nl> BOOST_CHECK_EQUAL ( 0 , c ( i , j ) ) ; <nl> } <nl> <nl> - / / void SetDiagonalValue ( const Matrix < ElemType > & vector ) ; <nl> + / / void SetDiagonalValue ( const Matrix < ElemType > & vector ) ; <nl> SingleMatrix d ( 4 , 1 , AUTOPLACEMATRIX ) ; <nl> const float val1 = 43 . 324f ; <nl> d . SetValue ( val1 ) ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixMultiAndDiv , RandomSeedFixture ) <nl> m2 ( 2 , 2 ) = 135 ; <nl> BOOST_CHECK ( m3 . IsEqualTo ( m2 ) ) ; <nl> <nl> - / / Multiplications of arbitrary matrix with 1x1 matrix <nl> + / / Multiplications of arbitrary matrix with 1x1 matrix <nl> <nl> SingleMatrix a ( 2 , 3 , AUTOPLACEMATRIX ) ; <nl> a ( 0 , 0 ) = 1 ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixColumnElementMultiply , RandomSeedFixture ) <nl> <nl> BOOST_FIXTURE_TEST_CASE ( MatrixAssignXOf , RandomSeedFixture ) <nl> { <nl> - / / AssignDifferenceOf <nl> + / / AssignDifferenceOf <nl> Matrix < float > a = Matrix < float > : : RandomUniform ( 429 , 1024 , 5 , 32 , IncrementCounter ( ) ) ; <nl> Matrix < float > b = Matrix < float > : : RandomUniform ( 429 , 1024 , 5 , 32 , IncrementCounter ( ) ) ; <nl> Matrix < float > c ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixAssignXOf , RandomSeedFixture ) <nl> { <nl> BOOST_CHECK_EQUAL ( c ( i , j ) , 1 - a ( i , j ) ) ; <nl> } <nl> - / / <nl> + / / <nl> <nl> - / / AssignElementProductOf <nl> + / / AssignElementProductOf <nl> c . AssignElementProductOf ( a , b ) ; <nl> foreach_coord ( i , j , c ) <nl> { <nl> BOOST_CHECK_EQUAL ( c ( i , j ) , a ( i , j ) * b ( i , j ) ) ; <nl> } <nl> <nl> - / / AddElementProductOf <nl> + / / AddElementProductOf <nl> Matrix < float > c_copy ( c ) ; <nl> c . AddElementProductOf ( a , b ) ; <nl> foreach_coord ( i , j , c ) <nl> BOOST_FIXTURE_TEST_CASE ( MatrixAssignXOf , RandomSeedFixture ) <nl> BOOST_CHECK_EQUAL ( c ( i , j ) , c_copy ( i , j ) + a ( i , j ) * b ( i , j ) ) ; <nl> } <nl> <nl> - / / AssignSigmoidOf <nl> + / / AssignSigmoidOf <nl> CPUMatrix < float > ac = CPUMatrix < float > : : RandomUniform ( 429 , 1024 , 5 , 32 , IncrementCounter ( ) ) ; <nl> CPUMatrix < float > bc = CPUMatrix < float > : : RandomUniform ( 429 , 1024 , - 5 , 12 , IncrementCounter ( ) ) ; <nl> Matrix < float > d ( ac . GetNumRows ( ) , ac . GetNumCols ( ) , ac . GetArray ( ) , matrixFlagNormal ) ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixAssignXOf , RandomSeedFixture ) <nl> BOOST_CHECK_LT ( fabs ( ac ( i , j ) - d ( i , j ) ) , c_epsilonFloatE5 ) ; <nl> } <nl> <nl> - / / AssignSignOf <nl> + / / AssignSignOf <nl> Matrix < float > m1 = Matrix < float > : : RandomUniform ( 42 , 12 , - 5 , 12 , IncrementCounter ( ) ) ; <nl> Matrix < float > m2 ( 4 , 5 , AUTOPLACEMATRIX ) ; <nl> m2 . AssignSignOf ( m1 ) ; <nl> BOOST_FIXTURE_TEST_CASE ( MatrixAssignXOf , RandomSeedFixture ) <nl> BOOST_CHECK_EQUAL ( m4 ( i , j ) + SIGNUMZ ( v ) , m3 ( i , j ) ) ; <nl> } <nl> <nl> - / / AssignTruncateBottom and Top <nl> + / / AssignTruncateBottom and Top <nl> Matrix < float > m5 ( 2 , 2 , AUTOPLACEMATRIX ) ; <nl> m5 ( 0 , 0 ) = 1 ; <nl> m5 ( 0 , 1 ) = 2 ; <nl> | normalized inconsistent commenting style from " / / text " to " / / text " | microsoft/CNTK | a4cf44544a1b361452f34f68af9e1e1746425878 | 2016-01-22T21:58:47Z |
mmm a / include / caffe / blob . hpp <nl> ppp b / include / caffe / blob . hpp <nl> class Blob { <nl> diff_ ( ) { } <nl> explicit Blob ( const int num , const int channels , const int height , <nl> const int width ) ; <nl> - virtual ~ Blob ( ) { } <nl> void Reshape ( const int num , const int channels , const int height , <nl> const int width ) ; <nl> inline int num ( ) const { return num_ ; } <nl> class Blob { <nl> return * ( cpu_diff ( ) + offset ( n , c , h , w ) ) ; <nl> } <nl> <nl> + inline const shared_ptr < SyncedMemory > & data ( ) const { <nl> + CHECK ( data_ ) ; <nl> + return data_ ; <nl> + } <nl> + <nl> + inline const shared_ptr < SyncedMemory > & diff ( ) const { <nl> + CHECK ( diff_ ) ; <nl> + return diff_ ; <nl> + } <nl> + <nl> const Dtype * cpu_data ( ) const ; <nl> const Dtype * gpu_data ( ) const ; <nl> const Dtype * cpu_diff ( ) const ; <nl> class Blob { <nl> void FromProto ( const BlobProto & proto ) ; <nl> void ToProto ( BlobProto * proto , bool write_diff = false ) const ; <nl> <nl> + void AdoptData ( const Blob & other ) ; <nl> + void AdoptDiff ( const Blob & other ) ; <nl> + <nl> protected : <nl> shared_ptr < SyncedMemory > data_ ; <nl> shared_ptr < SyncedMemory > diff_ ; <nl> mmm a / src / caffe / blob . cpp <nl> ppp b / src / caffe / blob . cpp <nl> Dtype * Blob < Dtype > : : mutable_gpu_diff ( ) { <nl> return reinterpret_cast < Dtype * > ( diff_ - > mutable_gpu_data ( ) ) ; <nl> } <nl> <nl> + template < typename Dtype > <nl> + void Blob < Dtype > : : AdoptData ( const Blob & other ) { <nl> + CHECK_EQ ( count_ , other . count ( ) ) ; <nl> + data_ = other . data ( ) ; <nl> + } <nl> + <nl> + template < typename Dtype > <nl> + void Blob < Dtype > : : AdoptDiff ( const Blob & other ) { <nl> + CHECK_EQ ( count_ , other . count ( ) ) ; <nl> + diff_ = other . diff ( ) ; <nl> + } <nl> + <nl> template < typename Dtype > <nl> void Blob < Dtype > : : Update ( ) { <nl> / / We will perform update based on where the data is located . <nl> mmm a / src / caffe / layers / flatten_layer . cpp <nl> ppp b / src / caffe / layers / flatten_layer . cpp <nl> void FlattenLayer < Dtype > : : SetUp ( const vector < Blob < Dtype > * > & bottom , <nl> template < typename Dtype > <nl> Dtype FlattenLayer < Dtype > : : Forward_cpu ( const vector < Blob < Dtype > * > & bottom , <nl> vector < Blob < Dtype > * > * top ) { <nl> - const Dtype * bottom_data = bottom [ 0 ] - > cpu_data ( ) ; <nl> - Dtype * top_data = ( * top ) [ 0 ] - > mutable_cpu_data ( ) ; <nl> - caffe_copy ( count_ , bottom_data , top_data ) ; <nl> + ( * top ) [ 0 ] - > AdoptData ( * bottom [ 0 ] ) ; <nl> return Dtype ( 0 . ) ; <nl> } <nl> <nl> template < typename Dtype > <nl> void FlattenLayer < Dtype > : : Backward_cpu ( const vector < Blob < Dtype > * > & top , <nl> const bool propagate_down , vector < Blob < Dtype > * > * bottom ) { <nl> - const Dtype * top_diff = top [ 0 ] - > cpu_diff ( ) ; <nl> - Dtype * bottom_diff = ( * bottom ) [ 0 ] - > mutable_cpu_diff ( ) ; <nl> - caffe_copy ( count_ , top_diff , bottom_diff ) ; <nl> + ( * bottom ) [ 0 ] - > AdoptDiff ( * top [ 0 ] ) ; <nl> } <nl> <nl> INSTANTIATE_CLASS ( FlattenLayer ) ; <nl> mmm a / src / caffe / layers / flatten_layer . cu <nl> ppp b / src / caffe / layers / flatten_layer . cu <nl> namespace caffe { <nl> template < typename Dtype > <nl> Dtype FlattenLayer < Dtype > : : Forward_gpu ( const vector < Blob < Dtype > * > & bottom , <nl> vector < Blob < Dtype > * > * top ) { <nl> - const Dtype * bottom_data = bottom [ 0 ] - > gpu_data ( ) ; <nl> - Dtype * top_data = ( * top ) [ 0 ] - > mutable_gpu_data ( ) ; <nl> - caffe_gpu_copy ( count_ , bottom_data , top_data ) ; <nl> + ( * top ) [ 0 ] - > AdoptData ( * bottom [ 0 ] ) ; <nl> return Dtype ( 0 . ) ; <nl> } <nl> <nl> template < typename Dtype > <nl> void FlattenLayer < Dtype > : : Backward_gpu ( const vector < Blob < Dtype > * > & top , <nl> const bool propagate_down , vector < Blob < Dtype > * > * bottom ) { <nl> - const Dtype * top_diff = top [ 0 ] - > gpu_diff ( ) ; <nl> - Dtype * bottom_diff = ( * bottom ) [ 0 ] - > mutable_gpu_diff ( ) ; <nl> - caffe_gpu_copy ( count_ , top_diff , bottom_diff ) ; <nl> + ( * bottom ) [ 0 ] - > AdoptDiff ( * top [ 0 ] ) ; <nl> } <nl> <nl> INSTANTIATE_CLASS ( FlattenLayer ) ; <nl> mmm a / src / caffe / layers / split_layer . cpp <nl> ppp b / src / caffe / layers / split_layer . cpp <nl> void SplitLayer < Dtype > : : SetUp ( const vector < Blob < Dtype > * > & bottom , <nl> template < typename Dtype > <nl> Dtype SplitLayer < Dtype > : : Forward_cpu ( const vector < Blob < Dtype > * > & bottom , <nl> vector < Blob < Dtype > * > * top ) { <nl> - const Dtype * bottom_data = bottom [ 0 ] - > cpu_data ( ) ; <nl> for ( int i = 0 ; i < top - > size ( ) ; + + i ) { <nl> - if ( i = = 0 & & ( * top ) [ i ] = = bottom [ 0 ] ) { <nl> - continue ; <nl> - } <nl> - Dtype * top_data = ( * top ) [ i ] - > mutable_cpu_data ( ) ; <nl> - caffe_copy ( count_ , bottom_data , top_data ) ; <nl> + ( * top ) [ i ] - > AdoptData ( * bottom [ 0 ] ) ; <nl> } <nl> return Dtype ( 0 . ) ; <nl> } <nl> template < typename Dtype > <nl> void SplitLayer < Dtype > : : Backward_cpu ( const vector < Blob < Dtype > * > & top , <nl> const bool propagate_down , vector < Blob < Dtype > * > * bottom ) { <nl> if ( propagate_down ) { <nl> - const Dtype * top_diff = top [ 0 ] - > cpu_diff ( ) ; <nl> - Dtype * bottom_diff = ( * bottom ) [ 0 ] - > mutable_cpu_diff ( ) ; <nl> - / / Initialize by copying first top blob diff to our diff , unless we ' re <nl> - / / doing in - place computation for the first blob , in which case the diff is <nl> - / / already initialized . <nl> - if ( top [ 0 ] ! = ( * bottom ) [ 0 ] ) { <nl> - caffe_copy ( count_ , top_diff , bottom_diff ) ; <nl> - } <nl> + ( * bottom ) [ 0 ] - > AdoptDiff ( * top [ 0 ] ) ; <nl> / / Add remaining top blob diffs . <nl> + Dtype * bottom_diff = ( * bottom ) [ 0 ] - > mutable_cpu_diff ( ) ; <nl> for ( int i = 1 ; i < top . size ( ) ; + + i ) { <nl> - top_diff = top [ i ] - > cpu_diff ( ) ; <nl> + const Dtype * top_diff = top [ i ] - > cpu_diff ( ) ; <nl> caffe_axpy ( count_ , Dtype ( 1 . ) , top_diff , bottom_diff ) ; <nl> } <nl> } <nl> mmm a / src / caffe / layers / split_layer . cu <nl> ppp b / src / caffe / layers / split_layer . cu <nl> namespace caffe { <nl> template < typename Dtype > <nl> Dtype SplitLayer < Dtype > : : Forward_gpu ( const vector < Blob < Dtype > * > & bottom , <nl> vector < Blob < Dtype > * > * top ) { <nl> - const Dtype * bottom_data = bottom [ 0 ] - > gpu_data ( ) ; <nl> for ( int i = 0 ; i < top - > size ( ) ; + + i ) { <nl> - if ( i = = 0 & & ( * top ) [ i ] = = bottom [ 0 ] ) { <nl> - continue ; <nl> - } <nl> - Dtype * top_data = ( * top ) [ i ] - > mutable_gpu_data ( ) ; <nl> - caffe_gpu_copy ( count_ , bottom_data , top_data ) ; <nl> + ( * top ) [ i ] - > AdoptData ( * bottom [ 0 ] ) ; <nl> } <nl> return Dtype ( 0 . ) ; <nl> } <nl> template < typename Dtype > <nl> void SplitLayer < Dtype > : : Backward_gpu ( const vector < Blob < Dtype > * > & top , <nl> const bool propagate_down , vector < Blob < Dtype > * > * bottom ) { <nl> if ( propagate_down ) { <nl> - const Dtype * top_diff = top [ 0 ] - > gpu_diff ( ) ; <nl> - Dtype * bottom_diff = ( * bottom ) [ 0 ] - > mutable_gpu_diff ( ) ; <nl> - / / Initialize by copying first top blob diff to our diff , unless we ' re <nl> - / / doing in - place computation for the first blob , in which case the diff is <nl> - / / already initialized . <nl> - if ( top [ 0 ] ! = ( * bottom ) [ 0 ] ) { <nl> - caffe_gpu_copy ( count_ , top_diff , bottom_diff ) ; <nl> - } <nl> + ( * bottom ) [ 0 ] - > AdoptDiff ( * top [ 0 ] ) ; <nl> / / Add remaining top blob diffs . <nl> + Dtype * bottom_diff = ( * bottom ) [ 0 ] - > mutable_gpu_diff ( ) ; <nl> for ( int i = 1 ; i < top . size ( ) ; + + i ) { <nl> - top_diff = top [ i ] - > gpu_diff ( ) ; <nl> + const Dtype * top_diff = top [ i ] - > gpu_diff ( ) ; <nl> caffe_gpu_axpy ( count_ , Dtype ( 1 . ) , top_diff , bottom_diff ) ; <nl> } <nl> } <nl> | add Adopt { Data , Diff } methods to blobs to enable " virtual copying " | BVLC/caffe | 7fb71deeb80bb538134e445d298517522823b90c | 2014-04-12T06:58:02Z |
mmm a / ccmain / linerec . cpp <nl> ppp b / ccmain / linerec . cpp <nl> void Tesseract : : TrainLineRecognizer ( const STRING & input_imagename , <nl> return ; <nl> } <nl> TrainFromBoxes ( boxes , texts , block_list , & images ) ; <nl> + images . Shuffle ( ) ; <nl> if ( ! images . SaveDocument ( lstmf_name . string ( ) , NULL ) ) { <nl> tprintf ( " Failed to write training data to % s ! \ n " , lstmf_name . string ( ) ) ; <nl> } <nl> void Tesseract : : TrainFromBoxes ( const GenericVector < TBOX > & boxes , <nl> int box_count = boxes . size ( ) ; <nl> / / Process all the text lines in this page , as defined by the boxes . <nl> int end_box = 0 ; <nl> - for ( int start_box = 0 ; start_box < box_count ; start_box = end_box ) { <nl> + / / Don ' t let \ t , which marks newlines in the box file , get into the line <nl> + / / content , as that makes the line unusable in training . <nl> + while ( end_box < texts . size ( ) & & texts [ end_box ] = = " \ t " ) + + end_box ; <nl> + for ( int start_box = end_box ; start_box < box_count ; start_box = end_box ) { <nl> / / Find the textline of boxes starting at start and their bounding box . <nl> TBOX line_box = boxes [ start_box ] ; <nl> STRING line_str = texts [ start_box ] ; <nl> void Tesseract : : TrainFromBoxes ( const GenericVector < TBOX > & boxes , <nl> } <nl> if ( imagedata ! = NULL ) <nl> training_data - > AddPageToDocument ( imagedata ) ; <nl> - if ( end_box < texts . size ( ) & & texts [ end_box ] = = " \ t " ) + + end_box ; <nl> + / / Don ' t let \ t , which marks newlines in the box file , get into the line <nl> + / / content , as that makes the line unusable in training . <nl> + while ( end_box < texts . size ( ) & & texts [ end_box ] = = " \ t " ) + + end_box ; <nl> } <nl> } <nl> <nl> mmm a / ccstruct / boxread . cpp <nl> ppp b / ccstruct / boxread . cpp <nl> bool ReadAllBoxes ( int target_page , bool skip_blanks , const STRING & filename , <nl> GenericVector < char > box_data ; <nl> if ( ! tesseract : : LoadDataFromFile ( BoxFileName ( filename ) , & box_data ) ) <nl> return false ; <nl> + / / Convert the array of bytes to a string , so it can be used by the parser . <nl> + box_data . push_back ( ' \ 0 ' ) ; <nl> return ReadMemBoxes ( target_page , skip_blanks , & box_data [ 0 ] , boxes , texts , <nl> box_texts , pages ) ; <nl> } <nl> mmm a / ccstruct / imagedata . cpp <nl> ppp b / ccstruct / imagedata . cpp <nl> <nl> <nl> # include " imagedata . h " <nl> <nl> + # if defined ( __MINGW32__ ) <nl> + # include < unistd . h > <nl> + # else <nl> + # include < thread > <nl> + # endif <nl> + <nl> # include " allheaders . h " <nl> # include " boxread . h " <nl> # include " callcpp . h " <nl> # include " helpers . h " <nl> # include " tprintf . h " <nl> <nl> - # if defined ( __MINGW32__ ) <nl> - # include < unistd . h > <nl> - # else <nl> - # include < thread > <nl> - # endif <nl> - <nl> / / Number of documents to read ahead while training . Doesn ' t need to be very <nl> / / large . <nl> const int kMaxReadAhead = 8 ; <nl> inT64 DocumentData : : UnCache ( ) { <nl> return memory_saved ; <nl> } <nl> <nl> + / / Shuffles all the pages in the document . <nl> + void DocumentData : : Shuffle ( ) { <nl> + TRand random ; <nl> + / / Different documents get shuffled differently , but the same for the same <nl> + / / name . <nl> + random . set_seed ( document_name_ . string ( ) ) ; <nl> + int num_pages = pages_ . size ( ) ; <nl> + / / Execute one random swap for each page in the document . <nl> + for ( int i = 0 ; i < num_pages ; + + i ) { <nl> + int src = random . IntRand ( ) % num_pages ; <nl> + int dest = random . IntRand ( ) % num_pages ; <nl> + std : : swap ( pages_ [ src ] , pages_ [ dest ] ) ; <nl> + } <nl> + } <nl> + <nl> / / Locks the pages_mutex_ and Loads as many pages can fit in max_memory_ <nl> / / starting at index pages_offset_ . <nl> bool DocumentData : : ReCachePages ( ) { <nl> mmm a / ccstruct / imagedata . h <nl> ppp b / ccstruct / imagedata . h <nl> class DocumentData { <nl> / / Removes all pages from memory and frees the memory , but does not forget <nl> / / the document metadata . Returns the memory saved . <nl> inT64 UnCache ( ) ; <nl> + / / Shuffles all the pages in the document . <nl> + void Shuffle ( ) ; <nl> <nl> private : <nl> / / Sets the value of total_pages_ behind a mutex . <nl> mmm a / ccstruct / pageres . cpp <nl> ppp b / ccstruct / pageres . cpp <nl> void WERD_RES : : FilterWordChoices ( int debug_level ) { <nl> if ( choice - > unichar_id ( i ) ! = best_choice - > unichar_id ( j ) & & <nl> choice - > certainty ( i ) - best_choice - > certainty ( j ) < threshold ) { <nl> if ( debug_level > = 2 ) { <nl> - STRING label ; <nl> - label . add_str_int ( " \ nDiscarding bad choice # " , index ) ; <nl> - choice - > print ( label . string ( ) ) ; <nl> - tprintf ( " i % d j % d Chunk % d Choice - > Blob [ i ] . Certainty % . 4g " <nl> - " BestChoice - > ChunkCertainty [ Chunk ] % g Threshold % g \ n " , <nl> - i , j , chunk , choice - > certainty ( i ) , <nl> - best_choice - > certainty ( j ) , threshold ) ; <nl> + choice - > print ( " WorstCertaintyDiffWorseThan " ) ; <nl> + tprintf ( <nl> + " i % d j % d Choice - > Blob [ i ] . Certainty % . 4g " <nl> + " WorstOtherChoiceCertainty % g Threshold % g \ n " , <nl> + i , j , choice - > certainty ( i ) , best_choice - > certainty ( j ) , threshold ) ; <nl> + tprintf ( " Discarding bad choice # % d \ n " , index ) ; <nl> } <nl> delete it . extract ( ) ; <nl> break ; <nl> mmm a / ccutil / genericvector . h <nl> ppp b / ccutil / genericvector . h <nl> inline bool LoadDataFromFile ( const STRING & filename , <nl> fseek ( fp , 0 , SEEK_END ) ; <nl> size_t size = ftell ( fp ) ; <nl> fseek ( fp , 0 , SEEK_SET ) ; <nl> - / / Pad with a 0 , just in case we treat the result as a string . <nl> - data - > init_to_size ( static_cast < int > ( size ) + 1 , 0 ) ; <nl> + data - > init_to_size ( static_cast < int > ( size ) , 0 ) ; <nl> bool result = fread ( & ( * data ) [ 0 ] , 1 , size , fp ) = = size ; <nl> fclose ( fp ) ; <nl> return result ; <nl> inline bool SaveDataToFile ( const GenericVector < char > & data , <nl> fclose ( fp ) ; <nl> return result ; <nl> } <nl> + / / Reads a file as a vector of STRING . <nl> + inline bool LoadFileLinesToStrings ( const STRING & filename , <nl> + GenericVector < STRING > * lines ) { <nl> + GenericVector < char > data ; <nl> + if ( ! LoadDataFromFile ( filename . string ( ) , & data ) ) { <nl> + return false ; <nl> + } <nl> + STRING lines_str ( & data [ 0 ] , data . size ( ) ) ; <nl> + lines_str . split ( ' \ n ' , lines ) ; <nl> + return true ; <nl> + } <nl> <nl> template < typename T > <nl> bool cmp_eq ( T const & t1 , T const & t2 ) { <nl> mmm a / ccutil / helpers . h <nl> ppp b / ccutil / helpers . h <nl> <nl> <nl> # include < stdio . h > <nl> # include < string . h > <nl> + # include < functional > <nl> + # include < string > <nl> <nl> # include " host . h " <nl> <nl> class TRand { <nl> void set_seed ( uinT64 seed ) { <nl> seed_ = seed ; <nl> } <nl> + / / Sets the seed using a hash of a string . <nl> + void set_seed ( const std : : string & str ) { <nl> + std : : hash < std : : string > hasher ; <nl> + set_seed ( static_cast < uinT64 > ( hasher ( str ) ) ) ; <nl> + } <nl> <nl> / / Returns an integer in the range 0 to MAX_INT32 . <nl> inT32 IntRand ( ) { <nl> mmm a / lstm / fullyconnected . cpp <nl> ppp b / lstm / fullyconnected . cpp <nl> StaticShape FullyConnected : : OutputShape ( const StaticShape & input_shape ) const { <nl> return result ; <nl> } <nl> <nl> + / / Suspends / Enables training by setting the training_ flag . Serialize and <nl> + / / DeSerialize only operate on the run - time data if state is false . <nl> + void FullyConnected : : SetEnableTraining ( TrainingState state ) { <nl> + if ( state = = TS_RE_ENABLE ) { <nl> + if ( training_ = = TS_DISABLED ) weights_ . InitBackward ( false ) ; <nl> + training_ = TS_ENABLED ; <nl> + } else { <nl> + training_ = state ; <nl> + } <nl> + } <nl> + <nl> / / Sets up the network for training . Initializes weights using weights of <nl> / / scale ` range ` picked according to the random number generator ` randomizer ` . <nl> int FullyConnected : : InitWeights ( float range , TRand * randomizer ) { <nl> void FullyConnected : : DebugWeights ( ) { <nl> / / Writes to the given file . Returns false in case of error . <nl> bool FullyConnected : : Serialize ( TFile * fp ) const { <nl> if ( ! Network : : Serialize ( fp ) ) return false ; <nl> - if ( ! weights_ . Serialize ( training_ , fp ) ) return false ; <nl> + if ( ! weights_ . Serialize ( IsTraining ( ) , fp ) ) return false ; <nl> return true ; <nl> } <nl> <nl> / / Reads from the given file . Returns false in case of error . <nl> / / If swap is true , assumes a big / little - endian swap is needed . <nl> bool FullyConnected : : DeSerialize ( bool swap , TFile * fp ) { <nl> - if ( ! weights_ . DeSerialize ( training_ , swap , fp ) ) return false ; <nl> + if ( ! weights_ . DeSerialize ( IsTraining ( ) , swap , fp ) ) return false ; <nl> return true ; <nl> } <nl> <nl> void FullyConnected : : Forward ( bool debug , const NetworkIO & input , <nl> } <nl> ForwardTimeStep ( d_input , i_input , t , temp_line ) ; <nl> output - > WriteTimeStep ( t , temp_line ) ; <nl> - if ( training ( ) & & type_ ! = NT_SOFTMAX ) { <nl> + if ( IsTraining ( ) & & type_ ! = NT_SOFTMAX ) { <nl> acts_ . CopyTimeStepFrom ( t , * output , t ) ; <nl> } <nl> } <nl> / / Zero all the elements that are in the padding around images that allows <nl> / / multiple different - sized images to exist in a single array . <nl> / / acts_ is only used if this is not a softmax op . <nl> - if ( training ( ) & & type_ ! = NT_SOFTMAX ) { <nl> + if ( IsTraining ( ) & & type_ ! = NT_SOFTMAX ) { <nl> acts_ . ZeroInvalidElements ( ) ; <nl> } <nl> output - > ZeroInvalidElements ( ) ; <nl> void FullyConnected : : SetupForward ( const NetworkIO & input , <nl> const TransposedArray * input_transpose ) { <nl> / / Softmax output is always float , so save the input type . <nl> int_mode_ = input . int_mode ( ) ; <nl> - if ( training ( ) ) { <nl> + if ( IsTraining ( ) ) { <nl> acts_ . Resize ( input , no_ ) ; <nl> / / Source_ is a transposed copy of input . It isn ' t needed if provided . <nl> external_source_ = input_transpose ; <nl> void FullyConnected : : SetupForward ( const NetworkIO & input , <nl> void FullyConnected : : ForwardTimeStep ( const double * d_input , const inT8 * i_input , <nl> int t , double * output_line ) { <nl> / / input is copied to source_ line - by - line for cache coherency . <nl> - if ( training ( ) & & external_source_ = = NULL & & d_input ! = NULL ) <nl> + if ( IsTraining ( ) & & external_source_ = = NULL & & d_input ! = NULL ) <nl> source_t_ . WriteStrided ( t , d_input ) ; <nl> if ( d_input ! = NULL ) <nl> weights_ . MatrixDotVector ( d_input , output_line ) ; <nl> mmm a / lstm / fullyconnected . h <nl> ppp b / lstm / fullyconnected . h <nl> class FullyConnected : public Network { <nl> type_ = type ; <nl> } <nl> <nl> + / / Suspends / Enables training by setting the training_ flag . Serialize and <nl> + / / DeSerialize only operate on the run - time data if state is false . <nl> + virtual void SetEnableTraining ( TrainingState state ) ; <nl> + <nl> / / Sets up the network for training . Initializes weights using weights of <nl> / / scale ` range ` picked according to the random number generator ` randomizer ` . <nl> virtual int InitWeights ( float range , TRand * randomizer ) ; <nl> mmm a / lstm / lstm . cpp <nl> ppp b / lstm / lstm . cpp <nl> StaticShape LSTM : : OutputShape ( const StaticShape & input_shape ) const { <nl> return result ; <nl> } <nl> <nl> + / / Suspends / Enables training by setting the training_ flag . Serialize and <nl> + / / DeSerialize only operate on the run - time data if state is false . <nl> + void LSTM : : SetEnableTraining ( TrainingState state ) { <nl> + if ( state = = TS_RE_ENABLE ) { <nl> + if ( training_ = = TS_DISABLED ) { <nl> + for ( int w = 0 ; w < WT_COUNT ; + + w ) { <nl> + if ( w = = GFS & & ! Is2D ( ) ) continue ; <nl> + gate_weights_ [ w ] . InitBackward ( false ) ; <nl> + } <nl> + } <nl> + training_ = TS_ENABLED ; <nl> + } else { <nl> + training_ = state ; <nl> + } <nl> + if ( softmax_ ! = NULL ) softmax_ - > SetEnableTraining ( state ) ; <nl> + } <nl> + <nl> / / Sets up the network for training . Initializes weights using weights of <nl> / / scale ` range ` picked according to the random number generator ` randomizer ` . <nl> int LSTM : : InitWeights ( float range , TRand * randomizer ) { <nl> bool LSTM : : Serialize ( TFile * fp ) const { <nl> if ( fp - > FWrite ( & na_ , sizeof ( na_ ) , 1 ) ! = 1 ) return false ; <nl> for ( int w = 0 ; w < WT_COUNT ; + + w ) { <nl> if ( w = = GFS & & ! Is2D ( ) ) continue ; <nl> - if ( ! gate_weights_ [ w ] . Serialize ( training_ , fp ) ) return false ; <nl> + if ( ! gate_weights_ [ w ] . Serialize ( IsTraining ( ) , fp ) ) return false ; <nl> } <nl> if ( softmax_ ! = NULL & & ! softmax_ - > Serialize ( fp ) ) return false ; <nl> return true ; <nl> bool LSTM : : DeSerialize ( bool swap , TFile * fp ) { <nl> is_2d_ = false ; <nl> for ( int w = 0 ; w < WT_COUNT ; + + w ) { <nl> if ( w = = GFS & & ! Is2D ( ) ) continue ; <nl> - if ( ! gate_weights_ [ w ] . DeSerialize ( training_ , swap , fp ) ) return false ; <nl> + if ( ! gate_weights_ [ w ] . DeSerialize ( IsTraining ( ) , swap , fp ) ) return false ; <nl> if ( w = = CI ) { <nl> ns_ = gate_weights_ [ CI ] . NumOutputs ( ) ; <nl> is_2d_ = na_ - nf_ = = ni_ + 2 * ns_ ; <nl> void LSTM : : Forward ( bool debug , const NetworkIO & input , <nl> MultiplyAccumulate ( ns_ , temp_lines [ CI ] , temp_lines [ GI ] , curr_state ) ; <nl> / / Clip curr_state to a sane range . <nl> ClipVector < double > ( ns_ , - kStateClip , kStateClip , curr_state ) ; <nl> - if ( training_ ) { <nl> + if ( IsTraining ( ) ) { <nl> / / Save the gate node values . <nl> node_values_ [ CI ] . WriteTimeStep ( t , temp_lines [ CI ] ) ; <nl> node_values_ [ GI ] . WriteTimeStep ( t , temp_lines [ GI ] ) ; <nl> void LSTM : : Forward ( bool debug , const NetworkIO & input , <nl> if ( Is2D ( ) ) node_values_ [ GFS ] . WriteTimeStep ( t , temp_lines [ GFS ] ) ; <nl> } <nl> FuncMultiply < HFunc > ( curr_state , temp_lines [ GO ] , ns_ , curr_output ) ; <nl> - if ( training_ ) state_ . WriteTimeStep ( t , curr_state ) ; <nl> + if ( IsTraining ( ) ) state_ . WriteTimeStep ( t , curr_state ) ; <nl> if ( softmax_ ! = NULL ) { <nl> if ( input . int_mode ( ) ) { <nl> int_output - > WriteTimeStep ( 0 , curr_output ) ; <nl> void LSTM : : PrintDW ( ) { <nl> void LSTM : : ResizeForward ( const NetworkIO & input ) { <nl> source_ . Resize ( input , na_ ) ; <nl> which_fg_ . ResizeNoInit ( input . Width ( ) , ns_ ) ; <nl> - if ( training_ ) { <nl> + if ( IsTraining ( ) ) { <nl> state_ . ResizeFloat ( input , ns_ ) ; <nl> for ( int w = 0 ; w < WT_COUNT ; + + w ) { <nl> if ( w = = GFS & & ! Is2D ( ) ) continue ; <nl> mmm a / lstm / lstm . h <nl> ppp b / lstm / lstm . h <nl> class LSTM : public Network { <nl> return spec ; <nl> } <nl> <nl> + / / Suspends / Enables training by setting the training_ flag . Serialize and <nl> + / / DeSerialize only operate on the run - time data if state is false . <nl> + virtual void SetEnableTraining ( TrainingState state ) ; <nl> + <nl> / / Sets up the network for training . Initializes weights using weights of <nl> / / scale ` range ` picked according to the random number generator ` randomizer ` . <nl> virtual int InitWeights ( float range , TRand * randomizer ) ; <nl> mmm a / lstm / lstmrecognizer . cpp <nl> ppp b / lstm / lstmrecognizer . cpp <nl> bool LSTMRecognizer : : RecognizeLine ( const ImageData & image_data , bool invert , <nl> float label_threshold , float * scale_factor , <nl> NetworkIO * inputs , NetworkIO * outputs ) { <nl> / / Maximum width of image to train on . <nl> - const int kMaxImageWidth = 2048 ; <nl> + const int kMaxImageWidth = 2560 ; <nl> / / This ensures consistent recognition results . <nl> SetRandomSeed ( ) ; <nl> int min_width = network_ - > XScaleFactor ( ) ; <nl> bool LSTMRecognizer : : RecognizeLine ( const ImageData & image_data , bool invert , <nl> tprintf ( " Line cannot be recognized ! ! \ n " ) ; <nl> return false ; <nl> } <nl> - if ( network_ - > training ( ) & & pixGetWidth ( pix ) > kMaxImageWidth ) { <nl> + if ( network_ - > IsTraining ( ) & & pixGetWidth ( pix ) > kMaxImageWidth ) { <nl> tprintf ( " Image too large to learn ! ! Size = % dx % d \ n " , pixGetWidth ( pix ) , <nl> pixGetHeight ( pix ) ) ; <nl> pixDestroy ( & pix ) ; <nl> mmm a / lstm / lstmtrainer . cpp <nl> ppp b / lstm / lstmtrainer . cpp <nl> bool LSTMTrainer : : TryLoadingCheckpoint ( const char * filename ) { <nl> / / Note : Call before InitNetwork ! <nl> void LSTMTrainer : : InitCharSet ( const UNICHARSET & unicharset , <nl> const STRING & script_dir , int train_flags ) { <nl> - / / Call before InitNetwork . <nl> - ASSERT_HOST ( network_ = = NULL ) ; <nl> EmptyConstructor ( ) ; <nl> training_flags_ = train_flags ; <nl> ccutil_ . unicharset . CopyFrom ( unicharset ) ; <nl> void LSTMTrainer : : InitCharSet ( const UNICHARSET & unicharset , <nl> / / Note : Call before InitNetwork ! <nl> void LSTMTrainer : : InitCharSet ( const UNICHARSET & unicharset , <nl> const UnicharCompress recoder ) { <nl> - / / Call before InitNetwork . <nl> - ASSERT_HOST ( network_ = = NULL ) ; <nl> EmptyConstructor ( ) ; <nl> int flags = TF_COMPRESS_UNICHARSET ; <nl> training_flags_ = static_cast < TrainingFlags > ( flags ) ; <nl> int LSTMTrainer : : InitTensorFlowNetwork ( const std : : string & tf_proto ) { <nl> # endif <nl> } <nl> <nl> + / / Resets all the iteration counters for fine tuning or traininng a head , <nl> + / / where we want the error reporting to reset . <nl> + void LSTMTrainer : : InitIterations ( ) { <nl> + sample_iteration_ = 0 ; <nl> + training_iteration_ = 0 ; <nl> + learning_iteration_ = 0 ; <nl> + prev_sample_iteration_ = 0 ; <nl> + best_error_rate_ = 100 . 0 ; <nl> + best_iteration_ = 0 ; <nl> + worst_error_rate_ = 0 . 0 ; <nl> + worst_iteration_ = 0 ; <nl> + stall_iteration_ = kMinStallIterations ; <nl> + improvement_steps_ = kMinStallIterations ; <nl> + perfect_delay_ = 0 ; <nl> + last_perfect_training_iteration_ = 0 ; <nl> + for ( int i = 0 ; i < ET_COUNT ; + + i ) { <nl> + best_error_rates_ [ i ] = 100 . 0 ; <nl> + worst_error_rates_ [ i ] = 0 . 0 ; <nl> + error_buffers_ [ i ] . init_to_size ( kRollingBufferSize_ , 0 . 0 ) ; <nl> + error_rates_ [ i ] = 100 . 0 ; <nl> + } <nl> + error_rate_of_last_saved_best_ = kMinStartedErrorRate ; <nl> + } <nl> + <nl> / / If the training sample is usable , grid searches for the optimal <nl> / / dict_ratio / cert_offset , and returns the results in a string of space - <nl> / / separated triplets of ratio , offset = worderr . <nl> bool LSTMTrainer : : Serialize ( TFile * fp ) const { <nl> / / If swap is true , assumes a big / little - endian swap is needed . <nl> bool LSTMTrainer : : DeSerialize ( bool swap , TFile * fp ) { <nl> if ( ! LSTMRecognizer : : DeSerialize ( swap , fp ) ) return false ; <nl> - if ( fp - > FRead ( & learning_iteration_ , sizeof ( learning_iteration_ ) , 1 ) ! = 1 ) <nl> - return false ; <nl> + if ( fp - > FRead ( & learning_iteration_ , sizeof ( learning_iteration_ ) , 1 ) ! = 1 ) { <nl> + / / Special case . If we successfully decoded the recognizer , but fail here <nl> + / / then it means we were just given a recognizer , so issue a warning and <nl> + / / allow it . <nl> + tprintf ( " Warning : LSTMTrainer deserialized an LSTMRecognizer ! \ n " ) ; <nl> + learning_iteration_ = 0 ; <nl> + network_ - > SetEnableTraining ( TS_RE_ENABLE ) ; <nl> + return true ; <nl> + } <nl> if ( fp - > FRead ( & prev_sample_iteration_ , sizeof ( prev_sample_iteration_ ) , 1 ) ! = <nl> 1 ) <nl> return false ; <nl> int LSTMTrainer : : ReduceLayerLearningRates ( double factor , int num_samples , <nl> SaveTrainingDump ( LIGHT , this , & orig_trainer ) ; <nl> for ( int i = 0 ; i < num_layers ; + + i ) { <nl> Network * layer = GetLayer ( layers [ i ] ) ; <nl> - num_weights [ i ] = layer - > training ( ) ? layer - > num_weights ( ) : 0 ; <nl> + num_weights [ i ] = layer - > IsTraining ( ) ? layer - > num_weights ( ) : 0 ; <nl> } <nl> int iteration = sample_iteration ( ) ; <nl> for ( int s = 0 ; s < num_samples ; + + s ) { <nl> Trainability LSTMTrainer : : TrainOnLine ( const ImageData * trainingdata , <nl> training_iteration ( ) % debug_interval_ = = 0 ; <nl> / / Run backprop on the output . <nl> NetworkIO bp_deltas ; <nl> - if ( network_ - > training ( ) & & <nl> + if ( network_ - > IsTraining ( ) & & <nl> ( trainable ! = PERFECT | | <nl> training_iteration ( ) > <nl> last_perfect_training_iteration_ + perfect_delay_ ) ) { <nl> Trainability LSTMTrainer : : PrepareForBackward ( const ImageData * trainingdata , <nl> return UNENCODABLE ; <nl> } <nl> targets - > Resize ( * fwd_outputs , network_ - > NumOutputs ( ) ) ; <nl> + double text_error = 100 . 0 ; <nl> LossType loss_type = OutputLossType ( ) ; <nl> if ( loss_type = = LT_SOFTMAX ) { <nl> if ( ! ComputeTextTargets ( * fwd_outputs , truth_labels , targets ) ) { <nl> bool LSTMTrainer : : ReadSizedTrainingDump ( const char * data , int size ) { <nl> void LSTMTrainer : : SaveRecognitionDump ( GenericVector < char > * data ) const { <nl> TFile fp ; <nl> fp . OpenWrite ( data ) ; <nl> - network_ - > SetEnableTraining ( false ) ; <nl> + network_ - > SetEnableTraining ( TS_TEMP_DISABLE ) ; <nl> ASSERT_HOST ( LSTMRecognizer : : Serialize ( & fp ) ) ; <nl> - network_ - > SetEnableTraining ( true ) ; <nl> + network_ - > SetEnableTraining ( TS_RE_ENABLE ) ; <nl> } <nl> <nl> / / Reads and returns a previously saved recognizer from memory . <nl> void LSTMTrainer : : EmptyConstructor ( ) { <nl> serialize_amount_ = FULL ; <nl> training_stage_ = 0 ; <nl> num_training_stages_ = 2 ; <nl> - prev_sample_iteration_ = 0 ; <nl> - best_error_rate_ = 100 . 0 ; <nl> - best_iteration_ = 0 ; <nl> - worst_error_rate_ = 0 . 0 ; <nl> - worst_iteration_ = 0 ; <nl> - stall_iteration_ = kMinStallIterations ; <nl> - learning_iteration_ = 0 ; <nl> - improvement_steps_ = kMinStallIterations ; <nl> - perfect_delay_ = 0 ; <nl> - last_perfect_training_iteration_ = 0 ; <nl> - for ( int i = 0 ; i < ET_COUNT ; + + i ) { <nl> - best_error_rates_ [ i ] = 100 . 0 ; <nl> - worst_error_rates_ [ i ] = 0 . 0 ; <nl> - error_buffers_ [ i ] . init_to_size ( kRollingBufferSize_ , 0 . 0 ) ; <nl> - error_rates_ [ i ] = 100 . 0 ; <nl> - } <nl> - sample_iteration_ = 0 ; <nl> - training_iteration_ = 0 ; <nl> - error_rate_of_last_saved_best_ = kMinStartedErrorRate ; <nl> + InitIterations ( ) ; <nl> } <nl> <nl> / / Sets the unicharset properties using the given script_dir as a source of <nl> mmm a / lstm / lstmtrainer . h <nl> ppp b / lstm / lstmtrainer . h <nl> class LSTMTrainer : public LSTMRecognizer { <nl> / / Returns the global step of TensorFlow graph or 0 if failed . <nl> / / Building a compatible TF graph : See tfnetwork . proto . <nl> int InitTensorFlowNetwork ( const std : : string & tf_proto ) ; <nl> + / / Resets all the iteration counters for fine tuning or training a head , <nl> + / / where we want the error reporting to reset . <nl> + void InitIterations ( ) ; <nl> <nl> / / Accessors . <nl> double ActivationError ( ) const { <nl> mmm a / lstm / network . cpp <nl> ppp b / lstm / network . cpp <nl> char const * const Network : : kTypeNames [ NT_COUNT ] = { <nl> } ; <nl> <nl> Network : : Network ( ) <nl> - : type_ ( NT_NONE ) , training_ ( true ) , needs_to_backprop_ ( true ) , <nl> - network_flags_ ( 0 ) , ni_ ( 0 ) , no_ ( 0 ) , num_weights_ ( 0 ) , <nl> - forward_win_ ( NULL ) , backward_win_ ( NULL ) , randomizer_ ( NULL ) { <nl> - } <nl> + : type_ ( NT_NONE ) , <nl> + training_ ( TS_ENABLED ) , <nl> + needs_to_backprop_ ( true ) , <nl> + network_flags_ ( 0 ) , <nl> + ni_ ( 0 ) , <nl> + no_ ( 0 ) , <nl> + num_weights_ ( 0 ) , <nl> + forward_win_ ( NULL ) , <nl> + backward_win_ ( NULL ) , <nl> + randomizer_ ( NULL ) { } <nl> Network : : Network ( NetworkType type , const STRING & name , int ni , int no ) <nl> - : type_ ( type ) , training_ ( true ) , needs_to_backprop_ ( true ) , <nl> - network_flags_ ( 0 ) , ni_ ( ni ) , no_ ( no ) , num_weights_ ( 0 ) , <nl> - name_ ( name ) , forward_win_ ( NULL ) , backward_win_ ( NULL ) , randomizer_ ( NULL ) { <nl> - } <nl> + : type_ ( type ) , <nl> + training_ ( TS_ENABLED ) , <nl> + needs_to_backprop_ ( true ) , <nl> + network_flags_ ( 0 ) , <nl> + ni_ ( ni ) , <nl> + no_ ( no ) , <nl> + num_weights_ ( 0 ) , <nl> + name_ ( name ) , <nl> + forward_win_ ( NULL ) , <nl> + backward_win_ ( NULL ) , <nl> + randomizer_ ( NULL ) { } <nl> <nl> Network : : ~ Network ( ) { <nl> } <nl> <nl> - / / Ends training by setting the training_ flag to false . Serialize and <nl> - / / DeSerialize will now only operate on the run - time data . <nl> - void Network : : SetEnableTraining ( bool state ) { <nl> - training_ = state ; <nl> + / / Suspends / Enables / Permanently disables training by setting the training_ <nl> + / / flag . Serialize and DeSerialize only operate on the run - time data if state <nl> + / / is TS_DISABLED or TS_TEMP_DISABLE . Specifying TS_TEMP_DISABLE will <nl> + / / temporarily disable layers in state TS_ENABLED , allowing a trainer to <nl> + / / serialize as if it were a recognizer . <nl> + / / TS_RE_ENABLE will re - enable layers that were previously in any disabled <nl> + / / state . If in TS_TEMP_DISABLE then the flag is just changed , but if in <nl> + / / TS_DISABLED , the deltas in the weight matrices are reinitialized so that a <nl> + / / recognizer can be converted back to a trainer . <nl> + void Network : : SetEnableTraining ( TrainingState state ) { <nl> + if ( state = = TS_RE_ENABLE ) { <nl> + training_ = TS_ENABLED ; <nl> + } else { <nl> + training_ = state ; <nl> + } <nl> } <nl> <nl> / / Sets flags that control the action of the network . See NetworkFlags enum <nl> bool Network : : DeSerialize ( bool swap , TFile * fp ) { <nl> } <nl> type_ = static_cast < NetworkType > ( data ) ; <nl> if ( fp - > FRead ( & data , sizeof ( data ) , 1 ) ! = 1 ) return false ; <nl> - training_ = data ! = 0 ; <nl> + training_ = data = = TS_ENABLED ? TS_ENABLED : TS_DISABLED ; <nl> if ( fp - > FRead ( & data , sizeof ( data ) , 1 ) ! = 1 ) return false ; <nl> needs_to_backprop_ = data ! = 0 ; <nl> if ( fp - > FRead ( & network_flags_ , sizeof ( network_flags_ ) , 1 ) ! = 1 ) return false ; <nl> mmm a / lstm / network . h <nl> ppp b / lstm / network . h <nl> enum NetworkFlags { <nl> NF_ADA_GRAD = 128 , / / Weight - specific learning rate . <nl> } ; <nl> <nl> + / / State of training and desired state used in SetEnableTraining . <nl> + enum TrainingState { <nl> + / / Valid states of training_ . <nl> + TS_DISABLED , / / Disabled permanently . <nl> + TS_ENABLED , / / Enabled for backprop and to write a training dump . <nl> + TS_TEMP_DISABLE , / / Temporarily disabled to write a recognition dump . <nl> + / / Valid only for SetEnableTraining . <nl> + TS_RE_ENABLE , / / Re - Enable whatever the current state . <nl> + } ; <nl> + <nl> / / Base class for network types . Not quite an abstract base class , but almost . <nl> / / Most of the time no isolated Network exists , except prior to <nl> / / deserialization . <nl> class Network { <nl> NetworkType type ( ) const { <nl> return type_ ; <nl> } <nl> - bool training ( ) const { <nl> - return training_ ; <nl> - } <nl> + bool IsTraining ( ) const { return training_ = = TS_ENABLED ; } <nl> bool needs_to_backprop ( ) const { <nl> return needs_to_backprop_ ; <nl> } <nl> class Network { <nl> / / multiple sub - networks that can have their own learning rate . <nl> virtual bool IsPlumbingType ( ) const { return false ; } <nl> <nl> - / / Suspends / Enables training by setting the training_ flag . Serialize and <nl> - / / DeSerialize only operate on the run - time data if state is false . <nl> - virtual void SetEnableTraining ( bool state ) ; <nl> + / / Suspends / Enables / Permanently disables training by setting the training_ <nl> + / / flag . Serialize and DeSerialize only operate on the run - time data if state <nl> + / / is TS_DISABLED or TS_TEMP_DISABLE . Specifying TS_TEMP_DISABLE will <nl> + / / temporarily disable layers in state TS_ENABLED , allowing a trainer to <nl> + / / serialize as if it were a recognizer . <nl> + / / TS_RE_ENABLE will re - enable layers that were previously in any disabled <nl> + / / state . If in TS_TEMP_DISABLE then the flag is just changed , but if in <nl> + / / TS_DISABLED , the deltas in the weight matrices are reinitialized so that a <nl> + / / recognizer can be converted back to a trainer . <nl> + virtual void SetEnableTraining ( TrainingState state ) ; <nl> <nl> / / Sets flags that control the action of the network . See NetworkFlags enum <nl> / / for bit values . <nl> class Network { <nl> <nl> protected : <nl> NetworkType type_ ; / / Type of the derived network class . <nl> - bool training_ ; / / Are we currently training ? <nl> + TrainingState training_ ; / / Are we currently training ? <nl> bool needs_to_backprop_ ; / / This network needs to output back_deltas . <nl> inT32 network_flags_ ; / / Behavior control flags in NetworkFlags . <nl> inT32 ni_ ; / / Number of input values . <nl> mmm a / lstm / parallel . cpp <nl> ppp b / lstm / parallel . cpp <nl> void Parallel : : Forward ( bool debug , const NetworkIO & input , <nl> / / Source for divided replicated . <nl> NetworkScratch : : IO source_part ; <nl> TransposedArray * src_transpose = NULL ; <nl> - if ( training ( ) & & type_ = = NT_REPLICATED ) { <nl> + if ( IsTraining ( ) & & type_ = = NT_REPLICATED ) { <nl> / / Make a transposed copy of the input . <nl> input . Transpose ( & transposed_input_ ) ; <nl> src_transpose = & transposed_input_ ; <nl> mmm a / lstm / plumbing . cpp <nl> ppp b / lstm / plumbing . cpp <nl> Plumbing : : ~ Plumbing ( ) { <nl> <nl> / / Suspends / Enables training by setting the training_ flag . Serialize and <nl> / / DeSerialize only operate on the run - time data if state is false . <nl> - void Plumbing : : SetEnableTraining ( bool state ) { <nl> + void Plumbing : : SetEnableTraining ( TrainingState state ) { <nl> Network : : SetEnableTraining ( state ) ; <nl> for ( int i = 0 ; i < stack_ . size ( ) ; + + i ) <nl> stack_ [ i ] - > SetEnableTraining ( state ) ; <nl> void Plumbing : : AddToStack ( Network * network ) { <nl> / / Sets needs_to_backprop_ to needs_backprop and calls on sub - network <nl> / / according to needs_backprop | | any weights in this network . <nl> bool Plumbing : : SetupNeedsBackprop ( bool needs_backprop ) { <nl> - needs_to_backprop_ = needs_backprop ; <nl> - bool retval = needs_backprop ; <nl> - for ( int i = 0 ; i < stack_ . size ( ) ; + + i ) { <nl> - if ( stack_ [ i ] - > SetupNeedsBackprop ( needs_backprop ) ) <nl> - retval = true ; <nl> + if ( IsTraining ( ) ) { <nl> + needs_to_backprop_ = needs_backprop ; <nl> + bool retval = needs_backprop ; <nl> + for ( int i = 0 ; i < stack_ . size ( ) ; + + i ) { <nl> + if ( stack_ [ i ] - > SetupNeedsBackprop ( needs_backprop ) ) retval = true ; <nl> + } <nl> + return retval ; <nl> } <nl> - return retval ; <nl> + / / Frozen networks don ' t do backprop . <nl> + needs_to_backprop_ = false ; <nl> + return false ; <nl> } <nl> <nl> / / Returns an integer reduction factor that the network applies to the <nl> void Plumbing : : Update ( float learning_rate , float momentum , int num_samples ) { <nl> else <nl> learning_rates_ . push_back ( learning_rate ) ; <nl> } <nl> - if ( stack_ [ i ] - > training ( ) ) <nl> + if ( stack_ [ i ] - > IsTraining ( ) ) { <nl> stack_ [ i ] - > Update ( learning_rate , momentum , num_samples ) ; <nl> + } <nl> } <nl> } <nl> <nl> mmm a / lstm / plumbing . h <nl> ppp b / lstm / plumbing . h <nl> class Plumbing : public Network { <nl> <nl> / / Suspends / Enables training by setting the training_ flag . Serialize and <nl> / / DeSerialize only operate on the run - time data if state is false . <nl> - virtual void SetEnableTraining ( bool state ) ; <nl> + virtual void SetEnableTraining ( TrainingState state ) ; <nl> <nl> / / Sets flags that control the action of the network . See NetworkFlags enum <nl> / / for bit values . <nl> mmm a / lstm / series . cpp <nl> ppp b / lstm / series . cpp <nl> void Series : : Forward ( bool debug , const NetworkIO & input , <nl> bool Series : : Backward ( bool debug , const NetworkIO & fwd_deltas , <nl> NetworkScratch * scratch , <nl> NetworkIO * back_deltas ) { <nl> - if ( ! training ( ) ) return false ; <nl> + if ( ! IsTraining ( ) ) return false ; <nl> int stack_size = stack_ . size ( ) ; <nl> ASSERT_HOST ( stack_size > 1 ) ; <nl> / / Revolving intermediate buffers . <nl> bool Series : : Backward ( bool debug , const NetworkIO & fwd_deltas , <nl> NetworkScratch : : IO buffer2 ( fwd_deltas , scratch ) ; <nl> / / Run each network in reverse order , giving the back_deltas output of n as <nl> / / the fwd_deltas input to n - 1 , with the 0 network providing the real output . <nl> - if ( ! stack_ . back ( ) - > training ( ) | | <nl> + if ( ! stack_ . back ( ) - > IsTraining ( ) | | <nl> ! stack_ . back ( ) - > Backward ( debug , fwd_deltas , scratch , buffer1 ) ) <nl> return false ; <nl> for ( int i = stack_size - 2 ; i > = 0 ; i - = 2 ) { <nl> - if ( ! stack_ [ i ] - > training ( ) | | <nl> + if ( ! stack_ [ i ] - > IsTraining ( ) | | <nl> ! stack_ [ i ] - > Backward ( debug , * buffer1 , scratch , <nl> i > 0 ? buffer2 : back_deltas ) ) <nl> return false ; <nl> if ( i = = 0 ) return needs_to_backprop_ ; <nl> - if ( ! stack_ [ i - 1 ] - > training ( ) | | <nl> + if ( ! stack_ [ i - 1 ] - > IsTraining ( ) | | <nl> ! stack_ [ i - 1 ] - > Backward ( debug , * buffer2 , scratch , <nl> i > 1 ? buffer1 : back_deltas ) ) <nl> return false ; <nl> mmm a / lstm / stridemap . h <nl> ppp b / lstm / stridemap . h <nl> class StrideMap { <nl> bool IsValid ( ) const ; <nl> / / Returns true if the index of the given dimension is the last . <nl> bool IsLast ( FlexDimensions dimension ) const ; <nl> - / / Given that the dimensions up to and including dim - 1 are valid , returns the <nl> - / / maximum index for dimension dim . <nl> + / / Given that the dimensions up to and including dim - 1 are valid , returns <nl> + / / the maximum index for dimension dim . <nl> int MaxIndexOfDim ( FlexDimensions dim ) const ; <nl> / / Adds the given offset to the given dimension . Returns true if the result <nl> / / makes a valid index . <nl> mmm a / lstm / weightmatrix . cpp <nl> ppp b / lstm / weightmatrix . cpp <nl> void TransposedArray : : Transpose ( const GENERIC_2D_ARRAY < double > & input ) { <nl> int WeightMatrix : : InitWeightsFloat ( int no , int ni , bool ada_grad , <nl> float weight_range , TRand * randomizer ) { <nl> int_mode_ = false ; <nl> - use_ada_grad_ = ada_grad ; <nl> - if ( use_ada_grad_ ) dw_sq_sum_ . Resize ( no , ni , 0 . 0 ) ; <nl> wf_ . Resize ( no , ni , 0 . 0 ) ; <nl> if ( randomizer ! = NULL ) { <nl> for ( int i = 0 ; i < no ; + + i ) { <nl> int WeightMatrix : : InitWeightsFloat ( int no , int ni , bool ada_grad , <nl> } <nl> } <nl> } <nl> - InitBackward ( ) ; <nl> + InitBackward ( ada_grad ) ; <nl> return ni * no ; <nl> } <nl> <nl> void WeightMatrix : : ConvertToInt ( ) { <nl> <nl> / / Allocates any needed memory for running Backward , and zeroes the deltas , <nl> / / thus eliminating any existing momentum . <nl> - void WeightMatrix : : InitBackward ( ) { <nl> + void WeightMatrix : : InitBackward ( bool ada_grad ) { <nl> int no = int_mode_ ? wi_ . dim1 ( ) : wf_ . dim1 ( ) ; <nl> int ni = int_mode_ ? wi_ . dim2 ( ) : wf_ . dim2 ( ) ; <nl> + use_ada_grad_ = ada_grad ; <nl> dw_ . Resize ( no , ni , 0 . 0 ) ; <nl> updates_ . Resize ( no , ni , 0 . 0 ) ; <nl> wf_t_ . Transpose ( wf_ ) ; <nl> + if ( use_ada_grad_ ) dw_sq_sum_ . Resize ( no , ni , 0 . 0 ) ; <nl> } <nl> <nl> / / Flag on mode to indicate that this weightmatrix uses inT8 . <nl> bool WeightMatrix : : DeSerialize ( bool training , bool swap , TFile * fp ) { <nl> } else { <nl> if ( ! wf_ . DeSerialize ( swap , fp ) ) return false ; <nl> if ( training ) { <nl> - InitBackward ( ) ; <nl> + InitBackward ( use_ada_grad_ ) ; <nl> if ( ! updates_ . DeSerialize ( swap , fp ) ) return false ; <nl> if ( use_ada_grad_ & & ! dw_sq_sum_ . DeSerialize ( swap , fp ) ) return false ; <nl> } <nl> bool WeightMatrix : : DeSerializeOld ( bool training , bool swap , TFile * fp ) { <nl> FloatToDouble ( float_array , & wf_ ) ; <nl> } <nl> if ( training ) { <nl> - InitBackward ( ) ; <nl> + InitBackward ( use_ada_grad_ ) ; <nl> if ( ! float_array . DeSerialize ( swap , fp ) ) return false ; <nl> FloatToDouble ( float_array , & updates_ ) ; <nl> / / Errs was only used in int training , which is now dead . <nl> mmm a / lstm / weightmatrix . h <nl> ppp b / lstm / weightmatrix . h <nl> class WeightMatrix { <nl> <nl> / / Allocates any needed memory for running Backward , and zeroes the deltas , <nl> / / thus eliminating any existing momentum . <nl> - void InitBackward ( ) ; <nl> + void InitBackward ( bool ada_grad ) ; <nl> <nl> / / Writes to the given file . Returns false in case of error . <nl> bool Serialize ( bool training , TFile * fp ) const ; <nl> mmm a / training / Makefile . am <nl> ppp b / training / Makefile . am <nl> endif <nl> <nl> noinst_HEADERS = \ <nl> boxchar . h commandlineflags . h commontraining . h degradeimage . h \ <nl> - fileio . h icuerrorcode . h ligature_table . h normstrngs . h \ <nl> + fileio . h icuerrorcode . h ligature_table . h lstmtester . h normstrngs . h \ <nl> mergenf . h pango_font_info . h stringrenderer . h \ <nl> tessopt . h tlog . h unicharset_training_utils . h util . h <nl> <nl> libtesseract_training_la_LIBADD = \ <nl> <nl> libtesseract_training_la_SOURCES = \ <nl> boxchar . cpp commandlineflags . cpp commontraining . cpp degradeimage . cpp \ <nl> - fileio . cpp ligature_table . cpp normstrngs . cpp pango_font_info . cpp \ <nl> + fileio . cpp ligature_table . cpp lstmtester . cpp normstrngs . cpp pango_font_info . cpp \ <nl> stringrenderer . cpp tlog . cpp unicharset_training_utils . cpp <nl> <nl> libtesseract_tessopt_la_SOURCES = \ <nl> tessopt . cpp <nl> <nl> bin_PROGRAMS = ambiguous_words classifier_tester cntraining combine_tessdata \ <nl> - dawg2wordlist lstmtraining mftraining set_unicharset_properties shapeclustering \ <nl> + dawg2wordlist lstmeval lstmtraining mftraining set_unicharset_properties shapeclustering \ <nl> text2image unicharset_extractor wordlist2dawg <nl> <nl> ambiguous_words_SOURCES = ambiguous_words . cpp <nl> dawg2wordlist_LDADD + = \ <nl> . . / api / libtesseract . la <nl> endif <nl> <nl> + lstmeval_SOURCES = lstmeval . cpp <nl> + # lstmeval_LDFLAGS = - static <nl> + lstmeval_LDADD = \ <nl> + libtesseract_training . la \ <nl> + libtesseract_tessopt . la \ <nl> + $ ( libicu ) <nl> + if USING_MULTIPLELIBS <nl> + lstmeval_LDADD + = \ <nl> + . . / textord / libtesseract_textord . la \ <nl> + . . / classify / libtesseract_classify . la \ <nl> + . . / dict / libtesseract_dict . la \ <nl> + . . / arch / libtesseract_avx . la \ <nl> + . . / arch / libtesseract_sse . la \ <nl> + . . / lstm / libtesseract_lstm . la \ <nl> + . . / ccstruct / libtesseract_ccstruct . la \ <nl> + . . / cutil / libtesseract_cutil . la \ <nl> + . . / viewer / libtesseract_viewer . la \ <nl> + . . / ccmain / libtesseract_main . la \ <nl> + . . / cube / libtesseract_cube . la \ <nl> + . . / neural_networks / runtime / libtesseract_neural . la \ <nl> + . . / wordrec / libtesseract_wordrec . la \ <nl> + . . / ccutil / libtesseract_ccutil . la <nl> + else <nl> + lstmeval_LDADD + = \ <nl> + . . / api / libtesseract . la <nl> + endif <nl> + <nl> lstmtraining_SOURCES = lstmtraining . cpp <nl> # lstmtraining_LDFLAGS = - static <nl> lstmtraining_LDADD = \ <nl> new file mode 100644 <nl> index 000000000 . . aa990e232 <nl> mmm / dev / null <nl> ppp b / training / lstmeval . cpp <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : lstmeval . cpp <nl> + / / Description : Evaluation program for LSTM - based networks . <nl> + / / Author : Ray Smith <nl> + / / Created : Wed Nov 23 12 : 20 : 06 PST 2016 <nl> + / / <nl> + / / ( C ) Copyright 2016 , Google Inc . <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # ifndef USE_STD_NAMESPACE <nl> + # include " base / commandlineflags . h " <nl> + # endif <nl> + # include " commontraining . h " <nl> + # include " genericvector . h " <nl> + # include " lstmtester . h " <nl> + # include " strngs . h " <nl> + # include " tprintf . h " <nl> + <nl> + STRING_PARAM_FLAG ( model , " " , " Name of model file ( training or recognition ) " ) ; <nl> + STRING_PARAM_FLAG ( eval_listfile , " " , <nl> + " File listing sample files in lstmf training format . " ) ; <nl> + INT_PARAM_FLAG ( max_image_MB , 2000 , " Max memory to use for images . " ) ; <nl> + <nl> + int main ( int argc , char * * argv ) { <nl> + ParseArguments ( & argc , & argv ) ; <nl> + if ( FLAGS_model . empty ( ) ) { <nl> + tprintf ( " Must provide a - - model ! \ n " ) ; <nl> + return 1 ; <nl> + } <nl> + if ( FLAGS_eval_listfile . empty ( ) ) { <nl> + tprintf ( " Must provide a - - eval_listfile ! \ n " ) ; <nl> + return 1 ; <nl> + } <nl> + GenericVector < char > model_data ; <nl> + if ( ! tesseract : : LoadDataFromFile ( FLAGS_model . c_str ( ) , & model_data ) ) { <nl> + tprintf ( " Failed to load model from : % s \ n " , FLAGS_eval_listfile . c_str ( ) ) ; <nl> + return 1 ; <nl> + } <nl> + tesseract : : LSTMTester tester ( static_cast < inT64 > ( FLAGS_max_image_MB ) * <nl> + 1048576 ) ; <nl> + if ( ! tester . LoadAllEvalData ( FLAGS_eval_listfile . c_str ( ) ) ) { <nl> + tprintf ( " Failed to load eval data from : % s \ n " , FLAGS_eval_listfile . c_str ( ) ) ; <nl> + return 1 ; <nl> + } <nl> + double errs = 0 . 0 ; <nl> + STRING result = tester . RunEvalSync ( 0 , & errs , model_data , 0 ) ; <nl> + tprintf ( " % s \ n " , result . string ( ) ) ; <nl> + return 0 ; <nl> + } / * main * / <nl> new file mode 100644 <nl> index 000000000 . . df37ebd7e <nl> mmm / dev / null <nl> ppp b / training / lstmtester . cpp <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : lstmtester . cpp <nl> + / / Description : Top - level line evaluation class for LSTM - based networks . <nl> + / / Author : Ray Smith <nl> + / / Created : Wed Nov 23 11 : 18 : 06 PST 2016 <nl> + / / <nl> + / / ( C ) Copyright 2016 , Google Inc . <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # include " lstmtester . h " <nl> + # include " genericvector . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + LSTMTester : : LSTMTester ( inT64 max_memory ) <nl> + : test_data_ ( max_memory ) , total_pages_ ( 0 ) , async_running_ ( false ) { } <nl> + <nl> + / / Loads a set of lstmf files that were created using the lstm . train config to <nl> + / / tesseract into memory ready for testing . Returns false if nothing was <nl> + / / loaded . The arg is a filename of a file that lists the filenames . <nl> + bool LSTMTester : : LoadAllEvalData ( const STRING & filenames_file ) { <nl> + GenericVector < STRING > filenames ; <nl> + if ( ! LoadFileLinesToStrings ( filenames_file , & filenames ) ) { <nl> + tprintf ( " Failed to load list of eval filenames from % s \ n " , <nl> + filenames_file . string ( ) ) ; <nl> + return false ; <nl> + } <nl> + return LoadAllEvalData ( filenames ) ; <nl> + } <nl> + <nl> + / / Loads a set of lstmf files that were created using the lstm . train config to <nl> + / / tesseract into memory ready for testing . Returns false if nothing was <nl> + / / loaded . <nl> + bool LSTMTester : : LoadAllEvalData ( const GenericVector < STRING > & filenames ) { <nl> + test_data_ . Clear ( ) ; <nl> + bool result = <nl> + test_data_ . LoadDocuments ( filenames , " eng " , CS_SEQUENTIAL , nullptr ) ; <nl> + total_pages_ = test_data_ . TotalPages ( ) ; <nl> + return result ; <nl> + } <nl> + <nl> + / / Runs an evaluation asynchronously on the stored data and returns a string <nl> + / / describing the results of the previous test . <nl> + STRING LSTMTester : : RunEvalAsync ( int iteration , const double * training_errors , <nl> + const GenericVector < char > & model_data , <nl> + int training_stage ) { <nl> + STRING result ; <nl> + if ( total_pages_ = = 0 ) { <nl> + result . add_str_int ( " No test data at iteration " , iteration ) ; <nl> + return result ; <nl> + } <nl> + if ( ! LockIfNotRunning ( ) ) { <nl> + result . add_str_int ( " Previous test incomplete , skipping test at iteration " , <nl> + iteration ) ; <nl> + return result ; <nl> + } <nl> + / / Save the args . <nl> + STRING prev_result = test_result_ ; <nl> + test_result_ = " " ; <nl> + if ( training_errors ! = nullptr ) { <nl> + test_iteration_ = iteration ; <nl> + test_training_errors_ = training_errors ; <nl> + test_model_data_ = model_data ; <nl> + test_training_stage_ = training_stage ; <nl> + SVSync : : StartThread ( & LSTMTester : : ThreadFunc , this ) ; <nl> + } else { <nl> + UnlockRunning ( ) ; <nl> + } <nl> + return prev_result ; <nl> + } <nl> + <nl> + / / Runs an evaluation synchronously on the stored data and returns a string <nl> + / / describing the results . <nl> + STRING LSTMTester : : RunEvalSync ( int iteration , const double * training_errors , <nl> + const GenericVector < char > & model_data , <nl> + int training_stage ) { <nl> + LSTMTrainer trainer ; <nl> + if ( ! trainer . ReadTrainingDump ( model_data , & trainer ) ) { <nl> + return " Deserialize failed " ; <nl> + } <nl> + int eval_iteration = 0 ; <nl> + double char_error = 0 . 0 ; <nl> + double word_error = 0 . 0 ; <nl> + int error_count = 0 ; <nl> + while ( error_count < total_pages_ ) { <nl> + const ImageData * trainingdata = test_data_ . GetPageBySerial ( eval_iteration ) ; <nl> + trainer . SetIteration ( + + eval_iteration ) ; <nl> + NetworkIO fwd_outputs , targets ; <nl> + if ( trainer . PrepareForBackward ( trainingdata , & fwd_outputs , & targets ) ! = <nl> + UNENCODABLE ) { <nl> + char_error + = trainer . NewSingleError ( tesseract : : ET_CHAR_ERROR ) ; <nl> + word_error + = trainer . NewSingleError ( tesseract : : ET_WORD_RECERR ) ; <nl> + + + error_count ; <nl> + } <nl> + } <nl> + char_error * = 100 . 0 / total_pages_ ; <nl> + word_error * = 100 . 0 / total_pages_ ; <nl> + STRING result ; <nl> + result . add_str_int ( " At iteration " , iteration ) ; <nl> + result . add_str_int ( " , stage " , training_stage ) ; <nl> + result . add_str_double ( " , Eval Char error rate = " , char_error ) ; <nl> + result . add_str_double ( " , Word error rate = " , word_error ) ; <nl> + return result ; <nl> + } <nl> + <nl> + / / Static helper thread function for RunEvalAsync , with a specific signature <nl> + / / required by SVSync : : StartThread . Actually a member function pretending to <nl> + / / be static , its arg is a this pointer that it will cast back to LSTMTester * <nl> + / / to call RunEvalSync using the stored args that RunEvalAsync saves in * this . <nl> + / / LockIfNotRunning must have returned true before calling ThreadFunc , and <nl> + / / it will call UnlockRunning to release the lock after RunEvalSync completes . <nl> + / * static * / <nl> + void * LSTMTester : : ThreadFunc ( void * lstmtester_void ) { <nl> + LSTMTester * lstmtester = reinterpret_cast < LSTMTester * > ( lstmtester_void ) ; <nl> + lstmtester - > test_result_ = lstmtester - > RunEvalSync ( <nl> + lstmtester - > test_iteration_ , lstmtester - > test_training_errors_ , <nl> + lstmtester - > test_model_data_ , lstmtester - > test_training_stage_ ) ; <nl> + lstmtester - > UnlockRunning ( ) ; <nl> + return lstmtester_void ; <nl> + } <nl> + <nl> + / / Returns true if there is currently nothing running , and takes the lock <nl> + / / if there is nothing running . <nl> + bool LSTMTester : : LockIfNotRunning ( ) { <nl> + SVAutoLock lock ( & running_mutex_ ) ; <nl> + if ( async_running_ ) return false ; <nl> + async_running_ = true ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Releases the running lock . <nl> + void LSTMTester : : UnlockRunning ( ) { <nl> + SVAutoLock lock ( & running_mutex_ ) ; <nl> + async_running_ = false ; <nl> + } <nl> + <nl> + } / / namespace tesseract <nl> new file mode 100644 <nl> index 000000000 . . 3b4cb05e7 <nl> mmm / dev / null <nl> ppp b / training / lstmtester . h <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : lstmtester . h <nl> + / / Description : Top - level line evaluation class for LSTM - based networks . <nl> + / / Author : Ray Smith <nl> + / / Created : Wed Nov 23 11 : 05 : 06 PST 2016 <nl> + / / <nl> + / / ( C ) Copyright 2016 , Google Inc . <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # ifndef TESSERACT_TRAINING_LSTMTESTER_H_ <nl> + # define TESSERACT_TRAINING_LSTMTESTER_H_ <nl> + <nl> + # include " genericvector . h " <nl> + # include " lstmtrainer . h " <nl> + # include " strngs . h " <nl> + # include " svutil . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + class LSTMTester { <nl> + public : <nl> + LSTMTester ( inT64 max_memory ) ; <nl> + <nl> + / / Loads a set of lstmf files that were created using the lstm . train config to <nl> + / / tesseract into memory ready for testing . Returns false if nothing was <nl> + / / loaded . The arg is a filename of a file that lists the filenames , with one <nl> + / / name per line . Conveniently , tesstrain . sh generates such a file , along <nl> + / / with the files themselves . <nl> + bool LoadAllEvalData ( const STRING & filenames_file ) ; <nl> + / / Loads a set of lstmf files that were created using the lstm . train config to <nl> + / / tesseract into memory ready for testing . Returns false if nothing was <nl> + / / loaded . <nl> + bool LoadAllEvalData ( const GenericVector < STRING > & filenames ) ; <nl> + <nl> + / / Runs an evaluation asynchronously on the stored eval data and returns a <nl> + / / string describing the results of the previous test . Args match TestCallback <nl> + / / declared in lstmtrainer . h : <nl> + / / iteration : Current learning iteration number . <nl> + / / training_errors : If not null , is an array of size ET_COUNT , indexed by <nl> + / / the ErrorTypes enum and indicates the current errors measured by the <nl> + / / trainer , and this is a serious request to run an evaluation . If null , <nl> + / / then the caller is just polling for the results of the previous eval . <nl> + / / model_data : is the model to evaluate , which should be a serialized <nl> + / / LSTMTrainer . <nl> + / / training_stage : an arbitrary number on the progress of training . <nl> + STRING RunEvalAsync ( int iteration , const double * training_errors , <nl> + const GenericVector < char > & model_data , <nl> + int training_stage ) ; <nl> + / / Runs an evaluation synchronously on the stored eval data and returns a <nl> + / / string describing the results . Args as RunEvalAsync . <nl> + STRING RunEvalSync ( int iteration , const double * training_errors , <nl> + const GenericVector < char > & model_data , int training_stage ) ; <nl> + <nl> + private : <nl> + / / Static helper thread function for RunEvalAsync , with a specific signature <nl> + / / required by SVSync : : StartThread . Actually a member function pretending to <nl> + / / be static , its arg is a this pointer that it will cast back to LSTMTester * <nl> + / / to call RunEvalSync using the stored args that RunEvalAsync saves in * this . <nl> + / / LockIfNotRunning must have returned true before calling ThreadFunc , and <nl> + / / it will call UnlockRunning to release the lock after RunEvalSync completes . <nl> + static void * ThreadFunc ( void * lstmtester_void ) ; <nl> + / / Returns true if there is currently nothing running , and takes the lock <nl> + / / if there is nothing running . <nl> + bool LockIfNotRunning ( ) ; <nl> + / / Releases the running lock . <nl> + void UnlockRunning ( ) ; <nl> + <nl> + / / The data to test with . <nl> + DocumentCache test_data_ ; <nl> + int total_pages_ ; <nl> + / / Flag that indicates an asynchronous test is currently running . <nl> + / / Protected by running_mutex_ . <nl> + bool async_running_ ; <nl> + SVMutex running_mutex_ ; <nl> + / / Stored copies of the args for use while running asynchronously . <nl> + int test_iteration_ ; <nl> + const double * test_training_errors_ ; <nl> + GenericVector < char > test_model_data_ ; <nl> + int test_training_stage_ ; <nl> + STRING test_result_ ; <nl> + } ; <nl> + <nl> + } / / namespace tesseract <nl> + <nl> + # endif / / TESSERACT_TRAINING_LSTMTESTER_H_ <nl> mmm a / training / lstmtraining . cpp <nl> ppp b / training / lstmtraining . cpp <nl> <nl> # include " base / commandlineflags . h " <nl> # endif <nl> # include " commontraining . h " <nl> + # include " lstmtester . h " <nl> # include " lstmtrainer . h " <nl> # include " params . h " <nl> # include " strngs . h " <nl> <nl> # include " unicharset_training_utils . h " <nl> <nl> INT_PARAM_FLAG ( debug_interval , 0 , " How often to display the alignment . " ) ; <nl> - STRING_PARAM_FLAG ( net_spec , " [ I1 , 48Lt1 , 100O ] " , " Network specification " ) ; <nl> - INT_PARAM_FLAG ( train_mode , 64 , " Controls gross training behavior . " ) ; <nl> + STRING_PARAM_FLAG ( net_spec , " " , " Network specification " ) ; <nl> + INT_PARAM_FLAG ( train_mode , 80 , " Controls gross training behavior . " ) ; <nl> INT_PARAM_FLAG ( net_mode , 192 , " Controls network behavior . " ) ; <nl> INT_PARAM_FLAG ( perfect_sample_delay , 4 , <nl> " How many imperfect samples between perfect ones . " ) ; <nl> STRING_PARAM_FLAG ( model_output , " lstmtrain " , " Basename for output models " ) ; <nl> STRING_PARAM_FLAG ( script_dir , " " , <nl> " Required to set unicharset properties or " <nl> " use unicharset compression . " ) ; <nl> + STRING_PARAM_FLAG ( train_listfile , " " , <nl> + " File listing training files in lstmf training format . " ) ; <nl> + STRING_PARAM_FLAG ( eval_listfile , " " , <nl> + " File listing eval files in lstmf training format . " ) ; <nl> BOOL_PARAM_FLAG ( stop_training , false , <nl> " Just convert the training model to a runtime model . " ) ; <nl> INT_PARAM_FLAG ( append_index , - 1 , " Index in continue_from Network at which to " <nl> int main ( int argc , char * * argv ) { <nl> } <nl> <nl> / / Get the list of files to process . <nl> + if ( FLAGS_train_listfile . empty ( ) ) { <nl> + tprintf ( " Must supply a list of training filenames ! - - train_listfile \ n " ) ; <nl> + return 1 ; <nl> + } <nl> GenericVector < STRING > filenames ; <nl> - for ( int arg = 1 ; arg < argc ; + + arg ) { <nl> - filenames . push_back ( STRING ( argv [ arg ] ) ) ; <nl> + if ( ! tesseract : : LoadFileLinesToStrings ( FLAGS_train_listfile . c_str ( ) , <nl> + & filenames ) ) { <nl> + tprintf ( " Failed to load list of training filenames from % s \ n " , <nl> + FLAGS_train_listfile . c_str ( ) ) ; <nl> + return 1 ; <nl> } <nl> <nl> UNICHARSET unicharset ; <nl> int main ( int argc , char * * argv ) { <nl> return 1 ; <nl> } <nl> tprintf ( " Continuing from % s \ n " , FLAGS_continue_from . c_str ( ) ) ; <nl> + trainer . InitIterations ( ) ; <nl> } <nl> if ( FLAGS_continue_from . empty ( ) | | FLAGS_append_index > = 0 ) { <nl> / / We need a unicharset to start from scratch or append . <nl> int main ( int argc , char * * argv ) { <nl> char * best_model_dump = NULL ; <nl> size_t best_model_size = 0 ; <nl> STRING best_model_name ; <nl> + tesseract : : LSTMTester tester ( static_cast < inT64 > ( FLAGS_max_image_MB ) * <nl> + 1048576 ) ; <nl> + tesseract : : TestCallback tester_callback = nullptr ; <nl> + if ( ! FLAGS_eval_listfile . empty ( ) ) { <nl> + if ( ! tester . LoadAllEvalData ( FLAGS_eval_listfile . c_str ( ) ) ) { <nl> + tprintf ( " Failed to load eval data from : % s \ n " , <nl> + FLAGS_eval_listfile . c_str ( ) ) ; <nl> + return 1 ; <nl> + } <nl> + tester_callback = <nl> + NewPermanentTessCallback ( & tester , & tesseract : : LSTMTester : : RunEvalAsync ) ; <nl> + } <nl> do { <nl> / / Train a few . <nl> int iteration = trainer . training_iteration ( ) ; <nl> int main ( int argc , char * * argv ) { <nl> trainer . TrainOnLine ( & trainer , false ) ; <nl> } <nl> STRING log_str ; <nl> - trainer . MaintainCheckpoints ( NULL , & log_str ) ; <nl> + trainer . MaintainCheckpoints ( tester_callback , & log_str ) ; <nl> tprintf ( " % s \ n " , log_str . string ( ) ) ; <nl> } while ( trainer . best_error_rate ( ) > FLAGS_target_error_rate & & <nl> ( trainer . training_iteration ( ) < FLAGS_max_iterations | | <nl> FLAGS_max_iterations = = 0 ) ) ; <nl> + delete tester_callback ; <nl> tprintf ( " Finished ! Error rate = % g \ n " , trainer . best_error_rate ( ) ) ; <nl> return 0 ; <nl> } / * main * / <nl> mmm a / training / tesstrain . sh <nl> ppp b / training / tesstrain . sh <nl> <nl> # - - langdata_dir DATADIR # Path to tesseract / training / langdata directory . <nl> # - - output_dir OUTPUTDIR # Location of output traineddata file . <nl> # - - overwrite # Safe to overwrite files in output_dir . <nl> + # - - linedata_only # Only generate training data for lstmtraining . <nl> # - - run_shape_clustering # Run shape clustering ( use for Indic langs ) . <nl> # - - exposures EXPOSURES # A list of exposure levels to use ( e . g . " - 1 0 1 " ) . <nl> # <nl> initialize_fontconfig <nl> phase_I_generate_image 8 <nl> phase_UP_generate_unicharset <nl> phase_D_generate_dawg <nl> - phase_E_extract_features " box . train " 8 <nl> - phase_C_cluster_prototypes " $ { TRAINING_DIR } / $ { LANG_CODE } . normproto " <nl> - if [ [ " $ { ENABLE_SHAPE_CLUSTERING } " = = " y " ] ] ; then <nl> - phase_S_cluster_shapes <nl> + if ( ( $ { LINEDATA } ) ) ; then <nl> + phase_E_extract_features " lstm . train " 8 " lstmf " <nl> + make__lstmdata <nl> + else <nl> + phase_E_extract_features " box . train " 8 " tr " <nl> + phase_C_cluster_prototypes " $ { TRAINING_DIR } / $ { LANG_CODE } . normproto " <nl> + if [ [ " $ { ENABLE_SHAPE_CLUSTERING } " = = " y " ] ] ; then <nl> + phase_S_cluster_shapes <nl> + fi <nl> + phase_M_cluster_microfeatures <nl> + phase_B_generate_ambiguities <nl> + make__traineddata <nl> fi <nl> - phase_M_cluster_microfeatures <nl> - phase_B_generate_ambiguities <nl> - make__traineddata <nl> <nl> tlog " \ nCompleted training for language ' $ { LANG_CODE } ' \ n " <nl> mmm a / training / tesstrain_utils . sh <nl> ppp b / training / tesstrain_utils . sh <nl> else <nl> fi <nl> OUTPUT_DIR = " / tmp / tesstrain / tessdata " <nl> OVERWRITE = 0 <nl> + LINEDATA = 0 <nl> RUN_SHAPE_CLUSTERING = 0 <nl> EXTRACT_FONT_PROPERTIES = 1 <nl> WORKSPACE_DIR = ` mktemp - d ` <nl> parse_flags ( ) { <nl> - - ) <nl> break ; ; <nl> - - fontlist ) <nl> - fn = 0 <nl> - FONTS = " " <nl> + fn = 0 <nl> + FONTS = " " <nl> while test $ j - lt $ { # ARGV [ @ ] } ; do <nl> test - z " $ { ARGV [ $ j ] } " & & break <nl> test ` echo $ { ARGV [ $ j ] } | cut - c - 2 ` = " - - " & & break <nl> parse_flags ( ) { <nl> i = $ j ; ; <nl> - - overwrite ) <nl> OVERWRITE = 1 ; ; <nl> + - - linedata_only ) <nl> + LINEDATA = 1 ; ; <nl> - - extract_font_properties ) <nl> EXTRACT_FONT_PROPERTIES = 1 ; ; <nl> - - noextract_font_properties ) <nl> phase_D_generate_dawg ( ) { <nl> phase_E_extract_features ( ) { <nl> local box_config = $ 1 <nl> local par_factor = $ 2 <nl> + local ext = $ 3 <nl> if [ [ - z $ { par_factor } | | $ { par_factor } - le 0 ] ] ; then <nl> par_factor = 1 <nl> fi <nl> - tlog " \ n = = = Phase E : Extracting features = = = " <nl> + tlog " \ n = = = Phase E : Generating $ { ext } files = = = " <nl> <nl> local img_files = " " <nl> for exposure in $ { EXPOSURES } ; do <nl> phase_E_extract_features ( ) { <nl> export TESSDATA_PREFIX = $ { OLD_TESSDATA_PREFIX } <nl> # Check that all the output files were produced . <nl> for img_file in $ { img_files } ; do <nl> - check_file_readable $ { img_file % . * } . tr <nl> + check_file_readable " $ { img_file % . * } . $ { ext } " <nl> done <nl> } <nl> <nl> phase_B_generate_ambiguities ( ) { <nl> # TODO : Add support for generating ambiguities automatically . <nl> } <nl> <nl> + make__lstmdata ( ) { <nl> + tlog " \ n = = = Constructing LSTM training data = = = " <nl> + local lang_prefix = $ { LANGDATA_ROOT } / $ { LANG_CODE } / $ { LANG_CODE } <nl> + if [ [ ! - d $ { OUTPUT_DIR } ] ] ; then <nl> + tlog " Creating new directory $ { OUTPUT_DIR } " <nl> + mkdir - p $ { OUTPUT_DIR } <nl> + fi <nl> + <nl> + # Copy available files for this language from the langdata dir . <nl> + if [ [ - r $ { lang_prefix } . config ] ] ; then <nl> + tlog " Copying $ { lang_prefix } . config to $ { OUTPUT_DIR } " <nl> + cp $ { lang_prefix } . config $ { OUTPUT_DIR } <nl> + chmod u + w $ { OUTPUT_DIR } / $ { LANG_CODE } . config <nl> + fi <nl> + if [ [ - r " $ { TRAINING_DIR } / $ { LANG_CODE } . unicharset " ] ] ; then <nl> + tlog " Moving $ { TRAINING_DIR } / $ { LANG_CODE } . unicharset to $ { OUTPUT_DIR } " <nl> + mv " $ { TRAINING_DIR } / $ { LANG_CODE } . unicharset " " $ { OUTPUT_DIR } " <nl> + fi <nl> + for ext in number - dawg punc - dawg word - dawg ; do <nl> + local src = " $ { TRAINING_DIR } / $ { LANG_CODE } . $ { ext } " <nl> + if [ [ - r " $ { src } " ] ] ; then <nl> + dest = " $ { OUTPUT_DIR } / $ { LANG_CODE } . lstm - $ { ext } " <nl> + tlog " Moving $ { src } to $ { dest } " <nl> + mv " $ { src } " " $ { dest } " <nl> + fi <nl> + done <nl> + for f in " $ { TRAINING_DIR } / $ { LANG_CODE } " . * . lstmf ; do <nl> + tlog " Moving $ { f } to $ { OUTPUT_DIR } " <nl> + mv " $ { f } " " $ { OUTPUT_DIR } " <nl> + done <nl> + local lstm_list = " $ { OUTPUT_DIR } / $ { LANG_CODE } . training_files . txt " <nl> + ls - 1 " $ { OUTPUT_DIR } " / * . lstmf > " $ { lstm_list } " <nl> + } <nl> <nl> make__traineddata ( ) { <nl> tlog " \ n = = = Making final traineddata file = = = " <nl> mmm a / viewer / svutil . h <nl> ppp b / viewer / svutil . h <nl> <nl> <nl> # ifdef _WIN32 <nl> # ifndef __GNUC__ <nl> - # include " platform . h " <nl> # include < windows . h > <nl> + # include " platform . h " <nl> # if defined ( _MSC_VER ) & & _MSC_VER < 1900 <nl> # define snprintf _snprintf <nl> # endif <nl> | Fixes to training process to allow incremental training from a recognition model | tesseract-ocr/tesseract | ce76d1c56983b364558c88a6dc99771653d5662b | 2016-11-30T23:51:17Z |
mmm a / tensorflow / core / kernels / constant_op . cc <nl> ppp b / tensorflow / core / kernels / constant_op . cc <nl> TF_CALL_ALL_TYPES ( REGISTER_CPU_KERNEL ) ; <nl> / / the conversion from uint8 to quint8 . <nl> REGISTER_KERNEL ( CPU , quint8 ) ; <nl> REGISTER_KERNEL ( CPU , quint16 ) ; <nl> + REGISTER_KERNEL ( CPU , qint8 ) ; <nl> + REGISTER_KERNEL ( CPU , qint16 ) ; <nl> # undef REGISTER_CPU_KERNEL <nl> <nl> # ifdef TENSORFLOW_USE_SYCL <nl> mmm a / tensorflow / core / kernels / fill_functor . cc <nl> ppp b / tensorflow / core / kernels / fill_functor . cc <nl> struct FillFunctor < Eigen : : ThreadPoolDevice , T > { <nl> TF_CALL_ALL_TYPES ( DEFINE_FILL_CPU ) ; <nl> DEFINE_FILL_CPU ( quint8 ) ; <nl> DEFINE_FILL_CPU ( quint16 ) ; <nl> + DEFINE_FILL_CPU ( qint8 ) ; <nl> + DEFINE_FILL_CPU ( qint16 ) ; <nl> # undef DEFINE_FILL_CPU <nl> <nl> # ifdef TENSORFLOW_USE_SYCL <nl> mmm a / tensorflow / python / kernel_tests / constant_op_test . py <nl> ppp b / tensorflow / python / kernel_tests / constant_op_test . py <nl> def testDtype ( self ) : <nl> self . assertFalse ( np . any ( z_value ) ) <nl> self . assertEqual ( ( 2 , 3 ) , z_value . shape ) <nl> <nl> + def testQintDtype ( self ) : <nl> + for dtype in [ <nl> + dtypes_lib . qint8 , dtypes_lib . quint8 , <nl> + dtypes_lib . qint16 , dtypes_lib . quint16 ] : <nl> + z = array_ops . zeros ( [ 2 , 3 ] , dtype = dtype ) <nl> + self . assertEqual ( z . dtype , dtype ) <nl> + self . assertEqual ( [ 2 , 3 ] , z . get_shape ( ) ) <nl> + # cast to int32 so that it can be compred with numpy <nl> + # where [ qint | quint ] [ 8 | 16 ] are not available . <nl> + z_value = self . evaluate ( math_ops . cast ( z , dtypes_lib . int32 ) ) <nl> + self . assertFalse ( np . any ( z_value ) ) <nl> + <nl> <nl> class ZerosLikeTest ( test . TestCase ) : <nl> <nl> | Add qint8 and qint16 support for FillOp | tensorflow/tensorflow | f8c8a778032db1685af4c746cef63fdcd39abf97 | 2020-07-25T00:32:47Z |
mmm a / xbmc / addons / include / xbmc_pvr_types . h <nl> ppp b / xbmc / addons / include / xbmc_pvr_types . h <nl> struct DemuxPacket ; <nl> # define PVR_STREAM_MAX_STREAMS 20 <nl> <nl> / * current PVR API version * / <nl> - # define XBMC_PVR_API_VERSION " 1 . 3 . 0 " <nl> + # define XBMC_PVR_API_VERSION " 1 . 4 . 0 " <nl> <nl> / * min . PVR API version * / <nl> - # define XBMC_PVR_MIN_API_VERSION " 1 . 3 . 0 " <nl> + # define XBMC_PVR_MIN_API_VERSION " 1 . 4 . 0 " <nl> <nl> # ifdef __cplusplus <nl> extern " C " { <nl> extern " C " { <nl> * @ brief Representation of a recording . <nl> * / <nl> typedef struct PVR_RECORDING { <nl> - char strRecordingId [ PVR_ADDON_NAME_STRING_LENGTH ] ; / * ! < @ brief ( required ) unique id of the recording on the client . * / <nl> - char strTitle [ PVR_ADDON_NAME_STRING_LENGTH ] ; / * ! < @ brief ( required ) the title of this recording * / <nl> - char strStreamURL [ PVR_ADDON_URL_STRING_LENGTH ] ; / * ! < @ brief ( required ) stream URL to access this recording * / <nl> - char strDirectory [ PVR_ADDON_URL_STRING_LENGTH ] ; / * ! < @ brief ( optional ) directory of this recording on the client * / <nl> - char strPlotOutline [ PVR_ADDON_DESC_STRING_LENGTH ] ; / * ! < @ brief ( optional ) plot outline * / <nl> - char strPlot [ PVR_ADDON_DESC_STRING_LENGTH ] ; / * ! < @ brief ( optional ) plot * / <nl> - char strChannelName [ PVR_ADDON_NAME_STRING_LENGTH ] ; / * ! < @ brief ( optional ) channel name * / <nl> - time_t recordingTime ; / * ! < @ brief ( optional ) start time of the recording * / <nl> - int iDuration ; / * ! < @ brief ( optional ) duration of the recording in seconds * / <nl> - int iPriority ; / * ! < @ brief ( optional ) priority of this recording ( from 0 - 100 ) * / <nl> - int iLifetime ; / * ! < @ brief ( optional ) life time in days of this recording * / <nl> - int iGenreType ; / * ! < @ brief ( optional ) genre type * / <nl> - int iGenreSubType ; / * ! < @ brief ( optional ) genre sub type * / <nl> - int iPlayCount ; / * ! < @ brief ( optional ) play count of this recording on the client * / <nl> + char strRecordingId [ PVR_ADDON_NAME_STRING_LENGTH ] ; / * ! < @ brief ( required ) unique id of the recording on the client . * / <nl> + char strTitle [ PVR_ADDON_NAME_STRING_LENGTH ] ; / * ! < @ brief ( required ) the title of this recording * / <nl> + char strStreamURL [ PVR_ADDON_URL_STRING_LENGTH ] ; / * ! < @ brief ( required ) stream URL to access this recording * / <nl> + char strDirectory [ PVR_ADDON_URL_STRING_LENGTH ] ; / * ! < @ brief ( optional ) directory of this recording on the client * / <nl> + char strPlotOutline [ PVR_ADDON_DESC_STRING_LENGTH ] ; / * ! < @ brief ( optional ) plot outline * / <nl> + char strPlot [ PVR_ADDON_DESC_STRING_LENGTH ] ; / * ! < @ brief ( optional ) plot * / <nl> + char strChannelName [ PVR_ADDON_NAME_STRING_LENGTH ] ; / * ! < @ brief ( optional ) channel name * / <nl> + char strIconPath [ PVR_ADDON_URL_STRING_LENGTH ] ; / * ! < @ brief ( optional ) icon path * / <nl> + char strThumbnailPath [ PVR_ADDON_URL_STRING_LENGTH ] ; / * ! < @ brief ( optional ) thumbnail path * / <nl> + char strFanartPath [ PVR_ADDON_URL_STRING_LENGTH ] ; / * ! < @ brief ( optional ) fanart path * / <nl> + time_t recordingTime ; / * ! < @ brief ( optional ) start time of the recording * / <nl> + int iDuration ; / * ! < @ brief ( optional ) duration of the recording in seconds * / <nl> + int iPriority ; / * ! < @ brief ( optional ) priority of this recording ( from 0 - 100 ) * / <nl> + int iLifetime ; / * ! < @ brief ( optional ) life time in days of this recording * / <nl> + int iGenreType ; / * ! < @ brief ( optional ) genre type * / <nl> + int iGenreSubType ; / * ! < @ brief ( optional ) genre sub type * / <nl> + int iPlayCount ; / * ! < @ brief ( optional ) play count of this recording on the client * / <nl> } ATTRIBUTE_PACKED PVR_RECORDING ; <nl> <nl> / * ! <nl> mmm a / xbmc / pvr / addons / PVRClient . cpp <nl> ppp b / xbmc / pvr / addons / PVRClient . cpp <nl> void CPVRClient : : WriteClientRecordingInfo ( const CPVRRecording & xbmcRecording , PV <nl> addonRecording . iLifetime = xbmcRecording . m_iLifetime ; <nl> strncpy ( addonRecording . strDirectory , xbmcRecording . m_strDirectory . c_str ( ) , sizeof ( addonRecording . strDirectory ) - 1 ) ; <nl> strncpy ( addonRecording . strStreamURL , xbmcRecording . m_strStreamURL . c_str ( ) , sizeof ( addonRecording . strStreamURL ) - 1 ) ; <nl> + strncpy ( addonRecording . strIconPath , xbmcRecording . m_strIconPath . c_str ( ) , sizeof ( addonRecording . strIconPath ) - 1 ) ; <nl> + strncpy ( addonRecording . strThumbnailPath , xbmcRecording . m_strThumbnailPath . c_str ( ) , sizeof ( addonRecording . strThumbnailPath ) - 1 ) ; <nl> + strncpy ( addonRecording . strFanartPath , xbmcRecording . m_strFanartPath . c_str ( ) , sizeof ( addonRecording . strFanartPath ) - 1 ) ; <nl> } <nl> <nl> / * ! <nl> mmm a / xbmc / pvr / recordings / PVRRecording . cpp <nl> ppp b / xbmc / pvr / recordings / PVRRecording . cpp <nl> CPVRRecording : : CPVRRecording ( const PVR_RECORDING & recording , unsigned int iClien <nl> { <nl> Reset ( ) ; <nl> <nl> - m_strRecordingId = recording . strRecordingId ; <nl> - m_strTitle = recording . strTitle ; <nl> - m_iClientId = iClientId ; <nl> - m_recordingTime = recording . recordingTime + g_advancedSettings . m_iPVRTimeCorrection ; <nl> - m_duration = CDateTimeSpan ( 0 , 0 , recording . iDuration / 60 , recording . iDuration % 60 ) ; <nl> - m_iPriority = recording . iPriority ; <nl> - m_iLifetime = recording . iLifetime ; <nl> - m_strDirectory = recording . strDirectory ; <nl> - m_strPlot = recording . strPlot ; <nl> - m_strPlotOutline = recording . strPlotOutline ; <nl> - m_strStreamURL = recording . strStreamURL ; <nl> - m_strChannelName = recording . strChannelName ; <nl> - m_genre = StringUtils : : Split ( CEpg : : ConvertGenreIdToString ( recording . iGenreType , recording . iGenreSubType ) , g_advancedSettings . m_videoItemSeparator ) ; <nl> - m_iRecPlayCount = recording . iPlayCount ; <nl> + m_strRecordingId = recording . strRecordingId ; <nl> + m_strTitle = recording . strTitle ; <nl> + m_iClientId = iClientId ; <nl> + m_recordingTime = recording . recordingTime + g_advancedSettings . m_iPVRTimeCorrection ; <nl> + m_duration = CDateTimeSpan ( 0 , 0 , recording . iDuration / 60 , recording . iDuration % 60 ) ; <nl> + m_iPriority = recording . iPriority ; <nl> + m_iLifetime = recording . iLifetime ; <nl> + m_strDirectory = recording . strDirectory ; <nl> + m_strPlot = recording . strPlot ; <nl> + m_strPlotOutline = recording . strPlotOutline ; <nl> + m_strStreamURL = recording . strStreamURL ; <nl> + m_strChannelName = recording . strChannelName ; <nl> + m_genre = StringUtils : : Split ( CEpg : : ConvertGenreIdToString ( recording . iGenreType , recording . iGenreSubType ) , g_advancedSettings . m_videoItemSeparator ) ; <nl> + m_iRecPlayCount = recording . iPlayCount ; <nl> + m_strIconPath = recording . strIconPath ; <nl> + m_strThumbnailPath = recording . strThumbnailPath ; <nl> + m_strFanartPath = recording . strFanartPath ; <nl> } <nl> <nl> bool CPVRRecording : : operator = = ( const CPVRRecording & right ) const <nl> bool CPVRRecording : : operator = = ( const CPVRRecording & right ) const <nl> m_strDirectory = = right . m_strDirectory & & <nl> m_strFileNameAndPath = = right . m_strFileNameAndPath & & <nl> m_strTitle = = right . m_strTitle & & <nl> - m_iRecPlayCount = = right . m_iRecPlayCount ) ; <nl> + m_iRecPlayCount = = right . m_iRecPlayCount & & <nl> + m_strIconPath = = right . m_strIconPath & & <nl> + m_strThumbnailPath = = right . m_strThumbnailPath & & <nl> + m_strFanartPath = = right . m_strFanartPath ) ; <nl> } <nl> <nl> bool CPVRRecording : : operator ! = ( const CPVRRecording & right ) const <nl> void CPVRRecording : : Reset ( void ) <nl> m_iLifetime = - 1 ; <nl> m_strFileNameAndPath = StringUtils : : EmptyString ; <nl> m_iRecPlayCount = 0 ; <nl> + m_strIconPath = StringUtils : : EmptyString ; <nl> + m_strThumbnailPath = StringUtils : : EmptyString ; <nl> + m_strFanartPath = StringUtils : : EmptyString ; <nl> <nl> m_recordingTime . Reset ( ) ; <nl> CVideoInfoTag : : Reset ( ) ; <nl> void CPVRRecording : : DisplayError ( PVR_ERROR err ) const <nl> <nl> void CPVRRecording : : Update ( const CPVRRecording & tag ) <nl> { <nl> - m_strRecordingId = tag . m_strRecordingId ; <nl> - m_iClientId = tag . m_iClientId ; <nl> - m_strTitle = tag . m_strTitle ; <nl> - m_recordingTime = tag . m_recordingTime ; <nl> - m_duration = tag . m_duration ; <nl> - m_iPriority = tag . m_iPriority ; <nl> - m_iLifetime = tag . m_iLifetime ; <nl> - m_strDirectory = tag . m_strDirectory ; <nl> - m_strPlot = tag . m_strPlot ; <nl> - m_strPlotOutline = tag . m_strPlotOutline ; <nl> - m_strStreamURL = tag . m_strStreamURL ; <nl> - m_strChannelName = tag . m_strChannelName ; <nl> - m_genre = tag . m_genre ; <nl> - m_iRecPlayCount = tag . m_iRecPlayCount ; <nl> + m_strRecordingId = tag . m_strRecordingId ; <nl> + m_iClientId = tag . m_iClientId ; <nl> + m_strTitle = tag . m_strTitle ; <nl> + m_recordingTime = tag . m_recordingTime ; <nl> + m_duration = tag . m_duration ; <nl> + m_iPriority = tag . m_iPriority ; <nl> + m_iLifetime = tag . m_iLifetime ; <nl> + m_strDirectory = tag . m_strDirectory ; <nl> + m_strPlot = tag . m_strPlot ; <nl> + m_strPlotOutline = tag . m_strPlotOutline ; <nl> + m_strStreamURL = tag . m_strStreamURL ; <nl> + m_strChannelName = tag . m_strChannelName ; <nl> + m_genre = tag . m_genre ; <nl> + m_iRecPlayCount = tag . m_iRecPlayCount ; <nl> + m_strIconPath = tag . m_strIconPath ; <nl> + m_strThumbnailPath = tag . m_strThumbnailPath ; <nl> + m_strFanartPath = tag . m_strFanartPath ; <nl> <nl> CStdString strShow ; <nl> strShow . Format ( " % s - " , g_localizeStrings . Get ( 20364 ) . c_str ( ) ) ; <nl> mmm a / xbmc / pvr / recordings / PVRRecording . h <nl> ppp b / xbmc / pvr / recordings / PVRRecording . h <nl> namespace PVR <nl> class CPVRRecording : public CVideoInfoTag <nl> { <nl> public : <nl> - int m_iClientId ; / * ! < ID of the backend * / <nl> - CStdString m_strRecordingId ; / * ! < unique id of the recording on the client * / <nl> - CStdString m_strChannelName ; / * ! < name of the channel this was recorded from * / <nl> - CDateTimeSpan m_duration ; / * ! < duration of this recording * / <nl> - int m_iPriority ; / * ! < priority of this recording * / <nl> - int m_iLifetime ; / * ! < lifetime of this recording * / <nl> - CStdString m_strStreamURL ; / * ! < stream URL . if empty use pvr client * / <nl> - CStdString m_strDirectory ; / * ! < directory of this recording on the client * / <nl> - int m_iRecPlayCount ; / * ! < play count of this recording on the client * / <nl> + int m_iClientId ; / * ! < ID of the backend * / <nl> + CStdString m_strRecordingId ; / * ! < unique id of the recording on the client * / <nl> + CStdString m_strChannelName ; / * ! < name of the channel this was recorded from * / <nl> + CDateTimeSpan m_duration ; / * ! < duration of this recording * / <nl> + int m_iPriority ; / * ! < priority of this recording * / <nl> + int m_iLifetime ; / * ! < lifetime of this recording * / <nl> + CStdString m_strStreamURL ; / * ! < stream URL . if empty use pvr client * / <nl> + CStdString m_strDirectory ; / * ! < directory of this recording on the client * / <nl> + int m_iRecPlayCount ; / * ! < play count of this recording on the client * / <nl> + CStdString m_strIconPath ; / * ! < icon path * / <nl> + CStdString m_strThumbnailPath ; / * ! < thumbnail path * / <nl> + CStdString m_strFanartPath ; / * ! < fanart path * / <nl> <nl> CPVRRecording ( void ) ; <nl> CPVRRecording ( const PVR_RECORDING & recording , unsigned int iClientId ) ; <nl> mmm a / xbmc / pvr / recordings / PVRRecordings . cpp <nl> ppp b / xbmc / pvr / recordings / PVRRecordings . cpp <nl> void CPVRRecordings : : GetContents ( const CStdString & strDirectory , CFileItemList * <nl> pFileItem - > m_dateTime = current - > RecordingTimeAsLocalTime ( ) ; <nl> pFileItem - > SetPath ( current - > m_strFileNameAndPath ) ; <nl> <nl> + if ( ! current - > m_strIconPath . IsEmpty ( ) ) <nl> + pFileItem - > SetIconImage ( current - > m_strIconPath ) ; <nl> + <nl> + if ( ! current - > m_strThumbnailPath . IsEmpty ( ) ) <nl> + pFileItem - > SetThumbnailImage ( current - > m_strThumbnailPath ) ; <nl> + <nl> + if ( ! current - > m_strFanartPath . IsEmpty ( ) ) <nl> + pFileItem - > SetProperty ( " Fanart_Image " , current - > m_strFanartPath ) ; <nl> + <nl> / / Set the play count either directly from client ( if supported ) or from video db <nl> if ( g_PVRClients - > SupportsRecordingPlayCount ( pFileItem - > GetPVRRecordingInfoTag ( ) - > m_iClientId ) ) <nl> { <nl> | Merge pull request from fetzerch / feature - pvr - recordingimages | xbmc/xbmc | d875510e44246ef74c150c37cb9dbbde77ec2ca0 | 2012-10-03T23:39:14Z |
mmm a / local - cli / runWindows / runWindows . js <nl> ppp b / local - cli / runWindows / runWindows . js <nl> function runWindows ( config , args , options ) { <nl> <nl> const slnFile = build . getSolutionFile ( options ) ; <nl> if ( ! slnFile ) { <nl> - console . error ( chalk . red ( ' Visual Studio Solution file not found . Maybe run " rnpm windows " first ? ' ) ) ; <nl> + console . error ( chalk . red ( ' Visual Studio Solution file not found . Maybe run " react - native windows " first ? ' ) ) ; <nl> return ; <nl> } <nl> <nl> | Update runWindows . js | microsoft/react-native-windows | 4106750357f2d544c7c3ab4520141f8c1daad3bf | 2016-10-25T13:18:31Z |
mmm a / drivers / python / rethinkdb / __init__ . py <nl> ppp b / drivers / python / rethinkdb / __init__ . py <nl> <nl> # This file includes all public facing Python API functions <nl> from net import connect , Connection , Cursor <nl> - from query import expr , js , error , do , row , table , db , db_create , db_drop , db_list , branch , count , sum , avg , asc , desc , eq , ne , le , ge , lt , gt , any , all , add , sub , mul , div , mod <nl> + from query import js , error , do , row , table , db , db_create , db_drop , db_list , branch , count , sum , avg , asc , desc , eq , ne , le , ge , lt , gt , any , all , add , sub , mul , div , mod <nl> from errors import RqlError , RqlClientError , RqlCompileError , RqlRuntimeError , RqlDriverError <nl> - from ast import RqlQuery <nl> + from ast import expr , RqlQuery <nl> mmm a / drivers / python / rethinkdb / ast . py <nl> ppp b / drivers / python / rethinkdb / ast . py <nl> <nl> import ql2_pb2 as p <nl> import types <nl> import sys <nl> + from threading import Lock <nl> from errors import * <nl> from net import Connection <nl> <nl> + # This is both an external function and one used extensively <nl> + # internally to convert coerce python values to RQL types <nl> + def expr ( val ) : <nl> + ' ' ' <nl> + Convert a Python primitive into a RQL primitive value <nl> + ' ' ' <nl> + if isinstance ( val , RqlQuery ) : <nl> + return val <nl> + elif isinstance ( val , list ) : <nl> + return MakeArray ( * val ) <nl> + elif isinstance ( val , dict ) : <nl> + return MakeObj ( * * val ) <nl> + elif callable ( val ) : <nl> + return Func ( val ) <nl> + else : <nl> + return Datum ( val ) <nl> + <nl> class RqlQuery ( object ) : <nl> <nl> # Instantiate this AST node with the given pos and opt args <nl> def run ( self , c = None , * * global_opt_args ) : <nl> c = Connection . repl_connection <nl> else : <nl> raise RqlDriverError ( " RqlQuery . run must be given a connection to run on . " ) <nl> - <nl> + <nl> return c . _start ( self , * * global_opt_args ) <nl> <nl> def __str__ ( self ) : <nl> def ivar_scan ( node ) : <nl> <nl> class Func ( RqlQuery ) : <nl> tt = p . Term . FUNC <nl> + lock = Lock ( ) <nl> nextVarId = 1 <nl> <nl> def __init__ ( self , lmbd ) : <nl> def __init__ ( self , lmbd ) : <nl> for i in xrange ( lmbd . func_code . co_argcount ) : <nl> vrs . append ( Var ( Func . nextVarId ) ) <nl> vrids . append ( Func . nextVarId ) <nl> + Func . lock . acquire ( ) <nl> Func . nextVarId + = 1 <nl> + Func . lock . release ( ) <nl> <nl> self . vrs = vrs <nl> self . args = [ MakeArray ( * vrids ) , expr ( lmbd ( * vrs ) ) ] <nl> class Asc ( RqlTopLevelQuery ) : <nl> class Desc ( RqlTopLevelQuery ) : <nl> tt = p . Term . DESC <nl> st = ' desc ' <nl> - <nl> - from query import expr <nl> mmm a / drivers / python / rethinkdb / net . py <nl> ppp b / drivers / python / rethinkdb / net . py <nl> def _send_query ( self , query , term ) : <nl> response = p . Response ( ) <nl> response . ParseFromString ( response_buf ) <nl> <nl> + # Check that this is the response we were expecting <nl> + if response . token ! = query . token : <nl> + # This response is corrupted or not intended for us . <nl> + raise RqlDriverError ( " Unexpected response received . " ) <nl> + <nl> # Error responses <nl> if response . type is p . Response . RUNTIME_ERROR : <nl> message = Datum . deconstruct ( response . response [ 0 ] ) <nl> mmm a / drivers / python / rethinkdb / query . py <nl> ppp b / drivers / python / rethinkdb / query . py <nl> <nl> All top level functions defined here are the starting points for RQL queries <nl> " " " <nl> <nl> - # This is both an external function and one used extensively <nl> - # internally to convert coerce python values to RQL types <nl> - def expr ( val ) : <nl> - ' ' ' <nl> - Convert a Python primitive into a RQL primitive value <nl> - ' ' ' <nl> - if isinstance ( val , RqlQuery ) : <nl> - return val <nl> - elif isinstance ( val , list ) : <nl> - return MakeArray ( * val ) <nl> - elif isinstance ( val , dict ) : <nl> - return MakeObj ( * * val ) <nl> - elif callable ( val ) : <nl> - return Func ( val ) <nl> - else : <nl> - return Datum ( val ) <nl> - <nl> def js ( js_str ) : <nl> return JavaScript ( js_str ) <nl> <nl> | python fixes as per review | rethinkdb/rethinkdb | 78c58f54013fe0c256f6efd85a7be77fe02ad1ee | 2013-03-25T19:10:58Z |
mmm a / stdlib / private / StdlibCollectionUnittest / MinimalCollections . swift . gyb <nl> ppp b / stdlib / private / StdlibCollectionUnittest / MinimalCollections . swift . gyb <nl> from gyb_stdlib_support import ( <nl> <nl> import StdlibUnittest <nl> <nl> - / / / State that is created every time a fresh generator is created with <nl> - / / / ` MinimalSequence . makeIterator ( ) ` . <nl> - internal class _MinimalIteratorPrivateState < T > { <nl> - internal init ( ) { } <nl> - <nl> - internal var returnedNilCounter : Int = 0 <nl> - } <nl> - <nl> / / / State shared by all generators of a MinimalSequence . <nl> internal class _MinimalIteratorSharedState < T > { <nl> internal init ( _ data : [ T ] ) { <nl> public struct MinimalIterator < T > : IteratorProtocol { <nl> <nl> public func next ( ) - > T ? { <nl> if _sharedState . i = = _sharedState . data . count { <nl> - if isConsumed { <nl> - expectUnreachable ( " next ( ) was called on a consumed generator " ) <nl> - } <nl> - _privateState . returnedNilCounter + = 1 <nl> return nil <nl> } <nl> defer { _sharedState . i + = 1 } <nl> return _sharedState . data [ _sharedState . i ] <nl> } <nl> <nl> - public var isConsumed : Bool { <nl> - return returnedNilCounter > = 1 <nl> - } <nl> - <nl> - public var returnedNilCounter : Int { <nl> - return _privateState . returnedNilCounter <nl> - } <nl> - <nl> - internal let _privateState : _MinimalIteratorPrivateState < T > = <nl> - _MinimalIteratorPrivateState ( ) <nl> internal let _sharedState : _MinimalIteratorSharedState < T > <nl> } <nl> <nl> | Merge pull request from apple / stdlib - collection - unittest - se - 0052 | apple/swift | 0b8d11bcb162047c224de3fca9047203cae810ba | 2016-05-11T01:31:17Z |
mmm a / cocos2dx / label_nodes / CCLabelBMFont . cpp <nl> ppp b / cocos2dx / label_nodes / CCLabelBMFont . cpp <nl> namespace cocos2d { <nl> CCSize tmpSize = CCSizeZero ; <nl> <nl> int longestLine = 0 ; <nl> - int totalHeight = 0 ; <nl> + unsigned int totalHeight = 0 ; <nl> <nl> - int quantityOfLines = 1 ; <nl> + unsigned int quantityOfLines = 1 ; <nl> <nl> - int len = m_sString . length ( ) ; <nl> + unsigned int stringLen = m_sString . length ( ) ; <nl> <nl> - if ( 0 = = len ) <nl> + if ( 0 = = stringLen ) <nl> { <nl> return ; <nl> } <nl> <nl> - for ( int i = 0 ; i < len - 1 ; + + i ) <nl> + for ( unsigned int i = 0 ; i < stringLen - 1 ; + + i ) <nl> { <nl> unsigned short c = m_sString [ i ] ; <nl> if ( c = = ' \ n ' ) <nl> namespace cocos2d { <nl> } <nl> <nl> totalHeight = m_pConfiguration - > m_uCommonHeight * quantityOfLines ; <nl> - nextFontPositionY = m_pConfiguration - > m_uCommonHeight * ( quantityOfLines - 1 ) ; <nl> + nextFontPositionY = - ( m_pConfiguration - > m_uCommonHeight - m_pConfiguration - > m_uCommonHeight * quantityOfLines ) ; <nl> <nl> - for ( int i = 0 ; i < len ; i + + ) <nl> + for ( unsigned int i = 0 ; i < stringLen ; i + + ) <nl> { <nl> unsigned short c = m_sString [ i ] ; <nl> CCAssert ( c < kCCBMFontMaxChars , " LabelBMFont : character outside bounds " ) ; <nl> namespace cocos2d { <nl> if ( ! fontChar ) <nl> { <nl> fontChar = new CCSprite ( ) ; <nl> - fontChar - > initWithBatchNode ( this , rect ) ; <nl> + fontChar - > initWithBatchNodeRectInPixels ( this , rect ) ; <nl> this - > addChild ( fontChar , 0 , i ) ; <nl> fontChar - > release ( ) ; <nl> } <nl> mmm a / cocos2dx / platform / CCPlatformMacros . h <nl> ppp b / cocos2dx / platform / CCPlatformMacros . h <nl> public : inline void set # # funName ( varType var ) { varName = var ; } <nl> / / assertion <nl> # include < assert . h > <nl> # define CC_ASSERT ( cond ) assert ( cond ) <nl> - # define CC_UNUSED_PARAM ( unusedparam ) unusedparam <nl> + # define CC_UNUSED_PARAM ( unusedparam ) ( void ) unusedparam <nl> <nl> <nl> <nl> mmm a / cocos2dx / platform / ios / EAGLView . mm <nl> ppp b / cocos2dx / platform / ios / EAGLView . mm <nl> - ( void ) onUIKeyboardNotification : ( NSNotification * ) notif ; <nl> } <nl> else if ( UIKeyboardDidShowNotification = = type ) <nl> { <nl> - CGSize screenSize = self . window . screen . bounds . size ; <nl> + / / CGSize screenSize = self . window . screen . bounds . size ; <nl> dispatcher - > dispatchKeyboardDidShow ( notiInfo ) ; <nl> caretRect_ = end ; <nl> caretRect_ . origin . y = viewSize . height - ( caretRect_ . origin . y + caretRect_ . size . height + [ UIFont smallSystemFontSize ] ) ; <nl> mmm a / cocos2dx / textures / CCTextureAtlas . cpp <nl> ppp b / cocos2dx / textures / CCTextureAtlas . cpp <nl> bool CCTextureAtlas : : initWithTexture ( CCTexture2D * texture , unsigned int capacity <nl> this - > m_pTexture = texture ; <nl> CC_SAFE_RETAIN ( m_pTexture ) ; <nl> <nl> - / / Re - initialization is not allowed <nl> + / / Re - initialization is not allowed <nl> assert ( m_pQuads = = NULL & & m_pIndices = = NULL ) ; <nl> <nl> m_pQuads = ( ccV3F_C4B_T2F_Quad * ) calloc ( sizeof ( ccV3F_C4B_T2F_Quad ) * m_uCapacity , 1 ) ; <nl> void CCTextureAtlas : : updateQuad ( ccV3F_C4B_T2F_Quad * quad , unsigned int index ) <nl> <nl> m_pQuads [ index ] = * quad ; <nl> <nl> - # if CC_USES_VBO <nl> - m_bDirty = true ; <nl> + # if CC_USES_VBO <nl> + m_bDirty = true ; <nl> # endif <nl> } <nl> <nl> void CCTextureAtlas : : insertQuad ( ccV3F_C4B_T2F_Quad * quad , unsigned int index ) <nl> <nl> m_pQuads [ index ] = * quad ; <nl> <nl> - # if CC_USES_VBO <nl> - m_bDirty = true ; <nl> + # if CC_USES_VBO <nl> + m_bDirty = true ; <nl> # endif <nl> } <nl> <nl> void CCTextureAtlas : : insertQuadFromIndex ( unsigned int oldIndex , unsigned int new <nl> <nl> / / because it is ambigious in iphone , so we implement abs ourself <nl> / / unsigned int howMany = abs ( oldIndex - newIndex ) ; <nl> - unsigned int howMany = ( oldIndex - newIndex ) > = 0 ? ( oldIndex - newIndex ) : ( newIndex - oldIndex ) ; <nl> + unsigned int howMany = ( oldIndex - newIndex ) > 0 ? ( oldIndex - newIndex ) : ( newIndex - oldIndex ) ; <nl> unsigned int dst = oldIndex ; <nl> unsigned int src = oldIndex + 1 ; <nl> if ( oldIndex > newIndex ) { <nl> void CCTextureAtlas : : insertQuadFromIndex ( unsigned int oldIndex , unsigned int new <nl> memmove ( & m_pQuads [ dst ] , & m_pQuads [ src ] , sizeof ( m_pQuads [ 0 ] ) * howMany ) ; <nl> m_pQuads [ newIndex ] = quadsBackup ; <nl> <nl> - # if CC_USES_VBO <nl> - m_bDirty = true ; <nl> + # if CC_USES_VBO <nl> + m_bDirty = true ; <nl> # endif <nl> } <nl> <nl> void CCTextureAtlas : : removeQuadAtIndex ( unsigned int index ) <nl> <nl> m_uTotalQuads - - ; <nl> <nl> - # if CC_USES_VBO <nl> - m_bDirty = true ; <nl> + # if CC_USES_VBO <nl> + m_bDirty = true ; <nl> # endif <nl> } <nl> <nl> bool CCTextureAtlas : : resizeCapacity ( unsigned int newCapacity ) <nl> <nl> this - > initIndices ( ) ; <nl> <nl> - # if CC_USES_VBO <nl> - m_bDirty = true ; <nl> + # if CC_USES_VBO <nl> + m_bDirty = true ; <nl> # endif <nl> <nl> return true ; <nl> void CCTextureAtlas : : drawNumberOfQuads ( unsigned int n ) <nl> <nl> void CCTextureAtlas : : drawNumberOfQuads ( unsigned int n , unsigned int start ) <nl> { <nl> - / / Default GL states : GL_TEXTURE_2D , GL_VERTEX_ARRAY , GL_COLOR_ARRAY , GL_TEXTURE_COORD_ARRAY <nl> - / / Needed states : GL_TEXTURE_2D , GL_VERTEX_ARRAY , GL_COLOR_ARRAY , GL_TEXTURE_COORD_ARRAY <nl> + / / Default GL states : GL_TEXTURE_2D , GL_VERTEX_ARRAY , GL_COLOR_ARRAY , GL_TEXTURE_COORD_ARRAY <nl> + / / Needed states : GL_TEXTURE_2D , GL_VERTEX_ARRAY , GL_COLOR_ARRAY , GL_TEXTURE_COORD_ARRAY <nl> / / Unneeded states : - <nl> <nl> glBindTexture ( GL_TEXTURE_2D , m_pTexture - > getName ( ) ) ; <nl> void CCTextureAtlas : : drawNumberOfQuads ( unsigned int n , unsigned int start ) <nl> <nl> glBindBuffer ( GL_ELEMENT_ARRAY_BUFFER , m_pBuffersVBO [ 1 ] ) ; <nl> <nl> - # if CC_ENABLE_CACHE_TEXTTURE_DATA <nl> + # if CC_ENABLE_CACHE_TEXTTURE_DATA <nl> glBufferData ( GL_ELEMENT_ARRAY_BUFFER , sizeof ( m_pIndices [ 0 ] ) * m_uCapacity * 6 , m_pIndices , GL_STATIC_DRAW ) ; <nl> # endif <nl> <nl> similarity index 100 % <nl> rename from template / xcode3 / cocos2d - x_app / ___PROJECTNAMEASIDENTIFIER____Prefix . pch <nl> rename to template / xcode3 / cocos2d - x_app / Prefix . pch <nl> mmm a / template / xcode3 / cocos2d - x_app / ___PROJECTNAME___ . xcodeproj / project . pbxproj . REMOVED . git - id <nl> ppp b / template / xcode3 / cocos2d - x_app / ___PROJECTNAME___ . xcodeproj / project . pbxproj . REMOVED . git - id <nl> @ @ - 1 + 1 @ @ <nl> - 8a8e4250f3cfe00ec9909ad8b1cedfcccb4acf64 <nl> \ No newline at end of file <nl> + 3aab8d3693dcaba52bbe6cf1d88bd085701c71bb <nl> \ No newline at end of file <nl> mmm a / template / xcode3 / cocos2d - x_app / ios / AppController . h <nl> ppp b / template / xcode3 / cocos2d - x_app / ios / AppController . h <nl> <nl> / / <nl> - / / ___PROJECTNAMEASIDENTIFIER___AppController . h <nl> + / / AppController . h <nl> / / ___PROJECTNAME___ <nl> / / <nl> / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> / / <nl> <nl> + @ class RootViewController ; <nl> + <nl> @ interface AppController : NSObject < UIAccelerometerDelegate , UIAlertViewDelegate , UITextFieldDelegate , UIApplicationDelegate > { <nl> UIWindow * window ; <nl> + RootViewController * viewController ; <nl> } <nl> <nl> @ end <nl> mmm a / template / xcode3 / cocos2d - x_app / ios / AppController . mm <nl> ppp b / template / xcode3 / cocos2d - x_app / ios / AppController . mm <nl> <nl> / / <nl> - / / ___PROJECTNAMEASIDENTIFIER___AppController . mm <nl> + / / AppController . mm <nl> / / ___PROJECTNAME___ <nl> / / <nl> / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> / / <nl> + <nl> # import < UIKit / UIKit . h > <nl> # import " AppController . h " <nl> # import " cocos2d . h " <nl> # import " EAGLView . h " <nl> # import " AppDelegate . h " <nl> <nl> + # import " RootViewController . h " <nl> + <nl> @ implementation AppController <nl> <nl> # pragma mark - <nl> - ( BOOL ) application : ( UIApplication * ) application didFinishLaunchingWithOptions : ( <nl> sharegroup : nil <nl> multiSampling : NO <nl> numberOfSamples : 0 ] ; <nl> - [ window addSubview : __glView ] ; <nl> + <nl> + / / Use RootViewController manage EAGLView <nl> + viewController = [ [ RootViewController alloc ] initWithNibName : nil bundle : nil ] ; <nl> + viewController . wantsFullScreenLayout = YES ; <nl> + viewController . view = __glView ; <nl> + <nl> + / / Set RootViewController to window <nl> + window . rootViewController = viewController ; <nl> [ window makeKeyAndVisible ] ; <nl> <nl> [ [ UIApplication sharedApplication ] setStatusBarHidden : YES ] ; <nl> - ( BOOL ) application : ( UIApplication * ) application didFinishLaunchingWithOptions : ( <nl> return YES ; <nl> } <nl> <nl> + <nl> - ( void ) applicationWillResignActive : ( UIApplication * ) application { <nl> / * <nl> Sent when the application is about to move from active to inactive state . This can occur for certain types of temporary interruptions ( such as an incoming phone call or SMS message ) or when the user quits the application and it begins the transition to the background state . <nl> - ( void ) dealloc { <nl> <nl> <nl> @ end <nl> + <nl> new file mode 100644 <nl> index 000000000000 . . dbc1baefdaca <nl> mmm / dev / null <nl> ppp b / template / xcode3 / cocos2d - x_app / ios / RootViewController . h <nl> <nl> + / / <nl> + / / RootViewController . h <nl> + / / ___PROJECTNAME___ <nl> + / / <nl> + / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> + / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> + / / <nl> + <nl> + # import < UIKit / UIKit . h > <nl> + <nl> + <nl> + @ interface RootViewController : UIViewController { <nl> + <nl> + } <nl> + <nl> + @ end <nl> new file mode 100644 <nl> index 000000000000 . . 88fcd37091ef <nl> mmm / dev / null <nl> ppp b / template / xcode3 / cocos2d - x_app / ios / RootViewController . mm <nl> <nl> + / / <nl> + / / RootViewController . mm <nl> + / / ___PROJECTNAME___ <nl> + / / <nl> + / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> + / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> + / / <nl> + <nl> + # import " RootViewController . h " <nl> + <nl> + <nl> + @ implementation RootViewController <nl> + <nl> + / * <nl> + / / The designated initializer . Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad . <nl> + - ( id ) initWithNibName : ( NSString * ) nibNameOrNil bundle : ( NSBundle * ) nibBundleOrNil { <nl> + if ( ( self = [ super initWithNibName : nibNameOrNil bundle : nibBundleOrNil ] ) ) { <nl> + / / Custom initialization <nl> + } <nl> + return self ; <nl> + } <nl> + * / <nl> + <nl> + / * <nl> + / / Implement loadView to create a view hierarchy programmatically , without using a nib . <nl> + - ( void ) loadView { <nl> + } <nl> + * / <nl> + <nl> + / * <nl> + / / Implement viewDidLoad to do additional setup after loading the view , typically from a nib . <nl> + - ( void ) viewDidLoad { <nl> + [ super viewDidLoad ] ; <nl> + } <nl> + <nl> + * / <nl> + / / Override to allow orientations other than the default portrait orientation . <nl> + - ( BOOL ) shouldAutorotateToInterfaceOrientation : ( UIInterfaceOrientation ) interfaceOrientation { <nl> + return UIInterfaceOrientationIsLandscape ( interfaceOrientation ) ; <nl> + } <nl> + <nl> + - ( void ) didReceiveMemoryWarning { <nl> + / / Releases the view if it doesn ' t have a superview . <nl> + [ super didReceiveMemoryWarning ] ; <nl> + <nl> + / / Release any cached data , images , etc that aren ' t in use . <nl> + } <nl> + <nl> + - ( void ) viewDidUnload { <nl> + [ super viewDidUnload ] ; <nl> + / / Release any retained subviews of the main view . <nl> + / / e . g . self . myOutlet = nil ; <nl> + } <nl> + <nl> + <nl> + - ( void ) dealloc { <nl> + [ super dealloc ] ; <nl> + } <nl> + <nl> + <nl> + @ end <nl> similarity index 100 % <nl> rename from template / xcode3 / cocos2d - x_box2d_app / ___PROJECTNAMEASIDENTIFIER____Prefix . pch <nl> rename to template / xcode3 / cocos2d - x_box2d_app / Prefix . pch <nl> mmm a / template / xcode3 / cocos2d - x_box2d_app / ___PROJECTNAME___ . xcodeproj / project . pbxproj . REMOVED . git - id <nl> ppp b / template / xcode3 / cocos2d - x_box2d_app / ___PROJECTNAME___ . xcodeproj / project . pbxproj . REMOVED . git - id <nl> @ @ - 1 + 1 @ @ <nl> - 66024535e3177e78e142dc5f54f603198c2c7550 <nl> \ No newline at end of file <nl> + d018a539198cdce661d24e7f45fbce6fe66ff1a1 <nl> \ No newline at end of file <nl> mmm a / template / xcode3 / cocos2d - x_box2d_app / ios / AppController . h <nl> ppp b / template / xcode3 / cocos2d - x_box2d_app / ios / AppController . h <nl> <nl> / / <nl> - / / ___PROJECTNAMEASIDENTIFIER___AppController . h <nl> + / / AppController . h <nl> / / ___PROJECTNAME___ <nl> / / <nl> / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> / / <nl> <nl> + @ class RootViewController ; <nl> + <nl> @ interface AppController : NSObject < UIAccelerometerDelegate , UIAlertViewDelegate , UITextFieldDelegate , UIApplicationDelegate > { <nl> UIWindow * window ; <nl> + RootViewController * viewController ; <nl> } <nl> <nl> @ end <nl> mmm a / template / xcode3 / cocos2d - x_box2d_app / ios / AppController . mm <nl> ppp b / template / xcode3 / cocos2d - x_box2d_app / ios / AppController . mm <nl> <nl> / / <nl> - / / ___PROJECTNAMEASIDENTIFIER___AppController . mm <nl> + / / AppController . mm <nl> / / ___PROJECTNAME___ <nl> / / <nl> / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> / / <nl> + <nl> # import < UIKit / UIKit . h > <nl> # import " AppController . h " <nl> # import " cocos2d . h " <nl> # import " EAGLView . h " <nl> # import " AppDelegate . h " <nl> <nl> + # import " RootViewController . h " <nl> + <nl> @ implementation AppController <nl> <nl> # pragma mark - <nl> - ( BOOL ) application : ( UIApplication * ) application didFinishLaunchingWithOptions : ( <nl> EAGLView * __glView = [ EAGLView viewWithFrame : [ window bounds ] <nl> pixelFormat : kEAGLColorFormatRGBA8 <nl> depthFormat : GL_DEPTH_COMPONENT16_OES <nl> - preserveBackbuffer : NO <nl> + preserveBackbuffer : NO <nl> sharegroup : nil <nl> - multiSampling : NO <nl> - numberOfSamples : 0 ] ; <nl> - [ window addSubview : __glView ] ; <nl> + multiSampling : NO <nl> + numberOfSamples : 0 ] ; <nl> + <nl> + / / Use RootViewController manage EAGLView <nl> + viewController = [ [ RootViewController alloc ] initWithNibName : nil bundle : nil ] ; <nl> + viewController . wantsFullScreenLayout = YES ; <nl> + viewController . view = __glView ; <nl> + <nl> + / / Set RootViewController to window <nl> + window . rootViewController = viewController ; <nl> [ window makeKeyAndVisible ] ; <nl> <nl> [ [ UIApplication sharedApplication ] setStatusBarHidden : YES ] ; <nl> - ( void ) dealloc { <nl> <nl> <nl> @ end <nl> + <nl> new file mode 100644 <nl> index 000000000000 . . dbc1baefdaca <nl> mmm / dev / null <nl> ppp b / template / xcode3 / cocos2d - x_box2d_app / ios / RootViewController . h <nl> <nl> + / / <nl> + / / RootViewController . h <nl> + / / ___PROJECTNAME___ <nl> + / / <nl> + / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> + / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> + / / <nl> + <nl> + # import < UIKit / UIKit . h > <nl> + <nl> + <nl> + @ interface RootViewController : UIViewController { <nl> + <nl> + } <nl> + <nl> + @ end <nl> new file mode 100644 <nl> index 000000000000 . . 88fcd37091ef <nl> mmm / dev / null <nl> ppp b / template / xcode3 / cocos2d - x_box2d_app / ios / RootViewController . mm <nl> <nl> + / / <nl> + / / RootViewController . mm <nl> + / / ___PROJECTNAME___ <nl> + / / <nl> + / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> + / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> + / / <nl> + <nl> + # import " RootViewController . h " <nl> + <nl> + <nl> + @ implementation RootViewController <nl> + <nl> + / * <nl> + / / The designated initializer . Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad . <nl> + - ( id ) initWithNibName : ( NSString * ) nibNameOrNil bundle : ( NSBundle * ) nibBundleOrNil { <nl> + if ( ( self = [ super initWithNibName : nibNameOrNil bundle : nibBundleOrNil ] ) ) { <nl> + / / Custom initialization <nl> + } <nl> + return self ; <nl> + } <nl> + * / <nl> + <nl> + / * <nl> + / / Implement loadView to create a view hierarchy programmatically , without using a nib . <nl> + - ( void ) loadView { <nl> + } <nl> + * / <nl> + <nl> + / * <nl> + / / Implement viewDidLoad to do additional setup after loading the view , typically from a nib . <nl> + - ( void ) viewDidLoad { <nl> + [ super viewDidLoad ] ; <nl> + } <nl> + <nl> + * / <nl> + / / Override to allow orientations other than the default portrait orientation . <nl> + - ( BOOL ) shouldAutorotateToInterfaceOrientation : ( UIInterfaceOrientation ) interfaceOrientation { <nl> + return UIInterfaceOrientationIsLandscape ( interfaceOrientation ) ; <nl> + } <nl> + <nl> + - ( void ) didReceiveMemoryWarning { <nl> + / / Releases the view if it doesn ' t have a superview . <nl> + [ super didReceiveMemoryWarning ] ; <nl> + <nl> + / / Release any cached data , images , etc that aren ' t in use . <nl> + } <nl> + <nl> + - ( void ) viewDidUnload { <nl> + [ super viewDidUnload ] ; <nl> + / / Release any retained subviews of the main view . <nl> + / / e . g . self . myOutlet = nil ; <nl> + } <nl> + <nl> + <nl> + - ( void ) dealloc { <nl> + [ super dealloc ] ; <nl> + } <nl> + <nl> + <nl> + @ end <nl> similarity index 100 % <nl> rename from template / xcode3 / cocos2d - x_chipmunk_app / ___PROJECTNAMEASIDENTIFIER____Prefix . pch <nl> rename to template / xcode3 / cocos2d - x_chipmunk_app / Prefix . pch <nl> mmm a / template / xcode3 / cocos2d - x_chipmunk_app / ___PROJECTNAME___ . xcodeproj / project . pbxproj . REMOVED . git - id <nl> ppp b / template / xcode3 / cocos2d - x_chipmunk_app / ___PROJECTNAME___ . xcodeproj / project . pbxproj . REMOVED . git - id <nl> @ @ - 1 + 1 @ @ <nl> - a6ca12b0bdd905d2b0dd4cad0ca30ea437326572 <nl> \ No newline at end of file <nl> + b59f29f9bd284c46876e7ecc47b74bfaf8a00aa6 <nl> \ No newline at end of file <nl> mmm a / template / xcode3 / cocos2d - x_chipmunk_app / ios / AppController . h <nl> ppp b / template / xcode3 / cocos2d - x_chipmunk_app / ios / AppController . h <nl> <nl> / / <nl> - / / ___PROJECTNAMEASIDENTIFIER___AppController . h <nl> + / / AppController . h <nl> / / ___PROJECTNAME___ <nl> / / <nl> / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> / / <nl> <nl> + @ class RootViewController ; <nl> + <nl> @ interface AppController : NSObject < UIAccelerometerDelegate , UIAlertViewDelegate , UITextFieldDelegate , UIApplicationDelegate > { <nl> UIWindow * window ; <nl> + RootViewController * viewController ; <nl> } <nl> <nl> @ end <nl> mmm a / template / xcode3 / cocos2d - x_chipmunk_app / ios / AppController . mm <nl> ppp b / template / xcode3 / cocos2d - x_chipmunk_app / ios / AppController . mm <nl> <nl> / / <nl> - / / ___PROJECTNAMEASIDENTIFIER___AppController . mm <nl> + / / AppController . mm <nl> / / ___PROJECTNAME___ <nl> / / <nl> / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> / / <nl> + <nl> # import < UIKit / UIKit . h > <nl> # import " AppController . h " <nl> # import " cocos2d . h " <nl> # import " EAGLView . h " <nl> # import " AppDelegate . h " <nl> <nl> + # import " RootViewController . h " <nl> + <nl> @ implementation AppController <nl> <nl> # pragma mark - <nl> - ( BOOL ) application : ( UIApplication * ) application didFinishLaunchingWithOptions : ( <nl> sharegroup : nil <nl> multiSampling : NO <nl> numberOfSamples : 0 ] ; <nl> - [ window addSubview : __glView ] ; <nl> + <nl> + / / Use RootViewController manage EAGLView <nl> + viewController = [ [ RootViewController alloc ] initWithNibName : nil bundle : nil ] ; <nl> + viewController . wantsFullScreenLayout = YES ; <nl> + viewController . view = __glView ; <nl> + <nl> + / / Set RootViewController to window <nl> + window . rootViewController = viewController ; <nl> [ window makeKeyAndVisible ] ; <nl> <nl> [ [ UIApplication sharedApplication ] setStatusBarHidden : YES ] ; <nl> - ( void ) applicationWillEnterForeground : ( UIApplication * ) application { <nl> cocos2d : : CCApplication : : sharedApplication ( ) . applicationWillEnterForeground ( ) ; <nl> } <nl> <nl> - <nl> - ( void ) applicationWillTerminate : ( UIApplication * ) application { <nl> / * <nl> Called when the application is about to terminate . <nl> - ( void ) dealloc { <nl> <nl> <nl> @ end <nl> + <nl> new file mode 100644 <nl> index 000000000000 . . dbc1baefdaca <nl> mmm / dev / null <nl> ppp b / template / xcode3 / cocos2d - x_chipmunk_app / ios / RootViewController . h <nl> <nl> + / / <nl> + / / RootViewController . h <nl> + / / ___PROJECTNAME___ <nl> + / / <nl> + / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> + / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> + / / <nl> + <nl> + # import < UIKit / UIKit . h > <nl> + <nl> + <nl> + @ interface RootViewController : UIViewController { <nl> + <nl> + } <nl> + <nl> + @ end <nl> new file mode 100644 <nl> index 000000000000 . . 88fcd37091ef <nl> mmm / dev / null <nl> ppp b / template / xcode3 / cocos2d - x_chipmunk_app / ios / RootViewController . mm <nl> <nl> + / / <nl> + / / RootViewController . mm <nl> + / / ___PROJECTNAME___ <nl> + / / <nl> + / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> + / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> + / / <nl> + <nl> + # import " RootViewController . h " <nl> + <nl> + <nl> + @ implementation RootViewController <nl> + <nl> + / * <nl> + / / The designated initializer . Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad . <nl> + - ( id ) initWithNibName : ( NSString * ) nibNameOrNil bundle : ( NSBundle * ) nibBundleOrNil { <nl> + if ( ( self = [ super initWithNibName : nibNameOrNil bundle : nibBundleOrNil ] ) ) { <nl> + / / Custom initialization <nl> + } <nl> + return self ; <nl> + } <nl> + * / <nl> + <nl> + / * <nl> + / / Implement loadView to create a view hierarchy programmatically , without using a nib . <nl> + - ( void ) loadView { <nl> + } <nl> + * / <nl> + <nl> + / * <nl> + / / Implement viewDidLoad to do additional setup after loading the view , typically from a nib . <nl> + - ( void ) viewDidLoad { <nl> + [ super viewDidLoad ] ; <nl> + } <nl> + <nl> + * / <nl> + / / Override to allow orientations other than the default portrait orientation . <nl> + - ( BOOL ) shouldAutorotateToInterfaceOrientation : ( UIInterfaceOrientation ) interfaceOrientation { <nl> + return UIInterfaceOrientationIsLandscape ( interfaceOrientation ) ; <nl> + } <nl> + <nl> + - ( void ) didReceiveMemoryWarning { <nl> + / / Releases the view if it doesn ' t have a superview . <nl> + [ super didReceiveMemoryWarning ] ; <nl> + <nl> + / / Release any cached data , images , etc that aren ' t in use . <nl> + } <nl> + <nl> + - ( void ) viewDidUnload { <nl> + [ super viewDidUnload ] ; <nl> + / / Release any retained subviews of the main view . <nl> + / / e . g . self . myOutlet = nil ; <nl> + } <nl> + <nl> + <nl> + - ( void ) dealloc { <nl> + [ super dealloc ] ; <nl> + } <nl> + <nl> + <nl> + @ end <nl> similarity index 100 % <nl> rename from template / xcode3 / cocos2d - x_lua_app / ___PROJECTNAMEASIDENTIFIER____Prefix . pch <nl> rename to template / xcode3 / cocos2d - x_lua_app / Prefix . pch <nl> mmm a / template / xcode3 / cocos2d - x_lua_app / ___PROJECTNAME___ . xcodeproj / project . pbxproj . REMOVED . git - id <nl> ppp b / template / xcode3 / cocos2d - x_lua_app / ___PROJECTNAME___ . xcodeproj / project . pbxproj . REMOVED . git - id <nl> @ @ - 1 + 1 @ @ <nl> - 4f2f642918e859dde3db5a24ebb9484634f1d2fc <nl> \ No newline at end of file <nl> + 8feced937b259baf35f5ea1d21cf2adad5d02f7d <nl> \ No newline at end of file <nl> mmm a / template / xcode3 / cocos2d - x_lua_app / ios / AppController . h <nl> ppp b / template / xcode3 / cocos2d - x_lua_app / ios / AppController . h <nl> <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> - Copyright ( c ) 2010 cocos2d - x . org <nl> - <nl> - http : / / www . cocos2d - x . org <nl> - <nl> - Permission is hereby granted , free of charge , to any person obtaining a copy <nl> - of this software and associated documentation files ( the " Software " ) , to deal <nl> - in the Software without restriction , including without limitation the rights <nl> - to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> - copies of the Software , and to permit persons to whom the Software is <nl> - furnished to do so , subject to the following conditions : <nl> - <nl> - The above copyright notice and this permission notice shall be included in <nl> - all copies or substantial portions of the Software . <nl> - <nl> - THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> - IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> - LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> - THE SOFTWARE . <nl> - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / / <nl> + / / AppController . h <nl> + / / ___PROJECTNAME___ <nl> + / / <nl> + / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> + / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> + / / <nl> <nl> @ class RootViewController ; <nl> <nl> mmm a / template / xcode3 / cocos2d - x_lua_app / ios / AppController . mm <nl> ppp b / template / xcode3 / cocos2d - x_lua_app / ios / AppController . mm <nl> <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> - Copyright ( c ) 2010 cocos2d - x . org <nl> - <nl> - http : / / www . cocos2d - x . org <nl> - <nl> - Permission is hereby granted , free of charge , to any person obtaining a copy <nl> - of this software and associated documentation files ( the " Software " ) , to deal <nl> - in the Software without restriction , including without limitation the rights <nl> - to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> - copies of the Software , and to permit persons to whom the Software is <nl> - furnished to do so , subject to the following conditions : <nl> - <nl> - The above copyright notice and this permission notice shall be included in <nl> - all copies or substantial portions of the Software . <nl> - <nl> - THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> - IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> - LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> - THE SOFTWARE . <nl> - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / / <nl> + / / AppController . mm <nl> + / / ___PROJECTNAME___ <nl> + / / <nl> + / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> + / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> + / / <nl> + <nl> # import < UIKit / UIKit . h > <nl> # import " AppController . h " <nl> # import " cocos2d . h " <nl> mmm a / template / xcode3 / cocos2d - x_lua_app / ios / RootViewController . h <nl> ppp b / template / xcode3 / cocos2d - x_lua_app / ios / RootViewController . h <nl> <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> - Copyright ( c ) 2010 - 2011 cocos2d - x . org <nl> - Copyright ( c ) 2010 Ricardo Quesada <nl> - <nl> - http : / / www . cocos2d - x . org <nl> - <nl> - Permission is hereby granted , free of charge , to any person obtaining a copy <nl> - of this software and associated documentation files ( the " Software " ) , to deal <nl> - in the Software without restriction , including without limitation the rights <nl> - to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> - copies of the Software , and to permit persons to whom the Software is <nl> - furnished to do so , subject to the following conditions : <nl> - <nl> - The above copyright notice and this permission notice shall be included in <nl> - all copies or substantial portions of the Software . <nl> - <nl> - THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> - IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> - LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> - THE SOFTWARE . <nl> - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / / <nl> + / / RootViewController . h <nl> + / / ___PROJECTNAME___ <nl> + / / <nl> + / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> + / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> + / / <nl> <nl> # import < UIKit / UIKit . h > <nl> <nl> mmm a / template / xcode3 / cocos2d - x_lua_app / ios / RootViewController . mm <nl> ppp b / template / xcode3 / cocos2d - x_lua_app / ios / RootViewController . mm <nl> <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> - Copyright ( c ) 2010 - 2011 cocos2d - x . org <nl> - Copyright ( c ) 2010 Ricardo Quesada <nl> - <nl> - http : / / www . cocos2d - x . org <nl> - <nl> - Permission is hereby granted , free of charge , to any person obtaining a copy <nl> - of this software and associated documentation files ( the " Software " ) , to deal <nl> - in the Software without restriction , including without limitation the rights <nl> - to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> - copies of the Software , and to permit persons to whom the Software is <nl> - furnished to do so , subject to the following conditions : <nl> - <nl> - The above copyright notice and this permission notice shall be included in <nl> - all copies or substantial portions of the Software . <nl> - <nl> - THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> - IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> - LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> - THE SOFTWARE . <nl> - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / / <nl> + / / RootViewController . mm <nl> + / / ___PROJECTNAME___ <nl> + / / <nl> + / / Created by ___FULLUSERNAME___ on ___DATE___ . <nl> + / / Copyright ___ORGANIZATIONNAME___ ___YEAR___ . All rights reserved . <nl> + / / <nl> <nl> # import " RootViewController . h " <nl> <nl> new file mode 100644 <nl> index 000000000000 . . 5696ae5bfc1f <nl> mmm / dev / null <nl> ppp b / tests / Res / fonts / tuffy_bold_italic - charmap - hd . png . REMOVED . git - id <nl> @ @ - 0 , 0 + 1 @ @ <nl> + 8167faf6c40ffd95a03028f1dcee1abdaa48b222 <nl> \ No newline at end of file <nl> | Merge commit ' 4aa33b094239d8f04758e8c6f42f94ab19b13226 ' | cocos2d/cocos2d-x | bb1202251ef57f335c0c4acc04417f9db8d3617a | 2011-08-11T07:30:28Z |
mmm a / test / AutolinkExtract / linker - order . ll <nl> ppp b / test / AutolinkExtract / linker - order . ll <nl> <nl> <nl> ; Ensure that the options in the object file preserve ordering . The linker <nl> ; options are order dependent , and we would accidentally reorder them because we <nl> - ; used a std : : set rather than a llvm : : SmallSetVector . <nl> + ; used a std : : set rather than an llvm : : SmallSetVector . <nl> <nl> @ _swift1_autolink_entries_1 = private constant [ 7 x i8 ] c " Saleem \ 00 " , section " . swift1_autolink_entries " , align 8 <nl> @ _swift1_autolink_entries_0 = private constant [ 8 x i8 ] c " Naureen \ 00 " , section " . swift1_autolink_entries " , align 8 <nl> | [ gardening ] Fix recently introduced typo : " a llvm " → " an llvm " | apple/swift | 4b1e3e427e098a564b8363ff454d660dae6697fe | 2016-04-03T07:41:30Z |
mmm a / Documentation / Books / HTTP / book . json <nl> ppp b / Documentation / Books / HTTP / book . json <nl> <nl> " js " : [ " styles / header . js " ] , <nl> " css " : [ " styles / header . css " ] <nl> } , <nl> - " add - header " : { <nl> - " BASE_PATH " : " https : / / docs . arangodb . com / devel " <nl> - } , <nl> " piwik " : { <nl> " URL " : " www . arangodb . com / piwik / " , <nl> " siteId " : 12 <nl> mmm a / Documentation / Books / Manual / book . json <nl> ppp b / Documentation / Books / Manual / book . json <nl> <nl> " js " : [ " styles / header . js " ] , <nl> " css " : [ " styles / header . css " ] <nl> } , <nl> - " add - header " : { <nl> - " BASE_PATH " : " https : / / docs . arangodb . com / devel " <nl> - } , <nl> " piwik " : { <nl> " URL " : " www . arangodb . com / piwik / " , <nl> " siteId " : 12 <nl> mmm a / Documentation / Books / Manual / styles / header . js <nl> ppp b / Documentation / Books / Manual / styles / header . js <nl> document . addEventListener ( " DOMContentLoaded " , function ( event ) { <nl> } <nl> } ) ; <nl> <nl> - $ ( document ) . ready ( function ( ) { <nl> - var bookVersion = gitbook . state . root . match ( / \ / ( \ d \ . \ d | devel ) \ / / ) ; <nl> - if ( bookVersion ) { <nl> - $ ( " . arangodb - version - switcher " ) . val ( bookVersion [ 1 ] ) ; <nl> - } <nl> - } ) ; <nl> - <nl> window . onload = function ( ) { <nl> window . localStorage . removeItem ( " : keyword " ) ; <nl> <nl> | Remove add - header settings , unify version switcher code | arangodb/arangodb | 53022968d5386bfeb55390fdb49132dbae9ab70a | 2016-07-11T17:21:00Z |
mmm a / src / backends / cpu_llvm . cpp <nl> ppp b / src / backends / cpu_llvm . cpp <nl> class RuntimeObject { <nl> return call ( fmt : : format ( " get_ { } " , field ) ) ; <nl> } <nl> <nl> + llvm : : Value * get ( const std : : string & field , llvm : : Value * index ) { <nl> + return call ( fmt : : format ( " get_ { } " , field ) , index ) ; <nl> + } <nl> + <nl> llvm : : Value * get_ptr ( const std : : string & field ) { <nl> return call ( fmt : : format ( " get_ptr_ { } " , field ) ) ; <nl> } <nl> class CPULLVMCodeGen : public IRVisitor , public ModuleBuilder { <nl> llvm : : Type * context_ty ; <nl> llvm : : Type * physical_coordinate_ty ; <nl> <nl> + llvm : : Value * current_coordinates ; <nl> + <nl> CPULLVMCodeGen ( CodeGenBase * codegen , Kernel * kernel ) <nl> : tlctx ( & get_current_program ( ) . llvm_context ) , <nl> llvm_context ( tlctx - > ctx . get ( ) ) , <nl> class CPULLVMCodeGen : public IRVisitor , public ModuleBuilder { <nl> builder - > SetInsertPoint ( body_bb ) ; <nl> / / initialize the coordinates <nl> <nl> - / / auto meta_obj = emit_struct_meta_object ( leaf_block ) ; <nl> - / / meta_obj - > get ( " refine_coordinate " ) ; <nl> auto refine = <nl> get_runtime_function ( leaf_block - > refine_coordinates_func_name ( ) ) ; <nl> auto new_coordinates = builder - > CreateAlloca ( physical_coordinate_ty ) ; <nl> class CPULLVMCodeGen : public IRVisitor , public ModuleBuilder { <nl> create_call ( refine , { element . get_ptr ( " pcoord " ) , new_coordinates , <nl> builder - > CreateLoad ( loop_index ) } ) ; <nl> <nl> + current_coordinates = new_coordinates ; <nl> for_stmt - > body - > accept ( this ) ; <nl> <nl> BasicBlock * after_loop = BasicBlock : : Create ( * llvm_context , " block " , func ) ; <nl> class CPULLVMCodeGen : public IRVisitor , public ModuleBuilder { <nl> <nl> void visit ( LocalLoadStmt * stmt ) { <nl> TC_ASSERT ( stmt - > width ( ) = = 1 ) ; <nl> - bool is_loop_var = false ; <nl> + int loop_var_index = - 1 ; <nl> if ( current_struct_for ) <nl> for ( int i = 0 ; i < current_struct_for - > loop_vars . size ( ) ; i + + ) { <nl> if ( stmt - > ptr [ 0 ] . var = = current_struct_for - > loop_vars [ i ] ) { <nl> - is_loop_var = true ; <nl> + loop_var_index = i ; <nl> } <nl> } <nl> - if ( is_loop_var ) { <nl> - / / TODO : replace this <nl> - auto alloca = builder - > CreateAlloca ( Type : : getInt32Ty ( * llvm_context ) ) ; <nl> - stmt - > value = builder - > CreateLoad ( alloca ) ; <nl> + if ( loop_var_index ! = - 1 ) { <nl> + stmt - > value = builder - > CreateLoad ( builder - > CreateGEP ( <nl> + current_coordinates , { tlctx - > get_constant ( 0 ) , tlctx - > get_constant ( 0 ) , <nl> + tlctx - > get_constant ( loop_var_index ) } ) ) ; <nl> + TC_P ( type_name ( stmt - > value - > getType ( ) ) ) ; <nl> } else { <nl> stmt - > value = builder - > CreateLoad ( stmt - > ptr [ 0 ] . var - > value ) ; <nl> } <nl> | LocalLoad loop var from coordinates | taichi-dev/taichi | def5fe032feef5f688cf2c4ce3f1025742f4248d | 2019-09-04T00:16:45Z |
mmm a / cocos / scripting / js - bindings / manual / cocos2d_specifics . hpp <nl> ppp b / cocos / scripting / js - bindings / manual / cocos2d_specifics . hpp <nl> bool js_cocos2dx_Node_onExitTransitionDidStart ( JSContext * cx , uint32_t argc , jsv <nl> bool js_cocos2dx_Component_onEnter ( JSContext * cx , uint32_t argc , jsval * vp ) ; <nl> bool js_cocos2dx_Component_onExit ( JSContext * cx , uint32_t argc , jsval * vp ) ; <nl> <nl> + bool js_cocos2dx_retain ( JSContext * cx , uint32_t argc , jsval * vp ) ; <nl> + bool js_cocos2dx_release ( JSContext * cx , uint32_t argc , jsval * vp ) ; <nl> + <nl> void get_or_create_js_obj ( JSContext * cx , JS : : HandleObject obj , const std : : string & name , JS : : MutableHandleObject jsObj ) ; <nl> <nl> # endif <nl> mmm a / cocos / scripting / js - bindings / manual / extension / jsb_cocos2dx_extension_manual . cpp <nl> ppp b / cocos / scripting / js - bindings / manual / extension / jsb_cocos2dx_extension_manual . cpp <nl> bool js_cocos2dx_ext_AssetsManager_getFailedAssets ( JSContext * cx , uint32_t argc , <nl> } <nl> * / <nl> <nl> - bool js_cocos2dx_ext_retain ( JSContext * cx , uint32_t argc , jsval * vp ) <nl> - { <nl> - JSObject * thisObj = JS_THIS_OBJECT ( cx , vp ) ; <nl> - if ( thisObj ) { <nl> - js_proxy_t * proxy = jsb_get_js_proxy ( thisObj ) ; <nl> - if ( proxy ) { <nl> - ( ( Ref * ) proxy - > ptr ) - > retain ( ) ; <nl> - return true ; <nl> - } <nl> - } <nl> - JS_ReportError ( cx , " Invalid Native Object . " ) ; <nl> - return false ; <nl> - } <nl> - <nl> - bool js_cocos2dx_ext_release ( JSContext * cx , uint32_t argc , jsval * vp ) <nl> - { <nl> - JSObject * thisObj = JS_THIS_OBJECT ( cx , vp ) ; <nl> - if ( thisObj ) { <nl> - js_proxy_t * proxy = jsb_get_js_proxy ( thisObj ) ; <nl> - if ( proxy ) { <nl> - ( ( Ref * ) proxy - > ptr ) - > release ( ) ; <nl> - return true ; <nl> - } <nl> - } <nl> - JS_ReportError ( cx , " Invalid Native Object . " ) ; <nl> - return false ; <nl> - } <nl> - <nl> - <nl> __JSDownloaderDelegator : : __JSDownloaderDelegator ( JSContext * cx , JS : : HandleObject obj , const std : : string & url , JS : : HandleObject callback ) <nl> : _cx ( cx ) <nl> , _url ( url ) <nl> void register_all_cocos2dx_extension_manual ( JSContext * cx , JS : : HandleObject glob <nl> get_or_create_js_obj ( cx , global , " cc " , & ccObj ) ; <nl> <nl> JS : : RootedObject am ( cx , jsb_cocos2d_extension_AssetsManagerEx_prototype ) ; <nl> - JS_DefineFunction ( cx , am , " retain " , js_cocos2dx_ext_retain , 0 , JSPROP_ENUMERATE | JSPROP_PERMANENT ) ; <nl> - JS_DefineFunction ( cx , am , " release " , js_cocos2dx_ext_release , 0 , JSPROP_ENUMERATE | JSPROP_PERMANENT ) ; <nl> + JS_DefineFunction ( cx , am , " retain " , js_cocos2dx_retain , 0 , JSPROP_ENUMERATE | JSPROP_PERMANENT ) ; <nl> + JS_DefineFunction ( cx , am , " release " , js_cocos2dx_release , 0 , JSPROP_ENUMERATE | JSPROP_PERMANENT ) ; <nl> JS : : RootedObject manifest ( cx , jsb_cocos2d_extension_Manifest_prototype ) ; <nl> - JS_DefineFunction ( cx , manifest , " retain " , js_cocos2dx_ext_retain , 0 , JSPROP_ENUMERATE | JSPROP_PERMANENT ) ; <nl> - JS_DefineFunction ( cx , manifest , " release " , js_cocos2dx_ext_release , 0 , JSPROP_ENUMERATE | JSPROP_PERMANENT ) ; <nl> + JS_DefineFunction ( cx , manifest , " retain " , js_cocos2dx_retain , 0 , JSPROP_ENUMERATE | JSPROP_PERMANENT ) ; <nl> + JS_DefineFunction ( cx , manifest , " release " , js_cocos2dx_release , 0 , JSPROP_ENUMERATE | JSPROP_PERMANENT ) ; <nl> <nl> / / JS_DefineFunction ( cx , jsb_cocos2d_extension_AssetsManager_prototype , " updateAssets " , js_cocos2dx_ext_AssetsManager_updateAssets , 1 , JSPROP_ENUMERATE | JSPROP_PERMANENT ) ; <nl> / / JS_DefineFunction ( cx , jsb_cocos2d_extension_AssetsManager_prototype , " getFailedAssets " , js_cocos2dx_ext_AssetsManager_getFailedAssets , 0 , JSPROP_ENUMERATE | JSPROP_PERMANENT ) ; <nl> mmm a / cocos / scripting / js - bindings / manual / network / XMLHTTPRequest . cpp <nl> ppp b / cocos / scripting / js - bindings / manual / network / XMLHTTPRequest . cpp <nl> <nl> # include " XMLHTTPRequest . h " <nl> # include < string > <nl> # include < algorithm > <nl> + # include " cocos2d_specifics . hpp " <nl> <nl> using namespace std ; <nl> <nl> void MinXmlHttpRequest : : _js_register ( JSContext * cx , JS : : HandleObject global ) <nl> JS_BINDED_FUNC_FOR_DEF ( MinXmlHttpRequest , getAllResponseHeaders ) , <nl> JS_BINDED_FUNC_FOR_DEF ( MinXmlHttpRequest , getResponseHeader ) , <nl> JS_BINDED_FUNC_FOR_DEF ( MinXmlHttpRequest , overrideMimeType ) , <nl> + JS_FN ( " retain " , js_cocos2dx_retain , 0 , JSPROP_PERMANENT | JSPROP_ENUMERATE ) , <nl> + JS_FN ( " release " , js_cocos2dx_release , 0 , JSPROP_PERMANENT | JSPROP_ENUMERATE ) , <nl> JS_FS_END <nl> } ; <nl> <nl> mmm a / tools / simulator / frameworks / runtime - src / Classes / js_module_register . h <nl> ppp b / tools / simulator / frameworks / runtime - src / Classes / js_module_register . h <nl> <nl> # include " navmesh / jsb_cocos2dx_navmesh_manual . h " <nl> <nl> # if ( CC_TARGET_PLATFORM = = CC_PLATFORM_ANDROID | | CC_TARGET_PLATFORM = = CC_PLATFORM_IOS ) <nl> + # include " experimental / jsb_cocos2dx_experimental_video_auto . hpp " <nl> # include " experimental / jsb_cocos2dx_experimental_video_manual . h " <nl> + # include " experimental / jsb_cocos2dx_experimental_webView_auto . hpp " <nl> # include " experimental / jsb_cocos2dx_experimental_webView_manual . h " <nl> # endif <nl> <nl> int js_module_register ( ) <nl> # endif <nl> <nl> # if ( CC_TARGET_PLATFORM = = CC_PLATFORM_ANDROID | | CC_TARGET_PLATFORM = = CC_PLATFORM_IOS ) <nl> + sc - > addRegisterCallback ( register_all_cocos2dx_experimental_video ) ; <nl> sc - > addRegisterCallback ( register_all_cocos2dx_experimental_video_manual ) ; <nl> + sc - > addRegisterCallback ( register_all_cocos2dx_experimental_webView ) ; <nl> sc - > addRegisterCallback ( register_all_cocos2dx_experimental_webView_manual ) ; <nl> # endif <nl> <nl> | Merge pull request from pandamicro / v3 . 7 - release | cocos2d/cocos2d-x | aeeb6eb6833790d9d72325ba8bcbe9afddbacd1a | 2015-07-04T00:40:55Z |
mmm a / buildscripts / resmokelib / config . py <nl> ppp b / buildscripts / resmokelib / config . py <nl> <nl> " variant_name " : None , <nl> " version_id " : None , <nl> <nl> + # Cedar options . <nl> + " cedar_url " : " cedar . mongodb . com " , <nl> + " cedar_rpc_port " : " 7070 " , <nl> + <nl> # WiredTiger options . <nl> " wt_coll_config " : None , <nl> " wt_engine_config " : None , <nl> def resolve ( self ) : <nl> # The root url of the buildlogger server . <nl> BUILDLOGGER_URL = None <nl> <nl> + # URL to connect to the Cedar service . <nl> + CEDAR_URL = None <nl> + <nl> + # Cedar gRPC service port . <nl> + CEDAR_RPC_PORT = None <nl> + <nl> # Root directory for where resmoke . py puts directories containing data files of mongod ' s it starts , <nl> # as well as those started by individual tests . <nl> DBPATH_PREFIX = None <nl> def resolve ( self ) : <nl> # or subprocess32 module to spawn threads . If jasper , resmoke uses the jasper module . <nl> SPAWN_USING = None <nl> <nl> + # The connection string to the jasper service , populated when the service is <nl> + # initialized in TestRunner . <nl> + JASPER_CONNECTION_STR = None <nl> + <nl> # If true , the launching of jobs is staggered in resmoke . py . <nl> STAGGER_JOBS = None <nl> <nl> mmm a / buildscripts / resmokelib / configure_resmoke . py <nl> ppp b / buildscripts / resmokelib / configure_resmoke . py <nl> def _merge_set_params ( param_list ) : <nl> _config . EVERGREEN_VARIANT_NAME = config . pop ( " variant_name " ) <nl> _config . EVERGREEN_VERSION_ID = config . pop ( " version_id " ) <nl> <nl> + # Cedar options . <nl> + _config . CEDAR_URL = config . pop ( " cedar_url " ) <nl> + _config . CEDAR_RPC_PORT = config . pop ( " cedar_rpc_port " ) <nl> + <nl> # Archival options . Archival is enabled only when running on evergreen . <nl> if not _config . EVERGREEN_TASK_ID : <nl> _config . ARCHIVE_FILE = None <nl> mmm a / buildscripts / resmokelib / core / jasper_process . py <nl> ppp b / buildscripts / resmokelib / core / jasper_process . py <nl> <nl> except ImportError : <nl> pass <nl> <nl> + from buildscripts . resmokelib import config <nl> from buildscripts . resmokelib import errors <nl> from buildscripts . resmokelib . core import process as _process <nl> + from buildscripts . resmokelib . logging . jasper_logger import get_logger_config <nl> from buildscripts . resmokelib . testing . fixtures import interface as fixture_interface <nl> <nl> <nl> class Process ( _process . Process ) : <nl> " " " Class for spawning a process using mongodb / jasper . " " " <nl> <nl> - jasper_pb2 = None <nl> - jasper_pb2_grpc = None <nl> - connection_str = None <nl> + pb = None <nl> + rpc = None <nl> <nl> - def __init__ ( self , logger , args , env = None , env_vars = None ) : <nl> + def __init__ ( self , logger , args , env = None , env_vars = None , job_num = None , test_id = None ) : # pylint : disable = too - many - arguments <nl> " " " Initialize the process with the specified logger , arguments , and environment . " " " <nl> _process . Process . __init__ ( self , logger , args , env = env , env_vars = env_vars ) <nl> self . _id = None <nl> - self . _stub = self . jasper_pb2_grpc . JasperProcessManagerStub ( <nl> - grpc . insecure_channel ( self . connection_str ) ) <nl> + self . job_num = job_num <nl> + self . test_id = test_id <nl> + self . _stub = self . rpc . JasperProcessManagerStub ( <nl> + grpc . insecure_channel ( config . JASPER_CONNECTION_STR ) ) <nl> self . _return_code = None <nl> <nl> def start ( self ) : <nl> " " " Start the process and the logger pipes for its stdout and stderr . " " " <nl> - log_format = self . jasper_pb2 . LogFormat . Value ( " LOGFORMATPLAIN " ) <nl> - log_level = self . jasper_pb2 . LogLevel ( ) <nl> - buffered = self . jasper_pb2 . BufferOptions ( ) <nl> - base_opts = self . jasper_pb2 . BaseOptions ( format = log_format , level = log_level , buffer = buffered ) <nl> - log_opts = self . jasper_pb2 . InheritedLoggerOptions ( base = base_opts ) <nl> - logger = self . jasper_pb2 . LoggerConfig ( ) <nl> - logger . inherited . CopyFrom ( log_opts ) <nl> - <nl> - output_opts = self . jasper_pb2 . OutputOptions ( loggers = [ logger ] ) <nl> - create_options = self . jasper_pb2 . CreateOptions ( <nl> + logger = get_logger_config ( group_id = self . job_num , test_id = self . test_id , <nl> + process_name = self . args [ 0 ] ) <nl> + output_opts = self . pb . OutputOptions ( loggers = [ logger ] ) <nl> + create_options = self . pb . CreateOptions ( <nl> args = self . args , <nl> environment = self . env , <nl> override_environ = True , <nl> def start ( self ) : <nl> <nl> val = self . _stub . Create ( create_options ) <nl> self . pid = val . pid <nl> - self . _id = self . jasper_pb2 . JasperProcessID ( value = val . id ) <nl> + self . _id = self . pb . JasperProcessID ( value = val . id ) <nl> self . _return_code = None <nl> <nl> def stop ( self , mode = None ) : <nl> def stop ( self , mode = None ) : <nl> mode = fixture_interface . TeardownMode . TERMINATE <nl> <nl> if mode = = fixture_interface . TeardownMode . KILL : <nl> - signal = self . jasper_pb2 . Signals . Value ( " KILL " ) <nl> + signal = self . pb . Signals . Value ( " KILL " ) <nl> elif mode = = fixture_interface . TeardownMode . TERMINATE : <nl> - signal = self . jasper_pb2 . Signals . Value ( " TERMINATE " ) <nl> + signal = self . pb . Signals . Value ( " TERMINATE " ) <nl> elif mode = = fixture_interface . TeardownMode . ABORT : <nl> - signal = self . jasper_pb2 . Signals . Value ( " ABRT " ) <nl> + signal = self . pb . Signals . Value ( " ABRT " ) <nl> else : <nl> raise errors . ProcessError ( " Process wrapper given unrecognized teardown mode : " + <nl> mode . value ) <nl> <nl> - signal_process = self . jasper_pb2 . SignalProcess ( ProcessID = self . _id , signal = signal ) <nl> + signal_process = self . pb . SignalProcess ( ProcessID = self . _id , signal = signal ) <nl> val = self . _stub . Signal ( signal_process ) <nl> if not val . success \ <nl> and " cannot signal a process that has terminated " not in val . text \ <nl> mmm a / buildscripts / resmokelib / core / programs . py <nl> ppp b / buildscripts / resmokelib / core / programs . py <nl> def mongos_program ( logger , executable = None , process_kwargs = None , * * kwargs ) : <nl> return make_process ( logger , args , * * process_kwargs ) <nl> <nl> <nl> - def mongo_shell_program ( # pylint : disable = too - many - branches , too - many - locals , too - many - statements <nl> - logger , executable = None , connection_string = None , filename = None , process_kwargs = None , <nl> - * * kwargs ) : <nl> + def mongo_shell_program ( # pylint : disable = too - many - arguments , too - many - branches , too - many - locals , too - many - statements <nl> + job_num , test_id , logger , executable = None , connection_string = None , filename = None , <nl> + process_kwargs = None , * * kwargs ) : <nl> " " " Return a Process instance that starts a mongo shell . <nl> <nl> The shell is started with the given connection string and arguments constructed from ' kwargs ' . <nl> def mongo_shell_program ( # pylint : disable = too - many - branches , too - many - locals , to <nl> _set_keyfile_permissions ( test_data ) <nl> <nl> process_kwargs = utils . default_if_none ( process_kwargs , { } ) <nl> + process_kwargs [ " job_num " ] = job_num <nl> + process_kwargs [ " test_id " ] = test_id <nl> return make_process ( logger , args , * * process_kwargs ) <nl> <nl> <nl> new file mode 100644 <nl> index 000000000000 . . abc3269b734e <nl> mmm / dev / null <nl> ppp b / buildscripts / resmokelib / logging / jasper_logger . py <nl> <nl> + " " " Jasper logging handlers and helpers . " " " <nl> + <nl> + import os <nl> + <nl> + from buildscripts . resmokelib import config <nl> + <nl> + <nl> + def get_logger_config ( group_id = " " , test_id = " " , process_name = " " ) : <nl> + " " " Return the jasper logger config . " " " <nl> + <nl> + import jasper . jasper_pb2 as pb <nl> + <nl> + username = os . getenv ( " CEDAR_USERNAME " , default = " " ) <nl> + api_key = os . getenv ( " CEDAR_API_KEY " , default = " " ) <nl> + <nl> + logger_config = pb . LoggerConfig ( ) <nl> + log_level = pb . LogLevel ( threshold = 30 , default = 30 ) <nl> + log_format = pb . LogFormat . Value ( " LOGFORMATPLAIN " ) <nl> + <nl> + if config . EVERGREEN_TASK_ID and group_id : <nl> + buildlogger_info = pb . BuildloggerV3Info ( <nl> + project = config . EVERGREEN_PROJECT_NAME , version = config . EVERGREEN_VERSION_ID , <nl> + variant = config . EVERGREEN_VARIANT_NAME , task_name = config . EVERGREEN_TASK_NAME , <nl> + task_id = config . EVERGREEN_TASK_ID , execution = config . EVERGREEN_EXECUTION , <nl> + test_name = str ( test_id ) , process_name = process_name , format = log_format , tags = [ <nl> + str ( group_id ) <nl> + ] , base_address = config . CEDAR_URL , rpc_port = config . CEDAR_RPC_PORT , username = username , <nl> + api_key = api_key ) <nl> + buildlogger_options = pb . BuildloggerV3Options ( buildloggerv3 = buildlogger_info , <nl> + level = log_level ) <nl> + logger_config . buildloggerv3 . CopyFrom ( buildlogger_options ) <nl> + else : <nl> + buffered = pb . BufferOptions ( ) <nl> + base_opts = pb . BaseOptions ( format = log_format , level = log_level , buffer = buffered ) <nl> + log_opts = pb . DefaultLoggerOptions ( base = base_opts ) <nl> + logger_config . default . CopyFrom ( log_opts ) <nl> + <nl> + return logger_config <nl> mmm a / buildscripts / resmokelib / run / __init__ . py <nl> ppp b / buildscripts / resmokelib / run / __init__ . py <nl> <nl> _INTERNAL_OPTIONS_TITLE = " Internal Options " <nl> _BENCHMARK_ARGUMENT_TITLE = " Benchmark / Benchrun test options " <nl> _EVERGREEN_ARGUMENT_TITLE = " Evergreen options " <nl> + _CEDAR_ARGUMENT_TITLE = " Cedar options " <nl> <nl> <nl> class TestRunner ( Subcommand ) : # pylint : disable = too - many - instance - attributes <nl> def _setup_jasper ( self ) : <nl> from jasper import jasper_pb2 <nl> from jasper import jasper_pb2_grpc <nl> <nl> - jasper_process . Process . jasper_pb2 = jasper_pb2 <nl> - jasper_process . Process . jasper_pb2_grpc = jasper_pb2_grpc <nl> + jasper_process . Process . pb = jasper_pb2 <nl> + jasper_process . Process . rpc = jasper_pb2_grpc <nl> <nl> jasper_port = config . BASE_PORT - 1 <nl> jasper_conn_str = " localhost : % d " % jasper_port <nl> - jasper_process . Process . connection_str = jasper_conn_str <nl> jasper_command = [ <nl> curator_path , " jasper " , " service " , " run " , " rpc " , " - - port " , <nl> str ( jasper_port ) <nl> ] <nl> self . _jasper_server = process . Process ( self . _resmoke_logger , jasper_command ) <nl> self . _jasper_server . start ( ) <nl> + config . JASPER_CONNECTION_STR = jasper_conn_str <nl> <nl> channel = grpc . insecure_channel ( jasper_conn_str ) <nl> grpc . channel_ready_future ( channel ) . result ( ) <nl> def _add_run ( cls , subparsers ) : # pylint : disable = too - many - statements <nl> evergreen_options . add_argument ( " - - versionId " , dest = " version_id " , metavar = " VERSION_ID " , <nl> help = " Sets the version ID of the task . " ) <nl> <nl> + cedar_options = parser . add_argument_group ( <nl> + title = _CEDAR_ARGUMENT_TITLE , <nl> + description = ( " Options used to propagate Cedar service connection information . " ) ) <nl> + <nl> + cedar_options . add_argument ( " - - cedarURL " , dest = " cedar_url " , metavar = " CEDAR_URL " , <nl> + help = ( " The URL of the Cedar service . " ) ) <nl> + <nl> + cedar_options . add_argument ( " - - cedarRPCPort " , dest = " cedar_rpc_port " , <nl> + metavar = " CEDAR_RPC_PORT " , <nl> + help = ( " The RPC port of the Cedar service . " ) ) <nl> + <nl> benchmark_options = parser . add_argument_group ( <nl> title = _BENCHMARK_ARGUMENT_TITLE , <nl> description = " Options for running Benchmark / Benchrun tests " ) <nl> mmm a / buildscripts / resmokelib / testing / report . py <nl> ppp b / buildscripts / resmokelib / testing / report . py <nl> def startTest ( self , test ) : # pylint : disable = invalid - name <nl> test_info . url_endpoint = url_endpoint <nl> if self . logging_prefix is not None : <nl> test_logger . info ( self . logging_prefix ) <nl> + # Set job_num in test . <nl> + test . job_num = self . job_num <nl> <nl> test . override_logger ( test_logger ) <nl> test_info . start_time = time . time ( ) <nl> mmm a / buildscripts / resmokelib / testing / testcases / jstest . py <nl> ppp b / buildscripts / resmokelib / testing / testcases / jstest . py <nl> def _get_data_dir ( self , global_vars ) : <nl> <nl> def _make_process ( self ) : <nl> return core . programs . mongo_shell_program ( <nl> - self . logger , executable = self . shell_executable , filename = self . js_filename , <nl> - connection_string = self . fixture . get_driver_connection_url ( ) , * * self . shell_options ) <nl> + self . fixture . job_num , self . _id , self . logger , executable = self . shell_executable , <nl> + filename = self . js_filename , connection_string = self . fixture . get_driver_connection_url ( ) , <nl> + * * self . shell_options ) <nl> <nl> <nl> class JSTestCase ( interface . ProcessTestCase ) : <nl> mmm a / etc / evergreen . yml <nl> ppp b / etc / evergreen . yml <nl> functions : <nl> # Windows path separator <nl> toolchain_txt = " $ pip_dir / toolchain - requirements . txt " <nl> $ { activate_virtualenv } <nl> + python - m pip install - - upgrade pip <nl> python - m pip install - r " $ toolchain_txt " - q <nl> python - m pip freeze > pip - requirements . txt <nl> <nl> functions : <nl> working_dir : src <nl> shell : bash <nl> script : | <nl> + # export these before verbose is set to avoid sharing sensitive info <nl> + export CEDAR_USERNAME = $ { cedar_user } <nl> + export CEDAR_API_KEY = $ { cedar_api_key } <nl> + <nl> set - o errexit <nl> set - o verbose <nl> <nl> functions : <nl> # this list of expansions . <nl> set + o errexit <nl> PATH = " $ path_value " \ <nl> + CEDAR_USERNAME = $ { cedar_user } \ <nl> + CEDAR_PASSWORD <nl> AWS_PROFILE = $ { aws_profile_remote } \ <nl> $ { gcov_environment } \ <nl> $ { lang_environment } \ <nl> mmm a / etc / pip / components / resmoke . req <nl> ppp b / etc / pip / components / resmoke . req <nl> ocspresponder = = 0 . 5 . 0 <nl> flask = = 1 . 1 . 1 <nl> ocspbuilder = = 0 . 10 . 2 <nl> # TODO : uncomment these lines with SERVER - 48156 <nl> - # grpcio = = 1 . 28 . 1 ; platform_machine ! = " x86_64 " <nl> - # grpcio - tools = = 1 . 28 . 1 ; platform_machine ! = " x86_64 " <nl> - # googleapis - common - protos = = 1 . 51 . 0 ; platform_machine ! = " x86_64 " <nl> + # grpcio = = 1 . 28 . 1 ; platform_machine = = " x86_64 " <nl> + # grpcio - tools = = 1 . 28 . 1 ; platform_machine = = " x86_64 " <nl> + # googleapis - common - protos = = 1 . 51 . 0 ; platform_machine = = " x86_64 " <nl> blackduck = = 0 . 0 . 51 <nl> | SERVER - 49504 : Allow resmoke ' s mongo shell to log to Jasper | mongodb/mongo | 308cc2fa21eb3a3d2b53cb47bb3dcdd3b259bf20 | 2020-10-12T20:59:36Z |
mmm a / src / btree / node . hpp <nl> ppp b / src / btree / node . hpp <nl> struct btree_superblock_t { <nl> static const block_magic_t expected_magic ; <nl> } ; <nl> <nl> + struct btree_statblock_t { <nl> + / / The total number of keys in the btree <nl> + int population ; <nl> <nl> + btree_statblock_t ( ) <nl> + : population ( 0 ) <nl> + { } <nl> + } ; <nl> <nl> / / Note : This struct is stored directly on disk . Changing it invalidates old data . <nl> struct internal_node_t { <nl> mmm a / src / btree / operations . cc <nl> ppp b / src / btree / operations . cc <nl> void clear_superblock_metainfo ( transaction_t * txn , buf_lock_t * superblock ) { <nl> blob_t blob ( data - > metainfo_blob , btree_superblock_t : : METAINFO_BLOB_MAXREFLEN ) ; <nl> blob . clear ( txn ) ; <nl> } <nl> + <nl> + void insert_root ( block_id_t root_id , superblock_t * sb ) { <nl> + sb - > set_root_block_id ( root_id ) ; <nl> + sb - > release ( ) ; / / XXX it ' s a little bit weird that we release this from here . <nl> + } <nl> + <nl> + void ensure_stat_block ( transaction_t * txn , superblock_t * sb , eviction_priority_t stat_block_eviction_priority ) { <nl> + rassert ( ZERO_EVICTION_PRIORITY < stat_block_eviction_priority ) ; <nl> + <nl> + block_id_t node_id = sb - > get_stat_block_id ( ) ; <nl> + <nl> + if ( node_id = = NULL_BLOCK_ID ) { <nl> + / / Create a block <nl> + buf_lock_t temp_lock ( txn ) ; <nl> + / / Make the stat block be the default constructed statblock <nl> + * reinterpret_cast < btree_statblock_t * > ( temp_lock . get_data_major_write ( ) ) = btree_statblock_t ( ) ; <nl> + sb - > set_stat_block_id ( temp_lock . get_block_id ( ) ) ; <nl> + <nl> + temp_lock . set_eviction_priority ( stat_block_eviction_priority ) ; <nl> + } <nl> + } <nl> + <nl> + inline void get_btree_superblock ( transaction_t * txn , access_t access , got_superblock_t * got_superblock_out ) { <nl> + buf_lock_t tmp_buf ( txn , SUPERBLOCK_ID , access ) ; <nl> + boost : : scoped_ptr < superblock_t > tmp_sb ( new real_superblock_t ( tmp_buf ) ) ; <nl> + tmp_sb - > set_eviction_priority ( ZERO_EVICTION_PRIORITY ) ; <nl> + got_superblock_out - > sb . swap ( tmp_sb ) ; <nl> + } <nl> + <nl> + void get_btree_superblock ( btree_slice_t * slice , access_t access , int expected_change_count , <nl> + repli_timestamp_t tstamp , order_token_t token , bool snapshotted , <nl> + const boost : : shared_ptr < cache_account_t > & cache_account , <nl> + got_superblock_t * got_superblock_out , boost : : scoped_ptr < transaction_t > & txn_out ) { <nl> + slice - > assert_thread ( ) ; <nl> + <nl> + slice - > pre_begin_transaction_sink_ . check_out ( token ) ; <nl> + order_token_t begin_transaction_token = ( is_read_mode ( access ) ? slice - > pre_begin_transaction_read_mode_source_ : slice - > pre_begin_transaction_write_mode_source_ ) . check_in ( token . tag ( ) + " + begin_transaction_token " ) ; <nl> + if ( is_read_mode ( access ) ) { <nl> + begin_transaction_token = begin_transaction_token . with_read_mode ( ) ; <nl> + } <nl> + txn_out . reset ( new transaction_t ( slice - > cache ( ) , access , expected_change_count , tstamp ) ) ; <nl> + txn_out - > set_token ( slice - > post_begin_transaction_checkpoint_ . check_through ( begin_transaction_token ) ) ; <nl> + <nl> + if ( cache_account ) { <nl> + txn_out - > set_account ( cache_account ) ; <nl> + } <nl> + if ( snapshotted ) { <nl> + txn_out - > snapshot ( ) ; <nl> + } <nl> + <nl> + get_btree_superblock ( txn_out . get ( ) , access , got_superblock_out ) ; <nl> + } <nl> + <nl> + void get_btree_superblock ( btree_slice_t * slice , access_t access , int expected_change_count , <nl> + repli_timestamp_t tstamp , order_token_t token , got_superblock_t * got_superblock_out , <nl> + boost : : scoped_ptr < transaction_t > & txn_out ) { <nl> + get_btree_superblock ( slice , access , expected_change_count , tstamp , token , false , boost : : shared_ptr < cache_account_t > ( ) , got_superblock_out , txn_out ) ; <nl> + } <nl> + <nl> + void get_btree_superblock_for_backfilling ( btree_slice_t * slice , order_token_t token , <nl> + got_superblock_t * got_superblock_out , <nl> + boost : : scoped_ptr < transaction_t > & txn_out ) { <nl> + get_btree_superblock ( slice , rwi_read_sync , 0 , repli_timestamp_t : : distant_past , token , true , slice - > get_backfill_account ( ) , got_superblock_out , txn_out ) ; <nl> + } <nl> + <nl> + void get_btree_superblock_for_reading ( btree_slice_t * slice , access_t access , order_token_t token , <nl> + bool snapshotted , got_superblock_t * got_superblock_out , <nl> + boost : : scoped_ptr < transaction_t > & txn_out ) { <nl> + rassert ( is_read_mode ( access ) ) ; <nl> + get_btree_superblock ( slice , access , 0 , repli_timestamp_t : : distant_past , token , snapshotted , boost : : shared_ptr < cache_account_t > ( ) , got_superblock_out , txn_out ) ; <nl> + } <nl> + <nl> mmm a / src / btree / operations . hpp <nl> ppp b / src / btree / operations . hpp <nl> void set_superblock_metainfo ( transaction_t * txn , buf_lock_t * superblock , const s <nl> void delete_superblock_metainfo ( transaction_t * txn , buf_lock_t * superblock , const std : : vector < char > & key ) ; <nl> void clear_superblock_metainfo ( transaction_t * txn , buf_lock_t * superblock ) ; <nl> <nl> + / * Set sb to have root id as its root block and release sb * / <nl> + void insert_root ( block_id_t root_id , superblock_t * sb ) ; <nl> + <nl> + / * Create a stat block for the superblock if it doesn ' t already have one . * / <nl> + void ensure_stat_block ( transaction_t * txn , superblock_t * sb , eviction_priority_t stat_block_eviction_priority ) ; <nl> + <nl> + void get_btree_superblock ( transaction_t * txn , access_t access , got_superblock_t * got_superblock_out ) ; <nl> + <nl> + void get_btree_superblock ( btree_slice_t * slice , access_t access , int expected_change_count , <nl> + repli_timestamp_t tstamp , order_token_t token , bool snapshotted , <nl> + const boost : : shared_ptr < cache_account_t > & cache_account , <nl> + got_superblock_t * got_superblock_out , boost : : scoped_ptr < transaction_t > & txn_out ) ; <nl> + <nl> + void get_btree_superblock ( btree_slice_t * slice , access_t access , int expected_change_count , <nl> + repli_timestamp_t tstamp , order_token_t token , got_superblock_t * got_superblock_out , <nl> + boost : : scoped_ptr < transaction_t > & txn_out ) ; <nl> + <nl> + void get_btree_superblock_for_backfilling ( btree_slice_t * slice , order_token_t token , <nl> + got_superblock_t * got_superblock_out , <nl> + boost : : scoped_ptr < transaction_t > & txn_out ) ; <nl> + <nl> + void get_btree_superblock_for_reading ( btree_slice_t * slice , access_t access , order_token_t token , <nl> + bool snapshotted , got_superblock_t * got_superblock_out , <nl> + boost : : scoped_ptr < transaction_t > & txn_out ) ; <nl> + <nl> # include " btree / operations . tcc " <nl> <nl> # endif / / BTREE_OPERATIONS_HPP_ <nl> mmm a / src / btree / operations . tcc <nl> ppp b / src / btree / operations . tcc <nl> <nl> / / relevant . <nl> <nl> <nl> - inline void insert_root ( block_id_t root_id , superblock_t * sb ) { <nl> - sb - > set_root_block_id ( root_id ) ; <nl> - sb - > release ( ) ; <nl> - } <nl> - <nl> / / Get a root block given a superblock , or make a new root if there isn ' t one . <nl> template < class Value > <nl> - void get_root ( value_sizer_t < Value > * sizer , transaction_t * txn , superblock_t * sb , buf_lock_t * buf_out , eviction_priority_t root_eviction_priority ) { <nl> + void get_root ( value_sizer_t < Value > * sizer , transaction_t * txn , superblock_t * sb , buf_lock_t * buf_out , eviction_priority_t root_eviction_priority ) { <nl> rassert ( ! buf_out - > is_acquired ( ) ) ; <nl> rassert ( ZERO_EVICTION_PRIORITY < root_eviction_priority ) ; <nl> <nl> void get_root ( value_sizer_t < Value > * sizer , transaction_t * txn , superblock_t * sb , <nl> } <nl> } <nl> <nl> - <nl> / / Split the node if necessary . If the node is a leaf_node , provide the new <nl> / / value that will be inserted ; if it ' s an internal node , provide NULL ( we <nl> / / split internal nodes proactively ) . <nl> void check_and_handle_underfull ( value_sizer_t < Value > * sizer , transaction_t * txn , <nl> } <nl> } <nl> <nl> - inline void get_btree_superblock ( transaction_t * txn , access_t access , got_superblock_t * got_superblock_out ) { <nl> - buf_lock_t tmp_buf ( txn , SUPERBLOCK_ID , access ) ; <nl> - boost : : scoped_ptr < superblock_t > tmp_sb ( new real_superblock_t ( tmp_buf ) ) ; <nl> - tmp_sb - > set_eviction_priority ( ZERO_EVICTION_PRIORITY ) ; <nl> - got_superblock_out - > sb . swap ( tmp_sb ) ; <nl> - } <nl> - <nl> - inline void get_btree_superblock ( btree_slice_t * slice , access_t access , int expected_change_count , repli_timestamp_t tstamp , order_token_t token , bool snapshotted , const boost : : shared_ptr < cache_account_t > & cache_account , got_superblock_t * got_superblock_out , boost : : scoped_ptr < transaction_t > & txn_out ) { <nl> - slice - > assert_thread ( ) ; <nl> - <nl> - slice - > pre_begin_transaction_sink_ . check_out ( token ) ; <nl> - order_token_t begin_transaction_token = ( is_read_mode ( access ) ? slice - > pre_begin_transaction_read_mode_source_ : slice - > pre_begin_transaction_write_mode_source_ ) . check_in ( token . tag ( ) + " + begin_transaction_token " ) ; <nl> - if ( is_read_mode ( access ) ) { <nl> - begin_transaction_token = begin_transaction_token . with_read_mode ( ) ; <nl> - } <nl> - txn_out . reset ( new transaction_t ( slice - > cache ( ) , access , expected_change_count , tstamp ) ) ; <nl> - txn_out - > set_token ( slice - > post_begin_transaction_checkpoint_ . check_through ( begin_transaction_token ) ) ; <nl> - <nl> - if ( cache_account ) { <nl> - txn_out - > set_account ( cache_account ) ; <nl> - } <nl> - if ( snapshotted ) { <nl> - txn_out - > snapshot ( ) ; <nl> - } <nl> - <nl> - get_btree_superblock ( txn_out . get ( ) , access , got_superblock_out ) ; <nl> - } <nl> - <nl> - inline void get_btree_superblock ( btree_slice_t * slice , access_t access , int expected_change_count , repli_timestamp_t tstamp , order_token_t token , got_superblock_t * got_superblock_out , boost : : scoped_ptr < transaction_t > & txn_out ) { <nl> - get_btree_superblock ( slice , access , expected_change_count , tstamp , token , false , boost : : shared_ptr < cache_account_t > ( ) , got_superblock_out , txn_out ) ; <nl> - } <nl> - <nl> - inline void get_btree_superblock_for_backfilling ( btree_slice_t * slice , order_token_t token , got_superblock_t * got_superblock_out , boost : : scoped_ptr < transaction_t > & txn_out ) { <nl> - get_btree_superblock ( slice , rwi_read_sync , 0 , repli_timestamp_t : : distant_past , token , true , slice - > get_backfill_account ( ) , got_superblock_out , txn_out ) ; <nl> - } <nl> - <nl> - inline void get_btree_superblock_for_reading ( btree_slice_t * slice , access_t access , order_token_t token , bool snapshotted , got_superblock_t * got_superblock_out , boost : : scoped_ptr < transaction_t > & txn_out ) { <nl> - rassert ( is_read_mode ( access ) ) ; <nl> - get_btree_superblock ( slice , access , 0 , repli_timestamp_t : : distant_past , token , snapshotted , boost : : shared_ptr < cache_account_t > ( ) , got_superblock_out , txn_out ) ; <nl> - } <nl> - <nl> - <nl> template < class Value > <nl> void find_keyvalue_location_for_write ( transaction_t * txn , got_superblock_t * got_superblock , btree_key_t * key , keyvalue_location_t < Value > * keyvalue_location_out , eviction_priority_t * root_eviction_priority ) { <nl> keyvalue_location_out - > sb . swap ( got_superblock - > sb ) ; <nl> | Adds a way to create statblocks . | rethinkdb/rethinkdb | 75c3037474f734dad3b121a694634eda69d9cb4b | 2012-04-17T23:32:20Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.