<commit_before>
#include "porting.hpp"
#include "config.hpp"
#include "hamsterdb.hpp"
#include "endian.hpp"
#include "os.hpp"
#include "misc.hpp"

static ham_u8_t aeskey[16]={
    0x00, 0x01, 0x02, 0x03,
    0x04, 0x05, 0x06, 0x07,
    0x08, 0x09, 0x0a, 0x0b,
    0x0c, 0x0d, 0x0e, 0x0f
};

static int
my_compare_keys(ham_db_t *db,
                const ham_u8_t *lhs, ham_size_t lhs_length,
                const ham_u8_t *rhs, ham_size_t rhs_length)
{
    unsigned ulhs, urhs;

    (void)db;

    memcpy(&ulhs, lhs, sizeof(ulhs));
    memcpy(&urhs, rhs, sizeof(urhs));
    ulhs=ham_db2h32(ulhs);
    urhs=ham_db2h32(urhs);

    if (ulhs<urhs)
        return -1;
    if (ulhs==urhs)
        return 0;
    return 1;
}

hamsterdb::~hamsterdb()
{
    if (m_db) {
        ham_delete(m_db);
        m_db=0;
    }

    if (m_env) {
        ham_env_delete(m_env);
        m_env=0;
    }

    print_profile();
}

ham_status_t
hamsterdb::create()
{
    ham_status_t st;
    ham_u32_t flags=0;
    ham_parameter_t params[6];

    if (!m_env) {
        st=ham_env_new(&m_env);
        if (st)
            return (st);
    }

    if (!m_db) {
        st=ham_new(&m_db);
        if (st)
            return (st);
    }

    params[0].name=HAM_PARAM_CACHESIZE;
    params[0].value=m_config->cachesize;
    params[1].name=HAM_PARAM_KEYSIZE;
    params[1].value=m_config->keysize;
    params[2].name=HAM_PARAM_PAGESIZE;
    params[2].value=m_config->pagesize;
    params[3].name=HAM_PARAM_DATA_ACCESS_MODE;
    params[3].value=m_config->data_access_mode;
    params[4].name=0;
    params[4].value=0;

    flags|=m_config->inmemory?HAM_IN_MEMORY_DB:0;
    flags|=m_config->no_mmap?HAM_DISABLE_MMAP:0;
    flags|=m_config->lock_excl?HAM_LOCK_EXCLUSIVE:0;
    flags|=m_config->duplicate?HAM_ENABLE_DUPLICATES:0;
    flags|=m_config->recovery?HAM_ENABLE_RECOVERY:0;
    flags|=m_config->cacheunlimited?HAM_CACHE_UNLIMITED:0;
    flags|=m_config->sort_dupes?HAM_SORT_DUPLICATES:0;
    flags|=m_config->enable_transactions?HAM_ENABLE_TRANSACTIONS:0;
    flags|=m_config->use_writethrough?HAM_WRITE_THROUGH:0;

    os::unlink(DB_PATH "test-ham.db");

    timer t(this, timer::misc);

    /*
     * aes-encrypted databases are created in the environment
     *
     * !!
     * currently, all other parameters are ignored
     */
    if (m_config->aes_encrypt) {
        st=ham_env_create_ex(m_env, DB_PATH "test-ham.db", flags, 0664, 0);
        if (st)
            return (st);
        st=ham_env_enable_encryption(m_env, aeskey, 0);
        if (st)
            return (st);
        st=ham_env_create_db(m_env, m_db, 1, 0, 0);
        if (st)
            return (st);
    }
    else {
        st=ham_create_ex(m_db, DB_PATH "test-ham.db", flags, 0664, &params[0]);
        if (st)
            return (st);
    }

    if (m_config->compression) {
        st=ham_enable_compression(m_db, 0, 0);
        if (st)
            return (st);
    }

    if (m_config->numeric) {
        st=ham_set_compare_func(m_db, my_compare_keys);
        if (st)
            return (st);
    }

    st=ham_cursor_create(m_db, 0, 0, &m_cursor);
    if (st)
        return (st);

    return (0);
}

ham_status_t
hamsterdb::open()
{
    ham_status_t st;
    ham_u32_t flags=0;
    ham_parameter_t params[6];

    timer t(this, timer::misc);

    if (!m_env) {
        st=ham_env_new(&m_env);
        if (st)
            return (st);
    }

    if (!m_db) {
        st=ham_new(&m_db);
        if (st)
            return (st);
    }

    params[0].name=HAM_PARAM_DATA_ACCESS_MODE;
    params[0].value=m_config->data_access_mode;
    params[1].name=0;
    params[1].value=0;

    flags|=m_config->no_mmap?HAM_DISABLE_MMAP:0;
    flags|=m_config->lock_excl?HAM_LOCK_EXCLUSIVE:0;
    flags|=m_config->cacheunlimited?HAM_CACHE_UNLIMITED:0;
    flags|=m_config->sort_dupes?HAM_SORT_DUPLICATES:0;
    flags|=m_config->enable_transactions?HAM_ENABLE_TRANSACTIONS:0;
    flags|=m_config->use_writethrough?HAM_WRITE_THROUGH:0;

    /*
     * aes encrypted databases are opened from an environment
     */
    if (m_config->aes_encrypt) {
        st=ham_env_open_ex(m_env, DB_PATH "test-ham.db", flags, 0);
        if (st)
            return (st);
        st=ham_env_enable_encryption(m_env, aeskey, 0);
        if (st)
            return (st);
        st=ham_env_open_db(m_env, m_db, 1, 0, &params[0]);
        if (st)
            return (st);
    }
    else {
        st=ham_open_ex(m_db, DB_PATH "test-ham.db", flags, &params[0]);
        if (st)
            return (st);
    }

    if (m_config->compression) {
        st=ham_enable_compression(m_db, 0, 0);
        if (st)
            return (st);
    }

    if (m_config->numeric) {
        st=ham_set_compare_func(m_db, my_compare_keys);
        if (st)
            return (st);
        if (m_config->sort_dupes) {
            st=ham_set_duplicate_compare_func(m_db, my_compare_keys);
            if (st)
                return (st);
        }
    }

    st=ham_cursor_create(m_db, 0, 0, &m_cursor);
    if (st)
        return (st);

    return (0);
}

ham_status_t
hamsterdb::close()
{
    timer t(this, timer::misc);
    ham_status_t st=0;

    if (m_cursor) {
        st=ham_cursor_close(m_cursor);
        if (st)
            return (st);
        m_cursor=0;
    }

    if (m_txn) {
        st=ham_txn_commit(m_txn, 0);
        if (st)
            return (st);
        m_txn=0;
    }

    if (m_db) {
        st=ham_close(m_db, HAM_AUTO_CLEANUP);
        if (st)
            return (st);
        m_db=0;
    }

    if (m_env)
        st=ham_env_close(m_env, 0);
    return (st);
}

ham_status_t
hamsterdb::flush()
{
    timer t(this, timer::misc);

    return (ham_flush(m_db, 0));
}

ham_status_t
hamsterdb::insert(ham_key_t *key, ham_record_t *record)
{
    ham_u32_t flags=0;

    if (m_config->hints&HAM_HINT_RANDOM_ACCESS)
        flags|=HAM_HINT_RANDOM_ACCESS;
    if (m_config->hints&HAM_HINT_SEQUENTIAL)
        flags|=HAM_HINT_SEQUENTIAL;
    if (m_config->hints&HAM_HINT_UBER_FAST_ACCESS)
        flags|=HAM_HINT_UBER_FAST_ACCESS;

    if (m_config->use_cursors) {

        flags|=m_config->hints&HAM_HINT_APPEND;

        if (m_config->overwrite)
            flags|=HAM_OVERWRITE;
        else if (m_config->duplicate) {
            flags|=HAM_DUPLICATE;
            flags|=m_config->dupe_flags;
        }

        timer t(this, timer::cursor);
        return (ham_cursor_insert(m_cursor, key, record, flags));
    }
    else {
        if (m_config->overwrite)
            flags|=HAM_OVERWRITE;
        if (m_config->duplicate)
            flags|=HAM_DUPLICATE;

        timer t(this, timer::insert);
        return (ham_insert(m_db, m_txn, key, record, flags));
    }
}

ham_status_t
hamsterdb::erase(ham_key_t *key)
{
    ham_status_t st;
    ham_u32_t flags=0;

    if (m_config->hints&HAM_HINT_RANDOM_ACCESS)
        flags|=HAM_HINT_RANDOM_ACCESS;
    if (m_config->hints&HAM_HINT_SEQUENTIAL)
        flags|=HAM_HINT_SEQUENTIAL;
    if (m_config->hints&HAM_HINT_UBER_FAST_ACCESS)
        flags|=HAM_HINT_UBER_FAST_ACCESS;

    if (m_config->use_cursors) {
        timer t(this, timer::cursor);
        st=ham_cursor_find(m_cursor, key, flags);
        if (st)
            return (st);
        return (ham_cursor_erase(m_cursor, flags));
    }
    else {
        timer t(this, timer::erase);
        return (ham_erase(m_db, m_txn, key, flags));
    }
}

ham_status_t
hamsterdb::find(ham_key_t *key, ham_record_t *record)
{
    ham_status_t st;
    ham_u32_t flags=0;

    if (m_config->hints&HAM_HINT_RANDOM_ACCESS)
        flags|=HAM_HINT_RANDOM_ACCESS;
    if (m_config->hints&HAM_HINT_SEQUENTIAL)
        flags|=HAM_HINT_SEQUENTIAL;
    if (m_config->hints&HAM_HINT_UBER_FAST_ACCESS)
        flags|=HAM_HINT_UBER_FAST_ACCESS;

    if (m_config->direct_access && m_config->inmemory)
        flags|=HAM_DIRECT_ACCESS;

    if (m_config->use_cursors) {
        timer t(this, timer::cursor);
        st=ham_cursor_find(m_cursor, key, flags);
        if (st)
            return (st);
        return (ham_cursor_move(m_cursor, 0, record, flags));
    }
    else {
        timer t(this, timer::find);
        return (ham_find(m_db, m_txn, key, record, flags));
    }
}

ham_status_t
hamsterdb::txn_begin(void)
{
    assert(m_txn==0);

    return (ham_txn_begin(&m_txn, m_db, 0));
}

ham_status_t
hamsterdb::txn_commit(void)
{
    assert(m_txn!=0);

    ham_status_t st=ham_txn_commit(m_txn, 0);
    if (st)
        return (st);
    m_txn=0;
    return (0);
}

const char *
hamsterdb::get_name(void)
{
    return ("hamsterdb");
}

ham_status_t
hamsterdb::check_integrity(void)
{
	return ham_check_integrity(m_db, 0);
}

void *
hamsterdb::create_cursor(void)
{
    ham_cursor_t *cursor;

    ham_status_t st=ham_cursor_create(m_db, m_txn, 0, &cursor);
    if (st) {
        TRACE(("failed to create cursor: %d\n", st));
        exit(-1);
    }

    return ((void *)cursor);
}

ham_status_t
hamsterdb::get_previous(void *cursor, ham_key_t *key,
                    ham_record_t *record, int flags)
{
    timer t(this, timer::cursor);

    if (m_config->direct_access && m_config->inmemory)
        flags|=HAM_DIRECT_ACCESS;

    return (ham_cursor_move((ham_cursor_t *)cursor, key, record,
                    HAM_CURSOR_PREVIOUS|flags));
}

ham_status_t
hamsterdb::get_next(void *cursor, ham_key_t *key, ham_record_t *record,
                int flags)
{
    timer t(this, timer::cursor);

    if (m_config->direct_access && m_config->inmemory)
        flags|=HAM_DIRECT_ACCESS;

    return (ham_cursor_move((ham_cursor_t *)cursor, key, record,
                    HAM_CURSOR_NEXT|flags));
}

void
hamsterdb::close_cursor(void *cursor)
{
    ham_status_t st=ham_cursor_close((ham_cursor_t *)cursor);
    if (st) {
        TRACE(("failed to close cursor: %d\n", st));
        exit(-1);
    }
}
<commit_msg>now using the transaction handle when verifying the integrity<commit_after>
#include "porting.hpp"
#include "config.hpp"
#include "hamsterdb.hpp"
#include "endian.hpp"
#include "os.hpp"
#include "misc.hpp"

static ham_u8_t aeskey[16]={
    0x00, 0x01, 0x02, 0x03,
    0x04, 0x05, 0x06, 0x07,
    0x08, 0x09, 0x0a, 0x0b,
    0x0c, 0x0d, 0x0e, 0x0f
};

static int
my_compare_keys(ham_db_t *db,
                const ham_u8_t *lhs, ham_size_t lhs_length,
                const ham_u8_t *rhs, ham_size_t rhs_length)
{
    unsigned ulhs, urhs;

    (void)db;

    memcpy(&ulhs, lhs, sizeof(ulhs));
    memcpy(&urhs, rhs, sizeof(urhs));
    ulhs=ham_db2h32(ulhs);
    urhs=ham_db2h32(urhs);

    if (ulhs<urhs)
        return -1;
    if (ulhs==urhs)
        return 0;
    return 1;
}

hamsterdb::~hamsterdb()
{
    if (m_db) {
        ham_delete(m_db);
        m_db=0;
    }

    if (m_env) {
        ham_env_delete(m_env);
        m_env=0;
    }

    print_profile();
}

ham_status_t
hamsterdb::create()
{
    ham_status_t st;
    ham_u32_t flags=0;
    ham_parameter_t params[6];

    if (!m_env) {
        st=ham_env_new(&m_env);
        if (st)
            return (st);
    }

    if (!m_db) {
        st=ham_new(&m_db);
        if (st)
            return (st);
    }

    params[0].name=HAM_PARAM_CACHESIZE;
    params[0].value=m_config->cachesize;
    params[1].name=HAM_PARAM_KEYSIZE;
    params[1].value=m_config->keysize;
    params[2].name=HAM_PARAM_PAGESIZE;
    params[2].value=m_config->pagesize;
    params[3].name=HAM_PARAM_DATA_ACCESS_MODE;
    params[3].value=m_config->data_access_mode;
    params[4].name=0;
    params[4].value=0;

    flags|=m_config->inmemory?HAM_IN_MEMORY_DB:0;
    flags|=m_config->no_mmap?HAM_DISABLE_MMAP:0;
    flags|=m_config->lock_excl?HAM_LOCK_EXCLUSIVE:0;
    flags|=m_config->duplicate?HAM_ENABLE_DUPLICATES:0;
    flags|=m_config->recovery?HAM_ENABLE_RECOVERY:0;
    flags|=m_config->cacheunlimited?HAM_CACHE_UNLIMITED:0;
    flags|=m_config->sort_dupes?HAM_SORT_DUPLICATES:0;
    flags|=m_config->enable_transactions?HAM_ENABLE_TRANSACTIONS:0;
    flags|=m_config->use_writethrough?HAM_WRITE_THROUGH:0;

    os::unlink(DB_PATH "test-ham.db");

    timer t(this, timer::misc);

    /*
     * aes-encrypted databases are created in the environment
     *
     * !!
     * currently, all other parameters are ignored
     */
    if (m_config->aes_encrypt) {
        st=ham_env_create_ex(m_env, DB_PATH "test-ham.db", flags, 0664, 0);
        if (st)
            return (st);
        st=ham_env_enable_encryption(m_env, aeskey, 0);
        if (st)
            return (st);
        st=ham_env_create_db(m_env, m_db, 1, 0, 0);
        if (st)
            return (st);
    }
    else {
        st=ham_create_ex(m_db, DB_PATH "test-ham.db", flags, 0664, &params[0]);
        if (st)
            return (st);
    }

    if (m_config->compression) {
        st=ham_enable_compression(m_db, 0, 0);
        if (st)
            return (st);
    }

    if (m_config->numeric) {
        st=ham_set_compare_func(m_db, my_compare_keys);
        if (st)
            return (st);
    }

    st=ham_cursor_create(m_db, 0, 0, &m_cursor);
    if (st)
        return (st);

    return (0);
}

ham_status_t
hamsterdb::open()
{
    ham_status_t st;
    ham_u32_t flags=0;
    ham_parameter_t params[6];

    timer t(this, timer::misc);

    if (!m_env) {
        st=ham_env_new(&m_env);
        if (st)
            return (st);
    }

    if (!m_db) {
        st=ham_new(&m_db);
        if (st)
            return (st);
    }

    params[0].name=HAM_PARAM_DATA_ACCESS_MODE;
    params[0].value=m_config->data_access_mode;
    params[1].name=0;
    params[1].value=0;

    flags|=m_config->no_mmap?HAM_DISABLE_MMAP:0;
    flags|=m_config->lock_excl?HAM_LOCK_EXCLUSIVE:0;
    flags|=m_config->cacheunlimited?HAM_CACHE_UNLIMITED:0;
    flags|=m_config->sort_dupes?HAM_SORT_DUPLICATES:0;
    flags|=m_config->enable_transactions?HAM_ENABLE_TRANSACTIONS:0;
    flags|=m_config->use_writethrough?HAM_WRITE_THROUGH:0;

    /*
     * aes encrypted databases are opened from an environment
     */
    if (m_config->aes_encrypt) {
        st=ham_env_open_ex(m_env, DB_PATH "test-ham.db", flags, 0);
        if (st)
            return (st);
        st=ham_env_enable_encryption(m_env, aeskey, 0);
        if (st)
            return (st);
        st=ham_env_open_db(m_env, m_db, 1, 0, &params[0]);
        if (st)
            return (st);
    }
    else {
        st=ham_open_ex(m_db, DB_PATH "test-ham.db", flags, &params[0]);
        if (st)
            return (st);
    }

    if (m_config->compression) {
        st=ham_enable_compression(m_db, 0, 0);
        if (st)
            return (st);
    }

    if (m_config->numeric) {
        st=ham_set_compare_func(m_db, my_compare_keys);
        if (st)
            return (st);
        if (m_config->sort_dupes) {
            st=ham_set_duplicate_compare_func(m_db, my_compare_keys);
            if (st)
                return (st);
        }
    }

    st=ham_cursor_create(m_db, 0, 0, &m_cursor);
    if (st)
        return (st);

    return (0);
}

ham_status_t
hamsterdb::close()
{
    timer t(this, timer::misc);
    ham_status_t st=0;

    if (m_cursor) {
        st=ham_cursor_close(m_cursor);
        if (st)
            return (st);
        m_cursor=0;
    }

    if (m_txn) {
        st=ham_txn_commit(m_txn, 0);
        if (st)
            return (st);
        m_txn=0;
    }

    if (m_db) {
        st=ham_close(m_db, HAM_AUTO_CLEANUP);
        if (st)
            return (st);
        m_db=0;
    }

    if (m_env)
        st=ham_env_close(m_env, 0);
    return (st);
}

ham_status_t
hamsterdb::flush()
{
    timer t(this, timer::misc);

    return (ham_flush(m_db, 0));
}

ham_status_t
hamsterdb::insert(ham_key_t *key, ham_record_t *record)
{
    ham_u32_t flags=0;

    if (m_config->hints&HAM_HINT_RANDOM_ACCESS)
        flags|=HAM_HINT_RANDOM_ACCESS;
    if (m_config->hints&HAM_HINT_SEQUENTIAL)
        flags|=HAM_HINT_SEQUENTIAL;
    if (m_config->hints&HAM_HINT_UBER_FAST_ACCESS)
        flags|=HAM_HINT_UBER_FAST_ACCESS;

    if (m_config->use_cursors) {

        flags|=m_config->hints&HAM_HINT_APPEND;

        if (m_config->overwrite)
            flags|=HAM_OVERWRITE;
        else if (m_config->duplicate) {
            flags|=HAM_DUPLICATE;
            flags|=m_config->dupe_flags;
        }

        timer t(this, timer::cursor);
        return (ham_cursor_insert(m_cursor, key, record, flags));
    }
    else {
        if (m_config->overwrite)
            flags|=HAM_OVERWRITE;
        if (m_config->duplicate)
            flags|=HAM_DUPLICATE;

        timer t(this, timer::insert);
        return (ham_insert(m_db, m_txn, key, record, flags));
    }
}

ham_status_t
hamsterdb::erase(ham_key_t *key)
{
    ham_status_t st;
    ham_u32_t flags=0;

    if (m_config->hints&HAM_HINT_RANDOM_ACCESS)
        flags|=HAM_HINT_RANDOM_ACCESS;
    if (m_config->hints&HAM_HINT_SEQUENTIAL)
        flags|=HAM_HINT_SEQUENTIAL;
    if (m_config->hints&HAM_HINT_UBER_FAST_ACCESS)
        flags|=HAM_HINT_UBER_FAST_ACCESS;

    if (m_config->use_cursors) {
        timer t(this, timer::cursor);
        st=ham_cursor_find(m_cursor, key, flags);
        if (st)
            return (st);
        return (ham_cursor_erase(m_cursor, flags));
    }
    else {
        timer t(this, timer::erase);
        return (ham_erase(m_db, m_txn, key, flags));
    }
}

ham_status_t
hamsterdb::find(ham_key_t *key, ham_record_t *record)
{
    ham_status_t st;
    ham_u32_t flags=0;

    if (m_config->hints&HAM_HINT_RANDOM_ACCESS)
        flags|=HAM_HINT_RANDOM_ACCESS;
    if (m_config->hints&HAM_HINT_SEQUENTIAL)
        flags|=HAM_HINT_SEQUENTIAL;
    if (m_config->hints&HAM_HINT_UBER_FAST_ACCESS)
        flags|=HAM_HINT_UBER_FAST_ACCESS;

    if (m_config->direct_access && m_config->inmemory)
        flags|=HAM_DIRECT_ACCESS;

    if (m_config->use_cursors) {
        timer t(this, timer::cursor);
        st=ham_cursor_find(m_cursor, key, flags);
        if (st)
            return (st);
        return (ham_cursor_move(m_cursor, 0, record, flags));
    }
    else {
        timer t(this, timer::find);
        return (ham_find(m_db, m_txn, key, record, flags));
    }
}

ham_status_t
hamsterdb::txn_begin(void)
{
    assert(m_txn==0);

    return (ham_txn_begin(&m_txn, m_db, 0));
}

ham_status_t
hamsterdb::txn_commit(void)
{
    assert(m_txn!=0);

    ham_status_t st=ham_txn_commit(m_txn, 0);
    if (st)
        return (st);
    m_txn=0;
    return (0);
}

const char *
hamsterdb::get_name(void)
{
    return ("hamsterdb");
}

ham_status_t
hamsterdb::check_integrity(void)
{
	return ham_check_integrity(m_db, m_txn);
}

void *
hamsterdb::create_cursor(void)
{
    ham_cursor_t *cursor;

    ham_status_t st=ham_cursor_create(m_db, m_txn, 0, &cursor);
    if (st) {
        TRACE(("failed to create cursor: %d\n", st));
        exit(-1);
    }

    return ((void *)cursor);
}

ham_status_t
hamsterdb::get_previous(void *cursor, ham_key_t *key,
                    ham_record_t *record, int flags)
{
    timer t(this, timer::cursor);

    if (m_config->direct_access && m_config->inmemory)
        flags|=HAM_DIRECT_ACCESS;

    return (ham_cursor_move((ham_cursor_t *)cursor, key, record,
                    HAM_CURSOR_PREVIOUS|flags));
}

ham_status_t
hamsterdb::get_next(void *cursor, ham_key_t *key, ham_record_t *record,
                int flags)
{
    timer t(this, timer::cursor);

    if (m_config->direct_access && m_config->inmemory)
        flags|=HAM_DIRECT_ACCESS;

    return (ham_cursor_move((ham_cursor_t *)cursor, key, record,
                    HAM_CURSOR_NEXT|flags));
}

void
hamsterdb::close_cursor(void *cursor)
{
    ham_status_t st=ham_cursor_close((ham_cursor_t *)cursor);
    if (st) {
        TRACE(("failed to close cursor: %d\n", st));
        exit(-1);
    }
}
<|endoftext|>


<commit_before>#include "PortalGame.h"
#include "PhysicsController.h"
#include "Sphere.h"
#include "PhysicsCamera.h"
#include "Box.h"
#include "Cylinder.h"
#include "Steerable3DController.h"
#include "Ground.h"
#include "Content.h"
#include <btBulletDynamicsCommon.h>
#include <gtc/quaternion.hpp>
#include <gtx/quaternion.hpp>
#include <gtx/euler_angles.hpp>
#include <gtx/norm.hpp>
#include "VectorDrawer.h"

using namespace BGE;

PortalGame::PortalGame(void)
{
	physicsFactory = NULL;
	dynamicsWorld = NULL;
	broadphase = NULL;
	dispatcher = NULL;
	solver = NULL;
	fullscreen = false;
}

PortalGame::~PortalGame(void)
{
}

std::shared_ptr<GameComponent> station;
//float theta = 0.0f;

bool PortalGame::Initialise()
{
	riftEnabled = false;
	// Set up the collision configuration and dispatcher
    collisionConfiguration = new btDefaultCollisionConfiguration();
    dispatcher = new btCollisionDispatcher(collisionConfiguration);

    // The world.
	btVector3 worldMin(-1000,-1000,-1000);
	btVector3 worldMax(1000,1000,1000);
	broadphase = new btAxisSweep3(worldMin,worldMax);
	solver = new btSequentialImpulseConstraintSolver();
	dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration);
    dynamicsWorld->setGravity(btVector3(0,-9,0));

	width = 800;
	height = 600;

	physicsFactory = make_shared<PhysicsFactory>(dynamicsWorld);

	physicsFactory->CreateGroundPhysics();
	physicsFactory->CreateCameraPhysics();

	//std::shared_ptr<GameComponent> box = make_shared<Box>(1, 1, 1);
	//box->position = glm::vec3(0, 5, -20);
	//Attach(box);

	//non kinematic cyl
	shared_ptr<PhysicsController> colCyl = physicsFactory->CreateCylinder(2,1, glm::vec3(5, 0, -10), glm::quat());

	colCyl->tag="colObject1";

	//box for collision
	shared_ptr<PhysicsController> colBox = physicsFactory->CreateBox(1,1,1, glm::vec3(5, 0, 0), glm::quat());
	colBox->tag="colObject2";

	//create walls for games
	//left wall for box 1
	shared_ptr<PhysicsController> leftWall1 = physicsFactory->CreateBox(0.5,10,15, glm::vec3(-10, 0, -20), glm::quat());
	leftWall1->diffuse = glm::vec3(1,0,1);
	//leftWall1

	//right wall for box 1
	shared_ptr<PhysicsController> rightWall1 = physicsFactory->CreateBox(0.5,10,15, glm::vec3(-2, 0, -20), glm::quat());
	rightWall1->diffuse = glm::vec3(1,0,1);

	//top wall for box 1
	shared_ptr<PhysicsController> topWall1 = physicsFactory->CreateBox(15,0.5,15, glm::vec3(-4, 0, -20), glm::quat());
	topWall1->diffuse = glm::vec3(1,0,1);

	//physicsFactory->CreateWall(glm::vec3(-20,0,20), 50, 10);

	 //Now some constraints
	/*shared_ptr<PhysicsController> box1 = physicsFactory->CreateBox(1,1,4, glm::vec3(5, 5, 0), glm::quat());
	shared_ptr<PhysicsController> box2 = physicsFactory->CreateBox(1,1,4, glm::vec3(5, 5, 5), glm::quat()); */
	//shared_ptr<PhysicsController> cap1 = physicsFactory->CreateCapsule(1,1, glm::vec3(5, 50, 5), glm::quat());
	//cap1->scale = glm::vec3(0.001,0.001,0.001);

	 //A hinge
	//btHingeConstraint * hinge = new btHingeConstraint(*box1->rigidBody, *box2->rigidBody, btVector3(0,0,2.5f),btVector3(0,0,-2.5f), btVector3(0,1,0), btVector3(0,1,0), true);
	//dynamicsWorld->addConstraint(hinge);

	//box1 = physicsFactory->CreateBox(1,1,4, glm::vec3(10, 5, 0), glm::quat());
	//box2 = physicsFactory->CreateBox(1,1,4, glm::vec3(10, 5, 5), glm::quat());
	//cap1 = physicsFactory->CreateCapsule(5,5, glm::vec3(5, 5, 5), glm::quat());

	//physicsFactory->CreateCylinder(10, 3, glm::vec3(0, 20, 0), glm::quat());

	///*std::shared_ptr<GameComponent> ship = make_shared<GameComponent>();
	//ship->ambient = glm::vec3(0.2f, 0.2, 0.2f);
	//ship->specular = glm::vec3(1.2f, 1.2f, 1.2f);
	//std::shared_ptr<Model> model = Content::LoadModel("cobramk3", glm::rotate(glm::mat4(1), 180.0f, GameComponent::basisUp));
	//std::shared_ptr<GameComponent> steerable = make_shared<Steerable3DController>(model);
	//steerable->position = glm::vec3(20, 5, -20);
	//std::shared_ptr<VectorDrawer> vectorDrawer = make_shared<VectorDrawer>();
	//vectorDrawer->scale = glm::vec3(5,5,10);
	//ship->Attach(steerable);
	//ship->Attach(model);
	//ship->Attach(vectorDrawer);
	//Attach(ship);*/

	//// Create a hierarchy
	//station = make_shared<GameComponent>();
	//station->worldMode = world_modes::from_self;
	//station->ambient = glm::vec3(0.2f, 0.2, 0.2f);
	//station->specular = glm::vec3(0,0,0);
	//station->scale = glm::vec3(2,2,2);
	//std::shared_ptr<Model> cmodel = Content::LoadModel("coriolis", glm::rotate(glm::mat4(1), 90.0f, GameComponent::basisUp));
	//station->Attach(cmodel);
	//station->Attach(make_shared<VectorDrawer>(glm::vec3(7,7,7)));
	//station->position = glm::vec3(40, 5, -20);
	//Attach(station);

	//// Add a child to the station and update by including the parent's world transform
	//std::shared_ptr<GameComponent> ship1 = make_shared<GameComponent>();
	//ship1->worldMode = world_modes::from_self_with_parent;
	//ship1->ambient = glm::vec3(0.2f, 0.2, 0.2f);
	//ship1->specular = glm::vec3(1.2f, 1.2f, 1.2f);
	//std::shared_ptr<Model> ana = Content::LoadModel("anaconda", glm::rotate(glm::mat4(1), 180.0f, GameComponent::basisUp));
	//ship1->Attach(ana);
	//ship1->position = glm::vec3(0, 0, -10);
	//station->Attach(ship1);

	//physicsFactory->CreateVehicle(glm::vec3(0,10,-30));

	// Create Inca Pyramid
	//position(), baseWidth, blockHeight, blockWidth, blockDepth
    //physicsFactory->CreateIncaPyramid(glm::vec3(20,0,-20), 6, 1.5, 1.5, 1.5);

	//Create Rag Doll
	//physicsFactory->CreateRagDoll(glm::vec3(25,0,-50));

	if (!Game::Initialise()) {
		return false;
	}

	camera->GetController()->position = glm::vec3(0,10, 0);

	return true;
}

void BGE::PortalGame::Update(float timeDelta)
{
	dynamicsWorld->stepSimulation(timeDelta,100);
	//station->Yaw(timeDelta * 20.0f);

	//collision detection check
	 int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();
        for (int i=0;i<numManifolds;i++)
        {
                btPersistentManifold* contactManifold =  dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
                btCollisionObject* obA = (btCollisionObject*)(contactManifold->getBody0());
				btCollisionObject* obB = (btCollisionObject*)(contactManifold->getBody1());
				// btCollisionObject* obA = (btCollisionObject*)(contactManifold->colCyl = physicsFactory->CreateCylinder(2,1, glm::vec3(5, 0, -10), glm::quat()); );
				//btCollisionObject* obB = (btCollisionObject*)(contactManifold->colBox = physicsFactory->CreateBox(1,1,1, glm::vec3(5, 0, 0), glm::quat()); );
                PhysicsController * pcA = reinterpret_cast<PhysicsController*>(obA->getUserPointer());
                PhysicsController * pcB = reinterpret_cast<PhysicsController*>(obB->getUserPointer());

                int numContacts = contactManifold->getNumContacts();
                if (numContacts > 0)
                {
                        if ((pcA != nullptr) && (pcB != nullptr))
                        {
							//PrintText("Collision between " + pcA->tag + " and " + pcB->tag);
							if (pcA->tag == "colObject1" && pcB->tag == "colObject2")
                            {
								  PrintText("Collision between " + pcA->tag + " and " + pcB->tag);
							}
							/*if (pcB->tag == "colObject1" && pcA->tag == "colObject2")
                            {
								  PrintText("Collision between " + pcA->tag + " and " + pcB->tag);
							}*/
                        }
                }
        }

	Game::Update(timeDelta);

}

void BGE::PortalGame::Cleanup()
{
	Game::Cleanup();
}
<commit_msg>Added Boxes and Stands<commit_after>#include "PortalGame.h"
#include "PhysicsController.h"
#include "Sphere.h"
#include "PhysicsCamera.h"
#include "Box.h"
#include "Cylinder.h"
#include "Steerable3DController.h"
#include "Ground.h"
#include "Content.h"
#include <btBulletDynamicsCommon.h>
#include <gtc/quaternion.hpp>
#include <gtx/quaternion.hpp>
#include <gtx/euler_angles.hpp>
#include <gtx/norm.hpp>
#include "VectorDrawer.h"

using namespace BGE;

PortalGame::PortalGame(void)
{
	physicsFactory = NULL;
	dynamicsWorld = NULL;
	broadphase = NULL;
	dispatcher = NULL;
	solver = NULL;
	fullscreen = false;
}

PortalGame::~PortalGame(void)
{
}

std::shared_ptr<GameComponent> station;
//float theta = 0.0f;

bool PortalGame::Initialise()
{
	riftEnabled = false;
	// Set up the collision configuration and dispatcher
    collisionConfiguration = new btDefaultCollisionConfiguration();
    dispatcher = new btCollisionDispatcher(collisionConfiguration);

    // The world.
	btVector3 worldMin(-1000,-1000,-1000);
	btVector3 worldMax(1000,1000,1000);
	broadphase = new btAxisSweep3(worldMin,worldMax);
	solver = new btSequentialImpulseConstraintSolver();
	dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration);
    dynamicsWorld->setGravity(btVector3(0,-9,0));

	width = 800;
	height = 600;

	physicsFactory = make_shared<PhysicsFactory>(dynamicsWorld);

	physicsFactory->CreateGroundPhysics();
	physicsFactory->CreateCameraPhysics();

	//std::shared_ptr<GameComponent> box = make_shared<Box>(1, 1, 1);
	//box->position = glm::vec3(0, 5, -20);
	//Attach(box);

	//non kinematic cyl
	shared_ptr<PhysicsController> colCyl = physicsFactory->CreateCylinder(2,1, glm::vec3(5, 0, -10), glm::quat());

	colCyl->tag="colObject1";
<<<<<<< HEAD

	//box for collision
	shared_ptr<PhysicsController> colBox = physicsFactory->CreateBox(1,1,1, glm::vec3(5, 0, 0), glm::quat());
	colBox->tag="colObject2";

	//create walls for games
	//left wall for box 1
	shared_ptr<PhysicsController> leftWall1 = physicsFactory->CreateBox(0.5,10,15, glm::vec3(-10, 0, -20), glm::quat());
	leftWall1->diffuse = glm::vec3(1,0,1);
	//leftWall1

	//right wall for box 1
	shared_ptr<PhysicsController> rightWall1 = physicsFactory->CreateBox(0.5,10,15, glm::vec3(-2, 0, -20), glm::quat());
	rightWall1->diffuse = glm::vec3(1,0,1);

	//top wall for box 1
	shared_ptr<PhysicsController> topWall1 = physicsFactory->CreateBox(15,0.5,15, glm::vec3(-4, 0, -20), glm::quat());
	topWall1->diffuse = glm::vec3(1,0,1);

=======

	//box for collision
	shared_ptr<PhysicsController> colBox = physicsFactory->CreateBox(1,1,1, glm::vec3(5, 0, 0), glm::quat());
	colBox->tag="colObject2";
>>>>>>> parent of 8bc7c50... Added in Stands and Boxes to hit

	//create walls for games
	//left wall for box 1
	shared_ptr<PhysicsController> leftWall1 = physicsFactory->CreateBox(0.5,10,15, glm::vec3(-10, 0, -20), glm::quat());
	leftWall1->diffuse = glm::vec3(1,0,1);
	//leftWall1

	//right wall for box 1
	shared_ptr<PhysicsController> rightWall1 = physicsFactory->CreateBox(0.5,10,15, glm::vec3(-2, 0, -20), glm::quat());
	rightWall1->diffuse = glm::vec3(1,0,1);

	//top wall for box 1
	shared_ptr<PhysicsController> topWall1 = physicsFactory->CreateBox(15,0.5,15, glm::vec3(-4, 0, -20), glm::quat());
	topWall1->diffuse = glm::vec3(1,0,1);

	//physicsFactory->CreateWall(glm::vec3(-20,0,20), 50, 10);

	 //Now some constraints
	/*shared_ptr<PhysicsController> box1 = physicsFactory->CreateBox(1,1,4, glm::vec3(5, 5, 0), glm::quat());
	shared_ptr<PhysicsController> box2 = physicsFactory->CreateBox(1,1,4, glm::vec3(5, 5, 5), glm::quat()); */
	//shared_ptr<PhysicsController> cap1 = physicsFactory->CreateCapsule(1,1, glm::vec3(5, 50, 5), glm::quat());
	//cap1->scale = glm::vec3(0.001,0.001,0.001);

	 //A hinge
	//btHingeConstraint * hinge = new btHingeConstraint(*box1->rigidBody, *box2->rigidBody, btVector3(0,0,2.5f),btVector3(0,0,-2.5f), btVector3(0,1,0), btVector3(0,1,0), true);
	//dynamicsWorld->addConstraint(hinge);

	//box1 = physicsFactory->CreateBox(1,1,4, glm::vec3(10, 5, 0), glm::quat());
	//box2 = physicsFactory->CreateBox(1,1,4, glm::vec3(10, 5, 5), glm::quat());
	//cap1 = physicsFactory->CreateCapsule(5,5, glm::vec3(5, 5, 5), glm::quat());

	//physicsFactory->CreateCylinder(10, 3, glm::vec3(0, 20, 0), glm::quat());

	///*std::shared_ptr<GameComponent> ship = make_shared<GameComponent>();
	//ship->ambient = glm::vec3(0.2f, 0.2, 0.2f);
	//ship->specular = glm::vec3(1.2f, 1.2f, 1.2f);
	//std::shared_ptr<Model> model = Content::LoadModel("cobramk3", glm::rotate(glm::mat4(1), 180.0f, GameComponent::basisUp));
	//std::shared_ptr<GameComponent> steerable = make_shared<Steerable3DController>(model);
	//steerable->position = glm::vec3(20, 5, -20);
	//std::shared_ptr<VectorDrawer> vectorDrawer = make_shared<VectorDrawer>();
	//vectorDrawer->scale = glm::vec3(5,5,10);
	//ship->Attach(steerable);
	//ship->Attach(model);
	//ship->Attach(vectorDrawer);
	//Attach(ship);*/

	//// Create a hierarchy
	//station = make_shared<GameComponent>();
	//station->worldMode = world_modes::from_self;
	//station->ambient = glm::vec3(0.2f, 0.2, 0.2f);
	//station->specular = glm::vec3(0,0,0);
	//station->scale = glm::vec3(2,2,2);
	//std::shared_ptr<Model> cmodel = Content::LoadModel("coriolis", glm::rotate(glm::mat4(1), 90.0f, GameComponent::basisUp));
	//station->Attach(cmodel);
	//station->Attach(make_shared<VectorDrawer>(glm::vec3(7,7,7)));
	//station->position = glm::vec3(40, 5, -20);
	//Attach(station);

	//// Add a child to the station and update by including the parent's world transform
	//std::shared_ptr<GameComponent> ship1 = make_shared<GameComponent>();
	//ship1->worldMode = world_modes::from_self_with_parent;
	//ship1->ambient = glm::vec3(0.2f, 0.2, 0.2f);
	//ship1->specular = glm::vec3(1.2f, 1.2f, 1.2f);
	//std::shared_ptr<Model> ana = Content::LoadModel("anaconda", glm::rotate(glm::mat4(1), 180.0f, GameComponent::basisUp));
	//ship1->Attach(ana);
	//ship1->position = glm::vec3(0, 0, -10);
	//station->Attach(ship1);

	//physicsFactory->CreateVehicle(glm::vec3(0,10,-30));

	// Create Inca Pyramid
	//position(), baseWidth, blockHeight, blockWidth, blockDepth
    //physicsFactory->CreateIncaPyramid(glm::vec3(20,0,-20), 6, 1.5, 1.5, 1.5);

	//Create Rag Doll
	//physicsFactory->CreateRagDoll(glm::vec3(25,0,-50));

	if (!Game::Initialise()) {
		return false;
	}

	camera->GetController()->position = glm::vec3(0,10, 0);

	return true;
}

void BGE::PortalGame::Update(float timeDelta)
{
	dynamicsWorld->stepSimulation(timeDelta,100);
	//station->Yaw(timeDelta * 20.0f);

	//collision detection check
	 int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();
        for (int i=0;i<numManifolds;i++)
        {
                btPersistentManifold* contactManifold =  dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
                btCollisionObject* obA = (btCollisionObject*)(contactManifold->getBody0());
				btCollisionObject* obB = (btCollisionObject*)(contactManifold->getBody1());
				// btCollisionObject* obA = (btCollisionObject*)(contactManifold->colCyl = physicsFactory->CreateCylinder(2,1, glm::vec3(5, 0, -10), glm::quat()); );
				//btCollisionObject* obB = (btCollisionObject*)(contactManifold->colBox = physicsFactory->CreateBox(1,1,1, glm::vec3(5, 0, 0), glm::quat()); );
                PhysicsController * pcA = reinterpret_cast<PhysicsController*>(obA->getUserPointer());
                PhysicsController * pcB = reinterpret_cast<PhysicsController*>(obB->getUserPointer());

                int numContacts = contactManifold->getNumContacts();
                if (numContacts > 0)
                {
                        if ((pcA != nullptr) && (pcB != nullptr))
                        {
							//PrintText("Collision between " + pcA->tag + " and " + pcB->tag);
							if (pcA->tag == "colObject1" && pcB->tag == "colObject2")
                            {
								  PrintText("Collision between " + pcA->tag + " and " + pcB->tag);
							}
							/*if (pcB->tag == "colObject1" && pcA->tag == "colObject2")
                            {
								  PrintText("Collision between " + pcA->tag + " and " + pcB->tag);
							}*/
                        }
                }
        }

	Game::Update(timeDelta);

}

void BGE::PortalGame::Cleanup()
{
	Game::Cleanup();
}
<|endoftext|>


<commit_before>#include "IteratorAnalysis.h"

#include "iterators/Dialect/Iterators/IR/Iterators.h"
#include "iterators/Utils/NameAssigner.h"
#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "llvm/ADT/TypeSwitch.h"

using namespace mlir;
using namespace mlir::iterators;

using SymbolTriple = std::tuple<SymbolRefAttr, SymbolRefAttr, SymbolRefAttr>;

/// Pre-assigns names for the Open/Next/Close functions of the given iterator
/// op. The conversion is expected to create these names in the lowering of
/// the corresponding op and can look them up in the lowering of downstream
/// iterators.
static SymbolTriple assignFunctionNames(Operation *op,
                                        NameAssigner &nameAssigner) {
  SmallVector<SymbolRefAttr, 3> symbols;
  for (auto suffix : {"open", "next", "close"}) {
    // Construct base name from op type and Open/Next/Close.
    auto baseName = StringAttr::get(
        op->getContext(),
        (op->getName().getStringRef() + Twine(".") + suffix).str());

    // Make name unique. This may increment uniqueNumber.
    StringAttr uniqueName = nameAssigner.assignName(baseName);

    auto symbol = SymbolRefAttr::get(op->getContext(), uniqueName);
    symbols.push_back(symbol);
  }
  return std::make_tuple(symbols[0], symbols[1], symbols[2]);
}

/// The state of ConstantStreamOp consists of a single number that corresponds
/// to the next number returned by the iterator.
static LLVM::LLVMStructType computeStateType(ConstantStreamOp op) {
  MLIRContext *context = op->getContext();
  Type i32 = IntegerType::get(context, /*width=*/32);
  return LLVM::LLVMStructType::getNewIdentified(
      context, "iterators.constant_stream_state", {i32});
}

/// The state of ReduceOp only consists of the state of its upstream iterator,
/// i.e., the state of the iterator that produces its input stream.
static LLVM::LLVMStructType
computeStateType(ReduceOp op, LLVM::LLVMStructType upstreamStateType) {
  return LLVM::LLVMStructType::getNewIdentified(
      op->getContext(), "iterators.reduce_state", {upstreamStateType});
}

/// Build IteratorInfo, assigning new unique names as needed.
/// Takes the `LLVM::LLVMStructType` as a parameter, to ensure proper build
/// order (all uses are visited before any def).
mlir::iterators::IteratorInfo::IteratorInfo(IteratorOpInterface op,
                                            NameAssigner &nameAssigner,
                                            LLVM::LLVMStructType t) {
  std::tie(openFunc, nextFunc, closeFunc) =
      assignFunctionNames(op, nameAssigner);
  stateType = t;
}

IteratorInfo mlir::iterators::IteratorAnalysis::getExpectedIteratorInfo(
    IteratorOpInterface op) const {
  auto it = opMap.find(op);
  assert(it != opMap.end() && "analysis does not contain this op");
  return it->getSecond();
}

void mlir::iterators::IteratorAnalysis::setIteratorInfo(
    IteratorOpInterface op, const IteratorInfo &info) {
  assert(info.stateType && "state type must be computed");
  auto inserted = opMap.insert({op, info});
  assert(inserted.second && "IteratorInfo already present");
}

template <typename OpTy>
static OpTy getSelfOrParentOfType(Operation *op) {
  auto maybe = dyn_cast<OpTy>(op);
  return maybe ? maybe : op->getParentOfType<OpTy>();
}

mlir::iterators::IteratorAnalysis::IteratorAnalysis(Operation *rootOp)
    : rootOp(rootOp), nameAssigner(getSelfOrParentOfType<ModuleOp>(rootOp)) {
  /// This needs to be built in use-def order so that all uses are visited
  /// before any def.
  rootOp->walk([&](IteratorOpInterface iteratorOp) {
    llvm::TypeSwitch<Operation *, void>(iteratorOp)
        /// The state of ConstantStreamOp consists of a single number that
        /// corresponds to the next number returned by the iterator.
        .Case<ConstantStreamOp>([&](auto op) {
          auto stateType = computeStateType(op);
          setIteratorInfo(op, IteratorInfo(op, nameAssigner, stateType));
        })
        /// The state of ReduceOp only consists of the state of its upstream
        /// iterator, i.e., the state of the iterator that produces its input
        /// stream.
        // TODO: ReduceOp verifier that op.input does not come from a bbArg.
        .Case<ReduceOp>([&](auto op) {
          Operation *def = op.input().getDefiningOp();
          auto stateType =
              computeStateType(op, getExpectedIteratorInfo(def).stateType);
          setIteratorInfo(op, IteratorInfo(op, nameAssigner, stateType));
        })
        .Default([&](auto op) { assert(false && "Unexpected op"); });
  });
}
<commit_msg>[Iterators] Clarify documentation of ConstantStreamOp. (#544)<commit_after>#include "IteratorAnalysis.h"

#include "iterators/Dialect/Iterators/IR/Iterators.h"
#include "iterators/Utils/NameAssigner.h"
#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "llvm/ADT/TypeSwitch.h"

using namespace mlir;
using namespace mlir::iterators;

using SymbolTriple = std::tuple<SymbolRefAttr, SymbolRefAttr, SymbolRefAttr>;

/// Pre-assigns names for the Open/Next/Close functions of the given iterator
/// op. The conversion is expected to create these names in the lowering of
/// the corresponding op and can look them up in the lowering of downstream
/// iterators.
static SymbolTriple assignFunctionNames(Operation *op,
                                        NameAssigner &nameAssigner) {
  SmallVector<SymbolRefAttr, 3> symbols;
  for (auto suffix : {"open", "next", "close"}) {
    // Construct base name from op type and Open/Next/Close.
    auto baseName = StringAttr::get(
        op->getContext(),
        (op->getName().getStringRef() + Twine(".") + suffix).str());

    // Make name unique. This may increment uniqueNumber.
    StringAttr uniqueName = nameAssigner.assignName(baseName);

    auto symbol = SymbolRefAttr::get(op->getContext(), uniqueName);
    symbols.push_back(symbol);
  }
  return std::make_tuple(symbols[0], symbols[1], symbols[2]);
}

/// The state of ConstantStreamOp consists of a single number that corresponds
/// to the index of the next struct returned by the iterator.
static LLVM::LLVMStructType computeStateType(ConstantStreamOp op) {
  MLIRContext *context = op->getContext();
  Type i32 = IntegerType::get(context, /*width=*/32);
  return LLVM::LLVMStructType::getNewIdentified(
      context, "iterators.constant_stream_state", {i32});
}

/// The state of ReduceOp only consists of the state of its upstream iterator,
/// i.e., the state of the iterator that produces its input stream.
static LLVM::LLVMStructType
computeStateType(ReduceOp op, LLVM::LLVMStructType upstreamStateType) {
  return LLVM::LLVMStructType::getNewIdentified(
      op->getContext(), "iterators.reduce_state", {upstreamStateType});
}

/// Build IteratorInfo, assigning new unique names as needed.
/// Takes the `LLVM::LLVMStructType` as a parameter, to ensure proper build
/// order (all uses are visited before any def).
mlir::iterators::IteratorInfo::IteratorInfo(IteratorOpInterface op,
                                            NameAssigner &nameAssigner,
                                            LLVM::LLVMStructType t) {
  std::tie(openFunc, nextFunc, closeFunc) =
      assignFunctionNames(op, nameAssigner);
  stateType = t;
}

IteratorInfo mlir::iterators::IteratorAnalysis::getExpectedIteratorInfo(
    IteratorOpInterface op) const {
  auto it = opMap.find(op);
  assert(it != opMap.end() && "analysis does not contain this op");
  return it->getSecond();
}

void mlir::iterators::IteratorAnalysis::setIteratorInfo(
    IteratorOpInterface op, const IteratorInfo &info) {
  assert(info.stateType && "state type must be computed");
  auto inserted = opMap.insert({op, info});
  assert(inserted.second && "IteratorInfo already present");
}

template <typename OpTy>
static OpTy getSelfOrParentOfType(Operation *op) {
  auto maybe = dyn_cast<OpTy>(op);
  return maybe ? maybe : op->getParentOfType<OpTy>();
}

mlir::iterators::IteratorAnalysis::IteratorAnalysis(Operation *rootOp)
    : rootOp(rootOp), nameAssigner(getSelfOrParentOfType<ModuleOp>(rootOp)) {
  /// This needs to be built in use-def order so that all uses are visited
  /// before any def.
  rootOp->walk([&](IteratorOpInterface iteratorOp) {
    llvm::TypeSwitch<Operation *, void>(iteratorOp)
        /// The state of ConstantStreamOp consists of a single number that
        /// corresponds to the next number returned by the iterator.
        .Case<ConstantStreamOp>([&](auto op) {
          auto stateType = computeStateType(op);
          setIteratorInfo(op, IteratorInfo(op, nameAssigner, stateType));
        })
        /// The state of ReduceOp only consists of the state of its upstream
        /// iterator, i.e., the state of the iterator that produces its input
        /// stream.
        // TODO: ReduceOp verifier that op.input does not come from a bbArg.
        .Case<ReduceOp>([&](auto op) {
          Operation *def = op.input().getDefiningOp();
          auto stateType =
              computeStateType(op, getExpectedIteratorInfo(def).stateType);
          setIteratorInfo(op, IteratorInfo(op, nameAssigner, stateType));
        })
        .Default([&](auto op) { assert(false && "Unexpected op"); });
  });
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ed_ioleobject.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: mav $ $Date: 2003-03-10 16:10:22 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "embeddoc.hxx"

STDMETHODIMP EmbedDocument_Impl::SetClientSite( IOleClientSite* pSite )
{
    m_pClientSite = pSite;
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::GetClientSite( IOleClientSite** pSite )
{
    *pSite = m_pClientSite;
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::SetHostNames( LPCOLESTR szContainerApp, LPCOLESTR szContainerObj )
{
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::Close( DWORD dwSaveOption)
{
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::SetMoniker( DWORD dwWhichMoniker, IMoniker *pmk )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetMoniker( DWORD dwAssign, DWORD dwWhichMoniker, IMoniker **ppmk )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::InitFromData( IDataObject *pDataObject, BOOL fCreation, DWORD dwReserved )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetClipboardData( DWORD dwReserved, IDataObject **ppDataObject )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::DoVerb( LONG iVerb, LPMSG lpmsg, IOleClientSite *pActiveSite, LONG lindex, HWND hwndParent, LPCRECT lprcPosRect )
{
    if ( iVerb == OLEIVERB_PRIMARY || iVerb == OLEIVERB_OPEN || iVerb == OLEIVERB_SHOW )
    {
        if ( m_pClientSite )
        {
            m_pClientSite->OnShowWindow( TRUE );
            m_pClientSite->OnShowWindow( FALSE );
        }

        for ( AdviseSinkHashMapIterator iAdvise = m_aAdviseHashMap.begin(); iAdvise != m_aAdviseHashMap.end(); iAdvise++ )
        {
            if ( iAdvise->second )
                iAdvise->second->OnViewChange( DVASPECT_CONTENT, -1 );
        }

        if ( m_pDAdviseHolder )
            m_pDAdviseHolder->SendOnDataChange( (IDataObject*)this, 0, 0 );

        return S_OK;
    }

    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::EnumVerbs( IEnumOLEVERB **ppEnumOleVerb )
{
    return OLE_S_USEREG;
}

STDMETHODIMP EmbedDocument_Impl::Update()
{
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::IsUpToDate()
{
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::GetUserClassID( CLSID *pClsid )
{
    return GetClassID( pClsid );
}

STDMETHODIMP EmbedDocument_Impl::GetUserType( DWORD dwFormOfType, LPOLESTR *pszUserType )
{
    return OLE_S_USEREG;
}

STDMETHODIMP EmbedDocument_Impl::SetExtent( DWORD dwDrawAspect, SIZEL *psizel )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetExtent( DWORD dwDrawAspect, SIZEL *psizel )
{
    if ( psizel )
    {
        psizel->cx = 10000;
        psizel->cy = 10000;
    }

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::Advise( IAdviseSink *pAdvSink, DWORD *pdwConnection )
{
    if ( m_nAdviseNum == 0xFFFFFFFF )
        return E_OUTOFMEMORY;

    pAdvSink->AddRef();
    m_aAdviseHashMap.insert( ::std::pair< DWORD, IAdviseSink* >( m_nAdviseNum, pAdvSink ) );
    *pdwConnection = m_nAdviseNum++;

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::Unadvise( DWORD dwConnection )
{
    AdviseSinkHashMapIterator iAdvise = m_aAdviseHashMap.find( dwConnection );
    if ( iAdvise != m_aAdviseHashMap.end() )
    {
        iAdvise->second->Release();
        m_aAdviseHashMap.erase( iAdvise );
    }
    else
        return OLE_E_NOCONNECTION;

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::EnumAdvise( IEnumSTATDATA **ppenumAdvise )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetMiscStatus( DWORD dwAspect, DWORD *pdwStatus )
{
    return OLE_S_USEREG;
}

STDMETHODIMP EmbedDocument_Impl::SetColorScheme( LOGPALETTE *pLogpal )
{
    return E_NOTIMPL;
}

<commit_msg>#i2822# notification on close<commit_after>/*************************************************************************
 *
 *  $RCSfile: ed_ioleobject.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: mav $ $Date: 2003-03-11 13:02:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "embeddoc.hxx"

STDMETHODIMP EmbedDocument_Impl::SetClientSite( IOleClientSite* pSite )
{
    m_pClientSite = pSite;
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::GetClientSite( IOleClientSite** pSite )
{
    *pSite = m_pClientSite;
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::SetHostNames( LPCOLESTR szContainerApp, LPCOLESTR szContainerObj )
{
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::Close( DWORD dwSaveOption )
{
    HRESULT hr = S_OK;

    if ( dwSaveOption && m_pClientSite )
        hr = m_pClientSite->SaveObject();

    if ( m_pDAdviseHolder )
        m_pDAdviseHolder->SendOnDataChange( (IDataObject*)this, 0, ADVF_DATAONSTOP );

    if ( m_pClientSite )
        m_pClientSite->OnShowWindow( FALSE );

    for ( AdviseSinkHashMapIterator iAdvise = m_aAdviseHashMap.begin(); iAdvise != m_aAdviseHashMap.end(); iAdvise++ )
    {
        if ( iAdvise->second )
            iAdvise->second->OnClose();
    }

    return hr;
}

STDMETHODIMP EmbedDocument_Impl::SetMoniker( DWORD dwWhichMoniker, IMoniker *pmk )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetMoniker( DWORD dwAssign, DWORD dwWhichMoniker, IMoniker **ppmk )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::InitFromData( IDataObject *pDataObject, BOOL fCreation, DWORD dwReserved )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetClipboardData( DWORD dwReserved, IDataObject **ppDataObject )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::DoVerb( LONG iVerb, LPMSG lpmsg, IOleClientSite *pActiveSite, LONG lindex, HWND hwndParent, LPCRECT lprcPosRect )
{
    if ( iVerb == OLEIVERB_PRIMARY || iVerb == OLEIVERB_OPEN || iVerb == OLEIVERB_SHOW )
    {
        if ( m_pClientSite )
        {
            m_pClientSite->OnShowWindow( TRUE );
            m_pClientSite->OnShowWindow( FALSE );
        }

        for ( AdviseSinkHashMapIterator iAdvise = m_aAdviseHashMap.begin(); iAdvise != m_aAdviseHashMap.end(); iAdvise++ )
        {
            if ( iAdvise->second )
                iAdvise->second->OnViewChange( DVASPECT_CONTENT, -1 );
        }

        if ( m_pDAdviseHolder )
            m_pDAdviseHolder->SendOnDataChange( (IDataObject*)this, 0, 0 );

        return S_OK;
    }

    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::EnumVerbs( IEnumOLEVERB **ppEnumOleVerb )
{
    return OLE_S_USEREG;
}

STDMETHODIMP EmbedDocument_Impl::Update()
{
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::IsUpToDate()
{
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::GetUserClassID( CLSID *pClsid )
{
    return GetClassID( pClsid );
}

STDMETHODIMP EmbedDocument_Impl::GetUserType( DWORD dwFormOfType, LPOLESTR *pszUserType )
{
    return OLE_S_USEREG;
}

STDMETHODIMP EmbedDocument_Impl::SetExtent( DWORD dwDrawAspect, SIZEL *psizel )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetExtent( DWORD dwDrawAspect, SIZEL *psizel )
{
    if ( psizel )
    {
        psizel->cx = 10000;
        psizel->cy = 10000;
    }

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::Advise( IAdviseSink *pAdvSink, DWORD *pdwConnection )
{
    if ( m_nAdviseNum == 0xFFFFFFFF )
        return E_OUTOFMEMORY;

    pAdvSink->AddRef();
    m_aAdviseHashMap.insert( ::std::pair< DWORD, IAdviseSink* >( m_nAdviseNum, pAdvSink ) );
    *pdwConnection = m_nAdviseNum++;

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::Unadvise( DWORD dwConnection )
{
    AdviseSinkHashMapIterator iAdvise = m_aAdviseHashMap.find( dwConnection );
    if ( iAdvise != m_aAdviseHashMap.end() )
    {
        iAdvise->second->Release();
        m_aAdviseHashMap.erase( iAdvise );
    }
    else
        return OLE_E_NOCONNECTION;

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::EnumAdvise( IEnumSTATDATA **ppenumAdvise )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetMiscStatus( DWORD dwAspect, DWORD *pdwStatus )
{
    return OLE_S_USEREG;
}

STDMETHODIMP EmbedDocument_Impl::SetColorScheme( LOGPALETTE *pLogpal )
{
    return E_NOTIMPL;
}

<|endoftext|>


<commit_before>
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */

#include "paddle/operators/rank_loss_op.h"

namespace paddle {
namespace operators {

class RankLossOp : public framework::OperatorWithKernel {
 public:
  RankLossOp(const std::string &type, const framework::VariableNameMap &inputs,
             const framework::VariableNameMap &outputs,
             const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

 protected:
  void InferShape(const framework::InferShapeContext &ctx) const override {
    // input check
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("P"), "Input(P) shouldn't be null");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Oi"), "Input(Oi) shouldn't be null");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Oj"), "Input(Oj) shouldn't be null");
    auto p_dims = ctx.Input<framework::Tensor>("P")->dims();
    auto oi_dims = ctx.Input<framework::Tensor>("Oi")->dims();
    auto oj_dims = ctx.Input<framework::Tensor>("Oj")->dims();
    PADDLE_ENFORCE_EQ(oi_dims, oj_dims,
                      "Input(Oi) and Input(Oj) must have the same size");
    PADDLE_ENFORCE_EQ(
        p_dims, oi_dims,
        "Input(P) must have the same size with Input(Oi) & Input(Oj)");
    ctx.Output<framework::Tensor>("Out")->Resize(p_dims);
  }
};

class RankLossOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  RankLossOpMaker(framework::OpProto *proto,
                  framework::OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("P", "The first input of RankLoss operator.");
    AddInput("Oi", "The second input of RankLoss operator.");
    AddInput("Oj", "The third input of RankLoss operator.");
    AddOutput("Out", "The output tensor of RankLoss operator.");
    AddComment(R"DOC(RankLoss operator

A rank loss operator for learning to rank (LTR) task. This operator contains
three inputs: P, Oi, and Oj, and the rank cost can be expressed as

\f[
  C_{i,j} = -\tilde{P_{ij}} * o_{i,j} + log(1 + e^{o_{i,j}}) \\
  o_{i,j} =  o_i - o_j  \\
  \tilde{P_{i,j}} = \left \{0, 0.5, 1 \right \} \ or \ \left \{0, 1 \right \}
\f]

[1]. Chris Burges, Tal Shaked, Erin Renshaw, et al. Learning to
     Rank useing Gradient Descent.
)DOC");
  }
};

class RankLossGradOp : public framework::OperatorWithKernel {
 public:
  RankLossGradOp(const std::string &type,
                 const framework::VariableNameMap &inputs,
                 const framework::VariableNameMap &outputs,
                 const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

 protected:
  void InferShape(const framework::InferShapeContext &ctx) const override {
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("P"), "Input(P) shouldn't be null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Oi"), "Input(Oi) shouldn't be null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Oj"), "Input(Oj) shouldn't be null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar(framework::GradVarName("Out")),
                            "Input(Out@GRAD) shouldn't be null.");
    auto dims = ctx.Input<framework::Tensor>("P")->dims();
    ctx.Output<framework::Tensor>(framework::GradVarName("P"))->Resize(dims);
    ctx.Output<framework::Tensor>(framework::GradVarName("Oi"))->Resize(dims);
    ctx.Output<framework::Tensor>(framework::GradVarName("Oj"))->Resize(dims);
  }
};

}  // namespace operators
}  // namespace paddle
namespace ops = paddle::operators;

REGISTER_OP(rank_loss, ops::RankLossOp, ops::RankLossOpMaker, rank_loss_grad,
            ops::RankLossGradOp);
REGISTER_OP_CPU_KERNEL(rank_loss,
                       ops::RankLossKernel<paddle::platform::CPUPlace, float>);
REGISTER_OP_CPU_KERNEL(
    rank_loss_grad, ops::RankLossGradKernel<paddle::platform::CPUPlace, float>);
<commit_msg>update doc information<commit_after>
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */

#include "paddle/operators/rank_loss_op.h"

namespace paddle {
namespace operators {

class RankLossOp : public framework::OperatorWithKernel {
 public:
  RankLossOp(const std::string &type, const framework::VariableNameMap &inputs,
             const framework::VariableNameMap &outputs,
             const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

 protected:
  void InferShape(const framework::InferShapeContext &ctx) const override {
    // input check
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("P"), "Input(P) shouldn't be null");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Oi"), "Input(Oi) shouldn't be null");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Oj"), "Input(Oj) shouldn't be null");
    auto p_dims = ctx.Input<framework::Tensor>("P")->dims();
    auto oi_dims = ctx.Input<framework::Tensor>("Oi")->dims();
    auto oj_dims = ctx.Input<framework::Tensor>("Oj")->dims();
    PADDLE_ENFORCE_EQ(oi_dims, oj_dims,
                      "Input(Oi) and Input(Oj) must have the same size");
    PADDLE_ENFORCE_EQ(
        p_dims, oi_dims,
        "Input(P) must have the same size with Input(Oi) & Input(Oj)");
    ctx.Output<framework::Tensor>("Out")->Resize(p_dims);
  }
};

class RankLossOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  RankLossOpMaker(framework::OpProto *proto,
                  framework::OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("P", "The desired target values for posteriors.");
    AddInput("Oi", "The model output for item i.");
    AddInput("Oj", "The model output for item j.");
    AddOutput("Out", "The output tensor of RankLoss operator.");
    AddComment(R"DOC(RankLoss operator

A rank loss operator for learning to rank (LTR) task. This operator contains
three inputs: P, Oi, and Oj, and the rank cost can be expressed as

\f[
  C_{i,j} = -\tilde{P_{ij}} * o_{i,j} + log(1 + e^{o_{i,j}}) \\
  o_{i,j} =  o_i - o_j  \\
  \tilde{P_{i,j}} = \left \{0, 0.5, 1 \right \} \ or \ \left \{0, 1 \right \}
\f]

A detailed explanation about these notations can be found in

[1]. Chris Burges, Tal Shaked, Erin Renshaw, et al. Learning to
     Rank useing Gradient Descent.
)DOC");
  }
};

class RankLossGradOp : public framework::OperatorWithKernel {
 public:
  RankLossGradOp(const std::string &type,
                 const framework::VariableNameMap &inputs,
                 const framework::VariableNameMap &outputs,
                 const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

 protected:
  void InferShape(const framework::InferShapeContext &ctx) const override {
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("P"), "Input(P) shouldn't be null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Oi"), "Input(Oi) shouldn't be null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Oj"), "Input(Oj) shouldn't be null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar(framework::GradVarName("Out")),
                            "Input(Out@GRAD) shouldn't be null.");
    auto dims = ctx.Input<framework::Tensor>("P")->dims();
    ctx.Output<framework::Tensor>(framework::GradVarName("P"))->Resize(dims);
    ctx.Output<framework::Tensor>(framework::GradVarName("Oi"))->Resize(dims);
    ctx.Output<framework::Tensor>(framework::GradVarName("Oj"))->Resize(dims);
  }
};

}  // namespace operators
}  // namespace paddle
namespace ops = paddle::operators;

REGISTER_OP(rank_loss, ops::RankLossOp, ops::RankLossOpMaker, rank_loss_grad,
            ops::RankLossGradOp);
REGISTER_OP_CPU_KERNEL(rank_loss,
                       ops::RankLossKernel<paddle::platform::CPUPlace, float>);
REGISTER_OP_CPU_KERNEL(
    rank_loss_grad, ops::RankLossGradKernel<paddle::platform::CPUPlace, float>);
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: elementexport.hxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 09:41:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XMLOFF_ELEMENTEXPORT_HXX_
#define _XMLOFF_ELEMENTEXPORT_HXX_

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_SCRIPTEVENTDESCRIPTOR_HPP_
#include <com/sun/star/script/ScriptEventDescriptor.hpp>
#endif
#ifndef _XMLOFF_FORMS_PROPERTYEXPORT_HXX_
#include "propertyexport.hxx"
#endif
#ifndef _XMLOFF_FORMS_CALLBACKS_HXX_
#include "callbacks.hxx"
#endif
#ifndef _XMLOFF_FORMS_CONTROLELEMENT_HXX_
#include "controlelement.hxx"
#endif
#ifndef _XMLOFF_FORMS_VALUEPROPERTIES_HXX_
#include "valueproperties.hxx"
#endif

class SvXMLElementExport;
//.........................................................................
namespace xmloff
{
//.........................................................................

    //=====================================================================
    //= OElementExport
    //=====================================================================
    class OElementExport : public OPropertyExport
    {
    protected:
        ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >
                                m_aEvents;

        SvXMLElementExport*     m_pXMLElement;          // XML element doing the concrete startElement etc.

    public:
        OElementExport(IFormsExportContext& _rContext,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxProps,
            const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rEvents);
        virtual ~OElementExport();

        void doExport();

    protected:
        /// get the name of the XML element
        virtual const sal_Char* getXMLElementName() const = 0;
        /// examine the element we're exporting
        virtual void examine();
        /// export the attributes
        virtual void exportAttributes();
        /// export any sub tags
        virtual void exportSubTags();

        /** exports the events (as script:events tag)
        */
        void exportEvents();

        /** add the service-name attribute to the export context
        */
        virtual void exportServiceNameAttribute();

        /// start the XML element
        virtual void implStartElement(const sal_Char* _pName);

        /// ends the XML element
        virtual void implEndElement();
    };

    //=====================================================================
    //= OControlExport
    //=====================================================================
    /** Helper class for handling xml elements representing a form control
    */
    class OControlExport
                :public OControlElement
                ,public OValuePropertiesMetaData
                ,public OElementExport
    {
    protected:
        DECLARE_STL_STDKEY_SET(sal_Int16, Int16Set);
            // used below

        ::rtl::OUString         m_sControlId;           // the control id to use when exporting
        ::rtl::OUString         m_sReferringControls;   // list of referring controls (i.e. their id's)
        sal_Int16               m_nClassId;             // class id of the control we're representing
        ElementType             m_eType;                // (XML) type of the control we're representing
        sal_Int32               m_nIncludeCommon;       // common control attributes to include
        sal_Int32               m_nIncludeDatabase;     // common database attributes to include
        sal_Int32               m_nIncludeSpecial;      // special attributes to include
        sal_Int32               m_nIncludeEvents;       // events to include
        sal_Int32               m_nIncludeBindings;     // binding attributes to include

        SvXMLElementExport*     m_pOuterElement;        // XML element doing the concrete startElement etc. for the outer element

    public:
        /** constructs an object capable of exporting controls

You need at least two pre-requisites from outside: The control to be exported needs to have a class id
            assigned, and you need the list control-ids of all the controls referring to this one as LabelControl.

            This information can't be collected when known only the control itself and not it's complete context.

            @param _rControlId
                the control id to use when exporting the control
            @param _rReferringControls
                the comma-separated list of control-ids of all the controls referring to this one as LabelControl
        */
        OControlExport(IFormsExportContext& _rContext,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl,
            const ::rtl::OUString& _rControlId,
            const ::rtl::OUString& _rReferringControls,
            const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rxEvents);
        ~OControlExport();

    protected:
        /// start the XML element
        virtual void implStartElement(const sal_Char* _pName);

        /// ends the XML element
        virtual void implEndElement();

        /// get the name of the outer XML element
        virtual const sal_Char* getOuterXMLElementName() const;

        // get the name of the XML element
        virtual const sal_Char* getXMLElementName() const;

        /** examine the control. Some kind of CtorImpl.
        */
        virtual void examine();

        /// exports the attributes for the outer element
        void exportOuterAttributes();

        /// exports the attributes for the inner element
        void exportInnerAttributes();

        /// export the attributes
        virtual void exportAttributes();

        /** writes everything which needs to be represented as sub tag
        */
        void exportSubTags() throw (::com::sun::star::uno::Exception);

        /** adds common control attributes to the XMLExport context given

The attribute list of the context is not cleared initially, this is the responsibility of the caller.

        */
        void exportCommonControlAttributes();

        /** adds database attributes to the XMLExport context given

The attribute list of the context is not cleared initially, this is the responsibility of the caller.

        */
        void exportDatabaseAttributes();

        /** adds the XML attributes which are related to binding controls to
            external values and/or list sources
        */
        void exportBindingAtributes();

        /** adds attributes which are special to a control type to the export context's attribute list
        */
        void exportSpecialAttributes();

        /** exports the ListSource property of a control as attribute

            The ListSource property may be exported in different ways: For a ComboBox, it is an attribute
            of the form:combobox element.

            For a ListBox, it's an attribute if the ListSourceType states that the ListBox does not
            display a value list. In case of a value list, the ListSource is not exported, and the pairs of
            StringItem/ValueItem are exported as sub-elements.

            This method does the attribute part: It exports the ListSource property as attribute, not caring
            about whether the object is a ComboBox or a ListBox.
        */
        void exportListSourceAsAttribute();

        /** exports the ListSource property of a control as XML elements

            @see exportListSourceAsAttribute
        */
        void exportListSourceAsElements();

        /** get's a Sequence< sal_Int16 > property value as set of sal_Int16's
            @param _rPropertyName
                the property name to use
            @param _rOut
                out parameter. The set of integers.
        */
        void getSequenceInt16PropertyAsSet(const ::rtl::OUString& _rPropertyName, Int16Set& _rOut);

        /** exports the attribute which descrives a cell value binding of a control
            in a spreadsheet document
        */
        void exportCellBindingAttributes( bool _bIncludeListLinkageType );

        /** exports the attribute(s) which bind this control to XForms */
        void exportXFormsBindAttributes();

        /** exports the attribute(s) which bind the list of a list
            control to XForms */
        void exportXFormsListAttributes();

        /** exports the attribute(s) for an XForms submission */
        void exportXFormsSubmissionAttributes();

        /** exports the attribute which descrives a cell range which acts as list source for
            a list-like control
        */
        void exportCellListSourceRange( );

        /** exports the attribut(s) for the ImagePosition property
        */
        void exportImagePositionAttributes();

        /** determines whether the control we're exporting has an active data binding.

            Bindings which count here are:

an established connection to a database field

a binding to an external value supplier (<type scope="com::sun::star::form::binding">XValueBinding</type>)

        */
        bool controlHasActiveDataBinding() const;

        /** retrieves the string specifying the ListSource of a list or combo box
        */
        ::rtl::OUString getScalarListSourceValue() const;

        /** determines whether the list entries (of a combo or list box) are supplied by the user

            List entries may be

specified by the user

specified by an external list source (<type scope="com::sun::star::form::binding">XListEntrySource</type>)

obtained from a database query (in various ways)

            In the latter two cases, this method will return <FALSE/>
        */
        bool controlHasUserSuppliedListEntries() const;
    };

    //=====================================================================
    //= OColumnExport
    //=====================================================================
    /** Helper class for exporting a grid column
    */
    class OColumnExport : public OControlExport
    {
    public:
        /** ctor
            @see OColumnExport::OColumnExport
        */
        OColumnExport(IFormsExportContext& _rContext,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl,
            const ::rtl::OUString& _rControlId,
            const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rxEvents);

        ~OColumnExport();

    protected:
        // OControlExport overridables
        virtual const sal_Char* getOuterXMLElementName() const;
        virtual void exportServiceNameAttribute();
        virtual void exportAttributes();

        // OElementExport overridables
        virtual void examine();
    };

    //=====================================================================
    //= OFormExport
    //=====================================================================
    /** Helper class for handling xml elements representing a form

In opposite to the class <type>OControlExport</type>, OFormExport is unable to export a complete
        form. Instead the client has to care for sub elements of the form itself.

    */
    class OFormExport
                :public OControlElement
                ,public OElementExport
    {
        sal_Bool m_bCreateConnectionResourceElement;
    public:
        /** constructs an object capable of exporting controls
        */
        OFormExport(IFormsExportContext& _rContext,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxForm,
            const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rxEvents
            );

    protected:
        virtual const sal_Char* getXMLElementName() const;
        virtual void exportSubTags();
        virtual void exportAttributes();
    };
//.........................................................................
}   // namespace xmloff
//.........................................................................

#endif // _XMLOFF_ELEMENTEXPORT_HXX_

<commit_msg>INTEGRATION: CWS changefileheader (1.17.206); FILE MERGED 2008/04/01 13:04:49 thb 1.17.206.2: #i85898# Stripping all external header guards 2008/03/31 16:28:11 rt 1.17.206.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: elementexport.hxx,v $
 * $Revision: 1.18 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _XMLOFF_ELEMENTEXPORT_HXX_
#define _XMLOFF_ELEMENTEXPORT_HXX_

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/script/ScriptEventDescriptor.hpp>
#include "propertyexport.hxx"
#include "callbacks.hxx"
#include "controlelement.hxx"
#include "valueproperties.hxx"

class SvXMLElementExport;
//.........................................................................
namespace xmloff
{
//.........................................................................

    //=====================================================================
    //= OElementExport
    //=====================================================================
    class OElementExport : public OPropertyExport
    {
    protected:
        ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >
                                m_aEvents;

        SvXMLElementExport*     m_pXMLElement;          // XML element doing the concrete startElement etc.

    public:
        OElementExport(IFormsExportContext& _rContext,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxProps,
            const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rEvents);
        virtual ~OElementExport();

        void doExport();

    protected:
        /// get the name of the XML element
        virtual const sal_Char* getXMLElementName() const = 0;
        /// examine the element we're exporting
        virtual void examine();
        /// export the attributes
        virtual void exportAttributes();
        /// export any sub tags
        virtual void exportSubTags();

        /** exports the events (as script:events tag)
        */
        void exportEvents();

        /** add the service-name attribute to the export context
        */
        virtual void exportServiceNameAttribute();

        /// start the XML element
        virtual void implStartElement(const sal_Char* _pName);

        /// ends the XML element
        virtual void implEndElement();
    };

    //=====================================================================
    //= OControlExport
    //=====================================================================
    /** Helper class for handling xml elements representing a form control
    */
    class OControlExport
                :public OControlElement
                ,public OValuePropertiesMetaData
                ,public OElementExport
    {
    protected:
        DECLARE_STL_STDKEY_SET(sal_Int16, Int16Set);
            // used below

        ::rtl::OUString         m_sControlId;           // the control id to use when exporting
        ::rtl::OUString         m_sReferringControls;   // list of referring controls (i.e. their id's)
        sal_Int16               m_nClassId;             // class id of the control we're representing
        ElementType             m_eType;                // (XML) type of the control we're representing
        sal_Int32               m_nIncludeCommon;       // common control attributes to include
        sal_Int32               m_nIncludeDatabase;     // common database attributes to include
        sal_Int32               m_nIncludeSpecial;      // special attributes to include
        sal_Int32               m_nIncludeEvents;       // events to include
        sal_Int32               m_nIncludeBindings;     // binding attributes to include

        SvXMLElementExport*     m_pOuterElement;        // XML element doing the concrete startElement etc. for the outer element

    public:
        /** constructs an object capable of exporting controls

You need at least two pre-requisites from outside: The control to be exported needs to have a class id
            assigned, and you need the list control-ids of all the controls referring to this one as LabelControl.

            This information can't be collected when known only the control itself and not it's complete context.

            @param _rControlId
                the control id to use when exporting the control
            @param _rReferringControls
                the comma-separated list of control-ids of all the controls referring to this one as LabelControl
        */
        OControlExport(IFormsExportContext& _rContext,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl,
            const ::rtl::OUString& _rControlId,
            const ::rtl::OUString& _rReferringControls,
            const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rxEvents);
        ~OControlExport();

    protected:
        /// start the XML element
        virtual void implStartElement(const sal_Char* _pName);

        /// ends the XML element
        virtual void implEndElement();

        /// get the name of the outer XML element
        virtual const sal_Char* getOuterXMLElementName() const;

        // get the name of the XML element
        virtual const sal_Char* getXMLElementName() const;

        /** examine the control. Some kind of CtorImpl.
        */
        virtual void examine();

        /// exports the attributes for the outer element
        void exportOuterAttributes();

        /// exports the attributes for the inner element
        void exportInnerAttributes();

        /// export the attributes
        virtual void exportAttributes();

        /** writes everything which needs to be represented as sub tag
        */
        void exportSubTags() throw (::com::sun::star::uno::Exception);

        /** adds common control attributes to the XMLExport context given

The attribute list of the context is not cleared initially, this is the responsibility of the caller.

        */
        void exportCommonControlAttributes();

        /** adds database attributes to the XMLExport context given

The attribute list of the context is not cleared initially, this is the responsibility of the caller.

        */
        void exportDatabaseAttributes();

        /** adds the XML attributes which are related to binding controls to
            external values and/or list sources
        */
        void exportBindingAtributes();

        /** adds attributes which are special to a control type to the export context's attribute list
        */
        void exportSpecialAttributes();

        /** exports the ListSource property of a control as attribute

            The ListSource property may be exported in different ways: For a ComboBox, it is an attribute
            of the form:combobox element.

            For a ListBox, it's an attribute if the ListSourceType states that the ListBox does not
            display a value list. In case of a value list, the ListSource is not exported, and the pairs of
            StringItem/ValueItem are exported as sub-elements.

            This method does the attribute part: It exports the ListSource property as attribute, not caring
            about whether the object is a ComboBox or a ListBox.
        */
        void exportListSourceAsAttribute();

        /** exports the ListSource property of a control as XML elements

            @see exportListSourceAsAttribute
        */
        void exportListSourceAsElements();

        /** get's a Sequence< sal_Int16 > property value as set of sal_Int16's
            @param _rPropertyName
                the property name to use
            @param _rOut
                out parameter. The set of integers.
        */
        void getSequenceInt16PropertyAsSet(const ::rtl::OUString& _rPropertyName, Int16Set& _rOut);

        /** exports the attribute which descrives a cell value binding of a control
            in a spreadsheet document
        */
        void exportCellBindingAttributes( bool _bIncludeListLinkageType );

        /** exports the attribute(s) which bind this control to XForms */
        void exportXFormsBindAttributes();

        /** exports the attribute(s) which bind the list of a list
            control to XForms */
        void exportXFormsListAttributes();

        /** exports the attribute(s) for an XForms submission */
        void exportXFormsSubmissionAttributes();

        /** exports the attribute which descrives a cell range which acts as list source for
            a list-like control
        */
        void exportCellListSourceRange( );

        /** exports the attribut(s) for the ImagePosition property
        */
        void exportImagePositionAttributes();

        /** determines whether the control we're exporting has an active data binding.

            Bindings which count here are:

an established connection to a database field

a binding to an external value supplier (<type scope="com::sun::star::form::binding">XValueBinding</type>)

        */
        bool controlHasActiveDataBinding() const;

        /** retrieves the string specifying the ListSource of a list or combo box
        */
        ::rtl::OUString getScalarListSourceValue() const;

        /** determines whether the list entries (of a combo or list box) are supplied by the user

            List entries may be

specified by the user

specified by an external list source (<type scope="com::sun::star::form::binding">XListEntrySource</type>)

obtained from a database query (in various ways)

            In the latter two cases, this method will return <FALSE/>
        */
        bool controlHasUserSuppliedListEntries() const;
    };

    //=====================================================================
    //= OColumnExport
    //=====================================================================
    /** Helper class for exporting a grid column
    */
    class OColumnExport : public OControlExport
    {
    public:
        /** ctor
            @see OColumnExport::OColumnExport
        */
        OColumnExport(IFormsExportContext& _rContext,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl,
            const ::rtl::OUString& _rControlId,
            const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rxEvents);

        ~OColumnExport();

    protected:
        // OControlExport overridables
        virtual const sal_Char* getOuterXMLElementName() const;
        virtual void exportServiceNameAttribute();
        virtual void exportAttributes();

        // OElementExport overridables
        virtual void examine();
    };

    //=====================================================================
    //= OFormExport
    //=====================================================================
    /** Helper class for handling xml elements representing a form

In opposite to the class <type>OControlExport</type>, OFormExport is unable to export a complete
        form. Instead the client has to care for sub elements of the form itself.

    */
    class OFormExport
                :public OControlElement
                ,public OElementExport
    {
        sal_Bool m_bCreateConnectionResourceElement;
    public:
        /** constructs an object capable of exporting controls
        */
        OFormExport(IFormsExportContext& _rContext,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxForm,
            const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rxEvents
            );

    protected:
        virtual const sal_Char* getXMLElementName() const;
        virtual void exportSubTags();
        virtual void exportAttributes();
    };
//.........................................................................
}   // namespace xmloff
//.........................................................................

#endif // _XMLOFF_ELEMENTEXPORT_HXX_

<|endoftext|>


<commit_before><commit_msg>Move all functions in include/abaclade/io/binary.hxx to the end of the file to avoid forward declarations<commit_after><|endoftext|>


<commit_before>#include "diagnostic.h"
#include "ui.h"
#include "global.h"
#include "robot.h"

#include <FEHBuzzer.h>
#include <new>

namespace G8 {

namespace Tasks {

#define TASK_RESULT_QUIT    0x20000000
TASK_RESULT Quit(Robot * const pRob)
{
    return TASK_RESULT_SUCCESS | TASK_RESULT_QUIT;
}

TASK_RESULT RedfineConstants(Robot * const pRob)
{
    FEHBuzzer buzz;

    const size_t length = CONST.GetLength() + 1;
    char const ** ppNames = new char const *[length]; // Ignore first constant; add one for Quit
    ppNames[0] = "Quit";
    ppNames[length - 1] = "!!!RESET ALL!!!";
    for(int i = 1; i < CONST.GetLength(); i++)
    {
        ppNames[i] = CONST.GetName(i);
    }

    while(size_t index = UI::MenuSelect("Select a constant", ppNames, length))
    {
        if(index == length -1)
        {
            // Delete and rebuild constants
            CONST.~CONSTANT_SYS();
            new (&CONST) CONSTANT_SYS();
            DefineConstants();
            // Show message
            LCD.WriteLine("All CONSTANTS reset!");
            Sleep(2000);
        }else{
            switch(CONST.GetType(index))
            {
            case C_TYPE_INT:
                CONST.Redefine<int>(index, UI::GetInt(CONST.GetName(index), CONST.GetVal<int>(index)));
                break;
            case C_TYPE_INT | C_TYPE_UNSIGNED:
                CONST.Redefine<unsigned int>(index, UI::GetIntU(CONST.GetName(index), CONST.GetVal<unsigned int>(index)));
                break;
            default:
                buzz.Beep();
                break;
            }
        }
    }

    delete ppNames;

    return TASK_RESULT_SUCCESS;
}

TASK_RESULT RebuildRobot(Robot * const pRob)
{
    pRob->~Robot();

    if(new (pRob) Robot())
    {
        LCD.WriteLine("Rebuild successful");
        Sleep(2000);
        return TASK_RESULT_SUCCESS;
    }

    LCD.WriteLine("Rebuild failed");
    Sleep(2000);
    return TASK_RESULT_FAIL;
}

TASK_RESULT Diagnostics(Robot * const pRob)
{
    TaskSystem sys("Choose a diagnostic");
    sys.AddTask("Quit", Quit);
    sys.AddTask("Redefine constants", RedfineConstants);
    sys.AddTask("Rebuild Robot", RebuildRobot);

    while(true)
    {
        TASK_RESULT r = sys.RunTaskFromMenu(pRob);
        if((r & TASK_RESULT_QUIT) == TASK_RESULT_QUIT)
            return TASK_RESULT_SUCCESS;
        else if((r & TASK_RESULT_FAIL) == TASK_RESULT_FAIL)
            return r;
    }

    // We shouldn't get here
    return TASK_RESULT_FAIL;
}

}

} // namespace G8
<commit_msg>Added PrintPosition and CalibrateServo diagnostics<commit_after>#include "diagnostic.h"
#include "ui.h"
#include "global.h"
#include "robot.h"

#include <FEHBuzzer.h>
#include <FEHServo.h>
#include <new>

namespace G8 {

namespace Tasks {

#define TASK_RESULT_QUIT    0x20000000
TASK_RESULT Quit(Robot * const pRob)
{
    return TASK_RESULT_SUCCESS | TASK_RESULT_QUIT;
}

TASK_RESULT RedfineConstants(Robot * const pRob)
{
    FEHBuzzer buzz;

    const size_t length = CONST.GetLength() + 1;
    char const ** ppNames = new char const *[length]; // Ignore first constant; add one for Quit
    ppNames[0] = "Quit";
    ppNames[length - 1] = "!!!RESET ALL!!!";
    for(int i = 1; i < CONST.GetLength(); i++)
    {
        ppNames[i] = CONST.GetName(i);
    }

    while(size_t index = UI::MenuSelect("Select a constant", ppNames, length))
    {
        if(index == length -1)
        {
            // Delete and rebuild constants
            CONST.~CONSTANT_SYS();
            new (&CONST) CONSTANT_SYS();
            DefineConstants();
            // Show message
            LCD.WriteLine("All CONSTANTS reset!");
            Sleep(2000);
        }else{
            switch(CONST.GetType(index))
            {
            case C_TYPE_INT:
                CONST.Redefine<int>(index, UI::GetInt(CONST.GetName(index), CONST.GetVal<int>(index)));
                break;
            case C_TYPE_INT | C_TYPE_UNSIGNED:
                CONST.Redefine<unsigned int>(index, UI::GetIntU(CONST.GetName(index), CONST.GetVal<unsigned int>(index)));
                break;
            default:
                buzz.Beep();
                break;
            }
        }
    }

    delete ppNames;

    return TASK_RESULT_SUCCESS;
}

TASK_RESULT RebuildRobot(Robot * const pRob)
{
    pRob->~Robot();

    if(new (pRob) Robot())
    {
        LCD.WriteLine("Rebuild successful");
        Sleep(2000);
        return TASK_RESULT_SUCCESS;
    }

    LCD.WriteLine("Rebuild failed");
    Sleep(2000);
    return TASK_RESULT_FAIL;
}

TASK_RESULT CalibrateServo(Robot * const pRob)
{
    unsigned int nServo = UI::GetIntU("Servo Port", 0);

    FEHServo servo(static_cast<FEHServo::FEHServoPort>(nServo));
    servo.Calibrate();
    LCD.WriteLine("-Middle to quit-");
    while (pRob->pButtons->MiddlePressed());
    Sleep(100);
    while (!pRob->pButtons->MiddlePressed());
    return TASK_RESULT_SUCCESS;
}

TASK_RESULT PrintPosition(Robot * const pRob)
{
    LCD.WriteLine("Point in -Y dir.");
    LCD.WriteLine("-Middle to start-");
    while(!pRob->pButtons->MiddlePressed());
    Sleep(100);
    while(pRob->pButtons->MiddlePressed());

    pRob->pNav->CalibrateHeading(270);

    while(!pRob->pButtons->MiddlePressed())
    {
        Position p = pRob->pNav->UpdatePosition();

        LCD.Clear();
        LCD.Write("X: ");
        LCD.WriteLine(p.x);
        LCD.Write("Y: ");
        LCD.WriteLine(p.y);
        LCD.Write("H: ");
        LCD.WriteLine(p.heading);

        Sleep(100);
    }

    return TASK_RESULT_SUCCESS;
}

TASK_RESULT Diagnostics(Robot * const pRob)
{
    TaskSystem sys("Choose a diagnostic");
    sys.AddTask("Quit", Quit);
    sys.AddTask("Redefine constants", RedfineConstants);
    sys.AddTask("Rebuild Robot", RebuildRobot);
    sys.AddTask("Calibrate Servo", CalibrateServo);
    sys.AddTask("Print Position", PrintPosition);

    while(true)
    {
        TASK_RESULT r = sys.RunTaskFromMenu(pRob);
        if((r & TASK_RESULT_QUIT) == TASK_RESULT_QUIT)
            return TASK_RESULT_SUCCESS;
        else if((r & TASK_RESULT_FAIL) == TASK_RESULT_FAIL)
            return r;
    }

    // We shouldn't get here
    return TASK_RESULT_FAIL;
}

}

} // namespace G8
<|endoftext|>