<commit_before>#ifndef __GLOBALS_HPP_INCLUDED
#define __GLOBALS_HPP_INCLUDED

#include <string>
#include <vector>

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif

#ifndef ASPECT_RATIO
#define ASPECT_RATIO (4/3)
#endif

#ifndef WINDOW_WIDTH
#define WINDOW_WIDTH 1600
#endif

#ifndef WINDOW_HEIGHT
#define WINDOW_HEIGHT (WINDOW_WIDTH / ASPECT_RATIO)
#endif

#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef EARTH_RADIUS
#define EARTH_RADIUS 6371000.0f
#endif

#ifndef TEXT_SIZE
#define TEXT_SIZE 40
#endif

#ifndef FONT_SIZE
#define FONT_SIZE 16
#endif

#ifndef MAX_FPS
#define MAX_FPS 60
#endif

extern glm::vec3 position;
extern glm::vec3 spherical_position;
extern GLfloat horizontalAngle;
extern GLfloat verticalAngle;
extern GLfloat initialFoV;
extern GLfloat earth_radius;
extern bool hasMouseEverMoved;
extern bool is_invert_mouse_in_use;
extern bool is_key_I_released;
extern bool is_world_loaded; // no more than one world object can be loaded. TODO: check that no more than one world is loaded!
extern bool is_world_spherical;

typedef struct
{
    std::string texture_file_format;
    std::string image_path;
} TextureStruct;

typedef struct
{
    void *world_pointer;                     // pointer to the world (draw list).
    std::string vertex_shader;               // filename of vertex shader.
    std::string fragment_shader;             // filename of fragment shader.
} ShaderStruct;

typedef struct
{
    uint32_t *node_data;
} GraphStruct;

typedef struct
{
    GLuint nodeID;
    void* graph_pointer;
    glm::vec3 coordinate_vector;
    std::vector<uint32_t> neighbor_nodeIDs;
} NodeStruct;

typedef struct
{
    glm::vec3 coordinate_vector;     // coordinate vector.
    GLfloat rotate_angle;            // rotate angle.
    glm::vec3 rotate_vector;         // rotate vector.
    glm::vec3 translate_vector;      // translate vector.
    glm::mat4 model_matrix;          // model matrix.
    glm::mat4 MVP_matrix;            // model view projection matrix.
    void *species_pointer;           // pointer to the species.
} ObjectStruct;

typedef struct
{
    // used for all files (for all species).
    void *shader_pointer;                    // pointer to the shader object.
    std::string model_file_format;           // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`.
                                             // TODO: add support for `"SRTM"`.
    std::string texture_file_format;         // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`.
    std::string texture_filename;            // filename of the model file.
    std::string vertex_shader;               // filename of vertex shader.
    std::string fragment_shader;             // filename of fragment shader.
    glm::vec3 lightPos;                      // light position.
    std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
    bool is_world;                           // worlds currently do not rotate nor translate.
    std::string coordinate_system;           // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`.
                                             // TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps.
    GLfloat world_radius;                    // radius of sea level in meters. used only for worlds.

    // for `"bmp"` model files.
    std::string model_filename;              // filename of the model file.
    std::string color_channel;               // color channel to use for altitude data.
} SpeciesStruct;

typedef struct
{
    GLuint screen_width;
    GLuint screen_height;
    GLuint x;
    GLuint y;
    GLuint text_size;
    GLuint font_size;
    const char *text;
    const char *char_font_texture_file_format;
    const char *horizontal_alignment;
    const char *vertical_alignment;
} PrintingStruct;

typedef struct
{
    double rho;
    double theta;
    double phi;
} SphericalCoordinatesStruct;

typedef struct
{
    double southern_latitude;
    double northern_latitude;
    double western_longitude;
    double eastern_longitude;
} SphericalWorldStruct;

#endif
<commit_msg>Bugikorjaus: `WINDOW_WIDTH`, `WINDOW_HEIGHT` & `ASPECT_RATIO`.<commit_after>#ifndef __GLOBALS_HPP_INCLUDED
#define __GLOBALS_HPP_INCLUDED

#include <string>
#include <vector>

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif

#ifndef WINDOW_WIDTH
#define WINDOW_WIDTH (1600.0f)
#endif

#ifndef WINDOW_HEIGHT
#define WINDOW_HEIGHT (900.0f)
#endif

#ifndef ASPECT_RATIO
#define ASPECT_RATIO (WINDOW_WIDTH / WINDOW_HEIGHT)
#endif

#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef EARTH_RADIUS
#define EARTH_RADIUS 6371000.0f
#endif

#ifndef TEXT_SIZE
#define TEXT_SIZE 40
#endif

#ifndef FONT_SIZE
#define FONT_SIZE 16
#endif

#ifndef MAX_FPS
#define MAX_FPS 60
#endif

extern glm::vec3 position;
extern glm::vec3 spherical_position;
extern GLfloat horizontalAngle;
extern GLfloat verticalAngle;
extern GLfloat initialFoV;
extern GLfloat earth_radius;
extern bool hasMouseEverMoved;
extern bool is_invert_mouse_in_use;
extern bool is_key_I_released;
extern bool is_world_loaded; // no more than one world object can be loaded. TODO: check that no more than one world is loaded!
extern bool is_world_spherical;

typedef struct
{
    std::string texture_file_format;
    std::string image_path;
} TextureStruct;

typedef struct
{
    void *world_pointer;                     // pointer to the world (draw list).
    std::string vertex_shader;               // filename of vertex shader.
    std::string fragment_shader;             // filename of fragment shader.
} ShaderStruct;

typedef struct
{
    uint32_t *node_data;
} GraphStruct;

typedef struct
{
    GLuint nodeID;
    void* graph_pointer;
    glm::vec3 coordinate_vector;
    std::vector<uint32_t> neighbor_nodeIDs;
} NodeStruct;

typedef struct
{
    glm::vec3 coordinate_vector;     // coordinate vector.
    GLfloat rotate_angle;            // rotate angle.
    glm::vec3 rotate_vector;         // rotate vector.
    glm::vec3 translate_vector;      // translate vector.
    glm::mat4 model_matrix;          // model matrix.
    glm::mat4 MVP_matrix;            // model view projection matrix.
    void *species_pointer;           // pointer to the species.
} ObjectStruct;

typedef struct
{
    // used for all files (for all species).
    void *shader_pointer;                    // pointer to the shader object.
    std::string model_file_format;           // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`.
                                             // TODO: add support for `"SRTM"`.
    std::string texture_file_format;         // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`.
    std::string texture_filename;            // filename of the model file.
    std::string vertex_shader;               // filename of vertex shader.
    std::string fragment_shader;             // filename of fragment shader.
    glm::vec3 lightPos;                      // light position.
    std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
    bool is_world;                           // worlds currently do not rotate nor translate.
    std::string coordinate_system;           // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`.
                                             // TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps.
    GLfloat world_radius;                    // radius of sea level in meters. used only for worlds.

    // for `"bmp"` model files.
    std::string model_filename;              // filename of the model file.
    std::string color_channel;               // color channel to use for altitude data.
} SpeciesStruct;

typedef struct
{
    GLuint screen_width;
    GLuint screen_height;
    GLuint x;
    GLuint y;
    GLuint text_size;
    GLuint font_size;
    const char *text;
    const char *char_font_texture_file_format;
    const char *horizontal_alignment;
    const char *vertical_alignment;
} PrintingStruct;

typedef struct
{
    double rho;
    double theta;
    double phi;
} SphericalCoordinatesStruct;

typedef struct
{
    double southern_latitude;
    double northern_latitude;
    double western_longitude;
    double eastern_longitude;
} SphericalWorldStruct;

#endif
<|endoftext|>


<commit_before>// File_Wm - Info for Windows Media files
// Copyright (C) 2002-2008 Jerome Martinez, Zen@MediaArea.net
//
// This library is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Main part
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include <MediaInfo/Setup.h>
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#ifdef MEDIAINFO_WM_YES
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_Wm.h"
#if defined(MEDIAINFO_MPEGPS_YES)
    #include "MediaInfo/Multiple/File_MpegPs.h"
#endif
#include <ZenLib/Utils.h>
using namespace ZenLib;
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Format
//***************************************************************************

//---------------------------------------------------------------------------
File_Wm::File_Wm()
:File__Analyze()
{
    //Configuration
    DataMustAlwaysBeComplete=false;

    //Stream
    Stream_Number=0;
    Data_Parse_Padding=0;
    MaximumDataPacketSize=(int32u)-1;
    NumberPayloads=1;
    NumberPayloads_Pos=0;
    Data_Parse_Begin=true;
    IsDvrMs=false;

    //TO DELETE
    Buffer_MaximumSize=1000000000;
}

//---------------------------------------------------------------------------
void File_Wm::Read_Buffer_Finalize()
{
    //Encryption management
    /*const Ztring& Encryption=Get(Stream_General, 0, "Encryption");
    if (!Encryption.empty())
    {
        for (size_t StreamKind=Stream_General+1; StreamKind<Stream_Max; StreamKind++)
            for (size_t Pos=0; Pos<(*Stream[StreamKind]).size(); Pos++)
                Fill ((stream_t)StreamKind, 0, "Encryption", Encryption);
    }

        Fill("BitRate", CurrentBitRate[StreamNumber]);
    */

    std::map<int16u, stream>::iterator Temp=Stream.begin();
    while (Temp!=Stream.end())
    {
        std::map<std::string, ZenLib::Ztring>::iterator Info_Temp=Temp->second.Info.begin();
        while (Info_Temp!=Temp->second.Info.end())
        {
            Fill(Temp->second.StreamKind, Temp->second.StreamPos, Info_Temp->first.c_str(), Info_Temp->second);
            Info_Temp++;
        }

        if (Temp->second.StreamKind==Stream_Video && Temp->second.AverageTimePerFrame>0)
            Fill(Temp->second.StreamKind, Temp->second.StreamPos, "FrameRate", ((float)10000000)/Temp->second.AverageTimePerFrame, 3, true);
        if (Temp->second.AverageBitRate>0)
            Fill(Temp->second.StreamKind, Temp->second.StreamPos, "BitRate", Temp->second.AverageBitRate, 10, true);
        if (Temp->second.LanguageID!=(int16u)-1 && Temp->second.LanguageID<(int16u)Languages.size())
            Fill(Temp->second.StreamKind, Temp->second.StreamPos, "Language", Languages[Temp->second.LanguageID]);
        else if (!Language_ForAll.empty())
            Fill(Temp->second.StreamKind, Temp->second.StreamPos, "Language", Language_ForAll);
        if (Temp->second.Parser)
        {
            if (Temp->second.StreamKind==Stream_Max)
                if (Temp->second.Parser->Count_Get(Stream_Audio))
                {
                    Stream_Prepare(Stream_Audio);
                    Temp->second.StreamKind=StreamKind_Last;
                    Temp->second.StreamPos=StreamPos_Last;
                }
            Merge(*Temp->second.Parser, Temp->second.StreamKind, 0, Temp->second.StreamPos);
        }
        Temp++;
    }

    //Purge what is not needed anymore
    if (!File_Name.empty()) //Only if this is not a buffer, with buffer we can have more data
        Stream.clear();
}

//***************************************************************************
// Buffer
//***************************************************************************

//---------------------------------------------------------------------------
void File_Wm::Header_Parse()
{
    if (!MustUseAlternativeParser)
    {
        //Parsing
        int128u Name;
        int64u Size;
        Get_UUID(Name,                                              "Name");
        Get_L8 (Size,                                               "Size");

        //Filling
        #ifndef __BORLANDC__
            Header_Fill_Code(Name.hi, Ztring().From_UUID(Name));
        #else //__BORLANDC__
            Header_Fill_Code(Name.hi&0xFFFFFFFF, Ztring().From_UUID(Name)); //Borland does not like int64u for const?
        #endif //__BORLANDC__
        Header_Fill_Size(Size);
    }
    else
        //Data
        Header_Parse_Data();
}

//---------------------------------------------------------------------------
void File_Wm::Header_Parse_Data()
{
    //Only Payload
    if (Data_Parse_Begin)
        Header_Parse_Data_Begin();

    //Parsing
    Header_Parse_Data_Payload();
}

//---------------------------------------------------------------------------
void File_Wm::Header_Parse_Data_Begin()
{
    //Parsing
    PacketLength=0; SizeOfMediaObject=0;
    int8u  Flags, ErrorCorrectionData_Length, ErrorCorrectionLengthType, SequenceType, PaddingLengthType, PacketLengthType;
    bool   ErrorCorrectionPresent;
    Element_Begin("Error Correction");
        Get_L1 (Flags,                                          "Flags");
            Get_Flags (Flags&0x0F, ErrorCorrectionData_Length,  "Error Correction Data Length"); //4 lowest bits
            Skip_Flags(Flags, 4,                                "Opaque Data Present");
            Get_Flags ((Flags>>5)&0x03, ErrorCorrectionLengthType, "Error Correction Length Type"); //bits 6 and 7
            Get_Flags (Flags, 7, ErrorCorrectionPresent,        "Error Correction Present");
        if (ErrorCorrectionPresent && ErrorCorrectionLengthType==0 && ErrorCorrectionData_Length==2)
        {
            int8u  TypeNumber;
            Get_L1 (TypeNumber,                                 "Type/Number");
                Skip_Flags((TypeNumber>>4)&0x0F, "Type");
                Skip_Flags( TypeNumber    &0x0F, "Number");
            Skip_L1(                                            "Cycle");
        }
    Element_End();
    Element_Begin("Payload Parsing Information");
        Get_L1 (Flags,                                          "Length Type Flags");
            Get_Flags (Flags, 0, MultiplePayloadsPresent,       "Multiple Payloads Present");
            Get_Flags ((Flags>>1)&0x3, SequenceType,            "Sequence Type");
            Get_Flags ((Flags>>3)&0x3, PaddingLengthType,       "Padding Length Type");
            Get_Flags ((Flags>>5)&0x3, PacketLengthType,        "Packet Length Type");
            Skip_Flags(Flags, 7,                                "Error Correction Present");
        Get_L1 (Flags,                                          "Property Flags");
            Get_Flags ( Flags    &0x3, ReplicatedDataLengthType, "Replicated Data Length Type");
            Get_Flags ((Flags>>2)&0x3, OffsetIntoMediaObjectLengthType, "Offset Into Media Object Length Type");
            Get_Flags ((Flags>>4)&0x3, MediaObjectNumberLengthType, "Media Object Number Length Type");
            Get_Flags ((Flags>>6)&0x3, StreamNumberLengthType,  "Stream Number Length Type");
        switch (PacketLengthType)
        {
            case 1 : {int8u  Data; Get_L1(Data,                 "Packet Length"); PacketLength=Data;} break;
            case 2 : {int16u Data; Get_L2(Data,                 "Packet Length"); PacketLength=Data;} break;
            case 3 :               Get_L4(PacketLength,         "Packet Length");                     break;
            default: ;
        }
        switch (SequenceType)
        {
            case 1 : Skip_L1(                                   "Sequence"); break;
            case 2 : Skip_L2(                                   "Sequence"); break;
            case 3 : Skip_L4(                                   "Sequence"); break;
            default: ;
        }
        switch (PaddingLengthType)
        {
            case 1 : {int8u  Data; Get_L1(Data,                 "Padding Length"); Data_Parse_Padding=Data;} break;
            case 2 : {int16u Data; Get_L2(Data,                 "Padding Length"); Data_Parse_Padding=Data;} break;
            case 3 :               Get_L4(Data_Parse_Padding,   "Padding Length");                           break;
            default: Data_Parse_Padding=0;
        }
        Skip_L4(                                                "Send Time");
        Skip_L2(                                                "Duration");
    Element_End();

    if (MultiplePayloadsPresent)
        Header_Parse_Data_MultiplePayloads();
}

//---------------------------------------------------------------------------
void File_Wm::Header_Parse_Data_MultiplePayloads()
{
    //Parsing
    Element_Begin("Multiple Payloads");
        int8u Flags;
        Get_L1 (Flags,                                          "Flags");
            Get_Flags ( Flags    &0x3F, NumberPayloads,         "Number of Payloads"); //6 bits
            Get_Flags ((Flags>>6)&0x03, PayloadLengthType,      "Payload Length Type"); //bits 6 and 7
    Element_End();

    //Filling
    NumberPayloads_Pos=0;
}

//---------------------------------------------------------------------------
void File_Wm::Header_Parse_Data_Payload()
{
    Element_Begin("Payload");
        int32u ReplicatedDataLength;
        int8u  StreamNumber;
        Get_L1 (StreamNumber,                                   "Stream Number");
        StreamNumber&=0x7F; //For KeyFrame
        Element_Info(StreamNumber);
        switch (MediaObjectNumberLengthType)
        {
            case 1 : Skip_L1(                                   "Media Object Number"); break;
            case 2 : Skip_L2(                                   "Media Object Number"); break;
            case 3 : Skip_L4(                                   "Media Object Number"); break;
            default: ;
        }
        switch (OffsetIntoMediaObjectLengthType)
        {
            case 1 : Skip_L1(                                   "Offset Into Media Object"); break;
            case 2 : Skip_L2(                                   "Offset Into Media Object"); break;
            case 3 : Skip_L4(                                   "Offset Into Media Object"); break;
            default: ;
        }
        switch (ReplicatedDataLengthType)
        {
            case 1 : {int8u  Data; Get_L1(Data,                 "Replicated Data Length"); ReplicatedDataLength=Data;} break;
            case 2 : {int16u Data; Get_L2(Data,                 "Replicated Data Length"); ReplicatedDataLength=Data;} break;
            case 3 :               Get_L4(ReplicatedDataLength, "Replicated Data Length");                             break;
            default: ;
        }
        if (ReplicatedDataLengthType!=0 && ReplicatedDataLength>0)
        {
            if (ReplicatedDataLength>=8)
            {
                Get_L4 (SizeOfMediaObject,                      "Size Of Media Object");
                Skip_L4(                                        "Presentation Time");
                if (ReplicatedDataLength>8)
                {
                    Skip_XX(ReplicatedDataLength-8,             "Payload Extension");
                }
            }
            else if (ReplicatedDataLength==1)
            {
                Skip_L1(                                        "Presentation Time Delta");
                //TODO
            }
            else
                Skip_XX(ReplicatedDataLength,                   "Replicated Data");
        }
    Element_End();

    if (MultiplePayloadsPresent)
    {
        switch (PayloadLengthType)
        {
            case 1 : {int8u  Data; Get_L1(Data,                 "Payload Length"); SizeOfMediaObject=Data;} break;
            case 2 : {int16u Data; Get_L2(Data,                 "Payload Length"); SizeOfMediaObject=Data;} break;
            case 3 :               Get_L4(SizeOfMediaObject,    "Payload Length");                             break;
            default: SizeOfMediaObject=0; //Problem
        }
    }

    if (PacketLength==0 && SizeOfMediaObject>0)
        PacketLength=Element_Offset+SizeOfMediaObject+Data_Parse_Padding;

    if (NumberPayloads_Pos+1<NumberPayloads)
        PacketLength-=Data_Parse_Padding; //Padding is only for the last packet
    if (PacketLength>MaximumDataPacketSize)
        PacketLength=MaximumDataPacketSize; //Some files seem to have a wrong SizeOfMediaObject, trying to parse them and trusting the header better than SizeOfMediaObject

    //Filling
    Header_Fill_Code(StreamNumber, "Packet");
    Header_Fill_Size(PacketLength);

    PacketLength=0; //Used
}

//***************************************************************************
// Information
//***************************************************************************

//---------------------------------------------------------------------------
void File_Wm::HowTo(stream_t UNUSED(StreamKind))
{
}

//***************************************************************************
// C++
//***************************************************************************

} //NameSpace

#endif //MEDIAINFO_WM_YES
<commit_msg><commit_after>// File_Wm - Info for Windows Media files
// Copyright (C) 2002-2008 Jerome Martinez, Zen@MediaArea.net
//
// This library is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Main part
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include <MediaInfo/Setup.h>
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#ifdef MEDIAINFO_WM_YES
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_Wm.h"
#if defined(MEDIAINFO_MPEGPS_YES)
    #include "MediaInfo/Multiple/File_MpegPs.h"
#endif
#include <ZenLib/Utils.h>
using namespace ZenLib;
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Format
//***************************************************************************

//---------------------------------------------------------------------------
File_Wm::File_Wm()
:File__Analyze()
{
    //Configuration
    DataMustAlwaysBeComplete=false;

    //Stream
    Stream_Number=0;
    Data_Parse_Padding=0;
    MaximumDataPacketSize=(int32u)-1;
    NumberPayloads=1;
    NumberPayloads_Pos=0;
    Data_Parse_Begin=true;
    IsDvrMs=false;

    //TO DELETE
    Buffer_MaximumSize=1000000000;
}

//---------------------------------------------------------------------------
void File_Wm::Read_Buffer_Finalize()
{
    //Encryption management
    /*const Ztring& Encryption=Get(Stream_General, 0, "Encryption");
    if (!Encryption.empty())
    {
        for (size_t StreamKind=Stream_General+1; StreamKind<Stream_Max; StreamKind++)
            for (size_t Pos=0; Pos<(*Stream[StreamKind]).size(); Pos++)
                Fill ((stream_t)StreamKind, 0, "Encryption", Encryption);
    }

        Fill("BitRate", CurrentBitRate[StreamNumber]);
    */

    std::map<int16u, stream>::iterator Temp=Stream.begin();
    while (Temp!=Stream.end())
    {
        std::map<std::string, ZenLib::Ztring>::iterator Info_Temp=Temp->second.Info.begin();
        while (Info_Temp!=Temp->second.Info.end())
        {
            Fill(Temp->second.StreamKind, Temp->second.StreamPos, Info_Temp->first.c_str(), Info_Temp->second);
            Info_Temp++;
        }

        if (Temp->second.StreamKind==Stream_Video && Temp->second.AverageTimePerFrame>0)
            Fill(Temp->second.StreamKind, Temp->second.StreamPos, "FrameRate", ((float)10000000)/Temp->second.AverageTimePerFrame, 3, true);
        if (Temp->second.AverageBitRate>0)
            Fill(Temp->second.StreamKind, Temp->second.StreamPos, "BitRate", Temp->second.AverageBitRate, 10, true);
        if (Temp->second.LanguageID!=(int16u)-1 && Temp->second.LanguageID<(int16u)Languages.size())
            Fill(Temp->second.StreamKind, Temp->second.StreamPos, "Language", Languages[Temp->second.LanguageID]);
        else if (!Language_ForAll.empty())
            Fill(Temp->second.StreamKind, Temp->second.StreamPos, "Language", Language_ForAll);
        if (Temp->second.Parser)
        {
            if (Temp->second.StreamKind==Stream_Max)
                if (Temp->second.Parser->Count_Get(Stream_Audio))
                {
                    Stream_Prepare(Stream_Audio);
                    Temp->second.StreamKind=StreamKind_Last;
                    Temp->second.StreamPos=StreamPos_Last;
                }
            Merge(*Temp->second.Parser, Temp->second.StreamKind, 0, Temp->second.StreamPos);
        }
        Temp++;
    }

    //Purge what is not needed anymore
    if (!File_Name.empty()) //Only if this is not a buffer, with buffer we can have more data
        Stream.clear();
}

//***************************************************************************
// Buffer
//***************************************************************************

//---------------------------------------------------------------------------
void File_Wm::Header_Parse()
{
    if (!MustUseAlternativeParser)
    {
        //Parsing
        int128u Name;
        int64u Size;
        Get_UUID(Name,                                              "Name");
        Get_L8 (Size,                                               "Size");

        //Filling
        #ifndef __BORLANDC__
            Header_Fill_Code(Name.hi, Ztring().From_UUID(Name));
        #else //__BORLANDC__
            Header_Fill_Code(Name.hi&0xFFFFFFFF, Ztring().From_UUID(Name)); //Borland does not like int64u for const?
        #endif //__BORLANDC__
        Header_Fill_Size(Size);
    }
    else
        //Data
        Header_Parse_Data();
}

//---------------------------------------------------------------------------
void File_Wm::Header_Parse_Data()
{
    //Only Payload
    if (Data_Parse_Begin)
        Header_Parse_Data_Begin();

    //Parsing
    Header_Parse_Data_Payload();
}

//---------------------------------------------------------------------------
void File_Wm::Header_Parse_Data_Begin()
{
    //Parsing
    PacketLength=0; SizeOfMediaObject=0;
    int8u  Flags, ErrorCorrectionData_Length, ErrorCorrectionLengthType, SequenceType, PaddingLengthType, PacketLengthType;
    bool   ErrorCorrectionPresent;
    Element_Begin("Error Correction");
        Get_L1 (Flags,                                          "Flags");
            Get_Flags (Flags&0x0F, ErrorCorrectionData_Length,  "Error Correction Data Length"); //4 lowest bits
            Skip_Flags(Flags, 4,                                "Opaque Data Present");
            Get_Flags ((Flags>>5)&0x03, ErrorCorrectionLengthType, "Error Correction Length Type"); //bits 6 and 7
            Get_Flags (Flags, 7, ErrorCorrectionPresent,        "Error Correction Present");
        if (ErrorCorrectionPresent && ErrorCorrectionLengthType==0 && ErrorCorrectionData_Length==2)
        {
            int8u  TypeNumber;
            Get_L1 (TypeNumber,                                 "Type/Number");
                Skip_Flags((TypeNumber>>4)&0x0F, "Type");
                Skip_Flags( TypeNumber    &0x0F, "Number");
            Skip_L1(                                            "Cycle");
        }
    Element_End();
    Element_Begin("Payload Parsing Information");
        Get_L1 (Flags,                                          "Length Type Flags");
            Get_Flags (Flags, 0, MultiplePayloadsPresent,       "Multiple Payloads Present");
            Get_Flags ((Flags>>1)&0x3, SequenceType,            "Sequence Type");
            Get_Flags ((Flags>>3)&0x3, PaddingLengthType,       "Padding Length Type");
            Get_Flags ((Flags>>5)&0x3, PacketLengthType,        "Packet Length Type");
            Skip_Flags(Flags, 7,                                "Error Correction Present");
        Get_L1 (Flags,                                          "Property Flags");
            Get_Flags ( Flags    &0x3, ReplicatedDataLengthType, "Replicated Data Length Type");
            Get_Flags ((Flags>>2)&0x3, OffsetIntoMediaObjectLengthType, "Offset Into Media Object Length Type");
            Get_Flags ((Flags>>4)&0x3, MediaObjectNumberLengthType, "Media Object Number Length Type");
            Get_Flags ((Flags>>6)&0x3, StreamNumberLengthType,  "Stream Number Length Type");
        switch (PacketLengthType)
        {
            case 1 : {int8u  Data; Get_L1(Data,                 "Packet Length"); PacketLength=Data;} break;
            case 2 : {int16u Data; Get_L2(Data,                 "Packet Length"); PacketLength=Data;} break;
            case 3 :               Get_L4(PacketLength,         "Packet Length");                     break;
            default: ;
        }
        switch (SequenceType)
        {
            case 1 : Skip_L1(                                   "Sequence"); break;
            case 2 : Skip_L2(                                   "Sequence"); break;
            case 3 : Skip_L4(                                   "Sequence"); break;
            default: ;
        }
        switch (PaddingLengthType)
        {
            case 1 : {int8u  Data; Get_L1(Data,                 "Padding Length"); Data_Parse_Padding=Data;} break;
            case 2 : {int16u Data; Get_L2(Data,                 "Padding Length"); Data_Parse_Padding=Data;} break;
            case 3 :               Get_L4(Data_Parse_Padding,   "Padding Length");                           break;
            default: Data_Parse_Padding=0;
        }
        Skip_L4(                                                "Send Time");
        Skip_L2(                                                "Duration");
    Element_End();

    if (MultiplePayloadsPresent)
        Header_Parse_Data_MultiplePayloads();
}

//---------------------------------------------------------------------------
void File_Wm::Header_Parse_Data_MultiplePayloads()
{
    //Parsing
    Element_Begin("Multiple Payloads");
        int8u Flags;
        Get_L1 (Flags,                                          "Flags");
            Get_Flags ( Flags    &0x3F, NumberPayloads,         "Number of Payloads"); //6 bits
            Get_Flags ((Flags>>6)&0x03, PayloadLengthType,      "Payload Length Type"); //bits 6 and 7
    Element_End();

    //Filling
    NumberPayloads_Pos=0;
}

//---------------------------------------------------------------------------
void File_Wm::Header_Parse_Data_Payload()
{
    Element_Begin("Payload");
        int32u ReplicatedDataLength;
        int8u  StreamNumber;
        Get_L1 (StreamNumber,                                   "Stream Number");
        StreamNumber&=0x7F; //For KeyFrame
        Element_Info(StreamNumber);
        switch (MediaObjectNumberLengthType)
        {
            case 1 : Skip_L1(                                   "Media Object Number"); break;
            case 2 : Skip_L2(                                   "Media Object Number"); break;
            case 3 : Skip_L4(                                   "Media Object Number"); break;
            default: ;
        }
        switch (OffsetIntoMediaObjectLengthType)
        {
            case 1 : Skip_L1(                                   "Offset Into Media Object"); break;
            case 2 : Skip_L2(                                   "Offset Into Media Object"); break;
            case 3 : Skip_L4(                                   "Offset Into Media Object"); break;
            default: ;
        }
        switch (ReplicatedDataLengthType)
        {
            case 1 : {int8u  Data; Get_L1(Data,                 "Replicated Data Length"); ReplicatedDataLength=Data;} break;
            case 2 : {int16u Data; Get_L2(Data,                 "Replicated Data Length"); ReplicatedDataLength=Data;} break;
            case 3 :               Get_L4(ReplicatedDataLength, "Replicated Data Length");                             break;
            default: ;
        }
        if (ReplicatedDataLengthType!=0 && ReplicatedDataLength>0)
        {
            if (ReplicatedDataLength>=8)
            {
                Get_L4 (SizeOfMediaObject,                      "Size Of Media Object");
                Skip_L4(                                        "Presentation Time");
                if (ReplicatedDataLength>8)
                {
                    Skip_XX(ReplicatedDataLength-8,             "Payload Extension");
                }
            }
            else if (ReplicatedDataLength==1)
            {
                Skip_L1(                                        "Presentation Time Delta");
                //TODO
            }
            else
                Skip_XX(ReplicatedDataLength,                   "Replicated Data");
        }
    Element_End();

    if (MultiplePayloadsPresent)
    {
        switch (PayloadLengthType)
        {
            case 1 : {int8u  Data; Get_L1(Data,                 "Payload Length"); SizeOfMediaObject=Data;} break;
            case 2 : {int16u Data; Get_L2(Data,                 "Payload Length"); SizeOfMediaObject=Data;} break;
            case 3 :               Get_L4(SizeOfMediaObject,    "Payload Length");                             break;
            default: SizeOfMediaObject=0; //Problem
        }
    }

    if (PacketLength==0 && SizeOfMediaObject>0)
        PacketLength=(int32u)(Element_Offset+SizeOfMediaObject+Data_Parse_Padding);

    if (NumberPayloads_Pos+1<NumberPayloads)
        PacketLength-=Data_Parse_Padding; //Padding is only for the last packet
    if (PacketLength>MaximumDataPacketSize)
        PacketLength=MaximumDataPacketSize; //Some files seem to have a wrong SizeOfMediaObject, trying to parse them and trusting the header better than SizeOfMediaObject

    //Filling
    Header_Fill_Code(StreamNumber, "Packet");
    Header_Fill_Size(PacketLength);

    PacketLength=0; //Used
}

//***************************************************************************
// Information
//***************************************************************************

//---------------------------------------------------------------------------
void File_Wm::HowTo(stream_t UNUSED(StreamKind))
{
}

//***************************************************************************
// C++
//***************************************************************************

} //NameSpace

#endif //MEDIAINFO_WM_YES
<|endoftext|>


<commit_before>#include "gd.h"
#include "vw.h"
#include "lrq.h"
#include "rand48.h"
#include <float.h>

namespace LRQ {

  struct LRQstate {
    vw* all;
    bool lrindices[256];
    size_t orig_size[256];
    std::vector<std::string> lrpairs;
    bool dropout;
    uint64_t seed;
    uint64_t initial_seed;
  };
}

namespace {
  bool
  valid_int (const char* s)
    {
      char* endptr;

      int v = strtoul (s, &endptr, 0);
      (void) v;

      return (*s != '\0' && *endptr == '\0');
    }

  inline bool
  cheesyrbit (uint64_t& seed)
    {
      return merand48 (seed) > 0.5;
    }

  inline float
  cheesyrand (uint32_t x)
    {
      uint32_t v = 1664525 * x + 1013904223;

      return ((float) v) / 2147483648;
    }

  inline bool
  example_is_test (example* ec)
    {
      return ec->test_only || (((label_data*) ec->ld)->label == FLT_MAX);
    }

  void
  reset_seed (void* d)
    {
      LRQ::LRQstate* lrq = (LRQ::LRQstate*) d;

      if (lrq->all->bfgs)
        lrq->seed = lrq->initial_seed;
    }
}

namespace LRQ {

  void learn(void* d, learner& base, example* ec)
  {
    LRQstate* lrq = (LRQstate*) d;
    vw& all = *lrq->all;

    // Remember original features

    for (unsigned char* i = ec->indices.begin; i != ec->indices.end; ++i)
      {
        if (lrq->lrindices[*i])
          lrq->orig_size[*i] = ec->atomics[*i].size ();
      }

    size_t which = ec->example_counter;
    simple_prediction first_prediction;
    float first_loss;
    unsigned int maxiter = (all.training && ! example_is_test (ec)) ? 2 : 1;

    bool do_dropout = lrq->dropout && all.training && ! example_is_test (ec);
    float scale = (! lrq->dropout || do_dropout) ? 1 : 0.5;

    for (unsigned int iter = 0; iter < maxiter; ++iter, ++which)
      {
        // Add left LRQ features, holding right LRQ features fixed
        //     and vice versa
        // TODO: what happens with --lrq ab2 --lrq ac2
        //       i.e. namespace occurs multiple times (?)

        for (vector<string>::iterator i = lrq->lrpairs.begin ();
             i != lrq->lrpairs.end ();
             ++i)
          {
            unsigned char left = (*i)[which%2];
            unsigned char right = (*i)[(which+1)%2];
            unsigned int k = atoi (i->c_str () + 2);

            for (unsigned int lfn = 0; lfn < lrq->orig_size[left]; ++lfn)
              {
                feature* lf = ec->atomics[left].begin + lfn;
                size_t lindex = lf->weight_index + ec->ft_offset;

                for (unsigned int n = 1; n <= k; ++n)
                  {
                    if (! do_dropout || cheesyrbit (lrq->seed))
                      {
                        uint32_t lwindex = lindex + n * all.reg.stride;

                        float* lw = &all.reg.weight_vector[lwindex & all.reg.weight_mask];

                        // perturb away from saddle point at (0, 0)
                        if (all.training && ! example_is_test (ec) && *lw == 0)
                          *lw = cheesyrand (lwindex);

                        for (unsigned int rfn = 0;
                             rfn < lrq->orig_size[right];
                             ++rfn)
                          {
                            feature* rf = ec->atomics[right].begin + rfn;

                            // NB: ec->ft_offset added by base learner
                            size_t rindex = rf->weight_index;
                            uint32_t rwindex = rindex + n * all.reg.stride;

                            feature lrq;
                            lrq.x = scale * *lw;
                            lrq.weight_index = rwindex;

                            ec->atomics[right].push_back (lrq);

                            if (all.audit)
                              {
                                char name[4] = { 'l', 'r', 'q', '\0' };
                                char subname[4] = { left, '^', right, '\0' };
                                audit_data ad = { name, subname, lrq.weight_index, lrq.x, false };
                                ec->audit_features[right].push_back (ad);
                              }
                          }
                      }
                  }
              }
          }

        base.learn(ec);//Recursive Call

        // Restore example

        if (iter == 0)
          {
            first_prediction = ec->final_prediction;
            first_loss = ec->loss;
          }
        else
          {
            ec->final_prediction = first_prediction;
            ec->loss = first_loss;
          }

        for (vector<string>::iterator i = lrq->lrpairs.begin ();
             i != lrq->lrpairs.end ();
             ++i)
          {
            unsigned char right = (*i)[(which+1)%2];

            ec->atomics[right].end =
              ec->atomics[right].begin + lrq->orig_size[right];

            if (all.audit)
              ec->audit_features[right].end =
                ec->audit_features[right].begin + lrq->orig_size[right];
          }
      }
  }

  learner* setup(vw& all, std::vector<std::string>&opts, po::variables_map& vm, po::variables_map& vm_file)
  {//parse and set arguments
    LRQstate* lrq = (LRQstate*) calloc (1, sizeof (LRQstate));
    unsigned int maxk = 0;
    lrq->all = &all;

    size_t random_seed = 0;
    if (vm.count("random_seed")) random_seed = vm["random_seed"].as<size_t> ();
    if (vm_file.count("random_seed")) random_seed = vm_file["random_seed"].as<size_t> ();

    lrq->initial_seed = lrq->seed = random_seed | 8675309;
    lrq->dropout = vm.count("lrqdropout") || vm_file.count("lrqdropout");

    if (lrq->dropout && !vm_file.count("lrqdropout"))
      all.options_from_file.append("--lrqdropout");

    if (!vm_file.count("lrq"))
      {
        lrq->lrpairs = vm["lrq"].as<vector<string> > ();

        // TODO: doesn't work for non-printable stuff

        stringstream ss;
        for (vector<string>::iterator i = lrq->lrpairs.begin ();
             i != lrq->lrpairs.end ();
             ++i)
          {
            ss << " --lrq " << *i;
          }

        all.options_from_file.append(ss.str());
      }
    else
      lrq->lrpairs = vm_file["lrq"].as<vector<string> > ();

    if (! all.quiet)
      {
        cerr << "creating low rank quadratic features for pairs: ";
        if (lrq->dropout)
          cerr << "(using dropout) ";
      }

    for (vector<string>::iterator i = lrq->lrpairs.begin ();
         i != lrq->lrpairs.end ();
         ++i)
      {
        if(!all.quiet){
          if (( i->length() < 3 ) || ! valid_int (i->c_str () + 2)) {
            cerr << endl << "error, low-rank quadratic features must involve two sets and a rank.\n";
            throw exception();
          }
          cerr << *i << " ";
        }
        // TODO: colon-syntax

        unsigned int k = atoi (i->c_str () + 2);

        lrq->lrindices[(int) (*i)[0]] = max (lrq->lrindices[(int) (*i)[0]], k);
        lrq->lrindices[(int) (*i)[1]] = max (lrq->lrindices[(int) (*i)[1]], k);

        maxk = max (maxk, k);
      }

    if(!all.quiet)
      cerr<<endl;

    all.wpp = all.wpp * (1 + maxk);
    learner* l = new learner(lrq, learn, all.l, 1 + maxk);
    l->set_end_pass (reset_seed);

    // TODO: leaks memory ?
    return l;
  }
}
<commit_msg>dropout mmf<commit_after>#include "gd.h"
#include "vw.h"
#include "lrq.h"
#include "rand48.h"
#include <float.h>

namespace LRQ {

  struct LRQstate {
    vw* all;
    bool lrindices[256];
    size_t orig_size[256];
    std::vector<std::string> lrpairs;
    bool dropout;
    uint64_t seed;
    uint64_t initial_seed;
  };
}

namespace {
  bool
  valid_int (const char* s)
    {
      char* endptr;

      int v = strtoul (s, &endptr, 0);
      (void) v;

      return (*s != '\0' && *endptr == '\0');
    }

  inline bool
  cheesyrbit (uint64_t& seed)
    {
      return merand48 (seed) > 0.5;
    }

  inline float
  cheesyrand (uint32_t x)
    {
      uint32_t v = 1664525 * x + 1013904223;

      return ((float) v) / 2147483648;
    }

  inline bool
  example_is_test (example* ec)
    {
      return ec->test_only || (((label_data*) ec->ld)->label == FLT_MAX);
    }

  void
  reset_seed (void* d)
    {
      LRQ::LRQstate* lrq = (LRQ::LRQstate*) d;

      if (lrq->all->bfgs)
        lrq->seed = lrq->initial_seed;
    }
}

namespace LRQ {

  void learn(void* d, learner& base, example* ec)
  {
    LRQstate* lrq = (LRQstate*) d;
    vw& all = *lrq->all;

    // Remember original features

    for (unsigned char* i = ec->indices.begin; i != ec->indices.end; ++i)
      {
        if (lrq->lrindices[*i])
          lrq->orig_size[*i] = ec->atomics[*i].size ();
      }

    size_t which = ec->example_counter;
    simple_prediction first_prediction;
    float first_loss;
    unsigned int maxiter = (all.training && ! example_is_test (ec)) ? 2 : 1;

    bool do_dropout = lrq->dropout && all.training && ! example_is_test (ec);
    float scale = (! lrq->dropout || do_dropout) ? 1 : 0.5;

    for (unsigned int iter = 0; iter < maxiter; ++iter, ++which)
      {
        // Add left LRQ features, holding right LRQ features fixed
        //     and vice versa
        // TODO: what happens with --lrq ab2 --lrq ac2
        //       i.e. namespace occurs multiple times (?)

        for (vector<string>::iterator i = lrq->lrpairs.begin ();
             i != lrq->lrpairs.end ();
             ++i)
          {
            unsigned char left = (*i)[which%2];
            unsigned char right = (*i)[(which+1)%2];
            unsigned int k = atoi (i->c_str () + 2);

            for (unsigned int lfn = 0; lfn < lrq->orig_size[left]; ++lfn)
              {
                feature* lf = ec->atomics[left].begin + lfn;
                float lfx = lf->x;
                size_t lindex = lf->weight_index + ec->ft_offset;

                for (unsigned int n = 1; n <= k; ++n)
                  {
                    if (! do_dropout || cheesyrbit (lrq->seed))
                      {
                        uint32_t lwindex = lindex + n * all.reg.stride;

                        float* lw = &all.reg.weight_vector[lwindex & all.reg.weight_mask];

                        // perturb away from saddle point at (0, 0)
                        if (all.training && ! example_is_test (ec) && *lw == 0)
                          *lw = cheesyrand (lwindex);

                        for (unsigned int rfn = 0;
                             rfn < lrq->orig_size[right];
                             ++rfn)
                          {
                            feature* rf = ec->atomics[right].begin + rfn;

                            // NB: ec->ft_offset added by base learner
                            float rfx = rf->x;
                            size_t rindex = rf->weight_index;
                            uint32_t rwindex = rindex + n * all.reg.stride;

                            feature lrq;
                            lrq.x = scale * *lw * lfx * rfx;
                            lrq.weight_index = rwindex;

                            ec->atomics[right].push_back (lrq);

                            if (all.audit)
                              {
                                char name[4] = { 'l', 'r', 'q', '\0' };
                                char subname[4] = { left, '^', right, '\0' };
                                audit_data ad = { name, subname, lrq.weight_index, lrq.x, false };
                                ec->audit_features[right].push_back (ad);
                              }
                          }
                      }
                  }
              }
          }

        base.learn(ec);//Recursive Call

        // Restore example

        if (iter == 0)
          {
            first_prediction = ec->final_prediction;
            first_loss = ec->loss;
          }
        else
          {
            ec->final_prediction = first_prediction;
            ec->loss = first_loss;
          }

        for (vector<string>::iterator i = lrq->lrpairs.begin ();
             i != lrq->lrpairs.end ();
             ++i)
          {
            unsigned char right = (*i)[(which+1)%2];

            ec->atomics[right].end =
              ec->atomics[right].begin + lrq->orig_size[right];

            if (all.audit)
              ec->audit_features[right].end =
                ec->audit_features[right].begin + lrq->orig_size[right];
          }
      }
  }

  learner* setup(vw& all, std::vector<std::string>&opts, po::variables_map& vm, po::variables_map& vm_file)
  {//parse and set arguments
    LRQstate* lrq = (LRQstate*) calloc (1, sizeof (LRQstate));
    unsigned int maxk = 0;
    lrq->all = &all;

    size_t random_seed = 0;
    if (vm.count("random_seed")) random_seed = vm["random_seed"].as<size_t> ();
    if (vm_file.count("random_seed")) random_seed = vm_file["random_seed"].as<size_t> ();

    lrq->initial_seed = lrq->seed = random_seed | 8675309;
    lrq->dropout = vm.count("lrqdropout") || vm_file.count("lrqdropout");

    if (lrq->dropout && !vm_file.count("lrqdropout"))
      all.options_from_file.append("--lrqdropout");

    if (!vm_file.count("lrq"))
      {
        lrq->lrpairs = vm["lrq"].as<vector<string> > ();

        // TODO: doesn't work for non-printable stuff

        stringstream ss;
        for (vector<string>::iterator i = lrq->lrpairs.begin ();
             i != lrq->lrpairs.end ();
             ++i)
          {
            ss << " --lrq " << *i;
          }

        all.options_from_file.append(ss.str());
      }
    else
      lrq->lrpairs = vm_file["lrq"].as<vector<string> > ();

    if (! all.quiet)
      {
        cerr << "creating low rank quadratic features for pairs: ";
        if (lrq->dropout)
          cerr << "(using dropout) ";
      }

    for (vector<string>::iterator i = lrq->lrpairs.begin ();
         i != lrq->lrpairs.end ();
         ++i)
      {
        if(!all.quiet){
          if (( i->length() < 3 ) || ! valid_int (i->c_str () + 2)) {
            cerr << endl << "error, low-rank quadratic features must involve two sets and a rank.\n";
            throw exception();
          }
          cerr << *i << " ";
        }
        // TODO: colon-syntax

        unsigned int k = atoi (i->c_str () + 2);

        lrq->lrindices[(int) (*i)[0]] = max (lrq->lrindices[(int) (*i)[0]], k);
        lrq->lrindices[(int) (*i)[1]] = max (lrq->lrindices[(int) (*i)[1]], k);

        maxk = max (maxk, k);
      }

    if(!all.quiet)
      cerr<<endl;

    all.wpp = all.wpp * (1 + maxk);
    learner* l = new learner(lrq, learn, all.l, 1 + maxk);
    l->set_end_pass (reset_seed);

    // TODO: leaks memory ?
    return l;
  }
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPolyDataMapper.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkPolyDataMapper.h"

#include "vtkExecutive.h"
#include "vtkGraphicsFactory.h"
#include "vtkInformation.h"
#include "vtkMath.h"
#include "vtkPolyData.h"
#include "vtkRenderWindow.h"

vtkCxxRevisionMacro(vtkPolyDataMapper, "1.38");

//----------------------------------------------------------------------------
// Needed when we don't use the vtkStandardNewMacro.
vtkInstantiatorNewMacro(vtkPolyDataMapper);

//----------------------------------------------------------------------------
// return the correct type of PolyDataMapper
vtkPolyDataMapper *vtkPolyDataMapper::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkGraphicsFactory::CreateInstance("vtkPolyDataMapper");
  return (vtkPolyDataMapper*)ret;
}

//----------------------------------------------------------------------------
vtkPolyDataMapper::vtkPolyDataMapper()
{
  this->Piece = 0;
  this->NumberOfPieces = 1;
  this->NumberOfSubPieces = 1;
  this->GhostLevel = 0;
}

void vtkPolyDataMapper::Render(vtkRenderer *ren, vtkActor *act)
{
  if (this->Static)
    {
    this->RenderPiece(ren,act);
    return;
    }

  int currentPiece, nPieces;
  vtkPolyData *input = this->GetInput();

  if (input == NULL)
    {
    vtkErrorMacro("Mapper has no input.");
    return;
    }

  nPieces = this->NumberOfPieces * this->NumberOfSubPieces;

  for(int i=0; i<this->NumberOfSubPieces; i++)
    {
    // If more than one pieces, render in loop.
    currentPiece = this->NumberOfSubPieces * this->Piece + i;
    input->SetUpdateExtent(currentPiece, nPieces, this->GhostLevel);
    this->RenderPiece(ren, act);
    }
}

//----------------------------------------------------------------------------
void vtkPolyDataMapper::SetInput(vtkPolyData *input)
{
  if(input)
    {
    this->SetInputConnection(0, input->GetProducerPort());
    }
  else
    {
    // Setting a NULL input removes the connection.
    this->SetInputConnection(0, 0);
    }
}

//----------------------------------------------------------------------------
// Specify the input data or filter.
vtkPolyData *vtkPolyDataMapper::GetInput()
{
  return vtkPolyData::SafeDownCast(
    this->GetExecutive()->GetInputData(0, 0));
}

// Update the network connected to this mapper.
void vtkPolyDataMapper::Update()
{
  if (this->Static)
    {
    return;
    }

  int currentPiece, nPieces = this->NumberOfPieces;
  vtkPolyData* input = this->GetInput();

  // If the estimated pipeline memory usage is larger than
  // the memory limit, break the current piece into sub-pieces.
  if (input)
    {
    currentPiece = this->NumberOfSubPieces * this->Piece;
    input->SetUpdateExtent(currentPiece, this->NumberOfSubPieces*nPieces,
                           this->GhostLevel);
    }

  this->vtkMapper::Update();
}

// Get the bounds for the input of this mapper as
// (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
double *vtkPolyDataMapper::GetBounds()
{
  static double bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};

  // do we have an input
  if ( ! this->GetNumberOfInputConnections(0))
    {
    return bounds;
    }
  else
    {
    if (!this->Static)
      {
      this->Update();
      this->GetInput()->GetBounds(this->Bounds);
      }
    // if the bounds indicate NAN and subpieces are being used then
    // return NULL
    if (!vtkMath::AreBoundsInitialized(this->Bounds)
        && this->NumberOfSubPieces > 1)
      {
      return NULL;
      }
    return this->Bounds;
    }
}

void vtkPolyDataMapper::ShallowCopy(vtkAbstractMapper *mapper)
{
  vtkPolyDataMapper *m = vtkPolyDataMapper::SafeDownCast(mapper);
  if ( m != NULL )
    {
    this->SetInput(m->GetInput());
    this->SetGhostLevel(m->GetGhostLevel());
    this->SetNumberOfPieces(m->GetNumberOfPieces());
    this->SetNumberOfSubPieces(m->GetNumberOfSubPieces());
    }

  // Now do superclass
  this->vtkMapper::ShallowCopy(mapper);
}

void vtkPolyDataMapper::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Piece : " << this->Piece << endl;
  os << indent << "NumberOfPieces : " << this->NumberOfPieces << endl;
  os << indent << "GhostLevel: " << this->GhostLevel << endl;
  os << indent << "Number of sub pieces: " << this->NumberOfSubPieces
     << endl;
}

//----------------------------------------------------------------------------
int vtkPolyDataMapper::FillInputPortInformation(
  int vtkNotUsed( port ), vtkInformation* info)
{
  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData");
  return 1;
}
<commit_msg>ENH: Changes necessary to get streaming woring in ParaView.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPolyDataMapper.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkPolyDataMapper.h"

#include "vtkExecutive.h"
#include "vtkGraphicsFactory.h"
#include "vtkInformation.h"
#include "vtkMath.h"
#include "vtkPolyData.h"
#include "vtkRenderWindow.h"

vtkCxxRevisionMacro(vtkPolyDataMapper, "1.39");

//----------------------------------------------------------------------------
// Needed when we don't use the vtkStandardNewMacro.
vtkInstantiatorNewMacro(vtkPolyDataMapper);

//----------------------------------------------------------------------------
// return the correct type of PolyDataMapper
vtkPolyDataMapper *vtkPolyDataMapper::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkGraphicsFactory::CreateInstance("vtkPolyDataMapper");
  return (vtkPolyDataMapper*)ret;
}

//----------------------------------------------------------------------------
vtkPolyDataMapper::vtkPolyDataMapper()
{
  this->Piece = 0;
  this->NumberOfPieces = 1;
  this->NumberOfSubPieces = 1;
  this->GhostLevel = 0;
}

void vtkPolyDataMapper::Render(vtkRenderer *ren, vtkActor *act)
{
  if (this->Static)
    {
    this->RenderPiece(ren,act);
    return;
    }

  int currentPiece, nPieces;
  vtkPolyData *input = this->GetInput();

  if (input == NULL)
    {
    vtkErrorMacro("Mapper has no input.");
    return;
    }

  nPieces = this->NumberOfPieces * this->NumberOfSubPieces;

  for(int i=0; i<this->NumberOfSubPieces; i++)
    {
    // If more than one pieces, render in loop.
    currentPiece = this->NumberOfSubPieces * this->Piece + i;
    input->SetUpdateExtent(currentPiece, nPieces, this->GhostLevel);
    this->RenderPiece(ren, act);
    }
}

//----------------------------------------------------------------------------
void vtkPolyDataMapper::SetInput(vtkPolyData *input)
{
  if(input)
    {
    this->SetInputConnection(0, input->GetProducerPort());
    }
  else
    {
    // Setting a NULL input removes the connection.
    this->SetInputConnection(0, 0);
    }
}

//----------------------------------------------------------------------------
// Specify the input data or filter.
vtkPolyData *vtkPolyDataMapper::GetInput()
{
  return vtkPolyData::SafeDownCast(
    this->GetExecutive()->GetInputData(0, 0));
}

// Update the network connected to this mapper.
void vtkPolyDataMapper::Update()
{
  if (this->Static)
    {
    return;
    }

  int currentPiece, nPieces = this->NumberOfPieces;
  vtkPolyData* input = this->GetInput();

  // If the estimated pipeline memory usage is larger than
  // the memory limit, break the current piece into sub-pieces.
  if (input)
    {
    currentPiece = this->NumberOfSubPieces * this->Piece;
    input->SetUpdateExtent(currentPiece, this->NumberOfSubPieces*nPieces,
                           this->GhostLevel);
    }

  this->vtkMapper::Update();
}

// Get the bounds for the input of this mapper as
// (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
double *vtkPolyDataMapper::GetBounds()
{
  static double bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};

  // do we have an input
  if ( ! this->GetNumberOfInputConnections(0))
    {
    return bounds;
    }
  else
    {
    if (!this->Static)
      {
      // For proper clipping, this would be this->Piece, this->NumberOfPieces ..
      // But that removes all benefites of streaming.
      // Update everything as a hack for paraview streaming.
      // This should not affect anything else, because no one uses this.
      // It should also render just the same.
      // Just remove this lie if we no longer need streaming in paraview :)
      this->GetInput()->SetUpdateExtent(0, 1, 0);
      this->GetInput()->Update();
      this->GetInput()->GetBounds(this->Bounds);
      }
    // if the bounds indicate NAN and subpieces are being used then
    // return NULL
    if (!vtkMath::AreBoundsInitialized(this->Bounds)
        && this->NumberOfSubPieces > 1)
      {
      return NULL;
      }
    return this->Bounds;
    }
}

void vtkPolyDataMapper::ShallowCopy(vtkAbstractMapper *mapper)
{
  vtkPolyDataMapper *m = vtkPolyDataMapper::SafeDownCast(mapper);
  if ( m != NULL )
    {
    this->SetInput(m->GetInput());
    this->SetGhostLevel(m->GetGhostLevel());
    this->SetNumberOfPieces(m->GetNumberOfPieces());
    this->SetNumberOfSubPieces(m->GetNumberOfSubPieces());
    }

  // Now do superclass
  this->vtkMapper::ShallowCopy(mapper);
}

void vtkPolyDataMapper::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Piece : " << this->Piece << endl;
  os << indent << "NumberOfPieces : " << this->NumberOfPieces << endl;
  os << indent << "GhostLevel: " << this->GhostLevel << endl;
  os << indent << "Number of sub pieces: " << this->NumberOfSubPieces
     << endl;
}

//----------------------------------------------------------------------------
int vtkPolyDataMapper::FillInputPortInformation(
  int vtkNotUsed( port ), vtkInformation* info)
{
  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData");
  return 1;
}
<|endoftext|>


<commit_before>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Actions/Targeting.hpp>
#include <Rosetta/Games/Game.hpp>

#include <algorithm>

namespace RosettaStone::Generic
{
//! A list of play requirements that needs a target.
constexpr std::array<PlayReq, 8> NEEDS_TARGET_LIST = {
    PlayReq::REQ_TARGET_TO_PLAY,
    PlayReq::REQ_TARGET_IF_AVAILABLE,
    PlayReq::REQ_TARGET_FOR_COMBO,
    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_DRAGON_IN_HAND,
    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_MINIONS,
    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_SECRETS,
    PlayReq::REQ_TARGET_IF_AVAILABE_AND_ELEMENTAL_PLAYED_LAST_TURN,
    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_NO_3_COST_CARD_IN_DECK
};

bool IsSourceNeedsTarget(Entity* source)
{
    for (auto& requirement : source->card.playRequirements)
    {
        auto iter = std::find(NEEDS_TARGET_LIST.begin(),
                              NEEDS_TARGET_LIST.end(), requirement.first);
        if (iter != NEEDS_TARGET_LIST.end())
        {
            return true;
        }
    }

    return false;
}

bool IsValidTarget(Entity* source, Entity* target)
{
    // Get valid play targets
    auto targetList = GetValidTargets(source);

    // Return if source needs a target, but target is null and list is empty
    if (IsSourceNeedsTarget(source) && target == nullptr && targetList.empty())
    {
        return false;
    }

    // Check source must require a target
    bool requiresTarget = false;
    for (auto& requirement : source->card.playRequirements)
    {
        if (requirement.first == PlayReq::REQ_TARGET_TO_PLAY)
        {
            requiresTarget = true;
            break;
        }
    }

    // Return if source must require a target, but target is null
    if (requiresTarget && target == nullptr)
    {
        return false;
    }

    // Return if target is exist, but not exist in target list
    if (target != nullptr && std::find(targetList.begin(), targetList.end(),
                                       target) == targetList.end())
    {
        return false;
    }

    return true;
}

std::vector<Character*> GetValidTargets(Entity* source)
{
    std::vector<Character*> ret;

    // If source don't need a target, return an empty vector
    if (!IsSourceNeedsTarget(source))
    {
        return ret;
    }

    auto game = source->owner->GetGame();

    // Check play requirements for player's hero
    if (CheckRequirements(source, game->GetPlayer1().GetHero()))
    {
        ret.emplace_back(game->GetPlayer1().GetHero());
    }
    if (CheckRequirements(source, game->GetPlayer2().GetHero()))
    {
        ret.emplace_back(game->GetPlayer2().GetHero());
    }

    // Check play requirements for player's minions
    for (auto& minion : game->GetPlayer1().GetField().GetAllMinions())
    {
        if (CheckRequirements(source, minion))
        {
            ret.emplace_back(minion);
        }
    }
    for (auto& minion : game->GetPlayer2().GetField().GetAllMinions())
    {
        if (CheckRequirements(source, minion))
        {
            ret.emplace_back(minion);
        }
    }

    return ret;
}

bool CheckRequirements(Entity* source, Character* target)
{
    for (auto& requirement : source->card.playRequirements)
    {
        const PlayReq req = requirement.first;
        const int param = requirement.second;

        switch (req)
        {
            case PlayReq::REQ_MINION_TARGET:
            {
                if (dynamic_cast<Minion*>(target) == nullptr)
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_FRIENDLY_TARGET:
                if (target->owner != source->owner)
                {
                    return false;
                }
                break;
            case PlayReq::REQ_ENEMY_TARGET:
            {
                if (target->owner == source->owner)
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_TARGET_MAX_ATTACK:
            {
                if (target->GetAttack() > param)
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_NONSELF_TARGET:
            {
                if (source == target)
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_TARGET_WITH_RACE:
            {
                if (target->card.GetRace() != static_cast<Race>(param))
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_TARGET_MIN_ATTACK:
            {
                if (target->GetAttack() < param)
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_UNDAMAGED_TARGET:
            {
                if (target->GetDamage() > 0)
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_TARGET_TO_PLAY:
            case PlayReq::REQ_TARGET_IF_AVAILABLE:
                break;
            default:
                break;
        }
    }

    return true;
}
}  // namespace RosettaStone::Generic
<commit_msg>feat(card-impl): Add code to consider PlayReq::REQ_DAMAGED_TARGET<commit_after>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Actions/Targeting.hpp>
#include <Rosetta/Games/Game.hpp>

#include <algorithm>

namespace RosettaStone::Generic
{
//! A list of play requirements that needs a target.
constexpr std::array<PlayReq, 8> NEEDS_TARGET_LIST = {
    PlayReq::REQ_TARGET_TO_PLAY,
    PlayReq::REQ_TARGET_IF_AVAILABLE,
    PlayReq::REQ_TARGET_FOR_COMBO,
    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_DRAGON_IN_HAND,
    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_MINIONS,
    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_SECRETS,
    PlayReq::REQ_TARGET_IF_AVAILABE_AND_ELEMENTAL_PLAYED_LAST_TURN,
    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_NO_3_COST_CARD_IN_DECK
};

bool IsSourceNeedsTarget(Entity* source)
{
    for (auto& requirement : source->card.playRequirements)
    {
        auto iter = std::find(NEEDS_TARGET_LIST.begin(),
                              NEEDS_TARGET_LIST.end(), requirement.first);
        if (iter != NEEDS_TARGET_LIST.end())
        {
            return true;
        }
    }

    return false;
}

bool IsValidTarget(Entity* source, Entity* target)
{
    // Get valid play targets
    auto targetList = GetValidTargets(source);

    // Return if source needs a target, but target is null and list is empty
    if (IsSourceNeedsTarget(source) && target == nullptr && targetList.empty())
    {
        return false;
    }

    // Check source must require a target
    bool requiresTarget = false;
    for (auto& requirement : source->card.playRequirements)
    {
        if (requirement.first == PlayReq::REQ_TARGET_TO_PLAY)
        {
            requiresTarget = true;
            break;
        }
    }

    // Return if source must require a target, but target is null
    if (requiresTarget && target == nullptr)
    {
        return false;
    }

    // Return if target is exist, but not exist in target list
    if (target != nullptr && std::find(targetList.begin(), targetList.end(),
                                       target) == targetList.end())
    {
        return false;
    }

    return true;
}

std::vector<Character*> GetValidTargets(Entity* source)
{
    std::vector<Character*> ret;

    // If source don't need a target, return an empty vector
    if (!IsSourceNeedsTarget(source))
    {
        return ret;
    }

    auto game = source->owner->GetGame();

    // Check play requirements for player's hero
    if (CheckRequirements(source, game->GetPlayer1().GetHero()))
    {
        ret.emplace_back(game->GetPlayer1().GetHero());
    }
    if (CheckRequirements(source, game->GetPlayer2().GetHero()))
    {
        ret.emplace_back(game->GetPlayer2().GetHero());
    }

    // Check play requirements for player's minions
    for (auto& minion : game->GetPlayer1().GetField().GetAllMinions())
    {
        if (CheckRequirements(source, minion))
        {
            ret.emplace_back(minion);
        }
    }
    for (auto& minion : game->GetPlayer2().GetField().GetAllMinions())
    {
        if (CheckRequirements(source, minion))
        {
            ret.emplace_back(minion);
        }
    }

    return ret;
}

bool CheckRequirements(Entity* source, Character* target)
{
    for (auto& requirement : source->card.playRequirements)
    {
        const PlayReq req = requirement.first;
        const int param = requirement.second;

        switch (req)
        {
            case PlayReq::REQ_MINION_TARGET:
            {
                if (dynamic_cast<Minion*>(target) == nullptr)
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_FRIENDLY_TARGET:
                if (target->owner != source->owner)
                {
                    return false;
                }
                break;
            case PlayReq::REQ_ENEMY_TARGET:
            {
                if (target->owner == source->owner)
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_DAMAGED_TARGET:
            {
                if (target->GetDamage() == 0)
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_TARGET_MAX_ATTACK:
            {
                if (target->GetAttack() > param)
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_NONSELF_TARGET:
            {
                if (source == target)
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_TARGET_WITH_RACE:
            {
                if (target->card.GetRace() != static_cast<Race>(param))
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_TARGET_MIN_ATTACK:
            {
                if (target->GetAttack() < param)
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_UNDAMAGED_TARGET:
            {
                if (target->GetDamage() > 0)
                {
                    return false;
                }
                break;
            }
            case PlayReq::REQ_TARGET_TO_PLAY:
            case PlayReq::REQ_TARGET_IF_AVAILABLE:
                break;
            default:
                break;
        }
    }

    return true;
}
}  // namespace RosettaStone::Generic
<|endoftext|>