<commit_before>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Test.h"
#include "TestClassDef.h"
#include "SkPaint.h"
#include "SkFontStream.h"
#include "SkOSFile.h"
#include "SkStream.h"
#include "SkTypeface.h"
#include "SkEndian.h"

//#define DUMP_TABLES
//#define DUMP_TTC_TABLES

#define kFontTableTag_head          SkSetFourByteTag('h', 'e', 'a', 'd')
#define kFontTableTag_hhea          SkSetFourByteTag('h', 'h', 'e', 'a')
#define kFontTableTag_maxp          SkSetFourByteTag('m', 'a', 'x', 'p')

static const struct TagSize {
    SkFontTableTag  fTag;
    size_t          fSize;
} gKnownTableSizes[] = {
    {   kFontTableTag_head,         54 },
    {   kFontTableTag_hhea,         36 },
    {   kFontTableTag_maxp,         32 },
};

// Test that getUnitsPerEm() agrees with a direct lookup in the 'head' table
// (if that table is available).
static void test_unitsPerEm(skiatest::Reporter* reporter, SkTypeface* face) {
    int nativeUPEM = face->getUnitsPerEm();

    int tableUPEM = -1;
    size_t size = face->getTableSize(kFontTableTag_head);
    if (size) {
        // unitsPerEm is at offset 18 into the 'head' table.
        uint16_t rawUPEM;
        face->getTableData(kFontTableTag_head, 18, sizeof(rawUPEM), &rawUPEM);
        tableUPEM = SkEndian_SwapBE16(rawUPEM);
    }

    if (tableUPEM >= 0) {
        REPORTER_ASSERT(reporter, tableUPEM == nativeUPEM);
    } else {
        // not sure this is a bug, but lets report it for now as info.
        SkDebugf("--- typeface returned 0 upem [%X]\n", face->uniqueID());
    }
}

// Test that countGlyphs() agrees with a direct lookup in the 'maxp' table
// (if that table is available).
static void test_countGlyphs(skiatest::Reporter* reporter, SkTypeface* face) {
    int nativeGlyphs = face->countGlyphs();

    int tableGlyphs = -1;
    size_t size = face->getTableSize(kFontTableTag_maxp);
    if (size) {
        // glyphs is at offset 4 into the 'maxp' table.
        uint16_t rawGlyphs;
        face->getTableData(kFontTableTag_maxp, 4, sizeof(rawGlyphs), &rawGlyphs);
        tableGlyphs = SkEndian_SwapBE16(rawGlyphs);
    }

    if (tableGlyphs >= 0) {
        REPORTER_ASSERT(reporter, tableGlyphs == nativeGlyphs);
    } else {
        // not sure this is a bug, but lets report it for now as info.
        SkDebugf("--- typeface returned 0 glyphs [%X]\n", face->uniqueID());
    }
}

// The following three are all the same code points in various encodings.
static uint8_t utf8Chars[] = { 0x61, 0xE4, 0xB8, 0xAD, 0xD0, 0xAF, 0xD7, 0x99, 0xD7, 0x95, 0xF0, 0x9D, 0x84, 0x9E, 0x61 };
static uint16_t utf16Chars[] = { 0x0061, 0x4E2D, 0x042F, 0x05D9, 0x05D5, 0xD834, 0xDD1E, 0x0061 };
static uint32_t utf32Chars[] = { 0x00000061, 0x00004E2D, 0x0000042F, 0x000005D9, 0x000005D5, 0x0001D11E, 0x00000061 };

struct CharsToGlyphs_TestData {
    const void* chars;
    int charCount;
    size_t charsByteLength;
    SkTypeface::Encoding typefaceEncoding;
    const char* name;
} static charsToGlyphs_TestData[] = {
    { utf8Chars, 7, sizeof(utf8Chars), SkTypeface::kUTF8_Encoding, "Simple UTF-8" },
    { utf16Chars, 7, sizeof(utf16Chars), SkTypeface::kUTF16_Encoding, "Simple UTF-16" },
    { utf32Chars, 7, sizeof(utf32Chars), SkTypeface::kUTF32_Encoding, "Simple UTF-32" },
};

// Test that SkPaint::textToGlyphs agrees with SkTypeface::charsToGlyphs.
static void test_charsToGlyphs(skiatest::Reporter* reporter, SkTypeface* face) {
    uint16_t paintGlyphIds[256];
    uint16_t faceGlyphIds[256];

    for (size_t testIndex = 0; testIndex < SK_ARRAY_COUNT(charsToGlyphs_TestData); ++testIndex) {
        CharsToGlyphs_TestData& test = charsToGlyphs_TestData[testIndex];

        SkPaint paint;
        paint.setTypeface(face);
        paint.setTextEncoding((SkPaint::TextEncoding)test.typefaceEncoding);
        paint.textToGlyphs(test.chars, test.charsByteLength, paintGlyphIds);

        face->charsToGlyphs(test.chars, test.typefaceEncoding, faceGlyphIds, test.charCount);

        for (int i = 0; i < test.charCount; ++i) {
            SkString name;
            face->getFamilyName(&name);
            SkString a;
            a.appendf("%s, paintGlyphIds[%d] = %d, faceGlyphIds[%d] = %d, face = %s",
                      test.name, i, (int)paintGlyphIds[i], i, (int)faceGlyphIds[i], name.c_str());
            REPORTER_ASSERT_MESSAGE(reporter, paintGlyphIds[i] == faceGlyphIds[i], a.c_str());
        }
    }
}

static void test_fontstream(skiatest::Reporter* reporter,
                            SkStream* stream, int ttcIndex) {
    int n = SkFontStream::GetTableTags(stream, ttcIndex, NULL);
    SkAutoTArray<SkFontTableTag> array(n);

    int n2 = SkFontStream::GetTableTags(stream, ttcIndex, array.get());
    REPORTER_ASSERT(reporter, n == n2);

    for (int i = 0; i < n; ++i) {
#ifdef DUMP_TTC_TABLES
        SkString str;
        SkFontTableTag t = array[i];
        str.appendUnichar((t >> 24) & 0xFF);
        str.appendUnichar((t >> 16) & 0xFF);
        str.appendUnichar((t >>  8) & 0xFF);
        str.appendUnichar((t >>  0) & 0xFF);
        SkDebugf("[%d:%d] '%s'\n", ttcIndex, i, str.c_str());
#endif
        size_t size = SkFontStream::GetTableSize(stream, ttcIndex, array[i]);
        for (size_t j = 0; j < SK_ARRAY_COUNT(gKnownTableSizes); ++j) {
            if (gKnownTableSizes[j].fTag == array[i]) {
                REPORTER_ASSERT(reporter, gKnownTableSizes[j].fSize == size);
            }
        }
    }
}

static void test_fontstream(skiatest::Reporter* reporter, SkStream* stream) {
    int count = SkFontStream::CountTTCEntries(stream);
#ifdef DUMP_TTC_TABLES
    SkDebugf("CountTTCEntries %d\n", count);
#endif
    for (int i = 0; i < count; ++i) {
        test_fontstream(reporter, stream, i);
    }
}

static void test_fontstream(skiatest::Reporter* reporter) {
    // This test cannot run if there is no resource path.
    SkString resourcePath = skiatest::Test::GetResourcePath();
    if (resourcePath.isEmpty()) {
        SkDebugf("Could not run fontstream test because resourcePath not specified.");
        return;
    }
    SkString filename = SkOSPath::SkPathJoin(resourcePath.c_str(), "test.ttc");

    SkFILEStream stream(filename.c_str());
    if (stream.isValid()) {
        test_fontstream(reporter, &stream);
    } else {
        SkDebugf("Could not run fontstream test because test.ttc not found.");
    }
}

static void test_tables(skiatest::Reporter* reporter, SkTypeface* face) {
    if (false) { // avoid bit rot, suppress warning
        SkFontID fontID = face->uniqueID();
        REPORTER_ASSERT(reporter, fontID);
    }

    int count = face->countTables();

    SkAutoTMalloc<SkFontTableTag> storage(count);
    SkFontTableTag* tags = storage.get();

    int count2 = face->getTableTags(tags);
    REPORTER_ASSERT(reporter, count2 == count);

    for (int i = 0; i < count; ++i) {
        size_t size = face->getTableSize(tags[i]);
        REPORTER_ASSERT(reporter, size > 0);

#ifdef DUMP_TABLES
        char name[5];
        name[0] = (tags[i] >> 24) & 0xFF;
        name[1] = (tags[i] >> 16) & 0xFF;
        name[2] = (tags[i] >>  8) & 0xFF;
        name[3] = (tags[i] >>  0) & 0xFF;
        name[4] = 0;
        SkDebugf("%s %d\n", name, size);
#endif

        for (size_t j = 0; j < SK_ARRAY_COUNT(gKnownTableSizes); ++j) {
            if (gKnownTableSizes[j].fTag == tags[i]) {
                REPORTER_ASSERT(reporter, gKnownTableSizes[j].fSize == size);
            }
        }

        // do we get the same size from GetTableData and GetTableSize
        {
            SkAutoMalloc data(size);
            size_t size2 = face->getTableData(tags[i], 0, size, data.get());
            REPORTER_ASSERT(reporter, size2 == size);
        }
    }
}

static void test_tables(skiatest::Reporter* reporter) {
    static const char* const gNames[] = {
        NULL,   // default font
        "Arial", "Times", "Times New Roman", "Helvetica", "Courier",
        "Courier New", "Terminal", "MS Sans Serif",
    };

    for (size_t i = 0; i < SK_ARRAY_COUNT(gNames); ++i) {
        SkAutoTUnref<SkTypeface> face(SkTypeface::CreateFromName(gNames[i], SkTypeface::kNormal));
        if (face) {
#ifdef DUMP_TABLES
            SkDebugf("%s\n", gNames[i]);
#endif
            test_tables(reporter, face);
            test_unitsPerEm(reporter, face);
            test_countGlyphs(reporter, face);
            test_charsToGlyphs(reporter, face);
        }
    }
}

/*
 * Verifies that the advance values returned by generateAdvance and
 * generateMetrics match.
 */
static void test_advances(skiatest::Reporter* reporter) {
    static const char* const faces[] = {
        NULL,   // default font
        "Arial", "Times", "Times New Roman", "Helvetica", "Courier",
        "Courier New", "Verdana", "monospace",
    };

    static const struct {
        SkPaint::Hinting    hinting;
        unsigned            flags;
    } settings[] = {
        { SkPaint::kNo_Hinting,     0                               },
        { SkPaint::kNo_Hinting,     SkPaint::kLinearText_Flag       },
        { SkPaint::kNo_Hinting,     SkPaint::kSubpixelText_Flag     },
        { SkPaint::kSlight_Hinting, 0                               },
        { SkPaint::kSlight_Hinting, SkPaint::kLinearText_Flag       },
        { SkPaint::kSlight_Hinting, SkPaint::kSubpixelText_Flag     },
        { SkPaint::kNormal_Hinting, 0                               },
        { SkPaint::kNormal_Hinting, SkPaint::kLinearText_Flag       },
        { SkPaint::kNormal_Hinting, SkPaint::kSubpixelText_Flag     },
    };

    static const struct {
        SkScalar    fScaleX;
        SkScalar    fSkewX;
    } gScaleRec[] = {
        { SK_Scalar1, 0 },
        { SK_Scalar1/2, 0 },
        // these two exercise obliquing (skew)
        { SK_Scalar1, -SK_Scalar1/4 },
        { SK_Scalar1/2, -SK_Scalar1/4 },
    };

    SkPaint paint;
    char txt[] = "long.text.with.lots.of.dots.";

    for (size_t i = 0; i < SK_ARRAY_COUNT(faces); i++) {
        SkAutoTUnref<SkTypeface> face(SkTypeface::CreateFromName(faces[i], SkTypeface::kNormal));
        paint.setTypeface(face);

        for (size_t j = 0; j  < SK_ARRAY_COUNT(settings); j++) {
            paint.setHinting(settings[j].hinting);
            paint.setLinearText((settings[j].flags & SkPaint::kLinearText_Flag) != 0);
            paint.setSubpixelText((settings[j].flags & SkPaint::kSubpixelText_Flag) != 0);

            for (size_t k = 0; k < SK_ARRAY_COUNT(gScaleRec); ++k) {
                paint.setTextScaleX(gScaleRec[k].fScaleX);
                paint.setTextSkewX(gScaleRec[k].fSkewX);

                SkRect bounds;

                // For no hinting and light hinting this should take the
                // optimized generateAdvance path.
                SkScalar width1 = paint.measureText(txt, strlen(txt));

                // Requesting the bounds forces a generateMetrics call.
                SkScalar width2 = paint.measureText(txt, strlen(txt), &bounds);

                // SkDebugf("Font: %s, generateAdvance: %f, generateMetrics: %f\n",
                //    faces[i], SkScalarToFloat(width1), SkScalarToFloat(width2));

                REPORTER_ASSERT(reporter, width1 == width2);
            }
        }
    }
}

DEF_TEST(FontHost, reporter) {
    test_tables(reporter);
    test_fontstream(reporter);
    test_advances(reporter);
}

// need tests for SkStrSearch
<commit_msg>Remove printfs from FontHostTest when font is not sfnt.<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Test.h"
#include "TestClassDef.h"
#include "SkPaint.h"
#include "SkFontStream.h"
#include "SkOSFile.h"
#include "SkStream.h"
#include "SkTypeface.h"
#include "SkEndian.h"

//#define DUMP_TABLES
//#define DUMP_TTC_TABLES

#define kFontTableTag_head          SkSetFourByteTag('h', 'e', 'a', 'd')
#define kFontTableTag_hhea          SkSetFourByteTag('h', 'h', 'e', 'a')
#define kFontTableTag_maxp          SkSetFourByteTag('m', 'a', 'x', 'p')

static const struct TagSize {
    SkFontTableTag  fTag;
    size_t          fSize;
} gKnownTableSizes[] = {
    {   kFontTableTag_head,         54 },
    {   kFontTableTag_hhea,         36 },
    {   kFontTableTag_maxp,         32 },
};

// Test that getUnitsPerEm() agrees with a direct lookup in the 'head' table
// (if that table is available).
static void test_unitsPerEm(skiatest::Reporter* reporter, SkTypeface* face) {
    int nativeUPEM = face->getUnitsPerEm();

    int tableUPEM = -1;
    size_t size = face->getTableSize(kFontTableTag_head);
    if (size) {
        // unitsPerEm is at offset 18 into the 'head' table.
        uint16_t rawUPEM;
        face->getTableData(kFontTableTag_head, 18, sizeof(rawUPEM), &rawUPEM);
        tableUPEM = SkEndian_SwapBE16(rawUPEM);
    }

    if (tableUPEM >= 0) {
        REPORTER_ASSERT(reporter, tableUPEM == nativeUPEM);
    }
}

// Test that countGlyphs() agrees with a direct lookup in the 'maxp' table
// (if that table is available).
static void test_countGlyphs(skiatest::Reporter* reporter, SkTypeface* face) {
    int nativeGlyphs = face->countGlyphs();

    int tableGlyphs = -1;
    size_t size = face->getTableSize(kFontTableTag_maxp);
    if (size) {
        // glyphs is at offset 4 into the 'maxp' table.
        uint16_t rawGlyphs;
        face->getTableData(kFontTableTag_maxp, 4, sizeof(rawGlyphs), &rawGlyphs);
        tableGlyphs = SkEndian_SwapBE16(rawGlyphs);
    }

    if (tableGlyphs >= 0) {
        REPORTER_ASSERT(reporter, tableGlyphs == nativeGlyphs);
    }
}

// The following three are all the same code points in various encodings.
static uint8_t utf8Chars[] = { 0x61, 0xE4, 0xB8, 0xAD, 0xD0, 0xAF, 0xD7, 0x99, 0xD7, 0x95, 0xF0, 0x9D, 0x84, 0x9E, 0x61 };
static uint16_t utf16Chars[] = { 0x0061, 0x4E2D, 0x042F, 0x05D9, 0x05D5, 0xD834, 0xDD1E, 0x0061 };
static uint32_t utf32Chars[] = { 0x00000061, 0x00004E2D, 0x0000042F, 0x000005D9, 0x000005D5, 0x0001D11E, 0x00000061 };

struct CharsToGlyphs_TestData {
    const void* chars;
    int charCount;
    size_t charsByteLength;
    SkTypeface::Encoding typefaceEncoding;
    const char* name;
} static charsToGlyphs_TestData[] = {
    { utf8Chars, 7, sizeof(utf8Chars), SkTypeface::kUTF8_Encoding, "Simple UTF-8" },
    { utf16Chars, 7, sizeof(utf16Chars), SkTypeface::kUTF16_Encoding, "Simple UTF-16" },
    { utf32Chars, 7, sizeof(utf32Chars), SkTypeface::kUTF32_Encoding, "Simple UTF-32" },
};

// Test that SkPaint::textToGlyphs agrees with SkTypeface::charsToGlyphs.
static void test_charsToGlyphs(skiatest::Reporter* reporter, SkTypeface* face) {
    uint16_t paintGlyphIds[256];
    uint16_t faceGlyphIds[256];

    for (size_t testIndex = 0; testIndex < SK_ARRAY_COUNT(charsToGlyphs_TestData); ++testIndex) {
        CharsToGlyphs_TestData& test = charsToGlyphs_TestData[testIndex];

        SkPaint paint;
        paint.setTypeface(face);
        paint.setTextEncoding((SkPaint::TextEncoding)test.typefaceEncoding);
        paint.textToGlyphs(test.chars, test.charsByteLength, paintGlyphIds);

        face->charsToGlyphs(test.chars, test.typefaceEncoding, faceGlyphIds, test.charCount);

        for (int i = 0; i < test.charCount; ++i) {
            SkString name;
            face->getFamilyName(&name);
            SkString a;
            a.appendf("%s, paintGlyphIds[%d] = %d, faceGlyphIds[%d] = %d, face = %s",
                      test.name, i, (int)paintGlyphIds[i], i, (int)faceGlyphIds[i], name.c_str());
            REPORTER_ASSERT_MESSAGE(reporter, paintGlyphIds[i] == faceGlyphIds[i], a.c_str());
        }
    }
}

static void test_fontstream(skiatest::Reporter* reporter,
                            SkStream* stream, int ttcIndex) {
    int n = SkFontStream::GetTableTags(stream, ttcIndex, NULL);
    SkAutoTArray<SkFontTableTag> array(n);

    int n2 = SkFontStream::GetTableTags(stream, ttcIndex, array.get());
    REPORTER_ASSERT(reporter, n == n2);

    for (int i = 0; i < n; ++i) {
#ifdef DUMP_TTC_TABLES
        SkString str;
        SkFontTableTag t = array[i];
        str.appendUnichar((t >> 24) & 0xFF);
        str.appendUnichar((t >> 16) & 0xFF);
        str.appendUnichar((t >>  8) & 0xFF);
        str.appendUnichar((t >>  0) & 0xFF);
        SkDebugf("[%d:%d] '%s'\n", ttcIndex, i, str.c_str());
#endif
        size_t size = SkFontStream::GetTableSize(stream, ttcIndex, array[i]);
        for (size_t j = 0; j < SK_ARRAY_COUNT(gKnownTableSizes); ++j) {
            if (gKnownTableSizes[j].fTag == array[i]) {
                REPORTER_ASSERT(reporter, gKnownTableSizes[j].fSize == size);
            }
        }
    }
}

static void test_fontstream(skiatest::Reporter* reporter, SkStream* stream) {
    int count = SkFontStream::CountTTCEntries(stream);
#ifdef DUMP_TTC_TABLES
    SkDebugf("CountTTCEntries %d\n", count);
#endif
    for (int i = 0; i < count; ++i) {
        test_fontstream(reporter, stream, i);
    }
}

static void test_fontstream(skiatest::Reporter* reporter) {
    // This test cannot run if there is no resource path.
    SkString resourcePath = skiatest::Test::GetResourcePath();
    if (resourcePath.isEmpty()) {
        SkDebugf("Could not run fontstream test because resourcePath not specified.");
        return;
    }
    SkString filename = SkOSPath::SkPathJoin(resourcePath.c_str(), "test.ttc");

    SkFILEStream stream(filename.c_str());
    if (stream.isValid()) {
        test_fontstream(reporter, &stream);
    } else {
        SkDebugf("Could not run fontstream test because test.ttc not found.");
    }
}

static void test_tables(skiatest::Reporter* reporter, SkTypeface* face) {
    if (false) { // avoid bit rot, suppress warning
        SkFontID fontID = face->uniqueID();
        REPORTER_ASSERT(reporter, fontID);
    }

    int count = face->countTables();

    SkAutoTMalloc<SkFontTableTag> storage(count);
    SkFontTableTag* tags = storage.get();

    int count2 = face->getTableTags(tags);
    REPORTER_ASSERT(reporter, count2 == count);

    for (int i = 0; i < count; ++i) {
        size_t size = face->getTableSize(tags[i]);
        REPORTER_ASSERT(reporter, size > 0);

#ifdef DUMP_TABLES
        char name[5];
        name[0] = (tags[i] >> 24) & 0xFF;
        name[1] = (tags[i] >> 16) & 0xFF;
        name[2] = (tags[i] >>  8) & 0xFF;
        name[3] = (tags[i] >>  0) & 0xFF;
        name[4] = 0;
        SkDebugf("%s %d\n", name, size);
#endif

        for (size_t j = 0; j < SK_ARRAY_COUNT(gKnownTableSizes); ++j) {
            if (gKnownTableSizes[j].fTag == tags[i]) {
                REPORTER_ASSERT(reporter, gKnownTableSizes[j].fSize == size);
            }
        }

        // do we get the same size from GetTableData and GetTableSize
        {
            SkAutoMalloc data(size);
            size_t size2 = face->getTableData(tags[i], 0, size, data.get());
            REPORTER_ASSERT(reporter, size2 == size);
        }
    }
}

static void test_tables(skiatest::Reporter* reporter) {
    static const char* const gNames[] = {
        NULL,   // default font
        "Arial", "Times", "Times New Roman", "Helvetica", "Courier",
        "Courier New", "Terminal", "MS Sans Serif",
    };

    for (size_t i = 0; i < SK_ARRAY_COUNT(gNames); ++i) {
        SkAutoTUnref<SkTypeface> face(SkTypeface::CreateFromName(gNames[i], SkTypeface::kNormal));
        if (face) {
#ifdef DUMP_TABLES
            SkDebugf("%s\n", gNames[i]);
#endif
            test_tables(reporter, face);
            test_unitsPerEm(reporter, face);
            test_countGlyphs(reporter, face);
            test_charsToGlyphs(reporter, face);
        }
    }
}

/*
 * Verifies that the advance values returned by generateAdvance and
 * generateMetrics match.
 */
static void test_advances(skiatest::Reporter* reporter) {
    static const char* const faces[] = {
        NULL,   // default font
        "Arial", "Times", "Times New Roman", "Helvetica", "Courier",
        "Courier New", "Verdana", "monospace",
    };

    static const struct {
        SkPaint::Hinting    hinting;
        unsigned            flags;
    } settings[] = {
        { SkPaint::kNo_Hinting,     0                               },
        { SkPaint::kNo_Hinting,     SkPaint::kLinearText_Flag       },
        { SkPaint::kNo_Hinting,     SkPaint::kSubpixelText_Flag     },
        { SkPaint::kSlight_Hinting, 0                               },
        { SkPaint::kSlight_Hinting, SkPaint::kLinearText_Flag       },
        { SkPaint::kSlight_Hinting, SkPaint::kSubpixelText_Flag     },
        { SkPaint::kNormal_Hinting, 0                               },
        { SkPaint::kNormal_Hinting, SkPaint::kLinearText_Flag       },
        { SkPaint::kNormal_Hinting, SkPaint::kSubpixelText_Flag     },
    };

    static const struct {
        SkScalar    fScaleX;
        SkScalar    fSkewX;
    } gScaleRec[] = {
        { SK_Scalar1, 0 },
        { SK_Scalar1/2, 0 },
        // these two exercise obliquing (skew)
        { SK_Scalar1, -SK_Scalar1/4 },
        { SK_Scalar1/2, -SK_Scalar1/4 },
    };

    SkPaint paint;
    char txt[] = "long.text.with.lots.of.dots.";

    for (size_t i = 0; i < SK_ARRAY_COUNT(faces); i++) {
        SkAutoTUnref<SkTypeface> face(SkTypeface::CreateFromName(faces[i], SkTypeface::kNormal));
        paint.setTypeface(face);

        for (size_t j = 0; j  < SK_ARRAY_COUNT(settings); j++) {
            paint.setHinting(settings[j].hinting);
            paint.setLinearText((settings[j].flags & SkPaint::kLinearText_Flag) != 0);
            paint.setSubpixelText((settings[j].flags & SkPaint::kSubpixelText_Flag) != 0);

            for (size_t k = 0; k < SK_ARRAY_COUNT(gScaleRec); ++k) {
                paint.setTextScaleX(gScaleRec[k].fScaleX);
                paint.setTextSkewX(gScaleRec[k].fSkewX);

                SkRect bounds;

                // For no hinting and light hinting this should take the
                // optimized generateAdvance path.
                SkScalar width1 = paint.measureText(txt, strlen(txt));

                // Requesting the bounds forces a generateMetrics call.
                SkScalar width2 = paint.measureText(txt, strlen(txt), &bounds);

                // SkDebugf("Font: %s, generateAdvance: %f, generateMetrics: %f\n",
                //    faces[i], SkScalarToFloat(width1), SkScalarToFloat(width2));

                REPORTER_ASSERT(reporter, width1 == width2);
            }
        }
    }
}

DEF_TEST(FontHost, reporter) {
    test_tables(reporter);
    test_fontstream(reporter);
    test_advances(reporter);
}

// need tests for SkStrSearch
<|endoftext|>


<commit_before>/*
 * Joey Button
 * Felix Wang
 * Peter Wang
 */

#include <stdio.h>
#include <opencv2/video/background_segm.hpp>
#include "opencv2/opencv.hpp"
#include "physics.h"

using namespace cv;
using namespace std;

const char *win = "video";
static bool reverseMirror = false;

int main(int argc, char **argv)
{
    if (argc > 2) {
        fprintf(stderr, "Error: Please limit arguments to 1 or none.\n");
        exit(1);
    }
    else if (argc == 2) {
        if (!strcmp(argv[1], "-m"))
            reverseMirror = true;
        else
            fprintf(stderr, "Usage: videoBall [-m]\n");
    }

    int cam = 0; // default camera
    VideoCapture cap(cam);
    if (!cap.isOpened()) {
        fprintf(stderr, "Error: Cannot open camera %d\n", cam);
        exit(1);
    }

    namedWindow(win, CV_WINDOW_AUTOSIZE);

    Mat fgMaskMOG;          // foreground mask generated by MOG method
    Mat inputFrame, outFrame;
    Mat circ;
    Point pt;               // center of the ball

    BackgroundSubtractorMOG2 MOG;

    pt.x = 500;
    pt.y = 0;

    Point momentum;
    momentum.x = 10;
    momentum.y = 50;

    cap >> inputFrame;
    cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);
    cvtColor(inputFrame, circ, CV_BGR2GRAY);

    int height = inputFrame.rows - 2 * RADIUS;
    int width = inputFrame.cols - 2 * RADIUS;

    // double overlap;
    int count = 0;
    int sum;
    Point small;
    Mat ballFrame, handFrame;
    Mat foregroundMask, backgroundMask;
    Mat reverseFrame;
    while (++count) {
        cap >> inputFrame;

        if (reverseMirror) {
            inputFrame.copyTo(reverseFrame);
            flip(reverseFrame, inputFrame, 1);
        }

        calcDir(&momentum, &pt, height, width);

        MOG(inputFrame, fgMaskMOG);

        // blank canvas
        circ.setTo(Scalar(0,0,0));

        Rect ballRegion(pt.x - RADIUS, pt.y - RADIUS, 2 * RADIUS, 2 * RADIUS);
        ballFrame = circ(ballRegion);

        foregroundMask = fgMaskMOG > THRESH;         // have to put here otherwise floating point exception
        backgroundMask = fgMaskMOG <= THRESH;
        fgMaskMOG.setTo(Scalar(255, 255, 255), foregroundMask);     // clean up
        fgMaskMOG.setTo(Scalar(0, 0, 0), backgroundMask);
        handFrame = fgMaskMOG(ballRegion);                          // cut to small size

        int halfRad = RADIUS / 2;
        // top left
        small.x = halfRad;    small.y = halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x += sum*3;              momentum.y += sum*3;

        // top right
        small.x = 3 * halfRad;   small.y = halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x -= sum*2;              momentum.y += sum*3;

        // bottom left
        small.x = halfRad;    small.y = 3 * halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x += sum*3;              momentum.y -= sum*2;

        // bottom right
        small.x = 3 * halfRad;   small.y = 3 * halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x -= sum*2;              momentum.y -= sum*2;

        // EVERYTHING BELOW THIS LINE SHOULD BE DRAWING THE outFrame
        outFrame.setTo(Scalar(0,0,0));      // set all of outFrame to be black
        outFrame.setTo(Scalar(255, 255, 255), foregroundMask);

        drawCircle(outFrame, pt, RADIUS);

        imshow(win, outFrame);
        if (count%30 == 0){
          printf("m.x: %d\tm.y: %d\n",momentum.x,momentum.y);
        }
        if (waitKey(1) >= 0)        // listening for key press
	        break;
    }

    return 0;
}
<commit_msg>Fixed bug<commit_after>/*
 * Joey Button
 * Felix Wang
 * Peter Wang
 */

#include <stdio.h>
#include <opencv2/video/background_segm.hpp>
#include "opencv2/opencv.hpp"
#include "physics.h"

using namespace cv;
using namespace std;

const char *win = "video";
static bool reverseMirror = false;

int main(int argc, char **argv)
{
    if (argc > 2) {
        fprintf(stderr, "Error: Please limit arguments to 1 or none.\n");
        exit(1);
    }
    else if (argc == 2) {
        if (!strcmp(argv[1], "-m"))
            reverseMirror = true;
        else {
            fprintf(stderr, "Usage: videoBall [-m]\n");
            exit(1);
        }
    }

    int cam = 0; // default camera
    VideoCapture cap(cam);
    if (!cap.isOpened()) {
        fprintf(stderr, "Error: Cannot open camera %d\n", cam);
        exit(1);
    }

    namedWindow(win, CV_WINDOW_AUTOSIZE);

    Mat fgMaskMOG;          // foreground mask generated by MOG method
    Mat inputFrame, outFrame;
    Mat circ;
    Point pt;               // center of the ball

    BackgroundSubtractorMOG2 MOG;

    pt.x = 500;
    pt.y = 0;

    Point momentum;
    momentum.x = 10;
    momentum.y = 50;

    cap >> inputFrame;
    cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);
    cvtColor(inputFrame, circ, CV_BGR2GRAY);

    int height = inputFrame.rows - 2 * RADIUS;
    int width = inputFrame.cols - 2 * RADIUS;

    // double overlap;
    int count = 0;
    int sum;
    Point small;
    Mat ballFrame, handFrame;
    Mat foregroundMask, backgroundMask;
    Mat reverseFrame;
    while (++count) {
        cap >> inputFrame;

        if (reverseMirror) {
            inputFrame.copyTo(reverseFrame);
            flip(reverseFrame, inputFrame, 1);
        }

        calcDir(&momentum, &pt, height, width);

        MOG(inputFrame, fgMaskMOG);

        // blank canvas
        circ.setTo(Scalar(0,0,0));

        Rect ballRegion(pt.x - RADIUS, pt.y - RADIUS, 2 * RADIUS, 2 * RADIUS);
        ballFrame = circ(ballRegion);

        foregroundMask = fgMaskMOG > THRESH;         // have to put here otherwise floating point exception
        backgroundMask = fgMaskMOG <= THRESH;
        fgMaskMOG.setTo(Scalar(255, 255, 255), foregroundMask);     // clean up
        fgMaskMOG.setTo(Scalar(0, 0, 0), backgroundMask);
        handFrame = fgMaskMOG(ballRegion);                          // cut to small size

        int halfRad = RADIUS / 2;
        // top left
        small.x = halfRad;    small.y = halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x += sum*3;              momentum.y += sum*3;

        // top right
        small.x = 3 * halfRad;   small.y = halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x -= sum*2;              momentum.y += sum*3;

        // bottom left
        small.x = halfRad;    small.y = 3 * halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x += sum*3;              momentum.y -= sum*2;

        // bottom right
        small.x = 3 * halfRad;   small.y = 3 * halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x -= sum*2;              momentum.y -= sum*2;

        // EVERYTHING BELOW THIS LINE SHOULD BE DRAWING THE outFrame
        outFrame.setTo(Scalar(0,0,0));      // set all of outFrame to be black
        outFrame.setTo(Scalar(255, 255, 255), foregroundMask);

        drawCircle(outFrame, pt, RADIUS);

        imshow(win, outFrame);
        if (count%30 == 0){
          printf("m.x: %d\tm.y: %d\n",momentum.x,momentum.y);
        }
        if (waitKey(1) >= 0)        // listening for key press
	        break;
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2010-2018 Branimir Karadzic. All rights reserved.
 * License: https://github.com/bkaradzic/bx#license-bsd-2-clause
 */

#include "bx_p.h"
#include <bx/semaphore.h>

#if BX_CONFIG_SUPPORTS_THREADING

#if BX_PLATFORM_OSX \
||  BX_PLATFORM_IOS
#	include <dispatch/dispatch.h>
#elif BX_PLATFORM_POSIX
#	include <errno.h>
#	include <pthread.h>
#	include <semaphore.h>
#	include <time.h>
#elif  BX_PLATFORM_WINDOWS \
	|| BX_PLATFORM_WINRT   \
	|| BX_PLATFORM_XBOXONE
#	include <windows.h>
#	include <limits.h>
#	if BX_PLATFORM_XBOXONE
#		include <synchapi.h>
#	endif // BX_PLATFORM_XBOXONE
#endif // BX_PLATFORM_

namespace bx
{
	struct SemaphoreInternal
	{
#if BX_PLATFORM_OSX \
||  BX_PLATFORM_IOS
		dispatch_semaphore_t m_handle;
#elif BX_PLATFORM_POSIX
		pthread_mutex_t m_mutex;
		pthread_cond_t m_cond;
		int32_t m_count;
#elif  BX_PLATFORM_WINDOWS \
	|| BX_PLATFORM_WINRT   \
	|| BX_PLATFORM_XBOXONE
		HANDLE m_handle;
#endif // BX_PLATFORM_
	};

#if BX_PLATFORM_OSX \
||  BX_PLATFORM_IOS

	Semaphore::Semaphore()
	{
		BX_STATIC_ASSERT(sizeof(SemaphoreInternal) <= sizeof(m_internal) );

		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;
		si->m_handle = dispatch_semaphore_create(0);
		BX_CHECK(NULL != si->m_handle, "dispatch_semaphore_create failed.");
	}

	Semaphore::~Semaphore()
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;
		dispatch_release(si->m_handle);
	}

	void Semaphore::post(uint32_t _count)
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		for (uint32_t ii = 0; ii < _count; ++ii)
		{
			dispatch_semaphore_signal(si->m_handle);
		}
	}

	bool Semaphore::wait(int32_t _msecs)
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		dispatch_time_t dt = 0 > _msecs
			? DISPATCH_TIME_FOREVER
			: dispatch_time(DISPATCH_TIME_NOW, _msecs*1000000)
			;
		return !dispatch_semaphore_wait(si->m_handle, dt);
	}

#elif BX_PLATFORM_POSIX

	uint64_t toNs(const timespec& _ts)
	{
		return _ts.tv_sec*UINT64_C(1000000000) + _ts.tv_nsec;
	}

	void toTimespecNs(timespec& _ts, uint64_t _nsecs)
	{
		_ts.tv_sec  = _nsecs/UINT64_C(1000000000);
		_ts.tv_nsec = _nsecs%UINT64_C(1000000000);
	}

	void toTimespecMs(timespec& _ts, int32_t _msecs)
	{
		toTimespecNs(_ts, _msecs*1000000);
	}

	void add(timespec& _ts, int32_t _msecs)
	{
		uint64_t ns = toNs(_ts);
		toTimespecNs(_ts, ns + _msecs*1000000);
	}

	Semaphore::Semaphore()
	{
		BX_STATIC_ASSERT(sizeof(SemaphoreInternal) <= sizeof(m_internal) );

		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;
		si->m_count = 0;

		int result;

		result = pthread_mutex_init(&si->m_mutex, NULL);
		BX_CHECK(0 == result, "pthread_mutex_init %d", result);

		result = pthread_cond_init(&si->m_cond, NULL);
		BX_CHECK(0 == result, "pthread_cond_init %d", result);

		BX_UNUSED(result);
	}

	Semaphore::~Semaphore()
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		int result;
		result = pthread_cond_destroy(&si->m_cond);
		BX_CHECK(0 == result, "pthread_cond_destroy %d", result);

		result = pthread_mutex_destroy(&si->m_mutex);
		BX_CHECK(0 == result, "pthread_mutex_destroy %d", result);

		BX_UNUSED(result);
	}

	void Semaphore::post(uint32_t _count)
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		int result = pthread_mutex_lock(&si->m_mutex);
		BX_CHECK(0 == result, "pthread_mutex_lock %d", result);

		for (uint32_t ii = 0; ii < _count; ++ii)
		{
			result = pthread_cond_signal(&si->m_cond);
			BX_CHECK(0 == result, "pthread_cond_signal %d", result);
		}

		si->m_count += _count;

		result = pthread_mutex_unlock(&si->m_mutex);
		BX_CHECK(0 == result, "pthread_mutex_unlock %d", result);

		BX_UNUSED(result);
	}

	bool Semaphore::wait(int32_t _msecs)
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		int result = pthread_mutex_lock(&si->m_mutex);
		BX_CHECK(0 == result, "pthread_mutex_lock %d", result);

		if (-1 == _msecs)
		{
			while (0 == result
			&&     0 >= si->m_count)
			{
				result = pthread_cond_wait(&si->m_cond, &si->m_mutex);
			}
		}
		else
		{
			timespec ts;
			clock_gettime(CLOCK_REALTIME, &ts);
			add(ts, _msecs);

			while (0 == result
			&&     0 >= si->m_count)
			{
				result = pthread_cond_timedwait(&si->m_cond, &si->m_mutex, &ts);
			}
		}

		bool ok = 0 == result;

		if (ok)
		{
			--si->m_count;
		}

		result = pthread_mutex_unlock(&si->m_mutex);
		BX_CHECK(0 == result, "pthread_mutex_unlock %d", result);

		BX_UNUSED(result);

		return ok;
	}

#elif  BX_PLATFORM_WINDOWS \
	|| BX_PLATFORM_WINRT   \
	|| BX_PLATFORM_XBOXONE

	Semaphore::Semaphore()
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

#if BX_PLATFORM_WINRT \
||  BX_PLATFORM_XBOXONE
		si->m_handle = CreateSemaphoreExW(NULL, 0, LONG_MAX, NULL, 0, SEMAPHORE_ALL_ACCESS);
#else
		si->m_handle = CreateSemaphoreA(NULL, 0, LONG_MAX, NULL);
#endif
		BX_CHECK(NULL != si->m_handle, "Failed to create Semaphore!");
	}

	Semaphore::~Semaphore()
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		CloseHandle(si->m_handle);
	}

	void Semaphore::post(uint32_t _count)
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		ReleaseSemaphore(si->m_handle, _count, NULL);
	}

	bool Semaphore::wait(int32_t _msecs)
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		DWORD milliseconds = (0 > _msecs) ? INFINITE : _msecs;
#if BX_PLATFORM_WINRT \
||  BX_PLATFORM_XBOXONE
		return WAIT_OBJECT_0 == WaitForSingleObjectEx(si->m_handle, milliseconds, FALSE);
#else
		return WAIT_OBJECT_0 == WaitForSingleObject(si->m_handle, milliseconds);
#endif
	}
#endif // BX_PLATFORM_

} // namespace bx

#endif // BX_CONFIG_SUPPORTS_THREADING
<commit_msg>Fixed signed integer overflow.<commit_after>/*
 * Copyright 2010-2018 Branimir Karadzic. All rights reserved.
 * License: https://github.com/bkaradzic/bx#license-bsd-2-clause
 */

#include "bx_p.h"
#include <bx/semaphore.h>

#if BX_CONFIG_SUPPORTS_THREADING

#if BX_PLATFORM_OSX \
||  BX_PLATFORM_IOS
#	include <dispatch/dispatch.h>
#elif BX_PLATFORM_POSIX
#	include <errno.h>
#	include <pthread.h>
#	include <semaphore.h>
#	include <time.h>
#elif  BX_PLATFORM_WINDOWS \
	|| BX_PLATFORM_WINRT   \
	|| BX_PLATFORM_XBOXONE
#	include <windows.h>
#	include <limits.h>
#	if BX_PLATFORM_XBOXONE
#		include <synchapi.h>
#	endif // BX_PLATFORM_XBOXONE
#endif // BX_PLATFORM_

namespace bx
{
	struct SemaphoreInternal
	{
#if BX_PLATFORM_OSX \
||  BX_PLATFORM_IOS
		dispatch_semaphore_t m_handle;
#elif BX_PLATFORM_POSIX
		pthread_mutex_t m_mutex;
		pthread_cond_t m_cond;
		int32_t m_count;
#elif  BX_PLATFORM_WINDOWS \
	|| BX_PLATFORM_WINRT   \
	|| BX_PLATFORM_XBOXONE
		HANDLE m_handle;
#endif // BX_PLATFORM_
	};

#if BX_PLATFORM_OSX \
||  BX_PLATFORM_IOS

	Semaphore::Semaphore()
	{
		BX_STATIC_ASSERT(sizeof(SemaphoreInternal) <= sizeof(m_internal) );

		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;
		si->m_handle = dispatch_semaphore_create(0);
		BX_CHECK(NULL != si->m_handle, "dispatch_semaphore_create failed.");
	}

	Semaphore::~Semaphore()
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;
		dispatch_release(si->m_handle);
	}

	void Semaphore::post(uint32_t _count)
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		for (uint32_t ii = 0; ii < _count; ++ii)
		{
			dispatch_semaphore_signal(si->m_handle);
		}
	}

	bool Semaphore::wait(int32_t _msecs)
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		dispatch_time_t dt = 0 > _msecs
			? DISPATCH_TIME_FOREVER
			: dispatch_time(DISPATCH_TIME_NOW, _msecs*1000000)
			;
		return !dispatch_semaphore_wait(si->m_handle, dt);
	}

#elif BX_PLATFORM_POSIX

	uint64_t toNs(const timespec& _ts)
	{
		return _ts.tv_sec*UINT64_C(1000000000) + _ts.tv_nsec;
	}

	void toTimespecNs(timespec& _ts, uint64_t _nsecs)
	{
		_ts.tv_sec  = _nsecs/UINT64_C(1000000000);
		_ts.tv_nsec = _nsecs%UINT64_C(1000000000);
	}

	void toTimespecMs(timespec& _ts, int32_t _msecs)
	{
		toTimespecNs(_ts, _msecs*1000000);
	}

	void add(timespec& _ts, int32_t _msecs)
	{
		uint64_t ns = toNs(_ts);
		toTimespecNs(_ts, ns + uint64_t(_msecs)*1000000);
	}

	Semaphore::Semaphore()
	{
		BX_STATIC_ASSERT(sizeof(SemaphoreInternal) <= sizeof(m_internal) );

		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;
		si->m_count = 0;

		int result;

		result = pthread_mutex_init(&si->m_mutex, NULL);
		BX_CHECK(0 == result, "pthread_mutex_init %d", result);

		result = pthread_cond_init(&si->m_cond, NULL);
		BX_CHECK(0 == result, "pthread_cond_init %d", result);

		BX_UNUSED(result);
	}

	Semaphore::~Semaphore()
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		int result;
		result = pthread_cond_destroy(&si->m_cond);
		BX_CHECK(0 == result, "pthread_cond_destroy %d", result);

		result = pthread_mutex_destroy(&si->m_mutex);
		BX_CHECK(0 == result, "pthread_mutex_destroy %d", result);

		BX_UNUSED(result);
	}

	void Semaphore::post(uint32_t _count)
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		int result = pthread_mutex_lock(&si->m_mutex);
		BX_CHECK(0 == result, "pthread_mutex_lock %d", result);

		for (uint32_t ii = 0; ii < _count; ++ii)
		{
			result = pthread_cond_signal(&si->m_cond);
			BX_CHECK(0 == result, "pthread_cond_signal %d", result);
		}

		si->m_count += _count;

		result = pthread_mutex_unlock(&si->m_mutex);
		BX_CHECK(0 == result, "pthread_mutex_unlock %d", result);

		BX_UNUSED(result);
	}

	bool Semaphore::wait(int32_t _msecs)
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		int result = pthread_mutex_lock(&si->m_mutex);
		BX_CHECK(0 == result, "pthread_mutex_lock %d", result);

		if (-1 == _msecs)
		{
			while (0 == result
			&&     0 >= si->m_count)
			{
				result = pthread_cond_wait(&si->m_cond, &si->m_mutex);
			}
		}
		else
		{
			timespec ts;
			clock_gettime(CLOCK_REALTIME, &ts);
			add(ts, _msecs);

			while (0 == result
			&&     0 >= si->m_count)
			{
				result = pthread_cond_timedwait(&si->m_cond, &si->m_mutex, &ts);
			}
		}

		bool ok = 0 == result;

		if (ok)
		{
			--si->m_count;
		}

		result = pthread_mutex_unlock(&si->m_mutex);
		BX_CHECK(0 == result, "pthread_mutex_unlock %d", result);

		BX_UNUSED(result);

		return ok;
	}

#elif  BX_PLATFORM_WINDOWS \
	|| BX_PLATFORM_WINRT   \
	|| BX_PLATFORM_XBOXONE

	Semaphore::Semaphore()
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

#if BX_PLATFORM_WINRT \
||  BX_PLATFORM_XBOXONE
		si->m_handle = CreateSemaphoreExW(NULL, 0, LONG_MAX, NULL, 0, SEMAPHORE_ALL_ACCESS);
#else
		si->m_handle = CreateSemaphoreA(NULL, 0, LONG_MAX, NULL);
#endif
		BX_CHECK(NULL != si->m_handle, "Failed to create Semaphore!");
	}

	Semaphore::~Semaphore()
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		CloseHandle(si->m_handle);
	}

	void Semaphore::post(uint32_t _count)
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		ReleaseSemaphore(si->m_handle, _count, NULL);
	}

	bool Semaphore::wait(int32_t _msecs)
	{
		SemaphoreInternal* si = (SemaphoreInternal*)m_internal;

		DWORD milliseconds = (0 > _msecs) ? INFINITE : _msecs;
#if BX_PLATFORM_WINRT \
||  BX_PLATFORM_XBOXONE
		return WAIT_OBJECT_0 == WaitForSingleObjectEx(si->m_handle, milliseconds, FALSE);
#else
		return WAIT_OBJECT_0 == WaitForSingleObject(si->m_handle, milliseconds);
#endif
	}
#endif // BX_PLATFORM_

} // namespace bx

#endif // BX_CONFIG_SUPPORTS_THREADING
<|endoftext|>


<commit_before>namespace mant {
  namespace bbob {
    template <typename T = double>
    class BentCigarFunction : public BlackBoxOptimisationBenchmark<T> {
      static_assert(std::is_floating_point<T>::value, "T must be a floating point type.");

      public:
        explicit BentCigarFunction(
            const std::size_t numberOfDimensions) noexcept;

        void setRotationQ(
            const arma::Mat<T>& rotationQ);

        std::string toString() const noexcept override;

      protected:
        arma::Mat<T> rotationQ_;

        T getObjectiveValueImplementation(
            const arma::Col<T>& parameter) const noexcept override;

#if defined(MANTELLA_USE_PARALLEL)
        friend class cereal::access;

        template <typename Archive>
        void serialize(
            Archive& archive) noexcept {
          archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(this)));
          archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions_));
          archive(cereal::make_nvp("rotationQ", rotationQ_));
        }

        template <typename Archive>
        static void load_and_construct(
            Archive& archive,
            cereal::construct<BentCigarFunction>& construct) noexcept {
          unsigned int numberOfDimensions;
          archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions));
          construct(numberOfDimensions);

          archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(construct.ptr())));
          archive(cereal::make_nvp("rotationQ", construct->rotationQ_));
        }
#endif
    };

    //
    // Implementation
    //

    template <typename T>
    BentCigarFunction<T>::BentCigarFunction(
        const std::size_t numberOfDimensions) noexcept
      : BlackBoxOptimisationBenchmark<T>(numberOfDimensions) {
      this->setParameterTranslation(this->getRandomParameterTranslation());
      setRotationQ(getRandomRotationMatrix(this->numberOfDimensions_));
    }

    template <typename T>
    void BentCigarFunction<T>::setRotationQ(
        const arma::Mat<T>& rotationQ) {
      verify(rotationQ.n_rows == this->numberOfDimensions_, "The number of rows must be equal to the number of dimensions");
      verify(isRotationMatrix(rotationQ), "The parameter must be a rotation matrix.");

      rotationQ_ = rotationQ;
    }

    template <typename T>
    T BentCigarFunction<T>::getObjectiveValueImplementation(
        const arma::Col<T>& parameter) const noexcept {
      const arma::Col<T>& z = arma::square(rotationQ_ * this->getAsymmetricParameter(static_cast<T>(0.5L), rotationQ_ * parameter));
      return z(0) + static_cast<T>(1000000.0L) * arma::accu(z.tail(z.n_elem - 1));
    }

    template <typename T>
    std::string BentCigarFunction<T>::toString() const noexcept {
      return "bbob_bent_cigar_function";
    }
  }
}<commit_msg>Added serialisation support for the bent cigar function<commit_after>namespace mant {
  namespace bbob {
    template <typename T = double>
    class BentCigarFunction : public BlackBoxOptimisationBenchmark<T> {
      static_assert(std::is_floating_point<T>::value, "T must be a floating point type.");

      public:
        explicit BentCigarFunction(
            const std::size_t numberOfDimensions) noexcept;

        void setRotationQ(
            const arma::Mat<T>& rotationQ);

        std::string toString() const noexcept override;

      protected:
        arma::Mat<T> rotationQ_;

        T getObjectiveValueImplementation(
            const arma::Col<T>& parameter) const noexcept override;

#if defined(MANTELLA_USE_PARALLEL_ALGORITHMS)
        friend class OptimisationAlgorithm;

        std::vector<long double> serialise() const noexcept;

        void deserialise(
            const std::vector<long double>& serialisedOptimisationProblem);
#endif
    };

    //
    // Implementation
    //

    template <typename T>
    BentCigarFunction<T>::BentCigarFunction(
        const std::size_t numberOfDimensions) noexcept
      : BlackBoxOptimisationBenchmark<T>(numberOfDimensions) {
      this->setParameterTranslation(this->getRandomParameterTranslation());
      setRotationQ(getRandomRotationMatrix(this->numberOfDimensions_));
    }

    template <typename T>
    void BentCigarFunction<T>::setRotationQ(
        const arma::Mat<T>& rotationQ) {
      verify(rotationQ.n_rows == this->numberOfDimensions_, "The number of rows must be equal to the number of dimensions");
      verify(isRotationMatrix(rotationQ), "The parameter must be a rotation matrix.");

      rotationQ_ = rotationQ;
    }

    template <typename T>
    T BentCigarFunction<T>::getObjectiveValueImplementation(
        const arma::Col<T>& parameter) const noexcept {
      const arma::Col<T>& z = arma::square(rotationQ_ * this->getAsymmetricParameter(static_cast<T>(0.5L), rotationQ_ * parameter));
      return z(0) + static_cast<T>(1000000.0L) * arma::accu(z.tail(z.n_elem - 1));
    }

    template <typename T>
    std::string BentCigarFunction<T>::toString() const noexcept {
      return "bbob_bent_cigar_function";
    }

#if defined(MANTELLA_USE_PARALLEL_ALGORITHMS)
    template <typename T>
    std::vector<long double> BentCigarFunction<T>::serialise() const noexcept {
      std::vector<long double> serialisedOptimisationProblem = BlackBoxOptimisationBenchmark<T, T>::serialise();

      for(std::size_t n = 0; n < rotationQ_.n_elem; ++n) {
        serialisedOptimisationProblem.push_back(rotationQ_(n));
      }

      return serialisedOptimisationProblem;
    }

    template <typename T>
    void BentCigarFunction<T>::deserialise(
        const std::vector<long double>& serialisedOptimisationProblem) {
      rotationQ_.set_size(this->numberOfDimensions_, this->numberOfDimensions_);
      for(std::size_t n = 0; n < rotationQ_.n_elem; ++n) {
        rotationQ_(n) = serialisedOptimisationProblem.pop_back();
      }

      BlackBoxOptimisationBenchmark<T, T>::deserialise(serialisedOptimisationProblem);
    }
#endif
  }
}<|endoftext|>


<commit_before>//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
#include <my_config.h>
#include "rocksdb/ldb_tool.h"
#include "../rdb_comparator.h"

int main(int argc, char** argv) {
  rocksdb::Options db_options;
  const myrocks::Rdb_pk_comparator pk_comparator;
  db_options.comparator= &pk_comparator;

  rocksdb::LDBTool tool;
  tool.Run(argc, argv, db_options);
  return 0;
}
<commit_msg>Make mysql_ldb work on clang<commit_after>//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
#include <my_config.h>
#include "rocksdb/ldb_tool.h"
#include "../rdb_comparator.h"

int main(int argc, char** argv) {
  rocksdb::Options db_options;
  myrocks::Rdb_pk_comparator pk_comparator;
  db_options.comparator= &pk_comparator;

  rocksdb::LDBTool tool;
  tool.Run(argc, argv, db_options);
  return 0;
}
<|endoftext|>


<commit_before>/*
 * Distributed memory pool in shared memory.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef SHM_DPOOL_HXX
#define SHM_DPOOL_HXX

#include <stddef.h>

#include <utility>
#include <new>

struct dpool;
struct shm;
struct StringView;

/**
 * Create a new memory pool.
 *
 * @return the new dpool object, or NULL if the shm object has no free
 * space
 */
struct dpool *
dpool_new(struct shm &shm);

/**
 * Destroy the memory pool.  All allocated memory is freed.
 */
void
dpool_destroy(struct dpool *pool);

bool
dpool_is_fragmented(const struct dpool &pool);

/**
 * Allocate memory from the pool.
 *
 * @return a pointer to the start, or NULL if allocation failed.
 */
void *
d_malloc(struct dpool *pool, size_t size)
    throw(std::bad_alloc);

/**
 * Frees the memory previously allocated by d_malloc().
 */
void
d_free(struct dpool *pool, const void *p);

/**
 * Duplicate a chunk of memory, allocating the new pointer from the
 * pool.
 */
char *
d_memdup(struct dpool *pool, const void *src, size_t length);

/**
 * Duplicate a C string, allocating the new pointer from the pool.
 */
char *
d_strdup(struct dpool *pool, const char *src);

char *
d_strdup(struct dpool *pool, StringView src);

static inline char *
d_strdup_checked(struct dpool *pool, const char *src)
{
    return src != NULL ? d_strdup(pool, src) : NULL;
}

/**
 * Duplicate a string, allocating the new pointer from the pool.
 */
char *
d_strndup(struct dpool *pool, const char *src, size_t length);

/**
 * Duplicate data in the given #StringView.  If src.IsNull(), then
 * nullptr is returned; if src.IsEmpty(), then an empty string literal
 * is returned.
 */
StringView
DupStringView(struct dpool &pool, StringView src)
    throw(std::bad_alloc);

/**
 * Free the data allocated by the given #StringView.  It is a no-op if
 * src.IsEmpty() because then it's either nullptr or the empty string
 * literal.
 */
void
FreeStringView(struct dpool &pool, StringView s);

template<typename T, typename... Args>
T *
NewFromPool(struct dpool *pool, Args&&... args)
{
    void *t = d_malloc(pool, sizeof(T));
    if (t == nullptr)
        return nullptr;

    return ::new(t) T(std::forward<Args>(args)...);
}

template<typename T>
void
DeleteFromPool(struct dpool *pool, T *t)
{
    t->~T();
    d_free(pool, t);
}

template<typename T>
void
DeleteDestroyPool(struct dpool &pool, T *t)
{
    t->~T();
    dpool_destroy(&pool);
}

#endif
<commit_msg>shm/dpool: remove unnecessary nullptr check<commit_after>/*
 * Distributed memory pool in shared memory.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef SHM_DPOOL_HXX
#define SHM_DPOOL_HXX

#include <stddef.h>

#include <utility>
#include <new>

struct dpool;
struct shm;
struct StringView;

/**
 * Create a new memory pool.
 *
 * @return the new dpool object, or NULL if the shm object has no free
 * space
 */
struct dpool *
dpool_new(struct shm &shm);

/**
 * Destroy the memory pool.  All allocated memory is freed.
 */
void
dpool_destroy(struct dpool *pool);

bool
dpool_is_fragmented(const struct dpool &pool);

/**
 * Allocate memory from the pool.
 *
 * @return a pointer to the start, or NULL if allocation failed.
 */
void *
d_malloc(struct dpool *pool, size_t size)
    throw(std::bad_alloc);

/**
 * Frees the memory previously allocated by d_malloc().
 */
void
d_free(struct dpool *pool, const void *p);

/**
 * Duplicate a chunk of memory, allocating the new pointer from the
 * pool.
 */
char *
d_memdup(struct dpool *pool, const void *src, size_t length);

/**
 * Duplicate a C string, allocating the new pointer from the pool.
 */
char *
d_strdup(struct dpool *pool, const char *src);

char *
d_strdup(struct dpool *pool, StringView src);

static inline char *
d_strdup_checked(struct dpool *pool, const char *src)
{
    return src != NULL ? d_strdup(pool, src) : NULL;
}

/**
 * Duplicate a string, allocating the new pointer from the pool.
 */
char *
d_strndup(struct dpool *pool, const char *src, size_t length);

/**
 * Duplicate data in the given #StringView.  If src.IsNull(), then
 * nullptr is returned; if src.IsEmpty(), then an empty string literal
 * is returned.
 */
StringView
DupStringView(struct dpool &pool, StringView src)
    throw(std::bad_alloc);

/**
 * Free the data allocated by the given #StringView.  It is a no-op if
 * src.IsEmpty() because then it's either nullptr or the empty string
 * literal.
 */
void
FreeStringView(struct dpool &pool, StringView s);

template<typename T, typename... Args>
T *
NewFromPool(struct dpool *pool, Args&&... args)
{
    void *t = d_malloc(pool, sizeof(T));

    return ::new(t) T(std::forward<Args>(args)...);
}

template<typename T>
void
DeleteFromPool(struct dpool *pool, T *t)
{
    t->~T();
    d_free(pool, t);
}

template<typename T>
void
DeleteDestroyPool(struct dpool &pool, T *t)
{
    t->~T();
    dpool_destroy(&pool);
}

#endif
<|endoftext|>


<commit_before><commit_msg>Fix JW equation<commit_after><|endoftext|>


<commit_before>#include "MoErCore.h"

MO_NAMESPACE_BEGIN

//============================================================
// <T>ַΪöݡ</T>
//
// @param pValue ַ
// @param fillModeCd Ĭ
// @return ö
//============================================================
TResult REffectParameter::Parse(TCharC* pValue, EEffectParameter& parameterCd, ERenderShader& shaderCd, ERenderParameterFormat& formatCd){
   MO_CHECK(pValue, return ENull);
   TFsCode code = pValue;
   code.ToLower();
   if(code.Equals("unknown")){
      parameterCd = EEffectParameter_Unknown;
      shaderCd = ERenderShader_Unknown;
      formatCd = ERenderParameterFormat_Unknown;
   }else if(code.Equals("vertexinstance")){
      parameterCd = EEffectParameter_VertexInstance;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float1;
   }else if(code.Equals("vertexmodelmatrix3x3")){
      parameterCd = EEffectParameter_VertexModelMatrix3x3;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float3x3;
   }else if(code.Equals("vertexmodelmatrix4x4")){
      parameterCd = EEffectParameter_VertexModelMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("vertexviewmatrix4x4")){
      parameterCd = EEffectParameter_VertexViewMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("vertexprojectionmatrix4x4")){
      parameterCd = EEffectParameter_VertexProjectionMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("vertexviewprojectionmatrix4x4")){
      parameterCd = EEffectParameter_VertexViewProjectionMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("vertexmodelviewprojectionmatrix3x3")){
      parameterCd = EEffectParameter_VertexModelViewProjectionMatrix3x3;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float3x3;
   }else if(code.Equals("vertexmodelviewprojectionmatrix4x4")){
      parameterCd = EEffectParameter_VertexModelViewProjectionMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("vertexbonematrix4x4")){
      parameterCd = EEffectParameter_VertexBoneMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("vertexcameraposition")){
      parameterCd = EEffectParameter_VertexCameraPosition;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("vertexcameradirection")){
      parameterCd = EEffectParameter_VertexCameraDirection;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("vertexlightmodelmatrix4x4")){
      parameterCd = EEffectParameter_VertexLightModelMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("vertexlightmodelviewmatrix4x4")){
      parameterCd = EEffectParameter_VertexLightModelViewMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("vertexlightmodelviewprojectrionmatrix4x4")){
      parameterCd = EEffectParameter_VertexLightModelViewProjectionMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("vertexlightposition")){
      parameterCd = EEffectParameter_VertexLightPosition;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("vertexlightdirection")){
      parameterCd = EEffectParameter_VertexLightDirection;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4;
   }
   //............................................................
   else if(code.Equals("fragmentcamera")){
      parameterCd = EEffectParameter_FragmentCamera;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentcameraposition")){
      parameterCd = EEffectParameter_FragmentCameraPosition;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentcameradirection")){
      parameterCd = EEffectParameter_FragmentCameraDirection;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentlightmodelmatrix4x4")){
      parameterCd = EEffectParameter_FragmentLightModelMatrix4x4;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("fragmentlightmodelviewprojectrionmatrix4x4")){
      parameterCd = EEffectParameter_FragmentLightModelViewProjectrionMatrix4x4;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("fragmentlightposition")){
      parameterCd = EEffectParameter_FragmentLightPosition;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentlightdirection")){
      parameterCd = EEffectParameter_FragmentLightDirection;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentlightdepth")){
      parameterCd = EEffectParameter_FragmentLightDepth;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentshadowmaterial")){
      parameterCd = EEffectParameter_FragmentShadowMaterial;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentshadowmaterialinv")){
      parameterCd = EEffectParameter_FragmentShadowMaterialInv;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentcolor")){
      parameterCd = EEffectParameter_FragmentColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentalpha")){
      parameterCd = EEffectParameter_FragmentAlpha;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentvertexcolor")){
      parameterCd = EEffectParameter_FragmentVertexColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentambientcolor")){
      parameterCd = EEffectParameter_FragmentAmbientColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentdiffusecolor")){
      parameterCd = EEffectParameter_FragmentDiffuseColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentdiffuseviewcolor")){
      parameterCd = EEffectParameter_FragmentDiffuseViewColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentspecularcolor")){
      parameterCd = EEffectParameter_FragmentSpecularColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentspecular")){
      parameterCd = EEffectParameter_FragmentSpecular;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentspecularviewcolor")){
      parameterCd = EEffectParameter_FragmentSpecularViewColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentspecularview")){
      parameterCd = EEffectParameter_FragmentSpecularView;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentreflectcolor")){
      parameterCd = EEffectParameter_FragmentReflectColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else{
      MO_STATIC_FATAL("Parse effect parameter failure. (value=%s)", pValue);
      return EFailure;
   }
   return ESuccess;
}

//============================================================
// <T>ʽöΪַ</T>
//
// @param fillModeCd ö
// @return ַ
//============================================================
TCharC* REffectParameter::Format(EEffectParameter parameterCd){
   switch(parameterCd){
      case EEffectParameter_VertexInstance:
         return "VertexInstance";
      case EEffectParameter_VertexModelMatrix3x3:
         return "VertexModelMatrix3x3";
      case EEffectParameter_VertexModelMatrix4x4:
         return "VertexModelMatrix4x4";
      case EEffectParameter_VertexViewMatrix4x4:
         return "VertexViewMatrix4x4";
      case EEffectParameter_VertexProjectionMatrix4x4:
         return "VertexProjectionMatrix4x4";
      case EEffectParameter_VertexViewProjectionMatrix4x4:
         return "VertexViewProjectionMatrix4x4";
      case EEffectParameter_VertexModelViewProjectionMatrix3x3:
         return "VertexModelViewProjectionMatrix3x3";
      case EEffectParameter_VertexModelViewProjectionMatrix4x4:
         return "VertexModelViewProjectionMatrix4x4";
      case EEffectParameter_VertexBoneMatrix4x4:
         return "VertexBoneMatrix4x4";
      case EEffectParameter_VertexCameraPosition:
         return "VertexCameraPosition";
      case EEffectParameter_VertexCameraDirection:
         return "VertexCameraDirection";
      case EEffectParameter_VertexLightPosition:
         return "VertexLightPosition";
      case EEffectParameter_VertexLightDirection:
         return "VertexLightDirection";
      //............................................................
      case EEffectParameter_FragmentCameraPosition:
         return "FragmentCameraPosition";
      case EEffectParameter_FragmentCameraDirection:
         return "FragmentCameraDirection";
      case EEffectParameter_FragmentLightPosition:
         return "FragmentLightPosition";
      case EEffectParameter_FragmentLightDirection:
         return "FragmentLightDirection";
      case EEffectParameter_FragmentLightDepth:
         return "FragmentLightDepth";
      case EEffectParameter_FragmentShadowMaterial:
         return "FragmentShadowMaterial";
      case EEffectParameter_FragmentShadowMaterialInv:
         return "FragmentShadowMaterialInv";
      case EEffectParameter_FragmentColor:
         return "FragmentColor";
      case EEffectParameter_FragmentAlpha:
         return "FragmentAlpha";
      case EEffectParameter_FragmentVertexColor:
         return "FragmentVertexColor";
      case EEffectParameter_FragmentAmbientColor:
         return "FragmentAmbientColor";
      case EEffectParameter_FragmentDiffuseColor:
         return "FragmentDiffuseColor";
      case EEffectParameter_FragmentDiffuseViewColor:
         return "FragmentDiffuseViewColor";
      case EEffectParameter_FragmentSpecularColor:
         return "FragmentSpecularColor";
      case EEffectParameter_FragmentSpecular:
         return "FragmentSpecular";
      case EEffectParameter_FragmentSpecularViewColor:
         return "FragmentSpecularViewColor";
      case EEffectParameter_FragmentSpecularView:
         return "FragmentSpecularView";
      case EEffectParameter_FragmentReflectColor:
         return "ReflectColor";
   }
   return "Unknown";
}

MO_NAMESPACE_END
<commit_msg>渲染修正。<commit_after>#include "MoErCore.h"

MO_NAMESPACE_BEGIN

//============================================================
// <T>ַΪöݡ</T>
//
// @param pValue ַ
// @param fillModeCd Ĭ
// @return ö
//============================================================
TResult REffectParameter::Parse(TCharC* pValue, EEffectParameter& parameterCd, ERenderShader& shaderCd, ERenderParameterFormat& formatCd){
   MO_CHECK(pValue, return ENull);
   TFsCode code = pValue;
   code.ToLower();
   if(code.Equals("unknown")){
      parameterCd = EEffectParameter_Unknown;
      shaderCd = ERenderShader_Unknown;
      formatCd = ERenderParameterFormat_Unknown;
   }else if(code.Equals("vertexinstance")){
      parameterCd = EEffectParameter_VertexInstance;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float1;
   }else if(code.Equals("vertexmodelmatrix3x3")){
      parameterCd = EEffectParameter_VertexModelMatrix3x3;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float3x3;
   }else if(code.Equals("vertexmodelmatrix4x4")){
      parameterCd = EEffectParameter_VertexModelMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("vertexviewmatrix4x4")){
      parameterCd = EEffectParameter_VertexViewMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("vertexprojectionmatrix4x4")){
      parameterCd = EEffectParameter_VertexProjectionMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("vertexviewprojectionmatrix4x4")){
      parameterCd = EEffectParameter_VertexViewProjectionMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("vertexmodelviewprojectionmatrix3x3")){
      parameterCd = EEffectParameter_VertexModelViewProjectionMatrix3x3;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float3x3;
   }else if(code.Equals("vertexmodelviewprojectionmatrix4x4")){
      parameterCd = EEffectParameter_VertexModelViewProjectionMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("vertexbonematrix4x4")){
      parameterCd = EEffectParameter_VertexBoneMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("vertexcameraposition")){
      parameterCd = EEffectParameter_VertexCameraPosition;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("vertexcameradirection")){
      parameterCd = EEffectParameter_VertexCameraDirection;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("vertexlightmodelmatrix4x4")){
      parameterCd = EEffectParameter_VertexLightModelMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("vertexlightmodelviewmatrix4x4")){
      parameterCd = EEffectParameter_VertexLightModelViewMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("vertexlightmodelviewprojectrionmatrix4x4")){
      parameterCd = EEffectParameter_VertexLightModelViewProjectionMatrix4x4;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("vertexlightposition")){
      parameterCd = EEffectParameter_VertexLightPosition;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("vertexlightdirection")){
      parameterCd = EEffectParameter_VertexLightDirection;
      shaderCd = ERenderShader_Vertex;
      formatCd = ERenderParameterFormat_Float4;
   }
   //............................................................
   else if(code.Equals("fragmentcamera")){
      parameterCd = EEffectParameter_FragmentCamera;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentcameraposition")){
      parameterCd = EEffectParameter_FragmentCameraPosition;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentcameradirection")){
      parameterCd = EEffectParameter_FragmentCameraDirection;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentlightmodelmatrix4x4")){
      parameterCd = EEffectParameter_FragmentLightModelMatrix4x4;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("fragmentlightmodelviewprojectrionmatrix4x4")){
      parameterCd = EEffectParameter_FragmentLightModelViewProjectrionMatrix4x4;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4x4;
   }else if(code.Equals("fragmentlightposition")){
      parameterCd = EEffectParameter_FragmentLightPosition;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentlightdirection")){
      parameterCd = EEffectParameter_FragmentLightDirection;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentlightdepth")){
      parameterCd = EEffectParameter_FragmentLightDepth;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentshadowmaterial")){
      parameterCd = EEffectParameter_FragmentShadowMaterial;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentshadowmaterialinv")){
      parameterCd = EEffectParameter_FragmentShadowMaterialInv;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentcolor")){
      parameterCd = EEffectParameter_FragmentColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentalpha")){
      parameterCd = EEffectParameter_FragmentAlpha;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentvertexcolor")){
      parameterCd = EEffectParameter_FragmentVertexColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentambientcolor")){
      parameterCd = EEffectParameter_FragmentAmbientColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentdiffusecolor")){
      parameterCd = EEffectParameter_FragmentDiffuseColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentdiffuseviewcolor")){
      parameterCd = EEffectParameter_FragmentDiffuseViewColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentspecularcolor")){
      parameterCd = EEffectParameter_FragmentSpecularColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentspecular")){
      parameterCd = EEffectParameter_FragmentSpecular;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentspecularviewcolor")){
      parameterCd = EEffectParameter_FragmentSpecularViewColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentspecularview")){
      parameterCd = EEffectParameter_FragmentSpecularView;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else if(code.Equals("fragmentreflectcolor")){
      parameterCd = EEffectParameter_FragmentReflectColor;
      shaderCd = ERenderShader_Fragment;
      formatCd = ERenderParameterFormat_Float4;
   }else{
      MO_STATIC_FATAL("Parse effect parameter failure. (value=%s)", pValue);
      return EFailure;
   }
   return ESuccess;
}

//============================================================
// <T>ʽöΪַ</T>
//
// @param fillModeCd ö
// @return ַ
//============================================================
TCharC* REffectParameter::Format(EEffectParameter parameterCd){
   switch(parameterCd){
      case EEffectParameter_VertexInstance:
         return "VertexInstance";
      case EEffectParameter_VertexModelMatrix3x3:
         return "VertexModelMatrix3x3";
      case EEffectParameter_VertexModelMatrix4x4:
         return "VertexModelMatrix4x4";
      case EEffectParameter_VertexViewMatrix4x4:
         return "VertexViewMatrix4x4";
      case EEffectParameter_VertexProjectionMatrix4x4:
         return "VertexProjectionMatrix4x4";
      case EEffectParameter_VertexViewProjectionMatrix4x4:
         return "VertexViewProjectionMatrix4x4";
      case EEffectParameter_VertexModelViewProjectionMatrix3x3:
         return "VertexModelViewProjectionMatrix3x3";
      case EEffectParameter_VertexModelViewProjectionMatrix4x4:
         return "VertexModelViewProjectionMatrix4x4";
      case EEffectParameter_VertexBoneMatrix4x4:
         return "VertexBoneMatrix4x4";
      case EEffectParameter_VertexCameraPosition:
         return "VertexCameraPosition";
      case EEffectParameter_VertexCameraDirection:
         return "VertexCameraDirection";
      case EEffectParameter_VertexLightPosition:
         return "VertexLightPosition";
      case EEffectParameter_VertexLightDirection:
         return "VertexLightDirection";
      //............................................................
      case EEffectParameter_FragmentCameraPosition:
         return "FragmentCameraPosition";
      case EEffectParameter_FragmentCameraDirection:
         return "FragmentCameraDirection";
      case EEffectParameter_FragmentLightPosition:
         return "FragmentLightPosition";
      case EEffectParameter_FragmentLightDirection:
         return "FragmentLightDirection";
      case EEffectParameter_FragmentLightDepth:
         return "FragmentLightDepth";
      case EEffectParameter_FragmentShadowMaterial:
         return "FragmentShadowMaterial";
      case EEffectParameter_FragmentShadowMaterialInv:
         return "FragmentShadowMaterialInv";
      case EEffectParameter_FragmentColor:
         return "FragmentColor";
      case EEffectParameter_FragmentAlpha:
         return "FragmentAlpha";
      case EEffectParameter_FragmentVertexColor:
         return "FragmentVertexColor";
      case EEffectParameter_FragmentAmbientColor:
         return "FragmentAmbientColor";
      case EEffectParameter_FragmentDiffuseColor:
         return "FragmentDiffuseColor";
      case EEffectParameter_FragmentDiffuseViewColor:
         return "FragmentDiffuseViewColor";
      case EEffectParameter_FragmentSpecularColor:
         return "FragmentSpecularColor";
      case EEffectParameter_FragmentSpecular:
         return "FragmentSpecular";
      case EEffectParameter_FragmentSpecularViewColor:
         return "FragmentSpecularViewColor";
      case EEffectParameter_FragmentSpecularView:
         return "FragmentSpecularView";
      case EEffectParameter_FragmentReflectColor:
         return "ReflectColor";
   }
   return "Unknown";
}

MO_NAMESPACE_END
<|endoftext|>


<commit_before><commit_msg>The min error is 0.2 instead of 0.1<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "views/widget/tooltip_manager.h"

#include <vector>

#include "app/gfx/text_elider.h"
#include "views/screen.h"

namespace views {

// Maximum number of characters we allow in a tooltip.
static const size_t kMaxTooltipLength = 1024;

// Maximum number of lines we allow in the tooltip.
static const size_t kMaxLines = 6;

// Breaks |text| along line boundaries, placing each line of text into lines.
static void SplitTooltipString(const std::wstring& text,
                               std::vector<std::wstring>* lines) {
  size_t index = 0;
  size_t next_index;
  while ((next_index = text.find(TooltipManager::GetLineSeparator(), index))
         != std::wstring::npos && lines->size() < kMaxLines) {
    lines->push_back(text.substr(index, next_index - index));
    index = next_index + TooltipManager::GetLineSeparator().size();
  }
  if (next_index != text.size() && lines->size() < kMaxLines)
    lines->push_back(text.substr(index, text.size() - index));
}

// static
int TooltipManager::GetMaxWidth(int x, int y) {
  gfx::Rect monitor_bounds =
      Screen::GetMonitorAreaNearestPoint(gfx::Point(x, y));
  // We don't want the tooltip to get too big, otherwise it looks wrong.
  return monitor_bounds.width() == 0 ? 400 : monitor_bounds.width() / 4;
}

// static
void TooltipManager::TrimTooltipToFit(std::wstring* text,
                                      int* max_width,
                                      int* line_count,
                                      int x,
                                      int y) {
  *max_width = 0;
  *line_count = 0;

  // Clamp the tooltip length to kMaxTooltipLength so that we don't
  // accidentally DOS the user with a mega tooltip.
  if (text->length() > kMaxTooltipLength)
    *text = text->substr(0, kMaxTooltipLength);

  // Determine the available width for the tooltip.
  int available_width = GetMaxWidth(x, y);

  // Split the string.
  std::vector<std::wstring> lines;
  SplitTooltipString(*text, &lines);
  *line_count = static_cast<int>(lines.size());

  // Format each line to fit.
  gfx::Font font = GetDefaultFont();
  std::wstring result;
  for (std::vector<std::wstring>::iterator i = lines.begin(); i != lines.end();
       ++i) {
    std::wstring elided_text = gfx::ElideText(*i, font, available_width);
    *max_width = std::max(*max_width, font.GetStringWidth(elided_text));
    if (i == lines.begin() && i + 1 == lines.end()) {
      *text = elided_text;
      return;
    }
    if (!result.empty())
      result.append(GetLineSeparator());
    result.append(elided_text);
  }
  *text = result;
}

}  // namespace views
<commit_msg>Fix tab and button tooltips being truncated with ellipsis.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "views/widget/tooltip_manager.h"

#include <vector>

#include "app/gfx/text_elider.h"
#include "views/screen.h"

namespace views {

// Maximum number of characters we allow in a tooltip.
static const size_t kMaxTooltipLength = 1024;

// Maximum number of lines we allow in the tooltip.
static const size_t kMaxLines = 6;

// Breaks |text| along line boundaries, placing each line of text into lines.
static void SplitTooltipString(const std::wstring& text,
                               std::vector<std::wstring>* lines) {
  size_t index = 0;
  size_t next_index;
  while ((next_index = text.find(TooltipManager::GetLineSeparator(), index))
         != std::wstring::npos && lines->size() < kMaxLines) {
    lines->push_back(text.substr(index, next_index - index));
    index = next_index + TooltipManager::GetLineSeparator().size();
  }
  if (next_index != text.size() && lines->size() < kMaxLines)
    lines->push_back(text.substr(index, text.size() - index));
}

// static
int TooltipManager::GetMaxWidth(int x, int y) {
  gfx::Rect monitor_bounds =
      Screen::GetMonitorAreaNearestPoint(gfx::Point(x, y));
  // Allow the tooltip to be almost as wide as the screen.
  // Otherwise, we would truncate important text, since we're not word-wrapping
  // the text onto multiple lines.
  return monitor_bounds.width() == 0 ? 800 : monitor_bounds.width() - 30;
}

// static
void TooltipManager::TrimTooltipToFit(std::wstring* text,
                                      int* max_width,
                                      int* line_count,
                                      int x,
                                      int y) {
  *max_width = 0;
  *line_count = 0;

  // Clamp the tooltip length to kMaxTooltipLength so that we don't
  // accidentally DOS the user with a mega tooltip.
  if (text->length() > kMaxTooltipLength)
    *text = text->substr(0, kMaxTooltipLength);

  // Determine the available width for the tooltip.
  int available_width = GetMaxWidth(x, y);

  // Split the string.
  std::vector<std::wstring> lines;
  SplitTooltipString(*text, &lines);
  *line_count = static_cast<int>(lines.size());

  // Format each line to fit.
  gfx::Font font = GetDefaultFont();
  std::wstring result;
  for (std::vector<std::wstring>::iterator i = lines.begin(); i != lines.end();
       ++i) {
    std::wstring elided_text = gfx::ElideText(*i, font, available_width);
    *max_width = std::max(*max_width, font.GetStringWidth(elided_text));
    if (i == lines.begin() && i + 1 == lines.end()) {
      *text = elided_text;
      return;
    }
    if (!result.empty())
      result.append(GetLineSeparator());
    result.append(elided_text);
  }
  *text = result;
}

}  // namespace views
<|endoftext|>