<commit_before>// Copyright (C) 2014 - 2015 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

#include "copasi/utilities/CBaseUnit.h"
#include "copasi/utilities/CCopasiMessage.h"
#include "copasi/UI/qtUtilities.h"

// static
const char * CBaseUnit::Name[] =
{
  "dimensionless",
  "meter",
  "gram",
  "second",
  "Ampere",
  "Kelvin",
  "item",
  "Candela",
  NULL
};

// static (because CBaseUnit is not meant to be constructed)
const std::string CBaseUnit::getSymbol(Kind kind)
{
  switch (kind)
    {
      case dimensionless:
        return "";

      case meter:
        return "m";

      case gram:
        return "g";

      case second:
        return "s";

      case ampere:
        return "A";

      case kelvin:
        return "K";

      case candela:
        return "cd";

      case item:
        return "#";

      default:
        return "";
    }
}

// static (because CBaseUnit is not meant to be constructed)
const CBaseUnit::Kind CBaseUnit::fromSymbol(const std::string & symbol)
{
  if (symbol == "m") return meter;

  if (symbol == "g") return gram;

  if (symbol == "s") return second;

  if (symbol == "A") return ampere;

  if (symbol == "K") return kelvin;

  if (symbol == "cd") return candela;

  if (symbol == "#") return item;

  if (symbol == "") return dimensionless;

  fatalError();

  return dimensionless;
}

// static (because CBaseUnit is not meant to be constructed)
const CBaseUnit::Scale CBaseUnit::scaleFromPrefix(const std::string & prefix)
{
  if (prefix == "a") return atto;

  if (prefix == "f") return femto;

  if (prefix == "p") return pico;

  if (prefix == "u" || prefix == "\xc2\xb5") return micro;

  if (prefix == "m") return milli;

  if (prefix == "c") return centi;

  if (prefix == "d") return deci;

  if (prefix == "h") return hecto;

  if (prefix == "k") return kilo;

  if (prefix == "M") return mega;

  if (prefix == "G") return giga;

  if (prefix == "T") return tera;

  if (prefix == "P") return peta;

  return zero;
}
<commit_msg>- cbaseuntit should not include qt, as we currently don't have a qt dependency for libcopasise/copasise<commit_after>// Copyright (C) 2014 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

#include "copasi/utilities/CBaseUnit.h"
#include "copasi/utilities/CCopasiMessage.h"

// static
const char * CBaseUnit::Name[] =
{
  "dimensionless",
  "meter",
  "gram",
  "second",
  "Ampere",
  "Kelvin",
  "item",
  "Candela",
  NULL
};

// static (because CBaseUnit is not meant to be constructed)
const std::string CBaseUnit::getSymbol(Kind kind)
{
  switch (kind)
    {
      case dimensionless:
        return "";

      case meter:
        return "m";

      case gram:
        return "g";

      case second:
        return "s";

      case ampere:
        return "A";

      case kelvin:
        return "K";

      case candela:
        return "cd";

      case item:
        return "#";

      default:
        return "";
    }
}

// static (because CBaseUnit is not meant to be constructed)
const CBaseUnit::Kind CBaseUnit::fromSymbol(const std::string & symbol)
{
  if (symbol == "m") return meter;

  if (symbol == "g") return gram;

  if (symbol == "s") return second;

  if (symbol == "A") return ampere;

  if (symbol == "K") return kelvin;

  if (symbol == "cd") return candela;

  if (symbol == "#") return item;

  if (symbol == "") return dimensionless;

  fatalError();

  return dimensionless;
}

// static (because CBaseUnit is not meant to be constructed)
const CBaseUnit::Scale CBaseUnit::scaleFromPrefix(const std::string & prefix)
{
  if (prefix == "a") return atto;

  if (prefix == "f") return femto;

  if (prefix == "p") return pico;

  if (prefix == "u" || prefix == "\xc2\xb5") return micro;

  if (prefix == "m") return milli;

  if (prefix == "c") return centi;

  if (prefix == "d") return deci;

  if (prefix == "h") return hecto;

  if (prefix == "k") return kilo;

  if (prefix == "M") return mega;

  if (prefix == "G") return giga;

  if (prefix == "T") return tera;

  if (prefix == "P") return peta;

  return zero;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
 *
 * 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 <string>
#include <votca/tools/statement.h>

namespace votca { namespace tools {

using namespace std;

Statement::~Statement()
{
	sqlite3_finalize(_stmt);
}

template<>
void Statement::Bind(int col, const int &value)
{
	sqlite3_bind_int(_stmt, col, value);
}

template<>
void Statement::Bind(int col, const double &value)
{
	sqlite3_bind_double(_stmt, col, value);
}

template<>
int Statement::Column<int>(int col)
{
	return sqlite3_column_int(_stmt, col);
}

template<>
double Statement::Column<double>(int col)
{
	return sqlite3_column_double(_stmt, col);
}

template<>
string Statement::Column<string>(int col)
{
	return string((const char*)sqlite3_column_text(_stmt, col));
}

template<>
void Statement::Bind(int col, const string &value)
{
    sqlite3_bind_text(_stmt, col, value.c_str(), -1, NULL);;
}

int Statement::Step()
{
	return sqlite3_step(_stmt);
}

void Statement::Reset()
{
	sqlite3_reset(_stmt);
}

}}

<commit_msg>error handling in statement<commit_after>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
 *
 * 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 <string>
#include <votca/tools/statement.h>
#include <stdexcept>

namespace votca { namespace tools {

using namespace std;

Statement::~Statement()
{
	sqlite3_finalize(_stmt);
}

template<>
void Statement::Bind(int col, const int &value)
{
	if(sqlite3_bind_int(_stmt, col, value) != SQLITE_OK)
      throw std::runtime_error("sqlite_bind failed");
}

template<>
void Statement::Bind(int col, const double &value)
{
	if(sqlite3_bind_double(_stmt, col, value) != SQLITE_OK)
      throw std::runtime_error("sqlite_bind failed");
}

template<>
int Statement::Column<int>(int col)
{
	return sqlite3_column_int(_stmt, col);
}

template<>
double Statement::Column<double>(int col)
{
	return sqlite3_column_double(_stmt, col);
}

template<>
string Statement::Column<string>(int col)
{
	return string((const char*)sqlite3_column_text(_stmt, col));
}

template<>
void Statement::Bind(int col, const string &value)
{
    if(sqlite3_bind_text(_stmt, col, value.c_str(), -1, NULL) != SQLITE_OK)
      throw std::runtime_error("sqlite_bind failed");
}

int Statement::Step()
{
	return sqlite3_step(_stmt);
}

void Statement::Reset()
{
	sqlite3_reset(_stmt);
}

}}

<|endoftext|>


<commit_before><commit_msg>Propagate first_and_last option into nonlinear iterative solvers.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix nvcc sign warning<commit_after><|endoftext|>


<commit_before>#define PGDLLIMPORT "C"

#include <cstdlib>

#include "postgres.h"
#include "funcapi.h"

#include "access/extprotocol.h"
#include "catalog/pg_proc.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "fmgr.h"

#include "S3ExtWrapper.h"
#include "S3Common.h"
#include "S3Log.h"
#include "utils.h"

#include "gps3ext.h"
#include "gps3conf.h"

#include <pthread.h>
#include <openssl/err.h>

/* Do the module magic dance */

PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(s3_export);
PG_FUNCTION_INFO_V1(s3_import);
PG_FUNCTION_INFO_V1(s3_validate_urls);

extern "C" {
Datum s3_export(PG_FUNCTION_ARGS);
Datum s3_import(PG_FUNCTION_ARGS);
Datum s3_validate_urls(PG_FUNCTION_ARGS);
}

#define MUTEX_TYPE pthread_mutex_t
#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
#define THREAD_ID pthread_self()

/* This array will store all of the mutexes available to OpenSSL. */
static MUTEX_TYPE *mutex_buf = NULL;

static void locking_function(int mode, int n, const char *file, int line) {
    if (mode & CRYPTO_LOCK)
        MUTEX_LOCK(mutex_buf[n]);
    else
        MUTEX_UNLOCK(mutex_buf[n]);
}

static unsigned long id_function(void) { return ((unsigned long)THREAD_ID); }

int thread_setup(void) {
    int i;

    mutex_buf =
        (pthread_mutex_t *)palloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
    if (!mutex_buf) return 0;
    for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_SETUP(mutex_buf[i]);
    CRYPTO_set_id_callback(id_function);
    CRYPTO_set_locking_callback(locking_function);
    return 1;
}

int thread_cleanup(void) {
    int i;

    if (!mutex_buf) return 0;
    CRYPTO_set_id_callback(NULL);
    CRYPTO_set_locking_callback(NULL);
    for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_CLEANUP(mutex_buf[i]);
    pfree(mutex_buf);
    mutex_buf = NULL;
    return 1;
}

/*
 * Import data into GPDB.
 */
Datum s3_import(PG_FUNCTION_ARGS) {
    S3ExtBase *myData;
    char *data;
    int data_len;
    size_t nread = 0;

    /* Must be called via the external table format manager */
    if (!CALLED_AS_EXTPROTOCOL(fcinfo))
        elog(ERROR,
             "extprotocol_import: not called by external protocol manager");

    /* Get our internal description of the protocol */
    myData = (S3ExtBase *)EXTPROTOCOL_GET_USER_CTX(fcinfo);

    if (EXTPROTOCOL_IS_LAST_CALL(fcinfo)) {
        if (myData) {
            thread_cleanup();
            if (!myData->Destroy()) {
                ereport(ERROR, (0, errmsg("Cleanup S3 extention failed")));
            }
            delete myData;
        }
        PG_RETURN_INT32(0);
    }

    if (myData == NULL) {
        /* first call. do any desired init */
        curl_global_init(CURL_GLOBAL_ALL);
        thread_setup();
        const char *p_name = "s3";
        char *url_with_options = EXTPROTOCOL_GET_URL(fcinfo);
        char *url = truncate_options(url_with_options);

        char *config_path = get_opt_s3(url_with_options, "config");
        if (!config_path) {
            // no config path in url, use default value
            // data_folder/gpseg0/s3/s3.conf
            config_path = pstrdup("s3/s3.conf");
        }

        bool result = InitConfig(config_path, "");
        if (!result) {
            ereport(ERROR,
                    (0, errmsg("Can't find config file %s", config_path)));
            pfree(config_path);
        } else {
            ClearConfig();
            pfree(config_path);
        }

        InitLog();

        if (s3ext_accessid == "") {
            ereport(ERROR, (0, errmsg("ERROR: access id is empty")));
        }

        if (s3ext_secret == "") {
            ereport(ERROR, (0, errmsg("ERROR: secret is empty")));
        }

        if ((s3ext_segnum == -1) || (s3ext_segid == -1)) {
            ereport(ERROR, (0, errmsg("ERROR: segment id is invalid")));
        }

        myData = CreateExtWrapper(url);

        if (!myData ||
            !myData->Init(s3ext_segid, s3ext_segnum, s3ext_chunksize)) {
            if (myData) delete myData;
            ereport(ERROR, (0, errmsg("Failed to init S3 extension, segid = "
                                      "%d, segnum = %d, please check your "
                                      "configurations and net connection",
                                      s3ext_segid, s3ext_segnum)));
        }
        /*
                  if(strcasecmp(parsed_url->protocol, p_name) != 0) {
                  elog(ERROR, "internal error: s3prot called with a different
                  protocol
                  (%s)",
                  parsed_url->protocol);
                  }
        */

        EXTPROTOCOL_SET_USER_CTX(fcinfo, myData);

        free(url);
    }

    /* =======================================================================
     *                            DO THE IMPORT
     * =======================================================================
     */

    data = EXTPROTOCOL_GET_DATABUF(fcinfo);
    data_len = EXTPROTOCOL_GET_DATALEN(fcinfo);
    uint64_t readlen = 0;
    if (data_len > 0) {
        readlen = data_len;
        if (!myData->TransferData(data, readlen))
            ereport(ERROR, (0, errmsg("s3_import: could not read data")));
        nread = (size_t)readlen;
        // S3DEBUG("read %d data from S3", nread);
    }

    PG_RETURN_INT32((int)nread);
}

/*
 * Export data out of GPDB.
 */
Datum s3_export(PG_FUNCTION_ARGS) { PG_RETURN_INT32(0); }

Datum s3_validate_urls(PG_FUNCTION_ARGS) {
    int nurls;
    int i;
    ValidatorDirection direction;
    PG_RETURN_VOID();
}
<commit_msg>don't use use pg alloc functions here, conflict with get_opt_s3() in unit test env<commit_after>#define PGDLLIMPORT "C"

#include <cstdlib>

#include "postgres.h"
#include "funcapi.h"

#include "access/extprotocol.h"
#include "catalog/pg_proc.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "fmgr.h"

#include "S3ExtWrapper.h"
#include "S3Common.h"
#include "S3Log.h"
#include "utils.h"

#include "gps3ext.h"
#include "gps3conf.h"

#include <pthread.h>
#include <openssl/err.h>

/* Do the module magic dance */

PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(s3_export);
PG_FUNCTION_INFO_V1(s3_import);
PG_FUNCTION_INFO_V1(s3_validate_urls);

extern "C" {
Datum s3_export(PG_FUNCTION_ARGS);
Datum s3_import(PG_FUNCTION_ARGS);
Datum s3_validate_urls(PG_FUNCTION_ARGS);
}

#define MUTEX_TYPE pthread_mutex_t
#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
#define THREAD_ID pthread_self()

/* This array will store all of the mutexes available to OpenSSL. */
static MUTEX_TYPE *mutex_buf = NULL;

static void locking_function(int mode, int n, const char *file, int line) {
    if (mode & CRYPTO_LOCK)
        MUTEX_LOCK(mutex_buf[n]);
    else
        MUTEX_UNLOCK(mutex_buf[n]);
}

static unsigned long id_function(void) { return ((unsigned long)THREAD_ID); }

int thread_setup(void) {
    int i;

    mutex_buf =
        (pthread_mutex_t *)palloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
    if (!mutex_buf) return 0;
    for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_SETUP(mutex_buf[i]);
    CRYPTO_set_id_callback(id_function);
    CRYPTO_set_locking_callback(locking_function);
    return 1;
}

int thread_cleanup(void) {
    int i;

    if (!mutex_buf) return 0;
    CRYPTO_set_id_callback(NULL);
    CRYPTO_set_locking_callback(NULL);
    for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_CLEANUP(mutex_buf[i]);
    pfree(mutex_buf);
    mutex_buf = NULL;
    return 1;
}

/*
 * Import data into GPDB.
 */
Datum s3_import(PG_FUNCTION_ARGS) {
    S3ExtBase *myData;
    char *data;
    int data_len;
    size_t nread = 0;

    /* Must be called via the external table format manager */
    if (!CALLED_AS_EXTPROTOCOL(fcinfo))
        elog(ERROR,
             "extprotocol_import: not called by external protocol manager");

    /* Get our internal description of the protocol */
    myData = (S3ExtBase *)EXTPROTOCOL_GET_USER_CTX(fcinfo);

    if (EXTPROTOCOL_IS_LAST_CALL(fcinfo)) {
        if (myData) {
            thread_cleanup();
            if (!myData->Destroy()) {
                ereport(ERROR, (0, errmsg("Cleanup S3 extention failed")));
            }
            delete myData;
        }
        PG_RETURN_INT32(0);
    }

    if (myData == NULL) {
        /* first call. do any desired init */
        curl_global_init(CURL_GLOBAL_ALL);
        thread_setup();
        const char *p_name = "s3";
        char *url_with_options = EXTPROTOCOL_GET_URL(fcinfo);
        char *url = truncate_options(url_with_options);

        char *config_path = get_opt_s3(url_with_options, "config");
        if (!config_path) {
            // no config path in url, use default value
            // data_folder/gpseg0/s3/s3.conf
            config_path = strdup("s3/s3.conf");
        }

        bool result = InitConfig(config_path, "");
        if (!result) {
            free(config_path);
            ereport(ERROR, (0, errmsg("Can't find config file, please check")));
        } else {
            ClearConfig();
            free(config_path);
        }

        InitLog();

        if (s3ext_accessid == "") {
            ereport(ERROR, (0, errmsg("ERROR: access id is empty")));
        }

        if (s3ext_secret == "") {
            ereport(ERROR, (0, errmsg("ERROR: secret is empty")));
        }

        if ((s3ext_segnum == -1) || (s3ext_segid == -1)) {
            ereport(ERROR, (0, errmsg("ERROR: segment id is invalid")));
        }

        myData = CreateExtWrapper(url);

        if (!myData ||
            !myData->Init(s3ext_segid, s3ext_segnum, s3ext_chunksize)) {
            if (myData) delete myData;
            ereport(ERROR, (0, errmsg("Failed to init S3 extension, segid = "
                                      "%d, segnum = %d, please check your "
                                      "configurations and net connection",
                                      s3ext_segid, s3ext_segnum)));
        }
        /*
                  if(strcasecmp(parsed_url->protocol, p_name) != 0) {
                  elog(ERROR, "internal error: s3prot called with a different
                  protocol
                  (%s)",
                  parsed_url->protocol);
                  }
        */

        EXTPROTOCOL_SET_USER_CTX(fcinfo, myData);

        free(url);
    }

    /* =======================================================================
     *                            DO THE IMPORT
     * =======================================================================
     */

    data = EXTPROTOCOL_GET_DATABUF(fcinfo);
    data_len = EXTPROTOCOL_GET_DATALEN(fcinfo);
    uint64_t readlen = 0;
    if (data_len > 0) {
        readlen = data_len;
        if (!myData->TransferData(data, readlen))
            ereport(ERROR, (0, errmsg("s3_import: could not read data")));
        nread = (size_t)readlen;
        // S3DEBUG("read %d data from S3", nread);
    }

    PG_RETURN_INT32((int)nread);
}

/*
 * Export data out of GPDB.
 */
Datum s3_export(PG_FUNCTION_ARGS) { PG_RETURN_INT32(0); }

Datum s3_validate_urls(PG_FUNCTION_ARGS) {
    int nurls;
    int i;
    ValidatorDirection direction;
    PG_RETURN_VOID();
}
<|endoftext|>


<commit_before>#include "renderState.h"

#include "platform.h"
#include "vertexLayout.h"
#include "gl/hardware.h"

namespace Tangram {

 // Incremented when the GL context is invalidated
static int s_validGeneration;
static int s_textureUnit;

namespace RenderState {

    Blending blending;
    DepthTest depthTest;
    StencilTest stencilTest;
    Culling culling;
    DepthWrite depthWrite;
    BlendingFunc blendingFunc;
    StencilWrite stencilWrite;
    StencilFunc stencilFunc;
    StencilOp stencilOp;
    ColorWrite colorWrite;
    FrontFace frontFace;
    CullFace cullFace;

    VertexBuffer vertexBuffer;
    IndexBuffer indexBuffer;

    ShaderProgram shaderProgram;

    TextureUnit textureUnit;
    Texture texture;

    ClearColor clearColor;

    GLuint getTextureUnit(GLuint _unit) {
        return GL_TEXTURE0 + _unit;
    }

    void bindVertexBuffer(GLuint _id) { GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, _id)); }
    void bindIndexBuffer(GLuint _id) { GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _id)); }
    void activeTextureUnit(GLuint _unit) { GL_CHECK(glActiveTexture(getTextureUnit(_unit))); }
    void bindTexture(GLenum _target, GLuint _textureId) { GL_CHECK(glBindTexture(_target, _textureId)); }

    void configure() {
        s_textureUnit = -1;
        s_validGeneration++;
        VertexLayout::clearCache();

        blending.init(GL_FALSE);
        blendingFunc.init(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        culling.init(GL_TRUE);
        cullFace.init(GL_BACK);
        frontFace.init(GL_CCW);
        depthTest.init(GL_TRUE);
        depthWrite.init(GL_TRUE);

        GL_CHECK(glDisable(GL_STENCIL_TEST));
        GL_CHECK(glDepthFunc(GL_LESS));
        GL_CHECK(glClearDepthf(1.0));
        GL_CHECK(glDepthRangef(0.0, 1.0));

        static size_t max = std::numeric_limits<size_t>::max();

        clearColor.init(0.0, 0.0, 0.0, 0.0);
        shaderProgram.init(max, false);
        vertexBuffer.init(max, false);
        indexBuffer.init(max, false);
        texture.init(GL_TEXTURE_2D, max, false);
        texture.init(GL_TEXTURE_CUBE_MAP, max, false);
        textureUnit.init(max, false);
    }

    bool isValidGeneration(int _generation) {
        return _generation == s_validGeneration;
    }

    int generation() {
        return s_validGeneration;
    }

    int nextAvailableTextureUnit() {
        if (s_textureUnit + 1 > Hardware::maxCombinedTextureUnits) {
            LOGE("Too many combined texture units are being used");
            LOGE("GPU supports %d combined texture units", Hardware::maxCombinedTextureUnits);
        }

        return ++s_textureUnit;
    }

    void releaseTextureUnit() {
        s_textureUnit--;
    }

    int currentTextureUnit() {
        return s_textureUnit;
    }

    void resetTextureUnit() {
        s_textureUnit = -1;
    }
}

}
<commit_msg>Invalidate render state tracking of current texture binding (#784)<commit_after>#include "renderState.h"

#include "platform.h"
#include "vertexLayout.h"
#include "gl/hardware.h"

namespace Tangram {

 // Incremented when the GL context is invalidated
static int s_validGeneration;
static int s_textureUnit;

namespace RenderState {

    Blending blending;
    DepthTest depthTest;
    StencilTest stencilTest;
    Culling culling;
    DepthWrite depthWrite;
    BlendingFunc blendingFunc;
    StencilWrite stencilWrite;
    StencilFunc stencilFunc;
    StencilOp stencilOp;
    ColorWrite colorWrite;
    FrontFace frontFace;
    CullFace cullFace;

    VertexBuffer vertexBuffer;
    IndexBuffer indexBuffer;

    ShaderProgram shaderProgram;

    TextureUnit textureUnit;
    Texture texture;

    ClearColor clearColor;

    GLuint getTextureUnit(GLuint _unit) {
        return GL_TEXTURE0 + _unit;
    }

    static size_t max = std::numeric_limits<size_t>::max();

    void bindVertexBuffer(GLuint _id) {
        GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, _id));
    }

    void bindIndexBuffer(GLuint _id) {
        GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _id));
    }

    void activeTextureUnit(GLuint _unit) {
        // current texture unit is changing, invalidate current texture binding:
        texture.init(GL_TEXTURE_2D, max, false);
        GL_CHECK(glActiveTexture(getTextureUnit(_unit)));
    }

    void bindTexture(GLenum _target, GLuint _textureId) {
        GL_CHECK(glBindTexture(_target, _textureId));
    }

    void configure() {
        s_textureUnit = -1;
        s_validGeneration++;
        VertexLayout::clearCache();

        blending.init(GL_FALSE);
        blendingFunc.init(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        culling.init(GL_TRUE);
        cullFace.init(GL_BACK);
        frontFace.init(GL_CCW);
        depthTest.init(GL_TRUE);
        depthWrite.init(GL_TRUE);

        GL_CHECK(glDisable(GL_STENCIL_TEST));
        GL_CHECK(glDepthFunc(GL_LESS));
        GL_CHECK(glClearDepthf(1.0));
        GL_CHECK(glDepthRangef(0.0, 1.0));

        clearColor.init(0.0, 0.0, 0.0, 0.0);
        shaderProgram.init(max, false);
        vertexBuffer.init(max, false);
        indexBuffer.init(max, false);
        texture.init(GL_TEXTURE_2D, max, false);
        texture.init(GL_TEXTURE_CUBE_MAP, max, false);
        textureUnit.init(max, false);
    }

    bool isValidGeneration(int _generation) {
        return _generation == s_validGeneration;
    }

    int generation() {
        return s_validGeneration;
    }

    int nextAvailableTextureUnit() {
        if (s_textureUnit + 1 > Hardware::maxCombinedTextureUnits) {
            LOGE("Too many combined texture units are being used");
            LOGE("GPU supports %d combined texture units", Hardware::maxCombinedTextureUnits);
        }

        return ++s_textureUnit;
    }

    void releaseTextureUnit() {
        s_textureUnit--;
    }

    int currentTextureUnit() {
        return s_textureUnit;
    }

    void resetTextureUnit() {
        s_textureUnit = -1;
    }
}

}
<|endoftext|>


<commit_before>#include "pbfParser.h"

#include "tile/tile.h"
#include "platform.h"

namespace Tangram {

void PbfParser::extractGeometry(ParserContext& _ctx, protobuf::message& _geomIn) {

    pbfGeomCmd cmd = pbfGeomCmd::moveTo;
    uint32_t cmdRepeat = 0;

    double invTileExtent = (1.0/(double)_ctx.tileExtent);

    int64_t x = 0;
    int64_t y = 0;

    size_t numCoordinates = 0;

    while(_geomIn.getData() < _geomIn.getEnd()) {

        if(cmdRepeat == 0) { // get new command, lengh and parameters..
            uint32_t cmdData = static_cast<uint32_t>(_geomIn.varint());
            cmd = static_cast<pbfGeomCmd>(cmdData & 0x7); //first 3 bits of the cmdData
            cmdRepeat = cmdData >> 3; //last 5 bits
        }

        if(cmd == pbfGeomCmd::moveTo || cmd == pbfGeomCmd::lineTo) { // get parameters/points
            // if cmd is move then move to a new line/set of points and save this line
            if(cmd == pbfGeomCmd::moveTo) {
                if(_ctx.coordinates.size() > 0) {
                    _ctx.numCoordinates.push_back(numCoordinates);
                }
                numCoordinates = 0;
            }

            x += _geomIn.svarint();
            y += _geomIn.svarint();

            // bring the points in -1 to 1 space
            Point p;
            p.x = invTileExtent * (double)(2 * x - _ctx.tileExtent);
            p.y = invTileExtent * (double)(_ctx.tileExtent - 2 * y);

            _ctx.coordinates.push_back(p);
            numCoordinates++;

        } else if(cmd == pbfGeomCmd::closePath) {
            // end of a polygon, push first point in this line as last and push line to poly
            _ctx.coordinates.push_back(_ctx.coordinates[_ctx.coordinates.size() - numCoordinates]);
            _ctx.numCoordinates.push_back(numCoordinates + 1);
            numCoordinates = 0;
        }

        cmdRepeat--;
    }

    // Enter the last line
    if (numCoordinates > 0) {
        _ctx.numCoordinates.push_back(numCoordinates);
    }
}

void PbfParser::extractFeature(ParserContext& _ctx, protobuf::message& _featureIn, Feature& _out) {

    //Iterate through this feature
    protobuf::message geometry; // By default data_ and end_ are nullptr

    _ctx.properties.clear();
    _ctx.coordinates.clear();
    _ctx.numCoordinates.clear();

    while(_featureIn.next()) {
        switch(_featureIn.tag) {
            // Feature ID
            case 1:
                // ignored for now, also not used in json parsing
                _featureIn.skip();
                break;
            // Feature tags (properties)
            case 2:
            {
                // extract tags message
                protobuf::message tagsMsg = _featureIn.getMessage();

                while(tagsMsg) {
                    std::size_t tagKey = tagsMsg.varint();

                    if(_ctx.keys.size() <= tagKey) {
                        logMsg("ERROR: accessing out of bound key\n");
                        return;
                    }

                    if(!tagsMsg) {
                        logMsg("ERROR: uneven number of feature tag ids\n");
                        return;
                    }

                    std::size_t valueKey = tagsMsg.varint();

                    if( _ctx.values.size() <= valueKey ) {
                        logMsg("ERROR: accessing out of bound values\n");
                        return;
                    }

                    _ctx.properties.emplace_back(_ctx.keys[tagKey], _ctx.values[valueKey]);
                }
                break;
            }
            // Feature Type
            case 3:
                _out.geometryType = (GeometryType)_featureIn.varint();
                break;
            // Actual geometry data
            case 4:
                geometry = _featureIn.getMessage();
                extractGeometry(_ctx, geometry);
                break;
            // None.. skip
            default:
                _featureIn.skip();
                break;
        }
    }
    _out.props = std::move(_ctx.properties);

    switch(_out.geometryType) {
        case GeometryType::points:
            _out.points.insert(_out.points.begin(),
                               _ctx.coordinates.begin(),
                               _ctx.coordinates.end());
            break;

        case GeometryType::lines:
        case GeometryType::polygons:
        {
            std::vector<Line> lines;
            int offset = 0;
            lines.reserve(_ctx.numCoordinates.size());

            for (int length : _ctx.numCoordinates) {
                if (length == 0) {
                    continue;
                }

                lines.emplace_back();
                auto& line = lines.back();
                line.reserve(length);

                line.insert(line.begin(),
                            _ctx.coordinates.begin() + offset,
                            _ctx.coordinates.begin() + offset + length);

                offset += length;
            }
            if (_out.geometryType == GeometryType::lines) {
                _out.lines = std::move(lines);
            } else {
                _out.polygons.push_back(std::move(lines));
            }
            break;
        }
        case GeometryType::unknown:
            break;
        default:
            break;
    }

}

void PbfParser::extractLayer(ParserContext& _ctx, protobuf::message& _layerIn, Layer& _out) {

    _ctx.keys.clear();
    _ctx.values.clear();
    _ctx.featureMsgs.clear();

    //iterate layer to populate featureMsgs, keys and values
    while(_layerIn.next()) {
        switch(_layerIn.tag) {
            case 2: // features
            {
                _ctx.featureMsgs.push_back(_layerIn.getMessage());
                break;
            }

            case 3: // key string
            {
                _ctx.keys.push_back(_layerIn.string());
                break;
            }

            case 4: // values
            {
                protobuf::message valueItr = _layerIn.getMessage();

                while (valueItr.next()) {
                    switch (valueItr.tag) {
                        case 1: // string value
                            _ctx.values.push_back(valueItr.string());
                            break;
                        case 2: // float value
                            _ctx.values.push_back(valueItr.float32());
                            break;
                        case 3: // double value
                            _ctx.values.push_back(valueItr.float64());
                            break;
                        case 4: // int value
                            _ctx.values.push_back(valueItr.int64());
                            break;
                        case 5: // uint value
                            _ctx.values.push_back(valueItr.varint());
                            break;
                        case 6: // sint value
                            _ctx.values.push_back(valueItr.int64());
                            break;
                        case 7: // bool value
                            _ctx.values.push_back(valueItr.boolean());
                            break;
                        default:
                            _ctx.values.push_back(none_type{});
                            valueItr.skip();
                            break;
                    }
                }
                break;
            }

            case 5: //extent
                _ctx.tileExtent = static_cast<int>(_layerIn.int64());
                break;

            default: // skip
                _layerIn.skip();
                break;
        }
    }

    _out.features.reserve(_ctx.featureMsgs.size());
    for(auto& featureMsg : _ctx.featureMsgs) {
        _out.features.emplace_back();
        extractFeature(_ctx, featureMsg, _out.features.back());
    }
}

}
<commit_msg>move value string in pbf parser<commit_after>#include "pbfParser.h"

#include "tile/tile.h"
#include "platform.h"

namespace Tangram {

void PbfParser::extractGeometry(ParserContext& _ctx, protobuf::message& _geomIn) {

    pbfGeomCmd cmd = pbfGeomCmd::moveTo;
    uint32_t cmdRepeat = 0;

    double invTileExtent = (1.0/(double)_ctx.tileExtent);

    int64_t x = 0;
    int64_t y = 0;

    size_t numCoordinates = 0;

    while(_geomIn.getData() < _geomIn.getEnd()) {

        if(cmdRepeat == 0) { // get new command, lengh and parameters..
            uint32_t cmdData = static_cast<uint32_t>(_geomIn.varint());
            cmd = static_cast<pbfGeomCmd>(cmdData & 0x7); //first 3 bits of the cmdData
            cmdRepeat = cmdData >> 3; //last 5 bits
        }

        if(cmd == pbfGeomCmd::moveTo || cmd == pbfGeomCmd::lineTo) { // get parameters/points
            // if cmd is move then move to a new line/set of points and save this line
            if(cmd == pbfGeomCmd::moveTo) {
                if(_ctx.coordinates.size() > 0) {
                    _ctx.numCoordinates.push_back(numCoordinates);
                }
                numCoordinates = 0;
            }

            x += _geomIn.svarint();
            y += _geomIn.svarint();

            // bring the points in -1 to 1 space
            Point p;
            p.x = invTileExtent * (double)(2 * x - _ctx.tileExtent);
            p.y = invTileExtent * (double)(_ctx.tileExtent - 2 * y);

            _ctx.coordinates.push_back(p);
            numCoordinates++;

        } else if(cmd == pbfGeomCmd::closePath) {
            // end of a polygon, push first point in this line as last and push line to poly
            _ctx.coordinates.push_back(_ctx.coordinates[_ctx.coordinates.size() - numCoordinates]);
            _ctx.numCoordinates.push_back(numCoordinates + 1);
            numCoordinates = 0;
        }

        cmdRepeat--;
    }

    // Enter the last line
    if (numCoordinates > 0) {
        _ctx.numCoordinates.push_back(numCoordinates);
    }
}

void PbfParser::extractFeature(ParserContext& _ctx, protobuf::message& _featureIn, Feature& _out) {

    //Iterate through this feature
    protobuf::message geometry; // By default data_ and end_ are nullptr

    _ctx.properties.clear();
    _ctx.coordinates.clear();
    _ctx.numCoordinates.clear();

    while(_featureIn.next()) {
        switch(_featureIn.tag) {
            // Feature ID
            case 1:
                // ignored for now, also not used in json parsing
                _featureIn.skip();
                break;
            // Feature tags (properties)
            case 2:
            {
                // extract tags message
                protobuf::message tagsMsg = _featureIn.getMessage();

                while(tagsMsg) {
                    std::size_t tagKey = tagsMsg.varint();

                    if(_ctx.keys.size() <= tagKey) {
                        logMsg("ERROR: accessing out of bound key\n");
                        return;
                    }

                    if(!tagsMsg) {
                        logMsg("ERROR: uneven number of feature tag ids\n");
                        return;
                    }

                    std::size_t valueKey = tagsMsg.varint();

                    if( _ctx.values.size() <= valueKey ) {
                        logMsg("ERROR: accessing out of bound values\n");
                        return;
                    }

                    _ctx.properties.emplace_back(_ctx.keys[tagKey], _ctx.values[valueKey]);
                }
                break;
            }
            // Feature Type
            case 3:
                _out.geometryType = (GeometryType)_featureIn.varint();
                break;
            // Actual geometry data
            case 4:
                geometry = _featureIn.getMessage();
                extractGeometry(_ctx, geometry);
                break;
            // None.. skip
            default:
                _featureIn.skip();
                break;
        }
    }
    _out.props = std::move(_ctx.properties);

    switch(_out.geometryType) {
        case GeometryType::points:
            _out.points.insert(_out.points.begin(),
                               _ctx.coordinates.begin(),
                               _ctx.coordinates.end());
            break;

        case GeometryType::lines:
        case GeometryType::polygons:
        {
            std::vector<Line> lines;
            int offset = 0;
            lines.reserve(_ctx.numCoordinates.size());

            for (int length : _ctx.numCoordinates) {
                if (length == 0) {
                    continue;
                }

                lines.emplace_back();
                auto& line = lines.back();
                line.reserve(length);

                line.insert(line.begin(),
                            _ctx.coordinates.begin() + offset,
                            _ctx.coordinates.begin() + offset + length);

                offset += length;
            }
            if (_out.geometryType == GeometryType::lines) {
                _out.lines = std::move(lines);
            } else {
                _out.polygons.push_back(std::move(lines));
            }
            break;
        }
        case GeometryType::unknown:
            break;
        default:
            break;
    }

}

void PbfParser::extractLayer(ParserContext& _ctx, protobuf::message& _layerIn, Layer& _out) {

    _ctx.keys.clear();
    _ctx.values.clear();
    _ctx.featureMsgs.clear();

    //iterate layer to populate featureMsgs, keys and values
    while(_layerIn.next()) {
        switch(_layerIn.tag) {
            case 2: // features
            {
                _ctx.featureMsgs.push_back(_layerIn.getMessage());
                break;
            }

            case 3: // key string
            {
                _ctx.keys.push_back(_layerIn.string());
                break;
            }

            case 4: // values
            {
                protobuf::message valueItr = _layerIn.getMessage();

                while (valueItr.next()) {
                    switch (valueItr.tag) {
                        case 1: // string value
                            _ctx.values.push_back(std::move(valueItr.string()));
                            break;
                        case 2: // float value
                            _ctx.values.push_back(valueItr.float32());
                            break;
                        case 3: // double value
                            _ctx.values.push_back(valueItr.float64());
                            break;
                        case 4: // int value
                            _ctx.values.push_back(valueItr.int64());
                            break;
                        case 5: // uint value
                            _ctx.values.push_back(valueItr.varint());
                            break;
                        case 6: // sint value
                            _ctx.values.push_back(valueItr.int64());
                            break;
                        case 7: // bool value
                            _ctx.values.push_back(valueItr.boolean());
                            break;
                        default:
                            _ctx.values.push_back(none_type{});
                            valueItr.skip();
                            break;
                    }
                }
                break;
            }

            case 5: //extent
                _ctx.tileExtent = static_cast<int>(_layerIn.int64());
                break;

            default: // skip
                _layerIn.skip();
                break;
        }
    }

    _out.features.reserve(_ctx.featureMsgs.size());
    for(auto& featureMsg : _ctx.featureMsgs) {
        _out.features.emplace_back();
        extractFeature(_ctx, featureMsg, _out.features.back());
    }
}

}
<|endoftext|>


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

// This file implements the ViewGLContext and PbufferGLContext classes.

#include <dlfcn.h>
#include <GL/glew.h>
#include <GL/glxew.h>
#include <GL/glx.h>
#include <GL/osmew.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include "app/x11_util.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "app/gfx/gl/gl_context.h"
#include "app/gfx/gl/gl_context_osmesa.h"

namespace gfx {

typedef GLXContext GLContextHandle;
typedef GLXPbuffer PbufferHandle;

// This class is a wrapper around a GL context that renders directly to a
// window.
class ViewGLContext : public GLContext {
 public:
  explicit ViewGLContext(gfx::PluginWindowHandle window)
      : window_(window),
        context_(NULL) {
    DCHECK(window);
  }

  // Initializes the GL context.
  bool Initialize(bool multisampled);

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  gfx::PluginWindowHandle window_;
  GLContextHandle context_;

  DISALLOW_COPY_AND_ASSIGN(ViewGLContext);
};

// This class is a wrapper around a GL context used for offscreen rendering.
// It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful
// rendering.
class PbufferGLContext : public GLContext {
 public:
  explicit PbufferGLContext()
      : context_(NULL),
        pbuffer_(0) {
  }

  // Initializes the GL context.
  bool Initialize(void* shared_handle);

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  GLContextHandle context_;
  PbufferHandle pbuffer_;

  DISALLOW_COPY_AND_ASSIGN(PbufferGLContext);
};

// Backup context if Pbuffers (GLX 1.3) aren't supported. May run slower...
class PixmapGLContext : public GLContext {
 public:
  explicit PixmapGLContext()
      : context_(NULL),
        pixmap_(0),
        glx_pixmap_(0) {
  }

  // Initializes the GL context.
  bool Initialize(void* shared_handle);

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  GLContextHandle context_;
  Pixmap pixmap_;
  GLXPixmap glx_pixmap_;

  DISALLOW_COPY_AND_ASSIGN(PixmapGLContext);
};

// scoped_ptr functor for XFree(). Use as follows:
//   scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> foo(...);
// where "XVisualInfo" is any X type that is freed with XFree.
class ScopedPtrXFree {
 public:
  void operator()(void* x) const {
    ::XFree(x);
  }
};

// Some versions of NVIDIA's GL libGL.so include a broken version of
// dlopen/dlsym, and so linking it into chrome breaks it. So we dynamically
// load it, and use glew to dynamically resolve symbols.
// See http://code.google.com/p/chromium/issues/detail?id=16800

static bool InitializeOneOff() {
  static bool initialized = false;
  if (initialized)
    return true;

  osmewInit();
  if (!OSMesaCreateContext) {
    void* handle = dlopen("libGL.so.1", RTLD_LAZY | RTLD_GLOBAL);
    if (!handle) {
      LOG(ERROR) << "Could not find libGL.so.1";
      return false;
    }

    // Initializes context-independent parts of GLEW
    if (glxewInit() != GLEW_OK) {
      LOG(ERROR) << "glxewInit failed";
      return false;
    }
    // glxewContextInit really only needs a display connection to
    // complete, and we don't want to have to create an OpenGL context
    // just to get access to GLX 1.3 entry points to create pbuffers.
    // We therefore added a glxewContextInitWithDisplay entry point.
    Display* display = x11_util::GetXDisplay();
    if (glxewContextInitWithDisplay(display) != GLEW_OK) {
      LOG(ERROR) << "glxewContextInit failed";
      return false;
    }
  }

  initialized = true;
  return true;
}

bool ViewGLContext::Initialize(bool multisampled) {
  if (multisampled) {
    DLOG(WARNING) << "Multisampling not implemented.";
  }

  Display* display = x11_util::GetXDisplay();
  XWindowAttributes attributes;
  XGetWindowAttributes(display, window_, &attributes);
  XVisualInfo visual_info_template;
  visual_info_template.visualid = XVisualIDFromVisual(attributes.visual);
  int visual_info_count = 0;
  scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info_list(
      XGetVisualInfo(display, VisualIDMask,
                     &visual_info_template,
                     &visual_info_count));
  DCHECK(visual_info_list.get());
  DCHECK_GT(visual_info_count, 0);
  context_ = NULL;
  for (int i = 0; i < visual_info_count; ++i) {
    context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True);
    if (context_)
      break;
  }
  if (!context_) {
    DLOG(ERROR) << "Couldn't create GL context.";
    return false;
  }

  if (!MakeCurrent()) {
    Destroy();
    DLOG(ERROR) << "Couldn't make context current for initialization.";
    return false;
  }

  if (!InitializeGLEW()) {
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    Destroy();
    return false;
  }

  return true;
}

void ViewGLContext::Destroy() {
  Display* display = x11_util::GetXDisplay();
  Bool result = glXMakeCurrent(display, 0, 0);

  // glXMakeCurrent isn't supposed to fail when unsetting the context, unless
  // we have pending draws on an invalid window - which shouldn't be the case
  // here.
  DCHECK(result);
  if (context_) {
    glXDestroyContext(display, context_);
    context_ = NULL;
  }
}

bool ViewGLContext::MakeCurrent() {
  if (IsCurrent()) {
    return true;
  }

  Display* display = x11_util::GetXDisplay();
  if (glXMakeCurrent(display, window_, context_) != True) {
    glXDestroyContext(display, context_);
    context_ = 0;
    DLOG(ERROR) << "Couldn't make context current.";
    return false;
  }

  return true;
}

bool ViewGLContext::IsCurrent() {
  return glXGetCurrentDrawable() == window_ &&
      glXGetCurrentContext() == context_;
}

bool ViewGLContext::IsOffscreen() {
  return false;
}

void ViewGLContext::SwapBuffers() {
  Display* display = x11_util::GetXDisplay();
  glXSwapBuffers(display, window_);
}

gfx::Size ViewGLContext::GetSize() {
  XWindowAttributes attributes;
  Display* display = x11_util::GetXDisplay();
  XGetWindowAttributes(display, window_, &attributes);
  return gfx::Size(attributes.width, attributes.height);
}

void* ViewGLContext::GetHandle() {
  return context_;
}

GLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window,
                                          bool multisampled) {
  if (!InitializeOneOff())
    return NULL;

  if (OSMesaCreateContext) {
    // TODO(apatrick): Support OSMesa rendering to a window on Linux.
    NOTREACHED() << "OSMesa rendering to a window is not yet implemented.";
    return NULL;
  } else {
    scoped_ptr<ViewGLContext> context(new ViewGLContext(window));

    if (!context->Initialize(multisampled))
      return NULL;

    return context.release();
  }
}

bool PbufferGLContext::Initialize(void* shared_handle) {
  if (!glXChooseFBConfig ||
      !glXCreateNewContext ||
      !glXCreatePbuffer ||
      !glXDestroyPbuffer) {
    DLOG(ERROR) << "Pbuffer support not available.";
    return false;
  }

  static const int config_attributes[] = {
    GLX_DRAWABLE_TYPE,
    GLX_PBUFFER_BIT,
    GLX_RENDER_TYPE,
    GLX_RGBA_BIT,
    GLX_DOUBLEBUFFER,
    0,
    0
  };

  Display* display = x11_util::GetXDisplay();

  int nelements = 0;
  // TODO(kbr): figure out whether hardcoding screen to 0 is sufficient.
  scoped_ptr_malloc<GLXFBConfig, ScopedPtrXFree> config(
      glXChooseFBConfig(display, 0, config_attributes, &nelements));
  if (!config.get()) {
    DLOG(ERROR) << "glXChooseFBConfig failed.";
    return false;
  }
  if (!nelements) {
    DLOG(ERROR) << "glXChooseFBConfig returned 0 elements.";
    return false;
  }
  context_ = glXCreateNewContext(display,
                                 config.get()[0],
                                 GLX_RGBA_TYPE,
                                 static_cast<GLContextHandle>(shared_handle),
                                 True);
  if (!context_) {
    DLOG(ERROR) << "glXCreateNewContext failed.";
    return false;
  }
  static const int pbuffer_attributes[] = {
    GLX_PBUFFER_WIDTH,
    1,
    GLX_PBUFFER_HEIGHT,
    1,
    0
  };
  pbuffer_ = glXCreatePbuffer(display,
                              config.get()[0], pbuffer_attributes);
  if (!pbuffer_) {
    Destroy();
    DLOG(ERROR) << "glXCreatePbuffer failed.";
    return false;
  }

  if (!MakeCurrent()) {
    Destroy();
    DLOG(ERROR) << "Couldn't make context current for initialization.";
    return false;
  }

  if (!InitializeGLEW()) {
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    Destroy();
    return false;
  }

  return true;
}

void PbufferGLContext::Destroy() {
  Display* display = x11_util::GetXDisplay();
  Bool result = glXMakeCurrent(display, 0, 0);
  // glXMakeCurrent isn't supposed to fail when unsetting the context, unless
  // we have pending draws on an invalid window - which shouldn't be the case
  // here.
  DCHECK(result);
  if (context_) {
    glXDestroyContext(display, context_);
    context_ = NULL;
  }

  if (pbuffer_) {
    glXDestroyPbuffer(display, pbuffer_);
    pbuffer_ = 0;
  }
}

bool PbufferGLContext::MakeCurrent() {
  if (IsCurrent()) {
    return true;
  }
  Display* display = x11_util::GetXDisplay();
  if (glXMakeCurrent(display, pbuffer_, context_) != True) {
    glXDestroyContext(display, context_);
    context_ = NULL;
    DLOG(ERROR) << "Couldn't make context current.";
    return false;
  }

  return true;
}

bool PbufferGLContext::IsCurrent() {
  return glXGetCurrentDrawable() == pbuffer_ &&
      glXGetCurrentContext() == context_;
}

bool PbufferGLContext::IsOffscreen() {
  return true;
}

void PbufferGLContext::SwapBuffers() {
  NOTREACHED() << "Attempted to call SwapBuffers on a pbuffer.";
}

gfx::Size PbufferGLContext::GetSize() {
  NOTREACHED() << "Should not be requesting size of this pbuffer.";
  return gfx::Size(1, 1);
}

void* PbufferGLContext::GetHandle() {
  return context_;
}

bool PixmapGLContext::Initialize(void* shared_handle) {
  DLOG(INFO) << "GL context: using pixmaps.";
  if (!glXChooseVisual ||
      !glXCreateGLXPixmap ||
      !glXDestroyGLXPixmap) {
    DLOG(ERROR) << "Pixmap support not available.";
    return false;
  }

  static int attributes[] = {
    GLX_RGBA,
    0
  };

  Display* display = x11_util::GetXDisplay();
  int screen = DefaultScreen(display);

  scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info(
      glXChooseVisual(display, screen, attributes));

  if (!visual_info.get()) {
    DLOG(ERROR) << "glXChooseVisual failed.";
    return false;
  }
  context_ = glXCreateContext(display, visual_info.get(),
                              static_cast<GLContextHandle>(shared_handle),
                              True);
  if (!context_) {
    DLOG(ERROR) << "glXCreateContext failed.";
    return false;
  }

  pixmap_ = XCreatePixmap(display, RootWindow(display, screen), 1, 1,
                          visual_info->depth);
  if (!pixmap_) {
    DLOG(ERROR) << "XCreatePixmap failed.";
    return false;
  }

  glx_pixmap_ = glXCreateGLXPixmap(display, visual_info.get(), pixmap_);
  if (!glx_pixmap_) {
    DLOG(ERROR) << "XCreatePixmap failed.";
    return false;
  }

  if (!MakeCurrent()) {
    Destroy();
    DLOG(ERROR) << "Couldn't make context current for initialization.";
    return false;
  }

  if (!InitializeGLEW()) {
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    Destroy();
    return false;
  }

  return true;
}

void PixmapGLContext::Destroy() {
  Display* display = x11_util::GetXDisplay();
  Bool result = glXMakeCurrent(display, 0, 0);
  // glXMakeCurrent isn't supposed to fail when unsetting the context, unless
  // we have pending draws on an invalid window - which shouldn't be the case
  // here.
  DCHECK(result);
  if (context_) {
    glXDestroyContext(display, context_);
    context_ = NULL;
  }

  if (glx_pixmap_) {
    glXDestroyGLXPixmap(display, glx_pixmap_);
    glx_pixmap_ = 0;
  }

  if (pixmap_) {
    XFreePixmap(display, pixmap_);
    pixmap_ = 0;
  }
}

bool PixmapGLContext::MakeCurrent() {
  if (IsCurrent()) {
    return true;
  }
  Display* display = x11_util::GetXDisplay();
  if (glXMakeCurrent(display, glx_pixmap_, context_) != True) {
    glXDestroyContext(display, context_);
    context_ = NULL;
    DLOG(ERROR) << "Couldn't make context current.";
    return false;
  }

  return true;
}

bool PixmapGLContext::IsCurrent() {
  return glXGetCurrentDrawable() == glx_pixmap_ &&
      glXGetCurrentContext() == context_;
}

bool PixmapGLContext::IsOffscreen() {
  return true;
}

void PixmapGLContext::SwapBuffers() {
  NOTREACHED() << "Attempted to call SwapBuffers on a pixmap.";
}

gfx::Size PixmapGLContext::GetSize() {
  NOTREACHED() << "Should not be requesting size of this pixmap.";
  return gfx::Size(1, 1);
}

void* PixmapGLContext::GetHandle() {
  return context_;
}

GLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) {
  if (!InitializeOneOff())
    return NULL;

  if (OSMesaCreateContext) {
    scoped_ptr<OSMesaGLContext> context(new OSMesaGLContext);

    if (!context->Initialize(shared_handle))
      return NULL;

    return context.release();
  } else {
    scoped_ptr<PbufferGLContext> context(new PbufferGLContext);
    if (context->Initialize(shared_handle))
      return context.release();

    scoped_ptr<PixmapGLContext> context_pixmap(new PixmapGLContext);
    if (context_pixmap->Initialize(shared_handle))
      return context_pixmap.release();

    return NULL;
  }
}

}  // namespace gfx
<commit_msg>Changed DLOG to LOG in gl_context_linux.cc to get informative error messages even in release builds when WebGL initialization fails.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file implements the ViewGLContext and PbufferGLContext classes.

#include <dlfcn.h>
#include <GL/glew.h>
#include <GL/glxew.h>
#include <GL/glx.h>
#include <GL/osmew.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include "app/x11_util.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "app/gfx/gl/gl_context.h"
#include "app/gfx/gl/gl_context_osmesa.h"

namespace gfx {

typedef GLXContext GLContextHandle;
typedef GLXPbuffer PbufferHandle;

// This class is a wrapper around a GL context that renders directly to a
// window.
class ViewGLContext : public GLContext {
 public:
  explicit ViewGLContext(gfx::PluginWindowHandle window)
      : window_(window),
        context_(NULL) {
    DCHECK(window);
  }

  // Initializes the GL context.
  bool Initialize(bool multisampled);

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  gfx::PluginWindowHandle window_;
  GLContextHandle context_;

  DISALLOW_COPY_AND_ASSIGN(ViewGLContext);
};

// This class is a wrapper around a GL context used for offscreen rendering.
// It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful
// rendering.
class PbufferGLContext : public GLContext {
 public:
  explicit PbufferGLContext()
      : context_(NULL),
        pbuffer_(0) {
  }

  // Initializes the GL context.
  bool Initialize(void* shared_handle);

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  GLContextHandle context_;
  PbufferHandle pbuffer_;

  DISALLOW_COPY_AND_ASSIGN(PbufferGLContext);
};

// Backup context if Pbuffers (GLX 1.3) aren't supported. May run slower...
class PixmapGLContext : public GLContext {
 public:
  explicit PixmapGLContext()
      : context_(NULL),
        pixmap_(0),
        glx_pixmap_(0) {
  }

  // Initializes the GL context.
  bool Initialize(void* shared_handle);

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  GLContextHandle context_;
  Pixmap pixmap_;
  GLXPixmap glx_pixmap_;

  DISALLOW_COPY_AND_ASSIGN(PixmapGLContext);
};

// scoped_ptr functor for XFree(). Use as follows:
//   scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> foo(...);
// where "XVisualInfo" is any X type that is freed with XFree.
class ScopedPtrXFree {
 public:
  void operator()(void* x) const {
    ::XFree(x);
  }
};

// Some versions of NVIDIA's GL libGL.so include a broken version of
// dlopen/dlsym, and so linking it into chrome breaks it. So we dynamically
// load it, and use glew to dynamically resolve symbols.
// See http://code.google.com/p/chromium/issues/detail?id=16800

static bool InitializeOneOff() {
  static bool initialized = false;
  if (initialized)
    return true;

  osmewInit();
  if (!OSMesaCreateContext) {
    void* handle = dlopen("libGL.so.1", RTLD_LAZY | RTLD_GLOBAL);
    if (!handle) {
      LOG(ERROR) << "Could not find libGL.so.1";
      return false;
    }

    // Initializes context-independent parts of GLEW
    if (glxewInit() != GLEW_OK) {
      LOG(ERROR) << "glxewInit failed";
      return false;
    }
    // glxewContextInit really only needs a display connection to
    // complete, and we don't want to have to create an OpenGL context
    // just to get access to GLX 1.3 entry points to create pbuffers.
    // We therefore added a glxewContextInitWithDisplay entry point.
    Display* display = x11_util::GetXDisplay();
    if (glxewContextInitWithDisplay(display) != GLEW_OK) {
      LOG(ERROR) << "glxewContextInit failed";
      return false;
    }
  }

  initialized = true;
  return true;
}

bool ViewGLContext::Initialize(bool multisampled) {
  if (multisampled) {
    LOG(WARNING) << "Multisampling not implemented.";
  }

  Display* display = x11_util::GetXDisplay();
  XWindowAttributes attributes;
  XGetWindowAttributes(display, window_, &attributes);
  XVisualInfo visual_info_template;
  visual_info_template.visualid = XVisualIDFromVisual(attributes.visual);
  int visual_info_count = 0;
  scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info_list(
      XGetVisualInfo(display, VisualIDMask,
                     &visual_info_template,
                     &visual_info_count));
  DCHECK(visual_info_list.get());
  DCHECK_GT(visual_info_count, 0);
  context_ = NULL;
  for (int i = 0; i < visual_info_count; ++i) {
    context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True);
    if (context_)
      break;
  }
  if (!context_) {
    LOG(ERROR) << "Couldn't create GL context.";
    return false;
  }

  if (!MakeCurrent()) {
    Destroy();
    LOG(ERROR) << "Couldn't make context current for initialization.";
    return false;
  }

  if (!InitializeGLEW()) {
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    Destroy();
    return false;
  }

  return true;
}

void ViewGLContext::Destroy() {
  Display* display = x11_util::GetXDisplay();
  Bool result = glXMakeCurrent(display, 0, 0);

  // glXMakeCurrent isn't supposed to fail when unsetting the context, unless
  // we have pending draws on an invalid window - which shouldn't be the case
  // here.
  DCHECK(result);
  if (context_) {
    glXDestroyContext(display, context_);
    context_ = NULL;
  }
}

bool ViewGLContext::MakeCurrent() {
  if (IsCurrent()) {
    return true;
  }

  Display* display = x11_util::GetXDisplay();
  if (glXMakeCurrent(display, window_, context_) != True) {
    glXDestroyContext(display, context_);
    context_ = 0;
    LOG(ERROR) << "Couldn't make context current.";
    return false;
  }

  return true;
}

bool ViewGLContext::IsCurrent() {
  return glXGetCurrentDrawable() == window_ &&
      glXGetCurrentContext() == context_;
}

bool ViewGLContext::IsOffscreen() {
  return false;
}

void ViewGLContext::SwapBuffers() {
  Display* display = x11_util::GetXDisplay();
  glXSwapBuffers(display, window_);
}

gfx::Size ViewGLContext::GetSize() {
  XWindowAttributes attributes;
  Display* display = x11_util::GetXDisplay();
  XGetWindowAttributes(display, window_, &attributes);
  return gfx::Size(attributes.width, attributes.height);
}

void* ViewGLContext::GetHandle() {
  return context_;
}

GLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window,
                                          bool multisampled) {
  if (!InitializeOneOff())
    return NULL;

  if (OSMesaCreateContext) {
    // TODO(apatrick): Support OSMesa rendering to a window on Linux.
    NOTREACHED() << "OSMesa rendering to a window is not yet implemented.";
    return NULL;
  } else {
    scoped_ptr<ViewGLContext> context(new ViewGLContext(window));

    if (!context->Initialize(multisampled))
      return NULL;

    return context.release();
  }
}

bool PbufferGLContext::Initialize(void* shared_handle) {
  if (!glXChooseFBConfig ||
      !glXCreateNewContext ||
      !glXCreatePbuffer ||
      !glXDestroyPbuffer) {
    LOG(ERROR) << "Pbuffer support not available.";
    return false;
  }

  static const int config_attributes[] = {
    GLX_DRAWABLE_TYPE,
    GLX_PBUFFER_BIT,
    GLX_RENDER_TYPE,
    GLX_RGBA_BIT,
    GLX_DOUBLEBUFFER,
    0,
    0
  };

  Display* display = x11_util::GetXDisplay();

  int nelements = 0;
  // TODO(kbr): figure out whether hardcoding screen to 0 is sufficient.
  scoped_ptr_malloc<GLXFBConfig, ScopedPtrXFree> config(
      glXChooseFBConfig(display, 0, config_attributes, &nelements));
  if (!config.get()) {
    LOG(ERROR) << "glXChooseFBConfig failed.";
    return false;
  }
  if (!nelements) {
    LOG(ERROR) << "glXChooseFBConfig returned 0 elements.";
    return false;
  }
  context_ = glXCreateNewContext(display,
                                 config.get()[0],
                                 GLX_RGBA_TYPE,
                                 static_cast<GLContextHandle>(shared_handle),
                                 True);
  if (!context_) {
    LOG(ERROR) << "glXCreateNewContext failed.";
    return false;
  }
  static const int pbuffer_attributes[] = {
    GLX_PBUFFER_WIDTH,
    1,
    GLX_PBUFFER_HEIGHT,
    1,
    0
  };
  pbuffer_ = glXCreatePbuffer(display,
                              config.get()[0], pbuffer_attributes);
  if (!pbuffer_) {
    Destroy();
    LOG(ERROR) << "glXCreatePbuffer failed.";
    return false;
  }

  if (!MakeCurrent()) {
    Destroy();
    LOG(ERROR) << "Couldn't make context current for initialization.";
    return false;
  }

  if (!InitializeGLEW()) {
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    Destroy();
    return false;
  }

  return true;
}

void PbufferGLContext::Destroy() {
  Display* display = x11_util::GetXDisplay();
  Bool result = glXMakeCurrent(display, 0, 0);
  // glXMakeCurrent isn't supposed to fail when unsetting the context, unless
  // we have pending draws on an invalid window - which shouldn't be the case
  // here.
  DCHECK(result);
  if (context_) {
    glXDestroyContext(display, context_);
    context_ = NULL;
  }

  if (pbuffer_) {
    glXDestroyPbuffer(display, pbuffer_);
    pbuffer_ = 0;
  }
}

bool PbufferGLContext::MakeCurrent() {
  if (IsCurrent()) {
    return true;
  }
  Display* display = x11_util::GetXDisplay();
  if (glXMakeCurrent(display, pbuffer_, context_) != True) {
    glXDestroyContext(display, context_);
    context_ = NULL;
    LOG(ERROR) << "Couldn't make context current.";
    return false;
  }

  return true;
}

bool PbufferGLContext::IsCurrent() {
  return glXGetCurrentDrawable() == pbuffer_ &&
      glXGetCurrentContext() == context_;
}

bool PbufferGLContext::IsOffscreen() {
  return true;
}

void PbufferGLContext::SwapBuffers() {
  NOTREACHED() << "Attempted to call SwapBuffers on a pbuffer.";
}

gfx::Size PbufferGLContext::GetSize() {
  NOTREACHED() << "Should not be requesting size of this pbuffer.";
  return gfx::Size(1, 1);
}

void* PbufferGLContext::GetHandle() {
  return context_;
}

bool PixmapGLContext::Initialize(void* shared_handle) {
  LOG(INFO) << "GL context: using pixmaps.";
  if (!glXChooseVisual ||
      !glXCreateGLXPixmap ||
      !glXDestroyGLXPixmap) {
    LOG(ERROR) << "Pixmap support not available.";
    return false;
  }

  static int attributes[] = {
    GLX_RGBA,
    0
  };

  Display* display = x11_util::GetXDisplay();
  int screen = DefaultScreen(display);

  scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info(
      glXChooseVisual(display, screen, attributes));

  if (!visual_info.get()) {
    LOG(ERROR) << "glXChooseVisual failed.";
    return false;
  }
  context_ = glXCreateContext(display, visual_info.get(),
                              static_cast<GLContextHandle>(shared_handle),
                              True);
  if (!context_) {
    LOG(ERROR) << "glXCreateContext failed.";
    return false;
  }

  pixmap_ = XCreatePixmap(display, RootWindow(display, screen), 1, 1,
                          visual_info->depth);
  if (!pixmap_) {
    LOG(ERROR) << "XCreatePixmap failed.";
    return false;
  }

  glx_pixmap_ = glXCreateGLXPixmap(display, visual_info.get(), pixmap_);
  if (!glx_pixmap_) {
    LOG(ERROR) << "XCreatePixmap failed.";
    return false;
  }

  if (!MakeCurrent()) {
    Destroy();
    LOG(ERROR) << "Couldn't make context current for initialization.";
    return false;
  }

  if (!InitializeGLEW()) {
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    Destroy();
    return false;
  }

  return true;
}

void PixmapGLContext::Destroy() {
  Display* display = x11_util::GetXDisplay();
  Bool result = glXMakeCurrent(display, 0, 0);
  // glXMakeCurrent isn't supposed to fail when unsetting the context, unless
  // we have pending draws on an invalid window - which shouldn't be the case
  // here.
  DCHECK(result);
  if (context_) {
    glXDestroyContext(display, context_);
    context_ = NULL;
  }

  if (glx_pixmap_) {
    glXDestroyGLXPixmap(display, glx_pixmap_);
    glx_pixmap_ = 0;
  }

  if (pixmap_) {
    XFreePixmap(display, pixmap_);
    pixmap_ = 0;
  }
}

bool PixmapGLContext::MakeCurrent() {
  if (IsCurrent()) {
    return true;
  }
  Display* display = x11_util::GetXDisplay();
  if (glXMakeCurrent(display, glx_pixmap_, context_) != True) {
    glXDestroyContext(display, context_);
    context_ = NULL;
    LOG(ERROR) << "Couldn't make context current.";
    return false;
  }

  return true;
}

bool PixmapGLContext::IsCurrent() {
  return glXGetCurrentDrawable() == glx_pixmap_ &&
      glXGetCurrentContext() == context_;
}

bool PixmapGLContext::IsOffscreen() {
  return true;
}

void PixmapGLContext::SwapBuffers() {
  NOTREACHED() << "Attempted to call SwapBuffers on a pixmap.";
}

gfx::Size PixmapGLContext::GetSize() {
  NOTREACHED() << "Should not be requesting size of this pixmap.";
  return gfx::Size(1, 1);
}

void* PixmapGLContext::GetHandle() {
  return context_;
}

GLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) {
  if (!InitializeOneOff())
    return NULL;

  if (OSMesaCreateContext) {
    scoped_ptr<OSMesaGLContext> context(new OSMesaGLContext);

    if (!context->Initialize(shared_handle))
      return NULL;

    return context.release();
  } else {
    scoped_ptr<PbufferGLContext> context(new PbufferGLContext);
    if (context->Initialize(shared_handle))
      return context.release();

    scoped_ptr<PixmapGLContext> context_pixmap(new PixmapGLContext);
    if (context_pixmap->Initialize(shared_handle))
      return context_pixmap.release();

    return NULL;
  }
}

}  // namespace gfx
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<x<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int a[105][105];
int n;

int dp[105][105]={0};

void Init(){
	scanf("%d",&n);

	REP(i,1,n)
	REP(j,1,i){

		scanf("%d",&a[i][j]);
	}

	return ;
}

void Solve(){

	dp[0][0]=0;

	REPD(i,n,1)
	REP(j,1,i){
		print(a[i][j]<<" "<<dp[i+1][j]<<" "<<dp[i+1][j-1]);
		dp[i][j]=a[i][j]+max(dp[i+1][j],dp[i+1][j-1]);
	}

	REP(i,1,n){
	REP(j,1,n){
	cout<<dp[i][j]<<"\t";}
	cout<<endl;}
	return ;
}

int main(){

	freopen("hdu2084.in","r",stdin);

	int T;
	scanf("%d",&T);

	while(T--)
	Init(),Solve();
	return 0;
}<commit_msg>update hdu2084<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<x<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int a[105][105];
int n;

int dp[105][105]={0};

void Init(){
	scanf("%d",&n);

	REP(i,1,n)
	REP(j,1,i){

		scanf("%d",&a[i][j]);
	}

	return ;
}

void Solve(){

	dp[0][0]=0;

	REPD(i,n,1)
	REP(j,1,i){
		print(a[i][j]<<" "<<dp[i+1][j]<<" "<<dp[i+1][j+1]);
		dp[i][j]=a[i][j]+max(dp[i+1][j],dp[i+1][j+1]);
	}

	REP(i,1,n){
	REP(j,1,n){
	cout<<dp[i][j]<<"\t";}
	cout<<endl;}
	return ;
}

int main(){

	freopen("hdu2084.in","r",stdin);

	int T;
	scanf("%d",&T);

	while(T--)
	Init(),Solve();
	return 0;
}<|endoftext|>


<commit_before>#include "Runtime/CResFactory.hpp"

#include "Runtime/CSimplePool.hpp"
#include "Runtime/CStopwatch.hpp"

namespace urde {
static logvisor::Module Log("CResFactory");

void CResFactory::AddToLoadList(SLoadingData&& data) {
  const SObjectTag tag = data.x0_tag;
  m_loadMap.insert_or_assign(tag, m_loadList.insert(m_loadList.end(), std::move(data)));
}

CFactoryFnReturn CResFactory::BuildSync(const SObjectTag& tag, const CVParamTransfer& xfer, CObjectReference* selfRef) {
  CFactoryFnReturn ret;
  if (x5c_factoryMgr.CanMakeMemory(tag)) {
    std::unique_ptr<uint8_t[]> data;
    int size = 0;
    x4_loader.LoadMemResourceSync(tag, data, &size);
    if (size)
      ret = x5c_factoryMgr.MakeObjectFromMemory(tag, std::move(data), size, x4_loader.GetResourceCompression(tag), xfer,
                                                selfRef);
    else
      ret = std::make_unique<TObjOwnerDerivedFromIObjUntyped>(nullptr);
  } else {
    if (auto rp = x4_loader.LoadNewResourceSync(tag, nullptr))
      ret = x5c_factoryMgr.MakeObject(tag, *rp, xfer, selfRef);
    else
      ret = std::make_unique<TObjOwnerDerivedFromIObjUntyped>(nullptr);
  }
  Log.report(logvisor::Warning, FMT_STRING("sync-built {}"), tag);
  return ret;
}

bool CResFactory::PumpResource(SLoadingData& data) {
  if (data.x8_dvdReq && data.x8_dvdReq->IsComplete()) {
    data.x8_dvdReq.reset();
    *data.xc_targetPtr =
        x5c_factoryMgr.MakeObjectFromMemory(data.x0_tag, std::move(data.x10_loadBuffer), data.x14_resSize,
                                            data.m_compressed, data.x18_cvXfer, data.m_selfRef);
    Log.report(logvisor::Info, FMT_STRING("async-built {}"), data.x0_tag);
    return true;
  }
  return false;
}

std::unique_ptr<IObj> CResFactory::Build(const SObjectTag& tag, const CVParamTransfer& xfer,
                                         CObjectReference* selfRef) {
  auto search = m_loadMap.find(tag);
  if (search != m_loadMap.end()) {
    while (!PumpResource(*search->second) || !search->second->xc_targetPtr) {}
    std::unique_ptr<IObj> ret = std::move(*search->second->xc_targetPtr);
    m_loadList.erase(search->second);
    m_loadMap.erase(search);
    return ret;
  }
  return BuildSync(tag, xfer, selfRef);
}

void CResFactory::BuildAsync(const SObjectTag& tag, const CVParamTransfer& xfer, std::unique_ptr<IObj>* target,
                             CObjectReference* selfRef) {
  auto search = m_loadMap.find(tag);
  if (search == m_loadMap.end()) {
    SLoadingData data(tag, target, xfer, x4_loader.GetResourceCompression(tag), selfRef);
    data.x14_resSize = x4_loader.ResourceSize(tag);
    if (data.x14_resSize) {
      data.x10_loadBuffer = std::unique_ptr<u8[]>(new u8[data.x14_resSize]);
      data.x8_dvdReq = x4_loader.LoadResourceAsync(tag, data.x10_loadBuffer.get());
      AddToLoadList(std::move(data));
    } else {
      *target = std::make_unique<TObjOwnerDerivedFromIObjUntyped>(nullptr);
    }
  }
}

void CResFactory::AsyncIdle() {
  if (m_loadList.empty())
    return;
  auto startTime = std::chrono::steady_clock::now();
  while (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - startTime).count() <
         2) {
    auto& task = m_loadList.front();
    if (PumpResource(task)) {
      m_loadMap.erase(task.x0_tag);
      m_loadList.pop_front();
      if (m_loadList.empty())
        return;
    }
  }
}

void CResFactory::CancelBuild(const SObjectTag& tag) {
  auto search = m_loadMap.find(tag);
  if (search != m_loadMap.end()) {
    if (search->second->x8_dvdReq)
      search->second->x8_dvdReq->PostCancelRequest();
    m_loadList.erase(search->second);
    m_loadMap.erase(search);
  }
}

void CResFactory::LoadPersistentResources(CSimplePool& sp) {
  const auto& paks = x4_loader.GetPaks();
  for (auto it = paks.begin(); it != paks.end(); ++it) {
    if (!(*it)->IsWorldPak()) {
      for (const CAssetId& id : (*it)->GetDepList()) {
        SObjectTag tag(GetResourceTypeById(id), id);
        m_nonWorldTokens.push_back(sp.GetObj(tag));
        m_nonWorldTokens.back().Lock();
      }
    }
  }
}

} // namespace urde
<commit_msg>Change CResFactory::AsyncIdle timeout to 5ms<commit_after>#include "Runtime/CResFactory.hpp"

#include "Runtime/CSimplePool.hpp"
#include "Runtime/CStopwatch.hpp"

namespace urde {
static logvisor::Module Log("CResFactory");

void CResFactory::AddToLoadList(SLoadingData&& data) {
  const SObjectTag tag = data.x0_tag;
  m_loadMap.insert_or_assign(tag, m_loadList.insert(m_loadList.end(), std::move(data)));
}

CFactoryFnReturn CResFactory::BuildSync(const SObjectTag& tag, const CVParamTransfer& xfer, CObjectReference* selfRef) {
  CFactoryFnReturn ret;
  if (x5c_factoryMgr.CanMakeMemory(tag)) {
    std::unique_ptr<uint8_t[]> data;
    int size = 0;
    x4_loader.LoadMemResourceSync(tag, data, &size);
    if (size)
      ret = x5c_factoryMgr.MakeObjectFromMemory(tag, std::move(data), size, x4_loader.GetResourceCompression(tag), xfer,
                                                selfRef);
    else
      ret = std::make_unique<TObjOwnerDerivedFromIObjUntyped>(nullptr);
  } else {
    if (auto rp = x4_loader.LoadNewResourceSync(tag, nullptr))
      ret = x5c_factoryMgr.MakeObject(tag, *rp, xfer, selfRef);
    else
      ret = std::make_unique<TObjOwnerDerivedFromIObjUntyped>(nullptr);
  }
  Log.report(logvisor::Warning, FMT_STRING("sync-built {}"), tag);
  return ret;
}

bool CResFactory::PumpResource(SLoadingData& data) {
  if (data.x8_dvdReq && data.x8_dvdReq->IsComplete()) {
    data.x8_dvdReq.reset();
    *data.xc_targetPtr =
        x5c_factoryMgr.MakeObjectFromMemory(data.x0_tag, std::move(data.x10_loadBuffer), data.x14_resSize,
                                            data.m_compressed, data.x18_cvXfer, data.m_selfRef);
    Log.report(logvisor::Info, FMT_STRING("async-built {}"), data.x0_tag);
    return true;
  }
  return false;
}

std::unique_ptr<IObj> CResFactory::Build(const SObjectTag& tag, const CVParamTransfer& xfer,
                                         CObjectReference* selfRef) {
  auto search = m_loadMap.find(tag);
  if (search != m_loadMap.end()) {
    while (!PumpResource(*search->second) || !search->second->xc_targetPtr) {}
    std::unique_ptr<IObj> ret = std::move(*search->second->xc_targetPtr);
    m_loadList.erase(search->second);
    m_loadMap.erase(search);
    return ret;
  }
  return BuildSync(tag, xfer, selfRef);
}

void CResFactory::BuildAsync(const SObjectTag& tag, const CVParamTransfer& xfer, std::unique_ptr<IObj>* target,
                             CObjectReference* selfRef) {
  auto search = m_loadMap.find(tag);
  if (search == m_loadMap.end()) {
    SLoadingData data(tag, target, xfer, x4_loader.GetResourceCompression(tag), selfRef);
    data.x14_resSize = x4_loader.ResourceSize(tag);
    if (data.x14_resSize) {
      data.x10_loadBuffer = std::unique_ptr<u8[]>(new u8[data.x14_resSize]);
      data.x8_dvdReq = x4_loader.LoadResourceAsync(tag, data.x10_loadBuffer.get());
      AddToLoadList(std::move(data));
    } else {
      *target = std::make_unique<TObjOwnerDerivedFromIObjUntyped>(nullptr);
    }
  }
}

void CResFactory::AsyncIdle() {
  if (m_loadList.empty())
    return;
  auto startTime = std::chrono::steady_clock::now();
  while (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - startTime).count() <
         5) {
    auto& task = m_loadList.front();
    if (PumpResource(task)) {
      m_loadMap.erase(task.x0_tag);
      m_loadList.pop_front();
      if (m_loadList.empty())
        return;
    }
  }
}

void CResFactory::CancelBuild(const SObjectTag& tag) {
  auto search = m_loadMap.find(tag);
  if (search != m_loadMap.end()) {
    if (search->second->x8_dvdReq)
      search->second->x8_dvdReq->PostCancelRequest();
    m_loadList.erase(search->second);
    m_loadMap.erase(search);
  }
}

void CResFactory::LoadPersistentResources(CSimplePool& sp) {
  const auto& paks = x4_loader.GetPaks();
  for (auto it = paks.begin(); it != paks.end(); ++it) {
    if (!(*it)->IsWorldPak()) {
      for (const CAssetId& id : (*it)->GetDepList()) {
        SObjectTag tag(GetResourceTypeById(id), id);
        m_nonWorldTokens.push_back(sp.GetObj(tag));
        m_nonWorldTokens.back().Lock();
      }
    }
  }
}

} // namespace urde
<|endoftext|>


<commit_before><commit_msg>sw: RingContainer::merge(): assert that the Rings aren't already linked<commit_after><|endoftext|>