<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (      0, uint256("0x9677102b58bd0d0888deadf88cf15a3e6e32b0b1c66eacefc668126514995cb3"))
        (      1, uint256("0x872a8ca3430bcc1cfd892ca1ee1c5de6c559a8f651f849713419f6f9ce4cb1fb"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1397589171, // * UNIX timestamp of last checkpoint block
        2,    // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        8000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        (   0, uint256("0x"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1389241455,
        0,
        300
    };

    const CCheckpointData &Checkpoints() {
        if (fTestNet)
            return dataTestnet;
        else
            return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (fTestNet) return true; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
            return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (fTestNet) return 0; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (fTestNet) return NULL; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<commit_msg>new blockchain<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (      0, uint256("0x9677102b58bd0d0888deadf88cf15a3e6e32b0b1c66eacefc668126514995cb3"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1396381854, // * UNIX timestamp of last checkpoint block
        1,    // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        8000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        (   0, uint256("0x"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1389241455,
        0,
        300
    };

    const CCheckpointData &Checkpoints() {
        if (fTestNet)
            return dataTestnet;
        else
            return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (fTestNet) return true; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
            return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (fTestNet) return 0; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (fTestNet) return NULL; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<|endoftext|>


<commit_before>//
//  GLState.cpp
//  G3MiOSSDK
//
//  Created by Jose Miguel SN on 18/03/13.
//
//

#include "GLState.hpp"

#include "GLShaderAttributes.hpp"
#include "GLShaderUniforms.hpp"
#include "IFloatBuffer.hpp"
#include "IGLTextureId.hpp"

void GLState::applyChanges(const INativeGL* nativeGL, GLState& currentState, const AttributesStruct& attributes,const UniformsStruct& uniforms) const{

  // Depth Test
  if (_depthTest != currentState._depthTest) {
    if (_depthTest) {
      nativeGL->enable(GLFeature::depthTest());
    }
    else {
      nativeGL->disable(GLFeature::depthTest());
    }
    currentState._depthTest = _depthTest;
  }

  // Blending
  if (_blend != currentState._blend) {
    if (_blend) {
      nativeGL->enable(GLFeature::blend());
    }
    else {
      nativeGL->disable(GLFeature::blend());
    }
    currentState._blend = _blend;
  }

  // Textures
  if (_textures != currentState._textures) {
    if (_textures) {
      nativeGL->enableVertexAttribArray(attributes.TextureCoord);
    }
    else {
      nativeGL->disableVertexAttribArray(attributes.TextureCoord);
    }
    currentState._textures = _textures;
  }

  // Texture2D
  if (_texture2D != currentState._texture2D) {
    if (_texture2D) {
      nativeGL->uniform1i(uniforms.EnableTexture, 1);
    }
    else {
      nativeGL->uniform1i(uniforms.EnableTexture, 0);
    }
    currentState._texture2D = _texture2D;
  }

  // VertexColor
  if (_vertexColor != currentState._vertexColor) {
    if (_vertexColor) {
      nativeGL->uniform1i(uniforms.EnableColorPerVertex, 1);
      nativeGL->enableVertexAttribArray(attributes.Color);
    }else {
      nativeGL->disableVertexAttribArray(attributes.Color);
      nativeGL->uniform1i(uniforms.EnableColorPerVertex, 0);
    }
    currentState._vertexColor = _vertexColor;
  }
  if (_vertexColor) {
    if ((_colors != currentState._colors) || (_colorsTimeStamp != currentState._colorsTimeStamp)) {
      nativeGL->vertexAttribPointer(attributes.Color, 4, false, 0, _colors);
      currentState._colors = _colors;
      currentState._colorsTimeStamp = _colorsTimeStamp;
    }
  }

  // Vertex
  if (_vertices != NULL){
    if ((_vertices != currentState._vertices) || (_verticesTimestamp != currentState._verticesTimestamp) ||
        (_verticesSize != currentState._verticesSize) || (_verticesStride != currentState._verticesStride)  ) {
      nativeGL->vertexAttribPointer(attributes.Position, _verticesSize, false, _verticesStride, _vertices);
      currentState._vertices = _vertices;
      currentState._verticesTimestamp = _verticesTimestamp;
      currentState._verticesSize = _verticesSize;
      currentState._verticesStride = _verticesStride;
    }
  }

  // Vertices Position
  if (_verticesPosition != currentState._verticesPosition) {
    if (_verticesPosition) {
      nativeGL->enableVertexAttribArray(attributes.Position);
    }
    else {
      nativeGL->disableVertexAttribArray(attributes.Position);
    }
    currentState._verticesPosition = _verticesPosition;
  }

  //Texture Coordinates
  if (_textureCoordinates != NULL){
    if (_textureCoordinates != currentState._textureCoordinates ||
        _textureCoordinatesTimestamp != currentState._textureCoordinatesTimestamp ||
        _textureCoordinatesSize != currentState._textureCoordinatesSize ||
        _textureCoordinatesStride != currentState._textureCoordinatesStride){
      nativeGL->vertexAttribPointer(attributes.TextureCoord,
                                    _textureCoordinatesSize, false,
                                    _textureCoordinatesStride, _textureCoordinates);

      currentState._textureCoordinates = _textureCoordinates;
      currentState._textureCoordinatesTimestamp = _textureCoordinatesTimestamp;
      currentState._textureCoordinatesSize = _textureCoordinatesSize;
      currentState._textureCoordinatesStride = _textureCoordinatesStride;
    }
  }

  if (_textureCoordinatesScaleX != currentState._textureCoordinatesScaleX ||
      _textureCoordinatesScaleY != currentState._textureCoordinatesScaleY){
    nativeGL->uniform2f(uniforms.ScaleTexCoord, _textureCoordinatesScaleX, _textureCoordinatesScaleY);

    currentState._textureCoordinatesScaleX = _textureCoordinatesScaleX;
    currentState._textureCoordinatesScaleY = _textureCoordinatesScaleY;
  }

  if (_textureCoordinatesTranslationX != currentState._textureCoordinatesTranslationX ||
      _textureCoordinatesTranslationY != currentState._textureCoordinatesTranslationY){
    nativeGL->uniform2f(uniforms.TranslationTexCoord,
                        _textureCoordinatesTranslationX,
                        _textureCoordinatesTranslationY);

    currentState._textureCoordinatesTranslationX = _textureCoordinatesTranslationX;
    currentState._textureCoordinatesTranslationY = _textureCoordinatesTranslationY;
  }

  // Flat Color
  if (_flatColor != currentState._flatColor) {
    if (_flatColor) {
      nativeGL->uniform1i(uniforms.EnableFlatColor, 1);
    }
    else {
      nativeGL->uniform1i(uniforms.EnableFlatColor, 0);
    }
    currentState._flatColor = _flatColor;
  }

  if (_flatColor) {
    if ((_flatColorR != currentState._flatColorR) ||
        (_flatColorG != currentState._flatColorG) ||
        (_flatColorB != currentState._flatColorB) ||
        (_flatColorA != currentState._flatColorA)
        ) {
      nativeGL->uniform4f(uniforms.FlatColor, _flatColorR, _flatColorG, _flatColorB,_flatColorA);

      currentState._flatColorR = _flatColorR;
      currentState._flatColorG = _flatColorG;
      currentState._flatColorB = _flatColorB;
      currentState._flatColorA = _flatColorA;
    }

    if (_intensity != currentState._intensity) {
      nativeGL->uniform1f(uniforms.FlatColorIntensity, _intensity);

      currentState._intensity = _intensity;
    }
  }

  // Cull Face
  if (_cullFace != currentState._cullFace) {
    currentState._cullFace = _cullFace;
    if (_cullFace) {
      nativeGL->enable(GLFeature::cullFace());
      if (_culledFace != currentState._culledFace) {
        nativeGL->cullFace(_culledFace);
        currentState._culledFace = _culledFace;
      }
    }
    else {
      nativeGL->disable(GLFeature::cullFace());
    }
  }

  if (_lineWidth != currentState._lineWidth) {
    nativeGL->lineWidth(_lineWidth);
    currentState._lineWidth = _lineWidth;
  }

  if (_pointSize != currentState._pointSize) {
    nativeGL->uniform1f(uniforms.PointSize, _pointSize);
    currentState._pointSize = _pointSize;
  }

  //Polygon Offset
  if (_polygonOffsetFill != currentState._polygonOffsetFill){
    currentState._polygonOffsetFill = _polygonOffsetFill;
    if (_polygonOffsetFill){
      nativeGL->enable(GLFeature::polygonOffsetFill());

      if (_polygonOffsetFactor != currentState._polygonOffsetFactor ||
          _polygonOffsetUnits != currentState._polygonOffsetUnits){
        nativeGL->polygonOffset(_polygonOffsetFactor, _polygonOffsetUnits);

        currentState._polygonOffsetUnits = _polygonOffsetUnits;
        currentState._polygonOffsetFactor = _polygonOffsetFactor;
      }

    } else{
      nativeGL->disable(GLFeature::polygonOffsetFill());
    }
  }

  //Blending Factors
  if (_blendDFactor != currentState._blendDFactor || _blendSFactor != currentState._blendSFactor){
    nativeGL->blendFunc(_blendSFactor, _blendDFactor);
    currentState._blendDFactor = _blendDFactor;
    currentState._blendSFactor = _blendSFactor;
  }

  //Texture (After blending factors)
  if (_boundTextureId != NULL){
    if (currentState._boundTextureId == NULL ||
        !_boundTextureId->isEqualsTo(currentState._boundTextureId)){
      nativeGL->bindTexture(GLTextureType::texture2D(), _boundTextureId);

      currentState._boundTextureId = _boundTextureId;
    } else{
      //ILogger::instance()->logInfo("Texture already bound.\n");
    }
  }

  if (_billboarding != currentState._billboarding){
    if (_billboarding){
      nativeGL->uniform1i(uniforms.BillBoard, 1);
    } else{
      nativeGL->uniform1i(uniforms.BillBoard, 0);
    }
    currentState._billboarding = _billboarding;
  }

  //Viewport
  if (_viewportHeight != currentState._viewportHeight || _viewportWidth != currentState._viewportWidth){
    nativeGL->uniform2f(uniforms.ViewPortExtent, _viewportWidth, _viewportHeight);

    currentState._viewportWidth = _viewportWidth;
    currentState._viewportHeight = _viewportHeight;
  }

  //Tex parameters
  if (_boundTextureId != NULL){
    int texture2D = GLTextureType::texture2D();
    //if (_texParMinFilter != -1 && _texParMinFilter != currentState._texParMinFilter){
    nativeGL->texParameteri(texture2D, GLTextureParameter::minFilter(),_texParMinFilter);
    currentState._texParMinFilter = _texParMinFilter;
    //}

    //if (_texParMagFilter != currentState._texParMagFilter){
    nativeGL->texParameteri(texture2D, GLTextureParameter::magFilter(),_texParMagFilter);
    currentState._texParMagFilter = _texParMagFilter;
    //}

    //if (_texParWrapS != currentState._texParWrapS){
    nativeGL->texParameteri(texture2D, GLTextureParameter::wrapS(),_texParWrapS);
    currentState._texParWrapS = _texParWrapS;
    //}

    //if (_texParWrapT != currentState._texParWrapT){
    nativeGL->texParameteri(texture2D, GLTextureParameter::wrapT(),_texParWrapT);
    currentState._texParWrapT = _texParWrapT;
    //}
  }

  if (_pixelStoreIAlignmentUnpack != -1 || _pixelStoreIAlignmentUnpack != currentState._pixelStoreIAlignmentUnpack){
    nativeGL->pixelStorei(GLAlignment::unpack(), _pixelStoreIAlignmentUnpack);
    currentState._pixelStoreIAlignmentUnpack = _pixelStoreIAlignmentUnpack;
  }

  if (_clearColorR != currentState._clearColorR ||
      _clearColorG != currentState._clearColorG ||
      _clearColorB != currentState._clearColorB ||
      _clearColorA != currentState._clearColorA){
    nativeGL->clearColor(_clearColorR, _clearColorG, _clearColorB, _clearColorA);
    currentState._clearColorR = _clearColorR;
    currentState._clearColorG = _clearColorG;
    currentState._clearColorB = _clearColorB;
    currentState._clearColorA = _clearColorA;
  }

  //Projection
  if (!_projectionMatrix.isEqualsTo(currentState._projectionMatrix)){
    nativeGL->uniformMatrix4fv(uniforms.Projection, false, &_projectionMatrix);
    currentState._projectionMatrix = _projectionMatrix;
  }

  //Modelview
  if (!_modelViewMatrix.isEqualsTo(currentState._modelViewMatrix)){
    nativeGL->uniformMatrix4fv(uniforms.Modelview, false, &_modelViewMatrix);
    currentState._modelViewMatrix = _modelViewMatrix;
  }

  //Texture Extent
  if (_textureWidth != currentState._textureWidth || _textureHeight != currentState._textureHeight){
    nativeGL->uniform2f(uniforms.TextureExtent, _textureWidth, _textureHeight);
    currentState._textureHeight = _textureHeight;
    currentState._textureWidth = _textureWidth;
  }

}<commit_msg>more minor changes<commit_after>//
//  GLState.cpp
//  G3MiOSSDK
//
//  Created by Jose Miguel SN on 18/03/13.
//
//

#include "GLState.hpp"

#include "GLShaderAttributes.hpp"
#include "GLShaderUniforms.hpp"
#include "IFloatBuffer.hpp"
#include "IGLTextureId.hpp"

void GLState::applyChanges(const INativeGL* nativeGL, GLState& currentState, const AttributesStruct& attributes,const UniformsStruct& uniforms) const{

  // Depth Test
  if (_depthTest != currentState._depthTest) {
    if (_depthTest) {
      nativeGL->enable(GLFeature::depthTest());
    }
    else {
      nativeGL->disable(GLFeature::depthTest());
    }
    currentState._depthTest = _depthTest;
  }

  // Blending
  if (_blend != currentState._blend) {
    if (_blend) {
      nativeGL->enable(GLFeature::blend());
    }
    else {
      nativeGL->disable(GLFeature::blend());
    }
    currentState._blend = _blend;
  }

  // Textures
  if (_textures != currentState._textures) {
    if (_textures) {
      nativeGL->enableVertexAttribArray(attributes.TextureCoord);
    }
    else {
      nativeGL->disableVertexAttribArray(attributes.TextureCoord);
    }
    currentState._textures = _textures;
  }

  // Texture2D
  if (_texture2D != currentState._texture2D) {
    if (_texture2D) {
      nativeGL->uniform1i(uniforms.EnableTexture, 1);
    }
    else {
      nativeGL->uniform1i(uniforms.EnableTexture, 0);
    }
    currentState._texture2D = _texture2D;
  }

  // VertexColor
  if (_vertexColor != currentState._vertexColor) {
    if (_vertexColor) {
      nativeGL->uniform1i(uniforms.EnableColorPerVertex, 1);
      nativeGL->enableVertexAttribArray(attributes.Color);
    }else {
      nativeGL->disableVertexAttribArray(attributes.Color);
      nativeGL->uniform1i(uniforms.EnableColorPerVertex, 0);
    }
    currentState._vertexColor = _vertexColor;
  }
  if (_vertexColor) {
    if ((_colors != currentState._colors) || (_colorsTimeStamp != currentState._colorsTimeStamp)) {
      nativeGL->vertexAttribPointer(attributes.Color, 4, false, 0, _colors);
      currentState._colors = _colors;
      currentState._colorsTimeStamp = _colorsTimeStamp;
    }
  }

  // Vertex
  if (_vertices != NULL){
    if ((_vertices != currentState._vertices) || (_verticesTimestamp != currentState._verticesTimestamp) ||
        (_verticesSize != currentState._verticesSize) || (_verticesStride != currentState._verticesStride)  ) {
      nativeGL->vertexAttribPointer(attributes.Position, _verticesSize, false, _verticesStride, _vertices);
      currentState._vertices = _vertices;
      currentState._verticesTimestamp = _verticesTimestamp;
      currentState._verticesSize = _verticesSize;
      currentState._verticesStride = _verticesStride;
    }
  }

  // Vertices Position
  if (_verticesPosition != currentState._verticesPosition) {
    if (_verticesPosition) {
      nativeGL->enableVertexAttribArray(attributes.Position);
    }
    else {
      nativeGL->disableVertexAttribArray(attributes.Position);
    }
    currentState._verticesPosition = _verticesPosition;
  }

  //Texture Coordinates
  if (_textureCoordinates != NULL){
    if (_textureCoordinates != currentState._textureCoordinates ||
        _textureCoordinatesTimestamp != currentState._textureCoordinatesTimestamp ||
        _textureCoordinatesSize != currentState._textureCoordinatesSize ||
        _textureCoordinatesStride != currentState._textureCoordinatesStride){
      nativeGL->vertexAttribPointer(attributes.TextureCoord,
                                    _textureCoordinatesSize, false,
                                    _textureCoordinatesStride, _textureCoordinates);

      currentState._textureCoordinates = _textureCoordinates;
      currentState._textureCoordinatesTimestamp = _textureCoordinatesTimestamp;
      currentState._textureCoordinatesSize = _textureCoordinatesSize;
      currentState._textureCoordinatesStride = _textureCoordinatesStride;
    }
  }

  if (_textureCoordinatesScaleX != currentState._textureCoordinatesScaleX ||
      _textureCoordinatesScaleY != currentState._textureCoordinatesScaleY){
    nativeGL->uniform2f(uniforms.ScaleTexCoord, _textureCoordinatesScaleX, _textureCoordinatesScaleY);

    currentState._textureCoordinatesScaleX = _textureCoordinatesScaleX;
    currentState._textureCoordinatesScaleY = _textureCoordinatesScaleY;
  }

  if (_textureCoordinatesTranslationX != currentState._textureCoordinatesTranslationX ||
      _textureCoordinatesTranslationY != currentState._textureCoordinatesTranslationY){
    nativeGL->uniform2f(uniforms.TranslationTexCoord,
                        _textureCoordinatesTranslationX,
                        _textureCoordinatesTranslationY);

    currentState._textureCoordinatesTranslationX = _textureCoordinatesTranslationX;
    currentState._textureCoordinatesTranslationY = _textureCoordinatesTranslationY;
  }

  // Flat Color
  if (_flatColor != currentState._flatColor) {
    if (_flatColor) {
      nativeGL->uniform1i(uniforms.EnableFlatColor, 1);
    }
    else {
      nativeGL->uniform1i(uniforms.EnableFlatColor, 0);
    }
    currentState._flatColor = _flatColor;
  }

  if (_flatColor) {
    if ((_flatColorR != currentState._flatColorR) ||
        (_flatColorG != currentState._flatColorG) ||
        (_flatColorB != currentState._flatColorB) ||
        (_flatColorA != currentState._flatColorA)
        ) {
      nativeGL->uniform4f(uniforms.FlatColor, _flatColorR, _flatColorG, _flatColorB,_flatColorA);

      currentState._flatColorR = _flatColorR;
      currentState._flatColorG = _flatColorG;
      currentState._flatColorB = _flatColorB;
      currentState._flatColorA = _flatColorA;
    }

    if (_intensity != currentState._intensity) {
      nativeGL->uniform1f(uniforms.FlatColorIntensity, _intensity);

      currentState._intensity = _intensity;
    }
  }

  // Cull Face
  if (_cullFace != currentState._cullFace) {
    currentState._cullFace = _cullFace;
    if (_cullFace) {
      nativeGL->enable(GLFeature::cullFace());
      if (_culledFace != currentState._culledFace) {
        nativeGL->cullFace(_culledFace);
        currentState._culledFace = _culledFace;
      }
    }
    else {
      nativeGL->disable(GLFeature::cullFace());
    }
  }

  if (_lineWidth != currentState._lineWidth) {
    nativeGL->lineWidth(_lineWidth);
    currentState._lineWidth = _lineWidth;
  }

  if (_pointSize != currentState._pointSize) {
    nativeGL->uniform1f(uniforms.PointSize, _pointSize);
    currentState._pointSize = _pointSize;
  }

  //Polygon Offset
  if (_polygonOffsetFill != currentState._polygonOffsetFill){
    currentState._polygonOffsetFill = _polygonOffsetFill;
    if (_polygonOffsetFill){
      nativeGL->enable(GLFeature::polygonOffsetFill());

      if (_polygonOffsetFactor != currentState._polygonOffsetFactor ||
          _polygonOffsetUnits != currentState._polygonOffsetUnits){
        nativeGL->polygonOffset(_polygonOffsetFactor, _polygonOffsetUnits);

        currentState._polygonOffsetUnits = _polygonOffsetUnits;
        currentState._polygonOffsetFactor = _polygonOffsetFactor;
      }

    } else{
      nativeGL->disable(GLFeature::polygonOffsetFill());
    }
  }

  //Blending Factors
  if (_blendDFactor != currentState._blendDFactor || _blendSFactor != currentState._blendSFactor){
    nativeGL->blendFunc(_blendSFactor, _blendDFactor);
    currentState._blendDFactor = _blendDFactor;
    currentState._blendSFactor = _blendSFactor;
  }

  //Texture (After blending factors)
  if (_boundTextureId != NULL){
    if (currentState._boundTextureId == NULL ||
        !_boundTextureId->isEqualsTo(currentState._boundTextureId)){
      nativeGL->bindTexture(GLTextureType::texture2D(), _boundTextureId);

      currentState._boundTextureId = _boundTextureId;
    } else{
      //ILogger::instance()->logInfo("Texture already bound.\n");
    }
  }

  if (_billboarding != currentState._billboarding){
    if (_billboarding){
      nativeGL->uniform1i(uniforms.BillBoard, 1);
    } else{
      nativeGL->uniform1i(uniforms.BillBoard, 0);
    }
    currentState._billboarding = _billboarding;
  }

  //Viewport
  if (_viewportHeight != currentState._viewportHeight || _viewportWidth != currentState._viewportWidth){
    nativeGL->uniform2f(uniforms.ViewPortExtent, _viewportWidth, _viewportHeight);

    currentState._viewportWidth = _viewportWidth;
    currentState._viewportHeight = _viewportHeight;
  }

  //Tex parameters
  if (_boundTextureId != NULL){
    int texture2D = GLTextureType::texture2D();
    if (_texParMinFilter != -1){// && _texParMinFilter != currentState._texParMinFilter){
      nativeGL->texParameteri(texture2D, GLTextureParameter::minFilter(),_texParMinFilter);
      currentState._texParMinFilter = _texParMinFilter;
    }

    if (_texParMagFilter != -1){// _texParMagFilter != currentState._texParMagFilter){
      nativeGL->texParameteri(texture2D, GLTextureParameter::magFilter(),_texParMagFilter);
      currentState._texParMagFilter = _texParMagFilter;
    }

    if (_texParWrapS != -1){//_texParWrapS != currentState._texParWrapS){
      nativeGL->texParameteri(texture2D, GLTextureParameter::wrapS(),_texParWrapS);
      currentState._texParWrapS = _texParWrapS;
    }

    if (_texParWrapT != -1){//_texParWrapT != currentState._texParWrapT){
      nativeGL->texParameteri(texture2D, GLTextureParameter::wrapT(),_texParWrapT);
      currentState._texParWrapT = _texParWrapT;
    }
  }

  if (_pixelStoreIAlignmentUnpack != -1 && _pixelStoreIAlignmentUnpack != currentState._pixelStoreIAlignmentUnpack){
    nativeGL->pixelStorei(GLAlignment::unpack(), _pixelStoreIAlignmentUnpack);
    currentState._pixelStoreIAlignmentUnpack = _pixelStoreIAlignmentUnpack;
  }

  if (_clearColorR != currentState._clearColorR ||
      _clearColorG != currentState._clearColorG ||
      _clearColorB != currentState._clearColorB ||
      _clearColorA != currentState._clearColorA){
    nativeGL->clearColor(_clearColorR, _clearColorG, _clearColorB, _clearColorA);
    currentState._clearColorR = _clearColorR;
    currentState._clearColorG = _clearColorG;
    currentState._clearColorB = _clearColorB;
    currentState._clearColorA = _clearColorA;
  }

  //Projection
  if (!_projectionMatrix.isEqualsTo(currentState._projectionMatrix)){
    nativeGL->uniformMatrix4fv(uniforms.Projection, false, &_projectionMatrix);
    currentState._projectionMatrix = _projectionMatrix;
  }

  //Modelview
  if (!_modelViewMatrix.isEqualsTo(currentState._modelViewMatrix)){
    nativeGL->uniformMatrix4fv(uniforms.Modelview, false, &_modelViewMatrix);
    currentState._modelViewMatrix = _modelViewMatrix;
  }

  //Texture Extent
  if (_textureWidth != currentState._textureWidth || _textureHeight != currentState._textureHeight){
    nativeGL->uniform2f(uniforms.TextureExtent, _textureWidth, _textureHeight);
    currentState._textureHeight = _textureHeight;
    currentState._textureWidth = _textureWidth;
  }

}<|endoftext|>


<commit_before>#include "dice.h"
#include <qDebug>
#include <ctime>
#include <cstdlib>
#include <QMediaPlayer>
#include <QFileInfo>
#include <QTimeLine>

using namespace std;

Dice::Dice()
{
    qDebug() << "Dice Created";
    srand((unsigned)time(NULL));
    value1 = 0;
    value2 = 0;
    roll_sound = new QMediaPlayer();
    roll_sound->setVolume(100);
    effect_sound = new QMediaPlayer();
    effect_sound->setVolume(100);
    timeline = new QTimeLine(1300);

    connect(timeline, SIGNAL(finished()), this, SLOT(afterRollSound()));
}

Dice::~Dice()
{
    qDebug() << "Dice Destroyed";
    delete roll_sound;
    delete effect_sound;
    delete timeline;
}

// Initialize Static Members
Dice* Dice::m_inst = NULL;

Dice* Dice::getInst()
{
    // create new instance if null
    if (!m_inst) {
        m_inst = new Dice();
    }

    return m_inst;
}

void Dice::delInst()
{
    // delete an instance
    if (m_inst) {
        delete m_inst;
        m_inst = NULL;
    }

    return;
}

// Methods
void Dice::roll()
{
    qDebug() << "Dice Rolled";

    value1 = rand() % 6 + 1;
    value2 = rand() % 6 + 1;

    emit diceRolled(getValue(),isDouble());
    emit firstDiceRolled(value1);
    emit secondDiceRolled(value2);
    emit diceRolled(getValue());
    emit diceRolled(this);

    timeline->start();

    // play sound
    roll_sound->setMedia(QUrl::fromLocalFile(QFileInfo("sound/roll.mp3").absoluteFilePath()));
    roll_sound->play();
}

bool Dice::isDouble()
{
    return (value1 == value2);
}

int Dice::getValue()
{
    return value1 + value2;
}
int Dice::getFirstDice()
{
    return value1;
}

int Dice::getSecondDice()
{
    return value2;
}

void Dice::afterRollSound()
{
    QString path = "";

    if(isDouble()) {
        path += "sound/double.wav";

        // emit singal for double popup
        emit diceDouble();
    }
    else {
        switch(value1 + value2) {
            case 2:
                path += "sound/two.wav";
                break;
            case 3:
                path += "sound/three.wav";
                break;
            case 4:
                path += "sound/four.wav";
                break;
            case 5:
                path += "sound/five.wav";
                break;
            case 6:
                path += "sound/six.wav";
                break;
            case 7:
                path += "sound/seven.wav";
                break;
            case 8:
                path += "sound/eight.wav";
                break;
            case 9:
                path += "sound/nine.wav";
                break;
            case 10:
                path += "sound/ten.wav";
                break;
            case 11:
                path += "sound/eleven.wav";
                break;
            case 12:
                path += "sound/twelve.wav";
                break;
        }
    }

    effect_sound->setMedia(QUrl::fromLocalFile(QFileInfo(path).absoluteFilePath()));
    effect_sound->play();

}
<commit_msg>dice.cpp Zoo Suk<commit_after>#include "dice.h"
#include <qDebug>
#include <ctime>
#include <cstdlib>
#include <QMediaPlayer>
#include <QFileInfo>
#include <QTimeLine>

using namespace std;

Dice::Dice()    //dice constructor
{
    qDebug() << "Dice Created";
    srand((unsigned)time(NULL));
    value1 = 0;
    value2 = 0;
    roll_sound = new QMediaPlayer();            // dice roll sounde setting
    roll_sound->setVolume(100);
    effect_sound = new QMediaPlayer();
    effect_sound->setVolume(100);
    timeline = new QTimeLine(1300);

    connect(timeline, SIGNAL(finished()), this, SLOT(afterRollSound()));
}

Dice::~Dice()   // dice destructor
{
    qDebug() << "Dice Destroyed";
    delete roll_sound;
    delete effect_sound;
    delete timeline;
}

// Initialize Static Members
Dice* Dice::m_inst = NULL;

Dice* Dice::getInst()
{
    // create new instance if null
    if (!m_inst) {
        m_inst = new Dice();
    }

    return m_inst;
}

void Dice::delInst()
{
    // delete an instance
    if (m_inst) {
        delete m_inst;
        m_inst = NULL;
    }

    return;
}

// Methods
void Dice::roll()           // dice roll
{
    qDebug() << "Dice Rolled";

    value1 = rand() % 6 + 1;        // there are two dices
    value2 = rand() % 6 + 1;

    emit diceRolled(getValue(),isDouble());
    emit firstDiceRolled(value1);
    emit secondDiceRolled(value2);
    emit diceRolled(getValue());
    emit diceRolled(this);

    timeline->start();

    // play sound
    roll_sound->setMedia(QUrl::fromLocalFile(QFileInfo("sound/roll.mp3").absoluteFilePath()));
    roll_sound->play();
}

bool Dice::isDouble() // both values of dices are same => true , else false
{
    return (value1 == value2);
}

int Dice::getValue()    // sum of two value
{
    return value1 + value2;
}
int Dice::getFirstDice()    // 1st dice value
{
    return value1;
}

int Dice::getSecondDice()       //2nd dice value
{
    return value2;
}

void Dice::afterRollSound()         // different sounds up to sum of the values
{
    QString path = "";

    if(isDouble()) {
        path += "sound/double.wav";

        // emit singal for double popup
        emit diceDouble();
    }
    else {
        switch(value1 + value2) {
            case 2:
                path += "sound/two.wav";
                break;
            case 3:
                path += "sound/three.wav";
                break;
            case 4:
                path += "sound/four.wav";
                break;
            case 5:
                path += "sound/five.wav";
                break;
            case 6:
                path += "sound/six.wav";
                break;
            case 7:
                path += "sound/seven.wav";
                break;
            case 8:
                path += "sound/eight.wav";
                break;
            case 9:
                path += "sound/nine.wav";
                break;
            case 10:
                path += "sound/ten.wav";
                break;
            case 11:
                path += "sound/eleven.wav";
                break;
            case 12:
                path += "sound/twelve.wav";
                break;
        }
    }

    effect_sound->setMedia(QUrl::fromLocalFile(QFileInfo(path).absoluteFilePath()));
    effect_sound->play();

}
<|endoftext|>


<commit_before>//
//  LoginScene.cpp
//  MonsterScramble
//
//  Created by Gyeongwook on 2014. 3. 5..
//
//

#include "LoginScene.h"
#include "GameManager.h"
#include "LayerWebView.h"
#include "GameSettingScene.h"
#include "BackgroundLayer.h"
#include "AdMobObjectCPP.h"

USING_NS_CC;

bool CLoginScene::init(void)
{
	//////////////////////////////
	// 1. super init first
	if ( !CCScene::init() )
	{
		return false;
	}

    // 광고 끄기
    gene::AdMobObjectCPP * admob = new gene::AdMobObjectCPP();
    admob->hideAdMob();

    CCLayer* BackgroundLayer = CBackgroundLayer::create();
	this->addChild(BackgroundLayer, 0);

	// send request for authentication
    CGameManager::GetInstance()->AuthenticationCheck();

    m_LoginLayer = nullptr;

	this->scheduleUpdate();

	return true;
}

void CLoginScene::update(float dt)
{
    switch (CGameManager::GetInstance()->GetCurrentLoginPhase() )
    {
        case LP_FAIL:
        {
            CGameManager::GetInstance()->SetCurrentLoginPhase(LP_WAITING);

            m_LoginLayer = LayerWebView::create();
            m_LoginLayer->run();
            this->addChild(m_LoginLayer, 1);

            break;
        }
        case LP_OK :
        {
            CGameManager::GetInstance()->SetCurrentLoginPhase(LP_WAITING);

            //this->removeAllChildren();
            if (nullptr != m_LoginLayer)
            {
                static_cast<LayerWebView *>(m_LoginLayer)->close();
                this->removeChild(m_LoginLayer);
            }

            // next scene gogo
            // 바로 바로 씬 전환을 시도하면 에러 발생 - 전환되는 시간 을 좀 두는 방식으로 일단 해결 시도
            float delayTime = 1.5;
            CCCallFunc* readyRequestCallback = CCCallFunc::create(this, callfunc_selector(CLoginScene::closeScene) );
            CCDelayTime* delayAction = CCDelayTime::create(delayTime);
            this->runAction(CCSequence::create(delayAction, readyRequestCallback, NULL));

            break;
        }
        case LP_WAITING:
        {
            break;
        }
    }
}

void CLoginScene::closeScene()
{
    CCScene* newScene = CGameSettingScene::create();
    CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(0.5, newScene) );
}<commit_msg>멀티플레이 시작할 때 배경화면만 나오는 문제 수<commit_after>//
//  LoginScene.cpp
//  MonsterScramble
//
//  Created by Gyeongwook on 2014. 3. 5..
//
//

#include "LoginScene.h"
#include "GameManager.h"
#include "LayerWebView.h"
#include "GameSettingScene.h"
#include "BackgroundLayer.h"
#include "AdMobObjectCPP.h"

USING_NS_CC;

bool CLoginScene::init(void)
{
	//////////////////////////////
	// 1. super init first
	if ( !CCScene::init() )
	{
		return false;
	}

    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();

    // 광고 끄기
    gene::AdMobObjectCPP * admob = new gene::AdMobObjectCPP();
    admob->hideAdMob();

    CCLayer* BackgroundLayer = CBackgroundLayer::create();
	this->addChild(BackgroundLayer, 0);

	// send request for authentication
    CGameManager::GetInstance()->AuthenticationCheck();

    CCSprite* pWaitingScreen = CCSprite::create(WAITING_ONLINE_IMAGE.c_str());
	pWaitingScreen->setAnchorPoint(ccp(0.5f,0.5f));
	pWaitingScreen->setPosition(CCPoint(visibleSize.width/2, visibleSize.height/2 ));
    this->addChild(pWaitingScreen, 1);

    m_LoginLayer = nullptr;

	this->scheduleUpdate();

	return true;
}

void CLoginScene::update(float dt)
{
    switch (CGameManager::GetInstance()->GetCurrentLoginPhase() )
    {
        case LP_FAIL:
        {
            CGameManager::GetInstance()->SetCurrentLoginPhase(LP_WAITING);

            m_LoginLayer = LayerWebView::create();
            m_LoginLayer->run();
            this->addChild(m_LoginLayer, 1);

            break;
        }
        case LP_OK :
        {
            CGameManager::GetInstance()->SetCurrentLoginPhase(LP_WAITING);

            //this->removeAllChildren();
            if (nullptr != m_LoginLayer)
            {
                static_cast<LayerWebView *>(m_LoginLayer)->close();
                this->removeChild(m_LoginLayer);
            }

            // next scene gogo
            // 바로 바로 씬 전환을 시도하면 에러 발생 - 전환되는 시간 을 좀 두는 방식으로 일단 해결 시도
            float delayTime = 1.5;
            CCCallFunc* readyRequestCallback = CCCallFunc::create(this, callfunc_selector(CLoginScene::closeScene) );
            CCDelayTime* delayAction = CCDelayTime::create(delayTime);
            this->runAction(CCSequence::create(delayAction, readyRequestCallback, NULL));

            break;
        }
        case LP_WAITING:
        {
            break;
        }
    }
}

void CLoginScene::closeScene()
{
    CCScene* newScene = CGameSettingScene::create();
    CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(0.5, newScene) );
}<|endoftext|>


<commit_before>#include <stan/prob/distributions/univariate/continuous/Cauchy.hpp>
#include <gtest/gtest.h>

TEST(stanProbDistributionsUnivariateContinuousCauchy,headerParses) {
  EXPECT_TRUE(true);
}
<commit_msg>Fix case of cauchy.h header in test to allow to compile on Linux.<commit_after>#include <stan/prob/distributions/univariate/continuous/cauchy.hpp>
#include <gtest/gtest.h>

TEST(stanProbDistributionsUnivariateContinuousCauchy,headerParses) {
  EXPECT_TRUE(true);
}
<|endoftext|>


<commit_before>// Copyright 2013 Mirus Project

// 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.

//
// kernel.cpp - main source file + kernel entry point
//              we all have to begin somewhere, right?
//

#include <stdafx.hpp>
#include <boot/multiboot.hpp>

#include <cpu/gdt.hpp>
#include <cpu/idt.hpp>
#include <cpu/isr.hpp>
#include <cpu/irq.hpp>

#include <hardware/timer.hpp>
#include <hardware/serial.hpp>
#include <hardware/rtc.hpp>
#include <hardware/atapio.hpp>

namespace mirus
{
    //
    // kernel_main - our kernel entry point
    //
    extern "C" void kernel_main(multiboot_info_t* mbd,
        unsigned int magic)
    {
        // Print debug stub
        debug::debugger::writeln("[log] Mirus 0.2.5-dev");
        debug::debugger::flush();

        // Get avalible memory
        if (magic != MULTIBOOT_BOOTLOADER_MAGIC)
            debug::debugger::writeln("[error] Multiboot bootloader magic doesn't match!");

        int memory_size = 0;

        if (mbd->flags & 1)
        {
            debug::debugger::writeln("[log] Memory map present, trying to get memory");

            memory_map_t* mmap = (memory_map_t*)mbd->mmap_addr;

            // parse entries
            while ((unsigned int)mmap < (unsigned int)(mbd->mmap_addr) + mbd->mmap_length)
            {
                memory_size += mmap->length_low;
                mmap = (memory_map_t*)((unsigned int)mmap + mmap->size + sizeof(unsigned int));
            }

            debug::debugger::write("[log] Avalible memory: ");
            debug::debugger::write((memory_size / 1024) / 1024);
            debug::debugger::writeln("m");
        }

        if (((memory_size / 1024) / 1024) < 512)
            debug::debugger::writeln("[warning] Memory is less than expected minimum");

        // Install CPU hardware devices
        cpu::gdt::install();
        cpu::idt::install();
        cpu::isr::install();
        cpu::irq::install();

        // Set up screen
        screen::terminal::install();

        // Set up additional hardware
        hardware::pit::install();
        hardware::serial::install();
        hardware::ide_install(0x1F0);

        // Test ATA PIO r/w

        // WE MUST NEVER RETURN!!!!
        while (true);
    }
} // !namespace
<commit_msg>Maybe this will work, but it probably won't<commit_after>// Copyright 2013 Mirus Project

// 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.

//
// kernel.cpp - main source file + kernel entry point
//              we all have to begin somewhere, right?
//

#include <stdafx.hpp>
#include <boot/multiboot.hpp>

#include <cpu/gdt.hpp>
#include <cpu/idt.hpp>
#include <cpu/isr.hpp>
#include <cpu/irq.hpp>

#include <hardware/timer.hpp>
#include <hardware/serial.hpp>
#include <hardware/rtc.hpp>
#include <hardware/atapio.hpp>

namespace mirus
{
    //
    // kernel_main - our kernel entry point
    //
    extern "C" void kernel_main(multiboot_info_t* mbd,
        unsigned int magic)
    {
        // Print debug stub
        debug::debugger::writeln("[log] Mirus 0.2.5-dev");
        debug::debugger::flush();

        // Get avalible memory
        if (magic != MULTIBOOT_BOOTLOADER_MAGIC)
            debug::debugger::writeln("[error] Multiboot bootloader magic doesn't match!");

        int memory_size = 0;

        if (mbd->flags & 1)
        {
            debug::debugger::writeln("[log] Memory map present, trying to get memory");

            memory_map_t* mmap = (memory_map_t*)mbd->mmap_addr;

            // parse entries
            while ((unsigned int)mmap < (unsigned int)(mbd->mmap_addr) + mbd->mmap_length)
            {
                memory_size += mmap->length_low;
                mmap = (memory_map_t*)((unsigned int)mmap + mmap->size + sizeof(unsigned int));
            }

            debug::debugger::write("[log] Avalible memory: ");
            debug::debugger::write((memory_size / 1024) / 1024);
            debug::debugger::writeln("m");
        }

        if (((memory_size / 1024) / 1024) < 512)
            debug::debugger::writeln("[warning] Memory is less than expected minimum");

        // Install CPU hardware devices
        cpu::gdt::install();
        cpu::idt::install();
        cpu::isr::install();
        cpu::irq::install();

        // Set up screen
        screen::terminal::install();

        // Set up additional hardware
        hardware::pit::install();
        hardware::serial::install();

        // Test ATA PIO r/w
        hardware::ide_install(0x1F0);
        hardware::ide_write_sector_entry(0x1F0,
            0x1F0,
            1,
            42);

        // WE MUST NEVER RETURN!!!!
        while (true);
    }
} // !namespace
<|endoftext|>


<commit_before>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string>
#include <memory>

#include "../command.hxx"
#include "../argument.hxx"
#include "../interp.hxx"
#include "../common.hxx"

using namespace std;

namespace tglng {
  class If: public Command {
    AutoSection condition, then, otherwise;

  public:
    If(Command* left,
       const Section& c,
       const Section& t,
       const Section& o)
    : Command(left),
      condition(c), then(t), otherwise(o)
    { }

    virtual bool exec(wstring& dst, Interpreter& interp) {
      wstring cond;
      if (!condition.exec(cond, interp)) return false;
      return (parseBool(cond)? then : otherwise).exec(dst, interp);
    }
  };

  class IfParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      AutoSection condition, then, otherwise;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.s(condition), a.s(then), -a.s(otherwise)])
        return ParseError;

      out = new If(out, condition, then, otherwise);
      condition.clear();
      then.clear();
      otherwise.clear();
      return ContinueParsing;
    }
  };

  static GlobalBinding<IfParser> _ifParser(L"if");

  class FalseCoalesce: public Command {
    AutoSection lhs, rhs;

  public:
    FalseCoalesce(Command* left,
                  const Section& l,
                  const Section& r)
    : Command(left), lhs(l), rhs(r) {}

    virtual bool exec(wstring& dst, Interpreter& interp) {
      if (!lhs.exec(dst, interp)) return false;
      return parseBool(dst) || rhs.exec(dst, interp);
    }
  };

  class FalseCoalesceParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      AutoSection lhs, rhs;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.s(lhs), a.s(rhs)]) return ParseError;

      out = new FalseCoalesce(out, lhs, rhs);
      lhs.clear();
      rhs.clear();
      return ContinueParsing;
    }
  };

  static GlobalBinding<FalseCoalesceParser>
  _falseCoalesceParser(L"false-coalesce");

  class ForInteger: public Command {
    //Whether to emit the counter before each execution of the right part of
    //the body section.
    bool emitCounterImplicitly;
    //The register on which to operate
    wchar_t reg;
    //The limiting value and the increment
    auto_ptr<Command> init, limit, increment;
    AutoSection body;

  public:
    ForInteger(Command* left,
               bool emitCounterImplicitly_,
               wchar_t reg_,
               auto_ptr<Command>& init_,
               auto_ptr<Command>& limit_,
               auto_ptr<Command>& increment_,
               const Section& body_)
    : Command(left),
      emitCounterImplicitly(emitCounterImplicitly_),
      reg(reg_),
      init(init_),
      limit(limit_),
      increment(increment_),
      body(body_)
    { }

    virtual bool exec(wstring& dst, Interpreter& interp) {
      dst.clear();

      wstring str;
      signed slim, sinit, sinc;

      //Left part of the section is executed before anything else
      if (!interp.exec(str, body.left)) return false;
      dst += str;

      //Initialise the parms and register
      if (limit.get()) {
        if (!interp.exec(str, limit.get())) return false;
        if (!parseInteger(slim, str)) {
          wcerr << L"Invalid integer for for-integer limit: " << str << endl;
          return false;
        }
      } else {
        slim = 10;
      }

      if (init.get()) {
        if (!interp.exec(str, init.get())) return false;
        if (!parseInteger(sinit, str)) {
          wcerr << L"Invalid integer for for-integer init: " << str << endl;
          return false;
        }
        interp.registers[reg] = str;
      } else {
        sinit = 0;
        interp.registers[reg] = L"0";
      }

      if (increment.get()) {
        if (!interp.exec(str, increment.get())) return false;
        if (!parseInteger(sinc, str) || !sinc) {
          wcerr << L"Invalid integer for for-integer increment: "
                << str << endl;
          return false;
        }
      } else {
        if (sinit <= slim) sinc = +1;
        else               sinc = -1;
      }

      for (signed curr = sinit; sinc > 0? curr < slim : curr > slim;
           /* Increment performed in body */) {
        //Run the body parts
        if (!interp.exec(str, body.left)) return false;
        dst += str;
        if (emitCounterImplicitly) {
          map<wchar_t,wstring>::const_iterator it = interp.registers.find(reg);
          if (it == interp.registers.end()) {
            wcerr << L"for-integer loop register " << reg
                  << L" was unset during execution." << endl;
            return false;
          }
          dst += it->second;
        }
        if (!interp.exec(str, body.right)) return false;
        dst += str;

        //Increment the value
        map<wchar_t,wstring>::iterator it = interp.registers.find(reg);
        if (it == interp.registers.end()) {
          wcerr << L"for-integer loop register " << reg
                << L" was unset during execution." << endl;
          return false;
        }

        if (!parseInteger(curr, it->second)) {
          wcerr << L"for-integer loop register " << reg
                << L" was set to invalid integer " << it->second
                << " during execution." << endl;
          return false;
        }

        curr += sinc;
        it->second = intToStr(curr);
      }

      return true;
    }
  };

  template<bool EmitCounterImplicitly>
  class ForIntegerParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      auto_ptr<Command> limit, init, inc;
      wchar_t reg = L'i';
      AutoSection body;
      ArgumentParser a(interp, text, offset, out);

      if (!a[a.h(),
             a.s(body) |
             (a.a(limit), a.s(body) |
              (a.h(reg), a.s(body) |
               (a.a(init), a.s(body) |
                (a.a(inc), a.s(body)))))])
        return ParseError;

      out = new ForInteger(out, EmitCounterImplicitly,
                           reg, init, limit, inc, body);
      body.clear();
      return ContinueParsing;
    }
  };

  static GlobalBinding<ForIntegerParser<false> >
  _forIntegerParser(L"for-integer");
  static GlobalBinding<ForIntegerParser<true > >
  _forIntPrintParser(L"for-int-print");
}
<commit_msg>Fix left body part being executed before loop test in for-integer.<commit_after>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string>
#include <memory>

#include "../command.hxx"
#include "../argument.hxx"
#include "../interp.hxx"
#include "../common.hxx"

using namespace std;

namespace tglng {
  class If: public Command {
    AutoSection condition, then, otherwise;

  public:
    If(Command* left,
       const Section& c,
       const Section& t,
       const Section& o)
    : Command(left),
      condition(c), then(t), otherwise(o)
    { }

    virtual bool exec(wstring& dst, Interpreter& interp) {
      wstring cond;
      if (!condition.exec(cond, interp)) return false;
      return (parseBool(cond)? then : otherwise).exec(dst, interp);
    }
  };

  class IfParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      AutoSection condition, then, otherwise;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.s(condition), a.s(then), -a.s(otherwise)])
        return ParseError;

      out = new If(out, condition, then, otherwise);
      condition.clear();
      then.clear();
      otherwise.clear();
      return ContinueParsing;
    }
  };

  static GlobalBinding<IfParser> _ifParser(L"if");

  class FalseCoalesce: public Command {
    AutoSection lhs, rhs;

  public:
    FalseCoalesce(Command* left,
                  const Section& l,
                  const Section& r)
    : Command(left), lhs(l), rhs(r) {}

    virtual bool exec(wstring& dst, Interpreter& interp) {
      if (!lhs.exec(dst, interp)) return false;
      return parseBool(dst) || rhs.exec(dst, interp);
    }
  };

  class FalseCoalesceParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      AutoSection lhs, rhs;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.s(lhs), a.s(rhs)]) return ParseError;

      out = new FalseCoalesce(out, lhs, rhs);
      lhs.clear();
      rhs.clear();
      return ContinueParsing;
    }
  };

  static GlobalBinding<FalseCoalesceParser>
  _falseCoalesceParser(L"false-coalesce");

  class ForInteger: public Command {
    //Whether to emit the counter before each execution of the right part of
    //the body section.
    bool emitCounterImplicitly;
    //The register on which to operate
    wchar_t reg;
    //The limiting value and the increment
    auto_ptr<Command> init, limit, increment;
    AutoSection body;

  public:
    ForInteger(Command* left,
               bool emitCounterImplicitly_,
               wchar_t reg_,
               auto_ptr<Command>& init_,
               auto_ptr<Command>& limit_,
               auto_ptr<Command>& increment_,
               const Section& body_)
    : Command(left),
      emitCounterImplicitly(emitCounterImplicitly_),
      reg(reg_),
      init(init_),
      limit(limit_),
      increment(increment_),
      body(body_)
    { }

    virtual bool exec(wstring& dst, Interpreter& interp) {
      dst.clear();

      wstring str;
      signed slim, sinit, sinc;

      //Initialise the parms and register
      if (limit.get()) {
        if (!interp.exec(str, limit.get())) return false;
        if (!parseInteger(slim, str)) {
          wcerr << L"Invalid integer for for-integer limit: " << str << endl;
          return false;
        }
      } else {
        slim = 10;
      }

      if (init.get()) {
        if (!interp.exec(str, init.get())) return false;
        if (!parseInteger(sinit, str)) {
          wcerr << L"Invalid integer for for-integer init: " << str << endl;
          return false;
        }
        interp.registers[reg] = str;
      } else {
        sinit = 0;
        interp.registers[reg] = L"0";
      }

      if (increment.get()) {
        if (!interp.exec(str, increment.get())) return false;
        if (!parseInteger(sinc, str) || !sinc) {
          wcerr << L"Invalid integer for for-integer increment: "
                << str << endl;
          return false;
        }
      } else {
        if (sinit <= slim) sinc = +1;
        else               sinc = -1;
      }

      for (signed curr = sinit; sinc > 0? curr < slim : curr > slim;
           /* Increment performed in body */) {
        //Run the body parts
        if (!interp.exec(str, body.left)) return false;
        dst += str;
        if (emitCounterImplicitly) {
          map<wchar_t,wstring>::const_iterator it = interp.registers.find(reg);
          if (it == interp.registers.end()) {
            wcerr << L"for-integer loop register " << reg
                  << L" was unset during execution." << endl;
            return false;
          }
          dst += it->second;
        }
        if (!interp.exec(str, body.right)) return false;
        dst += str;

        //Increment the value
        map<wchar_t,wstring>::iterator it = interp.registers.find(reg);
        if (it == interp.registers.end()) {
          wcerr << L"for-integer loop register " << reg
                << L" was unset during execution." << endl;
          return false;
        }

        if (!parseInteger(curr, it->second)) {
          wcerr << L"for-integer loop register " << reg
                << L" was set to invalid integer " << it->second
                << " during execution." << endl;
          return false;
        }

        curr += sinc;
        it->second = intToStr(curr);
      }

      return true;
    }
  };

  template<bool EmitCounterImplicitly>
  class ForIntegerParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      auto_ptr<Command> limit, init, inc;
      wchar_t reg = L'i';
      AutoSection body;
      ArgumentParser a(interp, text, offset, out);

      if (!a[a.h(),
             a.s(body) |
             (a.a(limit), a.s(body) |
              (a.h(reg), a.s(body) |
               (a.a(init), a.s(body) |
                (a.a(inc), a.s(body)))))])
        return ParseError;

      out = new ForInteger(out, EmitCounterImplicitly,
                           reg, init, limit, inc, body);
      body.clear();
      return ContinueParsing;
    }
  };

  static GlobalBinding<ForIntegerParser<false> >
  _forIntegerParser(L"for-integer");
  static GlobalBinding<ForIntegerParser<true > >
  _forIntPrintParser(L"for-int-print");
}
<|endoftext|>


<commit_before>#include "xchainer/array.h"

#include <array>
#include <cstddef>
#include <initializer_list>
#include <type_traits>

#ifdef XCHAINER_ENABLE_CUDA
#include <cuda_runtime.h>
#endif  // XCHAINER_ENABLE_CUDA
#include <gtest/gtest.h>

#include "xchainer/array_node.h"
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_runtime.h"
#endif  // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/op_node.h"

namespace xchainer {
namespace {

class ArrayTest : public ::testing::TestWithParam<::testing::tuple<std::string>> {
protected:
    virtual void SetUp() {
        std::string device_name = ::testing::get<0>(GetParam());
        device_scope_ = std::make_unique<DeviceScope>(device_name);
    }

    virtual void TearDown() { device_scope_.reset(); }

public:
    template <typename T>
    Array MakeArray(std::initializer_list<int64_t> shape, std::shared_ptr<void> data) {
        return {shape, TypeToDtype<T>, data};
    }

    template <typename T>
    Array MakeArray(std::initializer_list<int64_t> shape, std::initializer_list<T> data) {
        auto a = std::make_unique<T[]>(data.size());
        std::copy(data.begin(), data.end(), a.get());
        return {shape, TypeToDtype<T>, std::move(a)};
    }

    template <typename T>
    void AssertEqual(const Array& lhs, const Array& rhs) {
#ifdef XCHAINER_ENABLE_CUDA
        std::string device_name = ::testing::get<0>(GetParam());
        if (device_name == "cuda") {
            cuda::CheckError(cudaDeviceSynchronize());
        }
#endif  // XCHAINER_ENABLE_CUDA
        ASSERT_NO_THROW(CheckEqual(lhs.dtype(), rhs.dtype()));
        ASSERT_NO_THROW(CheckEqual(lhs.shape(), rhs.shape()));
        auto total_size = lhs.shape().total_size();
        const T* ldata = static_cast<const T*>(lhs.data().get());
        const T* rdata = static_cast<const T*>(rhs.data().get());
        for (decltype(total_size) i = 0; i < total_size; i++) {
            ASSERT_EQ(ldata[i], rdata[i]);
        }
    }

    bool IsPointerCudaManaged(const void* ptr) {
#ifdef XCHAINER_ENABLE_CUDA
        cudaPointerAttributes attr = {};
        cuda::CheckError(cudaPointerGetAttributes(&attr, ptr));
        return attr.isManaged != 0;
#else
        (void)ptr;
        return false;
#endif  // XCHAINER_ENABLE_CUDA
    }

    template <bool is_const>
    void CheckArray() {
        using TargetArray = std::conditional_t<is_const, const Array, Array>;

        std::shared_ptr<void> data = std::make_unique<float[]>(2 * 3 * 4);
        TargetArray x = MakeArray<float>({2, 3, 4}, data);

        // Basic attributes
        ASSERT_EQ(TypeToDtype<float>, x.dtype());
        ASSERT_EQ(3, x.ndim());
        ASSERT_EQ(2 * 3 * 4, x.total_size());
        ASSERT_EQ(4, x.element_bytes());
        ASSERT_EQ(2 * 3 * 4 * 4, x.total_bytes());
        ASSERT_EQ(0, x.offset());
        ASSERT_TRUE(x.is_contiguous());

        // Array::data
        std::shared_ptr<const void> x_data = x.data();
        if (GetCurrentDevice() == MakeDevice("cpu")) {
            ASSERT_EQ(data, x_data);
        } else if (GetCurrentDevice() == MakeDevice("cuda")) {
            ASSERT_NE(data, x_data);
            ASSERT_TRUE(IsPointerCudaManaged(x_data.get()));
        } else {
            FAIL() << "invalid device";
        }
    }

private:
    std::unique_ptr<DeviceScope> device_scope_;
};

TEST_P(ArrayTest, ArrayCtor) { CheckArray<false>(); }

TEST_P(ArrayTest, ConstArrayCtor) { CheckArray<true>(); }

TEST_P(ArrayTest, IAdd) {
    {
        Array a = MakeArray<bool>({4, 1}, {true, true, false, false});
        Array b = MakeArray<bool>({4, 1}, {true, false, true, false});
        Array e = MakeArray<bool>({4, 1}, {true, true, true, false});
        a.IAdd(b);
        AssertEqual<bool>(e, a);
    }
    {
        Array a = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array b = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array e = MakeArray<int8_t>({3, 1}, {2, 4, 6});
        a.IAdd(b);
        AssertEqual<int8_t>(e, a);
    }
    {
        Array a = MakeArray<float>({3, 1}, {1, 2, 3});
        Array b = MakeArray<float>({3, 1}, {1, 2, 3});
        Array e = MakeArray<float>({3, 1}, {2, 4, 6});
        a.IAdd(b);
        AssertEqual<float>(e, a);
    }
}

TEST_P(ArrayTest, IMul) {
    {
        Array a = MakeArray<bool>({4, 1}, {true, true, false, false});
        Array b = MakeArray<bool>({4, 1}, {true, false, true, false});
        Array e = MakeArray<bool>({4, 1}, {true, false, false, false});
        a.IMul(b);
        AssertEqual<bool>(e, a);
    }
    {
        Array a = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array b = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array e = MakeArray<int8_t>({3, 1}, {1, 4, 9});
        a.IMul(b);
        AssertEqual<int8_t>(e, a);
    }
    {
        Array a = MakeArray<float>({3, 1}, {1, 2, 3});
        Array b = MakeArray<float>({3, 1}, {1, 2, 3});
        Array e = MakeArray<float>({3, 1}, {1, 4, 9});
        a.IMul(b);
        AssertEqual<float>(e, a);
    }
}

TEST_P(ArrayTest, Add) {
    {
        Array a = MakeArray<bool>({4, 1}, {true, true, false, false});
        Array b = MakeArray<bool>({4, 1}, {true, false, true, false});
        Array e = MakeArray<bool>({4, 1}, {true, true, true, false});
        Array o = a.Add(b);
        AssertEqual<bool>(e, o);
    }
    {
        Array a = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array b = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array e = MakeArray<int8_t>({3, 1}, {2, 4, 6});
        Array o = a.Add(b);
        AssertEqual<int8_t>(e, o);
    }
    {
        Array a = MakeArray<float>({3, 1}, {1, 2, 3});
        Array b = MakeArray<float>({3, 1}, {1, 2, 3});
        Array e = MakeArray<float>({3, 1}, {2, 4, 6});
        Array o = a.Add(b);
        AssertEqual<float>(e, o);
    }
}

TEST_P(ArrayTest, Mul) {
    {
        Array a = MakeArray<bool>({4, 1}, {true, true, false, false});
        Array b = MakeArray<bool>({4, 1}, {true, false, true, false});
        Array e = MakeArray<bool>({4, 1}, {true, false, false, false});
        Array o = a.Mul(b);
        AssertEqual<bool>(e, o);
    }
    {
        Array a = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array b = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array e = MakeArray<int8_t>({3, 1}, {1, 4, 9});
        Array o = a.Mul(b);
        AssertEqual<int8_t>(e, o);
    }
    {
        Array a = MakeArray<float>({3, 1}, {1, 2, 3});
        Array b = MakeArray<float>({3, 1}, {1, 2, 3});
        Array e = MakeArray<float>({3, 1}, {1, 4, 9});
        Array o = a.Mul(b);
        AssertEqual<float>(e, o);
    }
}

TEST_P(ArrayTest, ComputationalGraph) {
    {
        // c = a + b
        // o = a * c
        Array a = MakeArray<bool>({4, 1}, {true, true, false, false});
        Array b = MakeArray<bool>({4, 1}, {true, false, true, false});
        {
            auto a_node = a.node();
            auto b_node = b.node();
            ASSERT_NE(a_node, nullptr) << "a's node is null";
            ASSERT_NE(b_node, nullptr) << "b's node is null";
            auto a_op_node = a_node->next_node();
            auto b_op_node = b_node->next_node();
            ASSERT_EQ(a_op_node, nullptr) << "a's op node is not null";
            ASSERT_EQ(b_op_node, nullptr) << "b's op node is not null";
        }

        Array c = a.Add(b);
        {
            auto a_node = a.node();
            auto b_node = b.node();
            auto c_node = c.node();
            ASSERT_NE(a_node, nullptr) << "a's node is null";
            ASSERT_NE(b_node, nullptr) << "b's node is null";
            ASSERT_NE(c_node, nullptr) << "c's node is null";
            auto a_op_node = a_node->next_node();
            auto b_op_node = b_node->next_node();
            auto c_op_node = c_node->next_node();
            ASSERT_EQ(a_op_node, nullptr) << "a's op node is not null";
            ASSERT_EQ(b_op_node, nullptr) << "b's op node is not null";
            ASSERT_NE(c_op_node, nullptr) << "c's op node is null";
            ASSERT_EQ(c_op_node->name(), "add") << "c's op node name is wrong";
        }

        Array o = a.Mul(c);
        {
            auto a_node = a.node();
            auto b_node = b.node();
            auto c_node = c.node();
            auto o_node = o.node();
            ASSERT_NE(a_node, nullptr) << "a's node is null";
            ASSERT_NE(b_node, nullptr) << "b's node is null";
            ASSERT_NE(c_node, nullptr) << "c's node is null";
            ASSERT_NE(o_node, nullptr) << "o's node is null";
            auto a_op_node = a_node->next_node();
            auto b_op_node = b_node->next_node();
            auto c_op_node = c_node->next_node();
            auto o_op_node = o_node->next_node();
            ASSERT_EQ(a_op_node, nullptr) << "a's op node is not null";
            ASSERT_EQ(b_op_node, nullptr) << "b's op node is not null";
            ASSERT_NE(c_op_node, nullptr) << "c's op node is null";
            ASSERT_NE(o_op_node, nullptr) << "o's op node is null";
            ASSERT_EQ(c_op_node->name(), "add") << "c's op node name is wrong";
            ASSERT_EQ(o_op_node->name(), "mul") << "o's op node name is wrong";
        }
    }
}

TEST_P(ArrayTest, ComputationalGraphInplace) {
    {
        // a += b
        // a *= b
        Array a = MakeArray<bool>({4, 1}, {true, true, false, false});
        Array b = MakeArray<bool>({4, 1}, {true, false, true, false});
        auto a_node_1 = a.node();
        {
            auto a_node = a_node_1;
            auto b_node = b.node();
            ASSERT_NE(a_node, nullptr) << "a's node is null";
            ASSERT_NE(b_node, nullptr) << "b's node is null";
            auto a_op_node = a_node->next_node();
            auto b_op_node = b_node->next_node();
            ASSERT_EQ(a_op_node, nullptr) << "a's op node is not null";
            ASSERT_EQ(b_op_node, nullptr) << "b's op node is not null";
        }

        a.IAdd(b);
        auto a_node_2 = a.node();
        {
            auto a_node = a_node_2;
            auto b_node = b.node();
            ASSERT_NE(a_node, nullptr) << "a's node is null";
            ASSERT_NE(a_node, a_node_1) << "a's node is not changed";
            ASSERT_NE(b_node, nullptr) << "b's node is null";
            auto a_op_node = a_node->next_node();
            auto b_op_node = b_node->next_node();
            ASSERT_NE(a_op_node, nullptr) << "a's op node is null";
            ASSERT_EQ(b_op_node, nullptr) << "b's op node is not null";
            ASSERT_EQ(a_op_node->name(), "add") << "a's op node name is wrong";
        }

        a.IMul(b);
        {
            auto a_node = a.node();
            auto b_node = b.node();
            ASSERT_NE(a_node, nullptr) << "a's node is null";
            ASSERT_NE(a_node, a_node_1) << "a's node is not changed";
            ASSERT_NE(a_node, a_node_2) << "a's node is not changed";
            ASSERT_NE(b_node, nullptr) << "b's node is null";
            auto a_op_node = a_node->next_node();
            auto b_op_node = b_node->next_node();
            ASSERT_NE(a_op_node, nullptr) << "a's op node is null";
            ASSERT_EQ(b_op_node, nullptr) << "b's op node is not null";
            ASSERT_EQ(a_op_node->name(), "mul") << "a's op node name is wrong";
        }
    }
}

INSTANTIATE_TEST_CASE_P(ForEachDevice, ArrayTest, ::testing::Values(
#ifdef XCHAINER_ENABLE_CUDA
                                                      std::string{"cuda"},
#endif  // XCHAINER_ENABLE_CUDA
                                                      std::string{"cpu"}));

}  // namespace
}  // namespace xchainer
<commit_msg>Remove obvious messages<commit_after>#include "xchainer/array.h"

#include <array>
#include <cstddef>
#include <initializer_list>
#include <type_traits>

#ifdef XCHAINER_ENABLE_CUDA
#include <cuda_runtime.h>
#endif  // XCHAINER_ENABLE_CUDA
#include <gtest/gtest.h>

#include "xchainer/array_node.h"
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_runtime.h"
#endif  // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/op_node.h"

namespace xchainer {
namespace {

class ArrayTest : public ::testing::TestWithParam<::testing::tuple<std::string>> {
protected:
    virtual void SetUp() {
        std::string device_name = ::testing::get<0>(GetParam());
        device_scope_ = std::make_unique<DeviceScope>(device_name);
    }

    virtual void TearDown() { device_scope_.reset(); }

public:
    template <typename T>
    Array MakeArray(std::initializer_list<int64_t> shape, std::shared_ptr<void> data) {
        return {shape, TypeToDtype<T>, data};
    }

    template <typename T>
    Array MakeArray(std::initializer_list<int64_t> shape, std::initializer_list<T> data) {
        auto a = std::make_unique<T[]>(data.size());
        std::copy(data.begin(), data.end(), a.get());
        return {shape, TypeToDtype<T>, std::move(a)};
    }

    template <typename T>
    void AssertEqual(const Array& lhs, const Array& rhs) {
#ifdef XCHAINER_ENABLE_CUDA
        std::string device_name = ::testing::get<0>(GetParam());
        if (device_name == "cuda") {
            cuda::CheckError(cudaDeviceSynchronize());
        }
#endif  // XCHAINER_ENABLE_CUDA
        ASSERT_NO_THROW(CheckEqual(lhs.dtype(), rhs.dtype()));
        ASSERT_NO_THROW(CheckEqual(lhs.shape(), rhs.shape()));
        auto total_size = lhs.shape().total_size();
        const T* ldata = static_cast<const T*>(lhs.data().get());
        const T* rdata = static_cast<const T*>(rhs.data().get());
        for (decltype(total_size) i = 0; i < total_size; i++) {
            ASSERT_EQ(ldata[i], rdata[i]);
        }
    }

    bool IsPointerCudaManaged(const void* ptr) {
#ifdef XCHAINER_ENABLE_CUDA
        cudaPointerAttributes attr = {};
        cuda::CheckError(cudaPointerGetAttributes(&attr, ptr));
        return attr.isManaged != 0;
#else
        (void)ptr;
        return false;
#endif  // XCHAINER_ENABLE_CUDA
    }

    template <bool is_const>
    void CheckArray() {
        using TargetArray = std::conditional_t<is_const, const Array, Array>;

        std::shared_ptr<void> data = std::make_unique<float[]>(2 * 3 * 4);
        TargetArray x = MakeArray<float>({2, 3, 4}, data);

        // Basic attributes
        ASSERT_EQ(TypeToDtype<float>, x.dtype());
        ASSERT_EQ(3, x.ndim());
        ASSERT_EQ(2 * 3 * 4, x.total_size());
        ASSERT_EQ(4, x.element_bytes());
        ASSERT_EQ(2 * 3 * 4 * 4, x.total_bytes());
        ASSERT_EQ(0, x.offset());
        ASSERT_TRUE(x.is_contiguous());

        // Array::data
        std::shared_ptr<const void> x_data = x.data();
        if (GetCurrentDevice() == MakeDevice("cpu")) {
            ASSERT_EQ(data, x_data);
        } else if (GetCurrentDevice() == MakeDevice("cuda")) {
            ASSERT_NE(data, x_data);
            ASSERT_TRUE(IsPointerCudaManaged(x_data.get()));
        } else {
            FAIL() << "invalid device";
        }
    }

private:
    std::unique_ptr<DeviceScope> device_scope_;
};

TEST_P(ArrayTest, ArrayCtor) { CheckArray<false>(); }

TEST_P(ArrayTest, ConstArrayCtor) { CheckArray<true>(); }

TEST_P(ArrayTest, IAdd) {
    {
        Array a = MakeArray<bool>({4, 1}, {true, true, false, false});
        Array b = MakeArray<bool>({4, 1}, {true, false, true, false});
        Array e = MakeArray<bool>({4, 1}, {true, true, true, false});
        a.IAdd(b);
        AssertEqual<bool>(e, a);
    }
    {
        Array a = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array b = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array e = MakeArray<int8_t>({3, 1}, {2, 4, 6});
        a.IAdd(b);
        AssertEqual<int8_t>(e, a);
    }
    {
        Array a = MakeArray<float>({3, 1}, {1, 2, 3});
        Array b = MakeArray<float>({3, 1}, {1, 2, 3});
        Array e = MakeArray<float>({3, 1}, {2, 4, 6});
        a.IAdd(b);
        AssertEqual<float>(e, a);
    }
}

TEST_P(ArrayTest, IMul) {
    {
        Array a = MakeArray<bool>({4, 1}, {true, true, false, false});
        Array b = MakeArray<bool>({4, 1}, {true, false, true, false});
        Array e = MakeArray<bool>({4, 1}, {true, false, false, false});
        a.IMul(b);
        AssertEqual<bool>(e, a);
    }
    {
        Array a = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array b = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array e = MakeArray<int8_t>({3, 1}, {1, 4, 9});
        a.IMul(b);
        AssertEqual<int8_t>(e, a);
    }
    {
        Array a = MakeArray<float>({3, 1}, {1, 2, 3});
        Array b = MakeArray<float>({3, 1}, {1, 2, 3});
        Array e = MakeArray<float>({3, 1}, {1, 4, 9});
        a.IMul(b);
        AssertEqual<float>(e, a);
    }
}

TEST_P(ArrayTest, Add) {
    {
        Array a = MakeArray<bool>({4, 1}, {true, true, false, false});
        Array b = MakeArray<bool>({4, 1}, {true, false, true, false});
        Array e = MakeArray<bool>({4, 1}, {true, true, true, false});
        Array o = a.Add(b);
        AssertEqual<bool>(e, o);
    }
    {
        Array a = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array b = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array e = MakeArray<int8_t>({3, 1}, {2, 4, 6});
        Array o = a.Add(b);
        AssertEqual<int8_t>(e, o);
    }
    {
        Array a = MakeArray<float>({3, 1}, {1, 2, 3});
        Array b = MakeArray<float>({3, 1}, {1, 2, 3});
        Array e = MakeArray<float>({3, 1}, {2, 4, 6});
        Array o = a.Add(b);
        AssertEqual<float>(e, o);
    }
}

TEST_P(ArrayTest, Mul) {
    {
        Array a = MakeArray<bool>({4, 1}, {true, true, false, false});
        Array b = MakeArray<bool>({4, 1}, {true, false, true, false});
        Array e = MakeArray<bool>({4, 1}, {true, false, false, false});
        Array o = a.Mul(b);
        AssertEqual<bool>(e, o);
    }
    {
        Array a = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array b = MakeArray<int8_t>({3, 1}, {1, 2, 3});
        Array e = MakeArray<int8_t>({3, 1}, {1, 4, 9});
        Array o = a.Mul(b);
        AssertEqual<int8_t>(e, o);
    }
    {
        Array a = MakeArray<float>({3, 1}, {1, 2, 3});
        Array b = MakeArray<float>({3, 1}, {1, 2, 3});
        Array e = MakeArray<float>({3, 1}, {1, 4, 9});
        Array o = a.Mul(b);
        AssertEqual<float>(e, o);
    }
}

TEST_P(ArrayTest, ComputationalGraph) {
    {
        // c = a + b
        // o = a * c
        Array a = MakeArray<bool>({4, 1}, {true, true, false, false});
        Array b = MakeArray<bool>({4, 1}, {true, false, true, false});
        {
            auto a_node = a.node();
            auto b_node = b.node();
            ASSERT_NE(a_node, nullptr);
            ASSERT_NE(b_node, nullptr);
            auto a_op_node = a_node->next_node();
            auto b_op_node = b_node->next_node();
            ASSERT_EQ(a_op_node, nullptr);
            ASSERT_EQ(b_op_node, nullptr);
        }

        Array c = a.Add(b);
        {
            auto a_node = a.node();
            auto b_node = b.node();
            auto c_node = c.node();
            ASSERT_NE(a_node, nullptr);
            ASSERT_NE(b_node, nullptr);
            ASSERT_NE(c_node, nullptr);
            auto a_op_node = a_node->next_node();
            auto b_op_node = b_node->next_node();
            auto c_op_node = c_node->next_node();
            ASSERT_EQ(a_op_node, nullptr);
            ASSERT_EQ(b_op_node, nullptr);
            ASSERT_NE(c_op_node, nullptr);
            ASSERT_EQ(c_op_node->name(), "add");
        }

        Array o = a.Mul(c);
        {
            auto a_node = a.node();
            auto b_node = b.node();
            auto c_node = c.node();
            auto o_node = o.node();
            ASSERT_NE(a_node, nullptr);
            ASSERT_NE(b_node, nullptr);
            ASSERT_NE(c_node, nullptr);
            ASSERT_NE(o_node, nullptr);
            auto a_op_node = a_node->next_node();
            auto b_op_node = b_node->next_node();
            auto c_op_node = c_node->next_node();
            auto o_op_node = o_node->next_node();
            ASSERT_EQ(a_op_node, nullptr);
            ASSERT_EQ(b_op_node, nullptr);
            ASSERT_NE(c_op_node, nullptr);
            ASSERT_NE(o_op_node, nullptr);
            ASSERT_EQ(c_op_node->name(), "add");
            ASSERT_EQ(o_op_node->name(), "mul");
        }
    }
}

TEST_P(ArrayTest, ComputationalGraphInplace) {
    {
        // a += b
        // a *= b
        Array a = MakeArray<bool>({4, 1}, {true, true, false, false});
        Array b = MakeArray<bool>({4, 1}, {true, false, true, false});
        auto a_node_1 = a.node();
        {
            auto a_node = a_node_1;
            auto b_node = b.node();
            ASSERT_NE(a_node, nullptr);
            ASSERT_NE(b_node, nullptr);
            auto a_op_node = a_node->next_node();
            auto b_op_node = b_node->next_node();
            ASSERT_EQ(a_op_node, nullptr);
            ASSERT_EQ(b_op_node, nullptr);
        }

        a.IAdd(b);
        auto a_node_2 = a.node();
        {
            auto a_node = a_node_2;
            auto b_node = b.node();
            ASSERT_NE(a_node, nullptr);
            ASSERT_NE(a_node, a_node_1) << "a's node is not renewed";
            ASSERT_NE(b_node, nullptr);
            auto a_op_node = a_node->next_node();
            auto b_op_node = b_node->next_node();
            ASSERT_NE(a_op_node, nullptr);
            ASSERT_EQ(b_op_node, nullptr);
            ASSERT_EQ(a_op_node->name(), "add");
        }

        a.IMul(b);
        {
            auto a_node = a.node();
            auto b_node = b.node();
            ASSERT_NE(a_node, nullptr);
            ASSERT_NE(a_node, a_node_1) << "a's node is not renewed";
            ASSERT_NE(a_node, a_node_2) << "a's node is not renewed";
            ASSERT_NE(b_node, nullptr);
            auto a_op_node = a_node->next_node();
            auto b_op_node = b_node->next_node();
            ASSERT_NE(a_op_node, nullptr);
            ASSERT_EQ(b_op_node, nullptr);
            ASSERT_EQ(a_op_node->name(), "mul");
        }
    }
}

INSTANTIATE_TEST_CASE_P(ForEachDevice, ArrayTest, ::testing::Values(
#ifdef XCHAINER_ENABLE_CUDA
                                                      std::string{"cuda"},
#endif  // XCHAINER_ENABLE_CUDA
                                                      std::string{"cpu"}));

}  // namespace
}  // namespace xchainer
<|endoftext|>