<commit_before>//
// Copyright (c) 2015 CNRS
// Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.
//
// This file is part of Pinocchio
// Pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// Pinocchio is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.

#include "pinocchio/multibody/parser/sample-models.hpp"

namespace se3
{
  namespace buildModels
  {

    void humanoid2d(Model& model)
    {
      model.addBody(model.getBodyId("universe"),JointModelRX(),SE3::Identity(),Inertia::Random(),
                    "ff1_joint", "ff1_body");
      model.addBody(model.getBodyId("ff1_body"),JointModelRY(),SE3::Identity(),Inertia::Random(),
                    "root_joint", "root_body");

      model.addBody(model.getBodyId("root_body"),JointModelRZ(),SE3::Random(),Inertia::Random(),
                    "lleg1_joint", "lleg1_body");
      model.addBody(model.getBodyId("lleg1_body"),JointModelRY(),SE3::Random(),Inertia::Random(),
                    "lleg2_joint", "lleg2_body");

      model.addBody(model.getBodyId("root_body"),JointModelRZ(),SE3::Random(),Inertia::Random(),
                    "rleg1_joint", "rleg1_body");
      model.addBody(model.getBodyId("rleg1_body"),JointModelRY(),SE3::Random(),Inertia::Random(),
                    "rleg2_joint", "rleg2_body");

      model.addBody(model.getBodyId("root_body"),JointModelRY(),SE3::Random(),Inertia::Random(),
                    "torso1_joint", "torso1_body");
      model.addBody(model.getBodyId("torso1_body"),JointModelRZ(),SE3::Random(),Inertia::Random(),
                    "chest_joint", "chest_body");

      model.addBody(model.getBodyId("chest_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rarm1_joint", "rarm1_body");
      model.addBody(model.getBodyId("rarm1_body"),JointModelRZ(),SE3::Random(),Inertia::Random(),
                    "rarm2_joint", "rarm2_body");

      model.addBody(model.getBodyId("chest_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "larm1_joint", "larm1_body");
      model.addBody(model.getBodyId("larm1_body"),JointModelRZ(),SE3::Random(),Inertia::Random(),
                    "larm2_joint", "larm2_body");
    }

    void humanoidSimple(Model& model, bool usingFF)
    {
      if(! usingFF )
      {
        model.addBody(model.getBodyId("universe"),JointModelRX(),SE3::Identity(),Inertia::Random(),
                      "ff1_joint", "ff1_body");
        model.addBody(model.getBodyId("ff1_body"),JointModelRY(),SE3::Identity(),Inertia::Random(),
                      "ff2_joint", "ff2_body");
        model.addBody(model.getBodyId("ff2_body"),JointModelRZ(),SE3::Identity(),Inertia::Random(),
                      "ff3_joint", "ff3_body");
        model.addBody(model.getBodyId("ff3_body"),JointModelRZ(),SE3::Random(),Inertia::Random(),
                      "ff4_joint", "ff4_body");
        model.addBody(model.getBodyId("ff4_body"),JointModelRY(),SE3::Identity(),Inertia::Random(),
                      "ff5_joint", "ff5_body");
        model.addBody(model.getBodyId("ff5_body"),JointModelRX(),SE3::Identity(),Inertia::Random(),
                      "root_joint", "root_body");
      }
      else
      {
        model.addBody(model.getBodyId("universe"),JointModelFreeFlyer(),SE3::Identity(),
                      Inertia::Random(),"root_joint", "root_body");
      }

      model.addBody(model.getBodyId("root_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "lleg1_joint", "lleg1_body");
      model.addBody(model.getBodyId("lleg1_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "lleg2_joint", "lleg2_body");
      model.addBody(model.getBodyId("lleg2_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "lleg3_joint", "lleg3_body");
      model.addBody(model.getBodyId("lleg3_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "lleg4_joint", "lleg4_body");
      model.addBody(model.getBodyId("lleg4_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "lleg5_joint", "lleg5_body");
      model.addBody(model.getBodyId("lleg5_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "lleg6_joint", "lleg6_body");

      model.addBody(model.getBodyId("root_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rleg1_joint", "rleg1_body");
      model.addBody(model.getBodyId("rleg1_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rleg2_joint", "rleg2_body");
      model.addBody(model.getBodyId("rleg2_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rleg3_joint", "rleg3_body");
      model.addBody(model.getBodyId("rleg3_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rleg4_joint", "rleg4_body");
      model.addBody(model.getBodyId("rleg4_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rleg5_joint", "rleg5_body");
      model.addBody(model.getBodyId("rleg5_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rleg6_joint", "rleg6_body");

      model.addBody(model.getBodyId("root_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "torso1_joint", "torso1_body");
      model.addBody(model.getBodyId("torso1_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "chest_joint", "chest_body");

      model.addBody(model.getBodyId("chest_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rarm1_joint", "rarm1_body");
      model.addBody(model.getBodyId("rarm1_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rarm2_joint", "rarm2_body");
      model.addBody(model.getBodyId("rarm2_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rarm3_joint", "rarm3_body");
      model.addBody(model.getBodyId("rarm3_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rarm4_joint", "rarm4_body");
      model.addBody(model.getBodyId("rarm4_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rarm5_joint", "rarm5_body");
      model.addBody(model.getBodyId("rarm5_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rarm6_joint", "rarm6_body");

      model.addBody(model.getBodyId("chest_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "larm1_joint", "larm1_body");
      model.addBody(model.getBodyId("larm1_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "larm2_joint", "larm2_body");
      model.addBody(model.getBodyId("larm2_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "larm3_joint", "larm3_body");
      model.addBody(model.getBodyId("larm3_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "larm4_joint", "larm4_body");
      model.addBody(model.getBodyId("larm4_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "larm5_joint", "larm5_body");
      model.addBody(model.getBodyId("larm5_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "larm6_joint", "larm6_body");
    }

  } // namespace buildModels
} // namespace se3
<commit_msg>Build sample humanoid model with joint limits.<commit_after>//
// Copyright (c) 2015 CNRS
// Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.
//
// This file is part of Pinocchio
// Pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// Pinocchio is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.

#include "pinocchio/multibody/parser/sample-models.hpp"

namespace se3
{
  namespace buildModels
  {

    void humanoid2d(Model& model)
    {
      model.addBody(model.getBodyId("universe"),JointModelRX(),SE3::Identity(),Inertia::Random(),
                    "ff1_joint", "ff1_body");
      model.addBody(model.getBodyId("ff1_body"),JointModelRY(),SE3::Identity(),Inertia::Random(),
                    "root_joint", "root_body");

      model.addBody(model.getBodyId("root_body"),JointModelRZ(),SE3::Random(),Inertia::Random(),
                    "lleg1_joint", "lleg1_body");
      model.addBody(model.getBodyId("lleg1_body"),JointModelRY(),SE3::Random(),Inertia::Random(),
                    "lleg2_joint", "lleg2_body");

      model.addBody(model.getBodyId("root_body"),JointModelRZ(),SE3::Random(),Inertia::Random(),
                    "rleg1_joint", "rleg1_body");
      model.addBody(model.getBodyId("rleg1_body"),JointModelRY(),SE3::Random(),Inertia::Random(),
                    "rleg2_joint", "rleg2_body");

      model.addBody(model.getBodyId("root_body"),JointModelRY(),SE3::Random(),Inertia::Random(),
                    "torso1_joint", "torso1_body");
      model.addBody(model.getBodyId("torso1_body"),JointModelRZ(),SE3::Random(),Inertia::Random(),
                    "chest_joint", "chest_body");

      model.addBody(model.getBodyId("chest_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "rarm1_joint", "rarm1_body");
      model.addBody(model.getBodyId("rarm1_body"),JointModelRZ(),SE3::Random(),Inertia::Random(),
                    "rarm2_joint", "rarm2_body");

      model.addBody(model.getBodyId("chest_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    "larm1_joint", "larm1_body");
      model.addBody(model.getBodyId("larm1_body"),JointModelRZ(),SE3::Random(),Inertia::Random(),
                    "larm2_joint", "larm2_body");
    }

    void humanoidSimple(Model& model, bool usingFF)
    {
      if(! usingFF )
      {
        model.addBody(model.getBodyId("universe"),JointModelRX(),SE3::Identity(),Inertia::Random(),
                      "ff1_joint", "ff1_body");
        model.addBody(model.getBodyId("ff1_body"),JointModelRY(),SE3::Identity(),Inertia::Random(),
                      "ff2_joint", "ff2_body");
        model.addBody(model.getBodyId("ff2_body"),JointModelRZ(),SE3::Identity(),Inertia::Random(),
                      "ff3_joint", "ff3_body");
        model.addBody(model.getBodyId("ff3_body"),JointModelRZ(),SE3::Random(),Inertia::Random(),
                      "ff4_joint", "ff4_body");
        model.addBody(model.getBodyId("ff4_body"),JointModelRY(),SE3::Identity(),Inertia::Random(),
                      "ff5_joint", "ff5_body");
        model.addBody(model.getBodyId("ff5_body"),JointModelRX(),SE3::Identity(),Inertia::Random(),
                      "root_joint", "root_body");
      }
      else
      {
        model.addBody(model.getBodyId("universe"),JointModelFreeFlyer(),
                      SE3::Identity(),Inertia::Random(),
                      Eigen::VectorXd::Zero(6), 1e3 * (Eigen::VectorXd::Random(6).array() + 1),
                      1e3 * (Eigen::VectorXd::Random(7).array() - 1),
                      1e3 * (Eigen::VectorXd::Random(7).array() + 1),
                      "root_joint", "root_body");
      }

      model.addBody(model.getBodyId("root_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "lleg1_joint", "lleg1_body");
      model.addBody(model.getBodyId("lleg1_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "lleg2_joint", "lleg2_body");
      model.addBody(model.getBodyId("lleg2_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "lleg3_joint", "lleg3_body");
      model.addBody(model.getBodyId("lleg3_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "lleg4_joint", "lleg4_body");
      model.addBody(model.getBodyId("lleg4_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "lleg5_joint", "lleg5_body");
      model.addBody(model.getBodyId("lleg5_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "lleg6_joint", "lleg6_body");

      model.addBody(model.getBodyId("root_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "rleg1_joint", "rleg1_body");
      model.addBody(model.getBodyId("rleg1_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "rleg2_joint", "rleg2_body");
      model.addBody(model.getBodyId("rleg2_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "rleg3_joint", "rleg3_body");
      model.addBody(model.getBodyId("rleg3_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "rleg4_joint", "rleg4_body");
      model.addBody(model.getBodyId("rleg4_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "rleg5_joint", "rleg5_body");
      model.addBody(model.getBodyId("rleg5_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "rleg6_joint", "rleg6_body");

      model.addBody(model.getBodyId("root_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "torso1_joint", "torso1_body");
      model.addBody(model.getBodyId("torso1_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "chest_joint", "chest_body");

      model.addBody(model.getBodyId("chest_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "rarm1_joint", "rarm1_body");
      model.addBody(model.getBodyId("rarm1_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "rarm2_joint", "rarm2_body");
      model.addBody(model.getBodyId("rarm2_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "rarm3_joint", "rarm3_body");
      model.addBody(model.getBodyId("rarm3_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "rarm4_joint", "rarm4_body");
      model.addBody(model.getBodyId("rarm4_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "rarm5_joint", "rarm5_body");
      model.addBody(model.getBodyId("rarm5_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "rarm6_joint", "rarm6_body");

      model.addBody(model.getBodyId("chest_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "larm1_joint", "larm1_body");
      model.addBody(model.getBodyId("larm1_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "larm2_joint", "larm2_body");
      model.addBody(model.getBodyId("larm2_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "larm3_joint", "larm3_body");
      model.addBody(model.getBodyId("larm3_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "larm4_joint", "larm4_body");
      model.addBody(model.getBodyId("larm4_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "larm5_joint", "larm5_body");
      model.addBody(model.getBodyId("larm5_body"),JointModelRX(),SE3::Random(),Inertia::Random(),
                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,
                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,
                    "larm6_joint", "larm6_body");
    }

  } // namespace buildModels
} // namespace se3
<|endoftext|>


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

#include <chainparams.h>
#include <consensus/merkle.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <core_memusage.h>
#include <pubkey.h>
#include <primitives/block.h>
#include <streams.h>
#include <test/fuzz/fuzz.h>
#include <validation.h>
#include <version.h>

#include <cassert>
#include <string>

void initialize()
{
    const static auto verify_handle = MakeUnique<ECCVerifyHandle>();
    SelectParams(CBaseChainParams::REGTEST);
}

void test_one_input(const std::vector<uint8_t>& buffer)
{
    CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
    CBlock block;
    try {
        int nVersion;
        ds >> nVersion;
        ds.SetVersion(nVersion);
        ds >> block;
    } catch (const std::ios_base::failure&) {
        return;
    }
    const Consensus::Params& consensus_params = Params().GetConsensus();
    BlockValidationState validation_state_pow_and_merkle;
    const bool valid_incl_pow_and_merkle = CheckBlock(block, validation_state_pow_and_merkle, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ true);
    BlockValidationState validation_state_pow;
    const bool valid_incl_pow = CheckBlock(block, validation_state_pow, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ false);
    BlockValidationState validation_state_merkle;
    const bool valid_incl_merkle = CheckBlock(block, validation_state_merkle, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ true);
    BlockValidationState validation_state_none;
    const bool valid_incl_none = CheckBlock(block, validation_state_none, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ false);
    if (valid_incl_pow_and_merkle) {
        assert(valid_incl_pow && valid_incl_merkle && valid_incl_none);
    } else if (valid_incl_merkle || valid_incl_pow) {
        assert(valid_incl_none);
    }
    (void)block.GetHash();
    (void)block.ToString();
    (void)BlockMerkleRoot(block);
    if (!block.vtx.empty()) {
        // TODO: Avoid array index out of bounds error in BlockWitnessMerkleRoot
        //       when block.vtx.empty().
        (void)BlockWitnessMerkleRoot(block);
    }
    (void)GetBlockWeight(block);
    (void)GetWitnessCommitmentIndex(block);
    (void)RecursiveDynamicUsage(block);
}
<commit_msg>tests: Fuzz RecursiveDynamicUsage(const std::shared_ptr<X>& p)<commit_after>// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <chainparams.h>
#include <consensus/merkle.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <core_memusage.h>
#include <pubkey.h>
#include <primitives/block.h>
#include <streams.h>
#include <test/fuzz/fuzz.h>
#include <validation.h>
#include <version.h>

#include <cassert>
#include <memory>
#include <string>

void initialize()
{
    const static auto verify_handle = MakeUnique<ECCVerifyHandle>();
    SelectParams(CBaseChainParams::REGTEST);
}

void test_one_input(const std::vector<uint8_t>& buffer)
{
    CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
    CBlock block;
    try {
        int nVersion;
        ds >> nVersion;
        ds.SetVersion(nVersion);
        ds >> block;
    } catch (const std::ios_base::failure&) {
        return;
    }
    const Consensus::Params& consensus_params = Params().GetConsensus();
    BlockValidationState validation_state_pow_and_merkle;
    const bool valid_incl_pow_and_merkle = CheckBlock(block, validation_state_pow_and_merkle, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ true);
    BlockValidationState validation_state_pow;
    const bool valid_incl_pow = CheckBlock(block, validation_state_pow, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ false);
    BlockValidationState validation_state_merkle;
    const bool valid_incl_merkle = CheckBlock(block, validation_state_merkle, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ true);
    BlockValidationState validation_state_none;
    const bool valid_incl_none = CheckBlock(block, validation_state_none, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ false);
    if (valid_incl_pow_and_merkle) {
        assert(valid_incl_pow && valid_incl_merkle && valid_incl_none);
    } else if (valid_incl_merkle || valid_incl_pow) {
        assert(valid_incl_none);
    }
    (void)block.GetHash();
    (void)block.ToString();
    (void)BlockMerkleRoot(block);
    if (!block.vtx.empty()) {
        // TODO: Avoid array index out of bounds error in BlockWitnessMerkleRoot
        //       when block.vtx.empty().
        (void)BlockWitnessMerkleRoot(block);
    }
    (void)GetBlockWeight(block);
    (void)GetWitnessCommitmentIndex(block);
    const size_t raw_memory_size = RecursiveDynamicUsage(block);
    const size_t raw_memory_size_as_shared_ptr = RecursiveDynamicUsage(std::make_shared<CBlock>(block));
    assert(raw_memory_size_as_shared_ptr > raw_memory_size);
}
<|endoftext|>


<commit_before>#include "parser.hpp"
#include <string>

std::string pre_rules(std::string def_out,std::string def_in)
{
	std::string pre;
	pre+="ufw --force disable\n";
	pre+="ufw --force reset\n";
	pre+="ufw logging on\n";
	pre+="ufw default "+def_out+" outgoing\n";
	pre+="ufw default "+def_in+" incoming\n";
	return pre;
}

std::string post_rules(std::string def_out,std::string def_in)
{
	return "ufw --force enable\n";
}

std::string gen_rule(wof_t wof)
{
	std::string rule;
	rule+="ufw ";
	if(wof.action=="deny")
		rule+="block";
	else
		rule+="allow";
	std::string dir_str=" out";
	if(wof.dir=="<")
	{
		dir_str=" in ";
		std::swap(wof.l_ip,wof.f_ip);
		std::swap(wof.l_mask,wof.f_mask);
		std::swap(wof.l_port,wof.f_port);
	}
	rule+=dir_str;
	rule+=" proto "+wof.proto;
	rule+=" from "+wof.l_ip+"/"+wof.l_mask;
	if(wof.l_port!="0")
		rule+=" port "+wof.l_port;
	rule+=" to "+wof.f_ip+"/"+wof.f_mask;
	if(wof.f_port!="0")
		rule+=" port "+wof.f_port;

	return rule;
}<commit_msg>Deny/block error ufw.<commit_after>#include "parser.hpp"
#include <string>

std::string pre_rules(std::string def_out,std::string def_in)
{
	if(def_out=="pass")
		def_out="allow";
	if(def_in=="pass")
		def_in="allow";
	std::string pre;
	pre+="ufw --force disable\n";
	pre+="ufw --force reset\n";
	pre+="ufw logging on\n";
	pre+="ufw default "+def_out+" outgoing\n";
	pre+="ufw default "+def_in+" incoming\n";
	return pre;
}

std::string post_rules(std::string def_out,std::string def_in)
{
	return "ufw --force enable\n";
}

std::string gen_rule(wof_t wof)
{
	std::string rule;
	rule+="ufw ";
	if(wof.action=="deny")
		rule+="deny";
	else
		rule+="allow";
	std::string dir_str=" out";
	if(wof.dir=="<")
	{
		dir_str=" in ";
		std::swap(wof.l_ip,wof.f_ip);
		std::swap(wof.l_mask,wof.f_mask);
		std::swap(wof.l_port,wof.f_port);
	}
	rule+=dir_str;
	rule+=" proto "+wof.proto;
	rule+=" from "+wof.l_ip+"/"+wof.l_mask;
	if(wof.l_port!="0")
		rule+=" port "+wof.l_port;
	rule+=" to "+wof.f_ip+"/"+wof.f_mask;
	if(wof.f_port!="0")
		rule+=" port "+wof.f_port;

	return rule;
}<|endoftext|>


<commit_before>/*  This file is part of the Tufão project
    Copyright (C) 2011 Vinícius dos Santos Oliveira <vini.ipsmaker@gmail.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 3 of the License, or (at your option) any
    later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "url.h"
#include "priv/url.h"

#include "httpserverrequest.h"

#include <QtNetwork/QSslSocket>
#include <QtNetwork/QHostAddress>

// Groups:
// 1  = scheme
// 2  = authority
// 3  = userinfo
// 4  = username
// 5  = userpass
// 6  = hostname
// 7  = port
// 8  = path
// 9  = query
// 10 = fragment
static QRegExp regex("^(?:([^:/?#]+):)?"
                     "(?://((?:(([^/?#@:]*)(?::([^/?#@]*))?)@)?"
                     "([^/?#:]*)(?::([^/?#]*))?))?"
                     "([^?#]*)"
                     "(?:\\?([^#]*))?"
                     "(?:#(.*))?");

namespace Tufao {

Url::Url(const QString &url) :
    priv(new Priv::Url(regex))
{
    priv->regex.indexIn(url);
}

Url::Url(const Url &url) :
    priv(new Priv::Url(url.priv->regex))
{
}

Url::~Url()
{
    delete priv;
}

Url &Url::operator =(const Url &url)
{
    if (this == &url)
        return *this;

    delete priv;
    priv = new Priv::Url(url.priv->regex);
    return *this;
}

QString Url::scheme() const
{
    return priv->regex.cap(1);
}

QString Url::authority() const
{
    return priv->regex.cap(2);
}

QString Url::path() const
{
    return priv->regex.cap(8);
}

QString Url::query() const
{
    return priv->regex.cap(9);
}

QString Url::fragment() const
{
    return priv->regex.cap(10);
}

QString Url::userinfo() const
{
    return priv->regex.cap(3);
}

QString Url::hostname() const
{
    return priv->regex.cap(6);
}

QString Url::port() const
{
    return priv->regex.cap(7);
}

QString Url::username() const
{
    return priv->regex.cap(4);
}

QString Url::password() const
{
    return priv->regex.cap(5);
}

QByteArray Url::url(HttpServerRequest *request)
{
    QByteArray host(request->headers().value("Host"));
    if (host.isEmpty())
        host = request->socket()->localAddress().toString();

    if (qobject_cast<QSslSocket*>(request->socket()))
        return "https://" + host + request->url();
    else
        return "http://" + host + request->url();
}

} // namespace Tufao
<commit_msg>fix: build issue in Url<commit_after>/*  This file is part of the Tufão project
    Copyright (C) 2011 Vinícius dos Santos Oliveira <vini.ipsmaker@gmail.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 3 of the License, or (at your option) any
    later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "url.h"
#include "priv/url.h"

#include "httpserverrequest.h"
#include "headers.h"

#include <QtNetwork/QSslSocket>
#include <QtNetwork/QHostAddress>

// Groups:
// 1  = scheme
// 2  = authority
// 3  = userinfo
// 4  = username
// 5  = userpass
// 6  = hostname
// 7  = port
// 8  = path
// 9  = query
// 10 = fragment
static QRegExp regex("^(?:([^:/?#]+):)?"
                     "(?://((?:(([^/?#@:]*)(?::([^/?#@]*))?)@)?"
                     "([^/?#:]*)(?::([^/?#]*))?))?"
                     "([^?#]*)"
                     "(?:\\?([^#]*))?"
                     "(?:#(.*))?");

namespace Tufao {

Url::Url(const QString &url) :
    priv(new Priv::Url(regex))
{
    priv->regex.indexIn(url);
}

Url::Url(const Url &url) :
    priv(new Priv::Url(url.priv->regex))
{
}

Url::~Url()
{
    delete priv;
}

Url &Url::operator =(const Url &url)
{
    if (this == &url)
        return *this;

    delete priv;
    priv = new Priv::Url(url.priv->regex);
    return *this;
}

QString Url::scheme() const
{
    return priv->regex.cap(1);
}

QString Url::authority() const
{
    return priv->regex.cap(2);
}

QString Url::path() const
{
    return priv->regex.cap(8);
}

QString Url::query() const
{
    return priv->regex.cap(9);
}

QString Url::fragment() const
{
    return priv->regex.cap(10);
}

QString Url::userinfo() const
{
    return priv->regex.cap(3);
}

QString Url::hostname() const
{
    return priv->regex.cap(6);
}

QString Url::port() const
{
    return priv->regex.cap(7);
}

QString Url::username() const
{
    return priv->regex.cap(4);
}

QString Url::password() const
{
    return priv->regex.cap(5);
}

QByteArray Url::url(HttpServerRequest *request)
{
    QByteArray host(request->headers().value("Host"));
    if (host.isEmpty())
        host = request->socket()->localAddress().toString().toUtf8();

    if (qobject_cast<QSslSocket*>(request->socket()))
        return "https://" + host + request->url();
    else
        return "http://" + host + request->url();
}

} // namespace Tufao
<|endoftext|>


<commit_before>#include <taichi/visual/gui.h>
#include "../tlang.h"

TLANG_NAMESPACE_BEGIN

Vector complex_mul(const Vector &a, const Vector &b) {
  Vector ret(2);
  ret(0) = a(0) * b(0) - a(1) * b(1);
  ret(1) = a(0) * b(1) + a(1) * b(0);
  return ret;
}

auto mset = [] {
  CoreState::set_trigger_gdb_when_crash(true);
  int n = 1024;
  Program prog(Arch::x86_64);

  Global(a, i32);

  layout([&]() { root.fixed(0, n * n).place(a); });

  auto func = kernel([&]() {
    Declare(i);

    Vectorize(8);
    For(i, 0, n * n, [&] {
      Local(j) = 0;
      int limit = 20;
      if (false) {
        Local(c_re) = cast<float>(i / n) / float(n / 2) - 1.5f;
        Local(c_im) = cast<float>(i % n) / float(n / 2) - 1.0f;
        Local(z_re) = c_re;
        Local(z_im) = c_im;

        While(j < limit && (z_re * z_re + z_im * z_im) < 4.0f, [&] {
          Local(new_re) = z_re * z_re - z_im * z_im;
          Local(new_im) = 2.0f * z_re * z_im;
          z_re = c_re + new_re;
          z_im = c_im + new_im;
          j += 1;
        });
      } else {
        Vector c(2);

        c(0) = cast<float>(i / n) / float(n / 2) - 1.5f;
        c(1) = cast<float>(i % n) / float(n / 2) - 1.0f;

        Vector z = c;

        While(j < limit && z.norm2() < 4.0f, [&] {
          z = complex_mul(z, z) + c;
          j += 1;
        });
      }
      a[i] = j;
    });
  });

  TC_P(measure_cpe(func, 1));

  GUI gui("Mandelbrot Set", Vector2i(n));
  for (int i = 0; i < n * n; i++) {
    gui.buffer[i / n][i % n] = Vector4(a.val<int>(i) % 11 * 0.1f);
  }
  while (1)
    gui.update();
};
TC_REGISTER_TASK(mset);

auto ray_march = [] {
  CoreState::set_trigger_gdb_when_crash(true);
  int n = 512;
  Program prog(Arch::x86_64);
  prog.config.print_ir = true;

  Global(color_r, f32);
  Global(color_g, f32);
  Global(color_b, f32);

  layout([&]() { root.fixed(0, n * n * 2).place(color_r, color_g, color_b); });

  auto sdf = [&](Vector p_) {
    float alpha = -0.7f;
    Vector p(3);
    p(0) = (cos(alpha) * p_(0) + sin(alpha) * p_(2) + 1.0_f) % 2.0_f - 1.0_f;
    p(1) = p_(1);
    p(2) = -sin(alpha) * p_(0) + cos(alpha) * p_(2);

    auto dist_sphere = p.norm() - 0.5_f;
    auto dist_walls = min(p(2) + 6.0f, p(1) + 1.0f);
    Vector d(3);
    d(0) = abs(p(0) - 1.0_f) - 0.3_f;
    d(1) = abs(p(1) + 0.5_f) - 1.2_f;
    d(2) = abs(p(2) - 1.0_f) - 0.2_f;
    auto dist_cube = norm(d.map([](const Expr &v) { return max(v, 0.0f); })) +
                     min(max(max(d(0), d(1)), d(2)), 0.0_f);
    return min(dist_sphere, min(dist_walls, dist_cube));
  };

  float32 eps = 1e-5f;
  float32 dist_limit = 1e2;
  int limit = 200;

  auto ray_march = [&](Vector p, Vector dir) {
    Local(j) = 0;
    Local(dist) = 0.0f;

    While(j < limit && sdf(p + dist * dir) > eps && dist < dist_limit, [&] {
      dist += sdf(p + dist * dir);
      j += 1;
    });
    return dist;
  };

  auto normal = [&](Vector p) {
    float d = 1e-3f;
    Vector n(3);
    for (int i = 0; i < 3; i++) {
      Vector inc = p, dec = p;
      inc(i) += d;
      dec(i) -= d;
      n(i) = (0.5f / d) * (sdf(inc) - sdf(dec));
    }
    return normalized(n);
  };

  auto out_dir = [&](Vector n) {
    Vector u({1.0f, 0.0f, 0.0f}), v(3);
    Mutable(u, DataType::f32);
    If(abs(n(1)) < 1 - 1e-3f, [&] {
      u = normalized(cross(n, Vector({0.0f, 1.0f, 0.0f})));
    });
    v = cross(n, u);
    Local(phi) = 2 * pi * Rand<float>();
    Local(r) = Rand<float>();
    Local(alpha) = 0.5_f * pi * (r * r);
    return sin(alpha) * (cos(phi) * u + sin(phi) * v) + cos(alpha) * n;
  };

  auto background = [](Vector dir) {
    return 1.0f * max(dir(1) + dir(0), 0.0f);
  };

  float fov = 0.3;

  auto main = kernel([&]() {
    Declare(i);
    Parallelize(8);
    // Vectorize(8);
    For(i, 0, n * n * 2, [&] {
      Vector orig({0.0f, 0.0f, 12.0f}), c(3);
      Mutable(orig, DataType::f32);

      c(0) = fov * (cast<float>(i / n) / float(n / 2) - 2.0f);
      c(1) = fov * (cast<float>(i % n) / float(n / 2) - 1.0f);
      c(2) = -1.0f;
      c = normalized(c);

      Mutable(c, DataType::f32);

      Vector color(3);
      color = Vector({1.0f, 1.0f, 1.0f});
      Mutable(color, DataType::f32);
      int depth_limit = 4;
      Local(depth) = 0;

      While(depth < depth_limit, [&] {
        depth += 1;
        Local(_dist) = ray_march(orig, c);
        If(_dist < dist_limit,
           [&] {
             orig += _dist * c;
             Vector nor;
             nor = normal(orig);
             c = normalized(out_dir(nor));
             orig += 0.01f * c;
             color *= 0.7_f;
           })
            .Else([&] {
              color = color * background(c);
              depth = depth_limit;
            });
      });

      color_r[i] += color(0);
      color_g[i] += color(1);
      color_b[i] += color(2);
    });
  });

  /// TC_P(measure_cpe(func, 1));

  GUI gui("ray march", Vector2i(n * 2, n));

  auto tone_map = [](real x) { return x; };
  constexpr int N = 1;
  for (int frame = 0;; frame++) {
    for (int i = 0; i < N; i++)
      main();
    real scale = 1.0_f / ((frame + 1) * N);
    for (int i = 0; i < n * n * 2; i++) {
      gui.buffer[i / n][i % n] =
          Vector4(tone_map(scale * color_r.val<float>(i)),
                  tone_map(scale * color_g.val<float>(i)),
                  tone_map(scale * color_b.val<float>(i)), 1);
    }
    gui.update();
  }
};
TC_REGISTER_TASK(ray_march);

TLANG_NAMESPACE_END
<commit_msg>Vectorized ray_march on CPU<commit_after>#include <taichi/visual/gui.h>
#include "../tlang.h"

TLANG_NAMESPACE_BEGIN

Vector complex_mul(const Vector &a, const Vector &b) {
  Vector ret(2);
  ret(0) = a(0) * b(0) - a(1) * b(1);
  ret(1) = a(0) * b(1) + a(1) * b(0);
  return ret;
}

auto mset = [] {
  CoreState::set_trigger_gdb_when_crash(true);
  int n = 1024;
  Program prog(Arch::x86_64);

  Global(a, i32);

  layout([&]() { root.fixed(0, n * n).place(a); });

  auto func = kernel([&]() {
    Declare(i);

    Vectorize(8);
    For(i, 0, n * n, [&] {
      Local(j) = 0;
      int limit = 20;
      if (false) {
        Local(c_re) = cast<float>(i / n) / float(n / 2) - 1.5f;
        Local(c_im) = cast<float>(i % n) / float(n / 2) - 1.0f;
        Local(z_re) = c_re;
        Local(z_im) = c_im;

        While(j < limit && (z_re * z_re + z_im * z_im) < 4.0f, [&] {
          Local(new_re) = z_re * z_re - z_im * z_im;
          Local(new_im) = 2.0f * z_re * z_im;
          z_re = c_re + new_re;
          z_im = c_im + new_im;
          j += 1;
        });
      } else {
        Vector c(2);

        c(0) = cast<float>(i / n) / float(n / 2) - 1.5f;
        c(1) = cast<float>(i % n) / float(n / 2) - 1.0f;

        Vector z = c;

        While(j < limit && z.norm2() < 4.0f, [&] {
          z = complex_mul(z, z) + c;
          j += 1;
        });
      }
      a[i] = j;
    });
  });

  TC_P(measure_cpe(func, 1));

  GUI gui("Mandelbrot Set", Vector2i(n));
  for (int i = 0; i < n * n; i++) {
    gui.buffer[i / n][i % n] = Vector4(a.val<int>(i) % 11 * 0.1f);
  }
  while (1)
    gui.update();
};
TC_REGISTER_TASK(mset);

auto ray_march = [] {
  CoreState::set_trigger_gdb_when_crash(true);
  int n = 512;
  Program prog(Arch::x86_64);
  prog.config.print_ir = true;

  Global(color_r, f32);
  Global(color_g, f32);
  Global(color_b, f32);

  layout([&]() { root.fixed(0, n * n * 2).place(color_r, color_g, color_b); });

  auto sdf = [&](Vector p_) {
    float alpha = -0.7f;
    Vector p(3);
    p(0) = (cos(alpha) * p_(0) + sin(alpha) * p_(2) + 1.0_f) % 2.0_f - 1.0_f;
    p(1) = p_(1);
    p(2) = -sin(alpha) * p_(0) + cos(alpha) * p_(2);

    auto dist_sphere = p.norm() - 0.5_f;
    auto dist_walls = min(p(2) + 6.0f, p(1) + 1.0f);
    Vector d(3);
    d(0) = abs(p(0) - 1.0_f) - 0.3_f;
    d(1) = abs(p(1) + 0.5_f) - 1.2_f;
    d(2) = abs(p(2) - 1.0_f) - 0.2_f;
    auto dist_cube = norm(d.map([](const Expr &v) { return max(v, 0.0f); })) +
                     min(max(max(d(0), d(1)), d(2)), 0.0_f);
    return min(dist_sphere, min(dist_walls, dist_cube));
  };

  float32 eps = 1e-5f;
  float32 dist_limit = 1e2;
  int limit = 200;

  auto ray_march = [&](Vector p, Vector dir) {
    Local(j) = 0;
    Local(dist) = 0.0f;

    While(j < limit && sdf(p + dist * dir) > eps && dist < dist_limit, [&] {
      dist += sdf(p + dist * dir);
      j += 1;
    });
    return dist;
  };

  auto normal = [&](Vector p) {
    float d = 1e-3f;
    Vector n(3);
    for (int i = 0; i < 3; i++) {
      Vector inc = p, dec = p;
      inc(i) += d;
      dec(i) -= d;
      n(i) = (0.5f / d) * (sdf(inc) - sdf(dec));
    }
    return normalized(n);
  };

  auto out_dir = [&](Vector n) {
    Vector u({1.0f, 0.0f, 0.0f}), v(3);
    Mutable(u, DataType::f32);
    If(abs(n(1)) < 1 - 1e-3f, [&] {
      u = normalized(cross(n, Vector({0.0f, 1.0f, 0.0f})));
    });
    v = cross(n, u);
    Local(phi) = 2 * pi * Rand<float>();
    Local(r) = Rand<float>();
    Local(alpha) = 0.5_f * pi * (r * r);
    return sin(alpha) * (cos(phi) * u + sin(phi) * v) + cos(alpha) * n;
  };

  auto background = [](Vector dir) {
    return 1.0f * max(dir(1) + dir(0), 0.0f);
  };

  float fov = 0.3;

  auto main = kernel([&]() {
    Declare(i);
    Parallelize(8);
    Vectorize(8);
    For(i, 0, n * n * 2, [&] {
      Vector orig({0.0f, 0.0f, 12.0f}), c(3);
      Mutable(orig, DataType::f32);

      c(0) = fov * (cast<float>(i / n) / float(n / 2) - 2.0f);
      c(1) = fov * (cast<float>(i % n) / float(n / 2) - 1.0f);
      c(2) = -1.0f;
      c = normalized(c);

      Mutable(c, DataType::f32);

      Vector color(3);
      color = Vector({1.0f, 1.0f, 1.0f});
      Mutable(color, DataType::f32);
      int depth_limit = 4;
      Local(depth) = 0;

      While(depth < depth_limit, [&] {
        depth += 1;
        Local(_dist) = ray_march(orig, c);
        If(_dist < dist_limit,
           [&] {
             orig += _dist * c;
             Vector nor;
             nor = normal(orig);
             c = normalized(out_dir(nor));
             orig += 0.01f * c;
             color *= 0.7_f;
           })
            .Else([&] {
              color = color * background(c);
              depth = depth_limit;
            });
      });

      color_r[i] += color(0);
      color_g[i] += color(1);
      color_b[i] += color(2);
    });
  });

  /// TC_P(measure_cpe(func, 1));

  GUI gui("ray march", Vector2i(n * 2, n));

  auto tone_map = [](real x) { return x; };
  constexpr int N = 1;
  for (int frame = 0;; frame++) {
    for (int i = 0; i < N; i++)
      main();
    real scale = 1.0_f / ((frame + 1) * N);
    for (int i = 0; i < n * n * 2; i++) {
      gui.buffer[i / n][i % n] =
          Vector4(tone_map(scale * color_r.val<float>(i)),
                  tone_map(scale * color_g.val<float>(i)),
                  tone_map(scale * color_b.val<float>(i)), 1);
    }
    gui.update();
  }
};
TC_REGISTER_TASK(ray_march);

TLANG_NAMESPACE_END
<|endoftext|>


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

#include "pow.h"

#include "arith_uint256.h"
#include "chain.h"
#include "chainparams.h"
#include "primitives/block.h"
#include "uint256.h"

#include <math.h>

unsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const Consensus::Params& params) {
    const CBlockIndex *BlockLastSolved = pindexLast;
    const CBlockIndex *BlockReading = pindexLast;
    uint64_t PastBlocksMass = 0;
    int64_t PastRateActualSeconds = 0;
    int64_t PastRateTargetSeconds = 0;
    double PastRateAdjustmentRatio = double(1);
    arith_uint256 PastDifficultyAverage;
    arith_uint256 PastDifficultyAveragePrev;
    double EventHorizonDeviation;
    double EventHorizonDeviationFast;
    double EventHorizonDeviationSlow;

    uint64_t pastSecondsMin = params.nPowTargetTimespan * 0.025;
    uint64_t pastSecondsMax = params.nPowTargetTimespan * 7;
    uint64_t PastBlocksMin = pastSecondsMin / params.nPowTargetSpacing;
    uint64_t PastBlocksMax = pastSecondsMax / params.nPowTargetSpacing;

    if (BlockLastSolved == nullptr || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return UintToArith256(params.powLimit).GetCompact(); }

    for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
        if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
        PastBlocksMass++;

        PastDifficultyAverage.SetCompact(BlockReading->nBits);
        if (i > 1) {
            // handle negative arith_uint256
            if(PastDifficultyAverage >= PastDifficultyAveragePrev)
                PastDifficultyAverage = ((PastDifficultyAverage - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev;
            else
                PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - PastDifficultyAverage) / i);
        }
        PastDifficultyAveragePrev = PastDifficultyAverage;

        PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime();
        PastRateTargetSeconds = params.nPowTargetSpacing * PastBlocksMass;
        PastRateAdjustmentRatio = double(1);
        if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; }
        if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
            PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds);
        }
        EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(28.2)), -1.228));
        EventHorizonDeviationFast = EventHorizonDeviation;
        EventHorizonDeviationSlow = 1 / EventHorizonDeviation;

        if (PastBlocksMass >= PastBlocksMin) {
                if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast))
                { assert(BlockReading); break; }
        }
        if (BlockReading->pprev == nullptr) { assert(BlockReading); break; }
        BlockReading = BlockReading->pprev;
    }

    arith_uint256 bnNew(PastDifficultyAverage);
    if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
        bnNew *= PastRateActualSeconds;
        bnNew /= PastRateTargetSeconds;
    }

    if (bnNew > UintToArith256(params.powLimit)) {
        bnNew = UintToArith256(params.powLimit);
    }

    return bnNew.GetCompact();
}

unsigned int static DarkGravityWave(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) {
    /* current difficulty formula, dash - DarkGravity v3, written by Evan Duffield - evan@dash.org */
    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
    int64_t nPastBlocks = 24;

    // make sure we have at least (nPastBlocks + 1) blocks, otherwise just return powLimit
    if (!pindexLast || pindexLast->nHeight < nPastBlocks) {
        return bnPowLimit.GetCompact();
    }

    if (params.fPowAllowMinDifficultyBlocks) {
        // recent block is more than 2 hours old
        if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + 2 * 60 * 60) {
            return bnPowLimit.GetCompact();
        }
        // recent block is more than 10 minutes old
        if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing * 4) {
            arith_uint256 bnNew = arith_uint256().SetCompact(pindexLast->nBits) * 10;
            if (bnNew > bnPowLimit) {
                bnNew = bnPowLimit;
            }
            return bnNew.GetCompact();
        }
    }

    const CBlockIndex *pindex = pindexLast;
    arith_uint256 bnPastTargetAvg;

    for (unsigned int nCountBlocks = 1; nCountBlocks <= nPastBlocks; nCountBlocks++) {
        arith_uint256 bnTarget = arith_uint256().SetCompact(pindex->nBits);
        if (nCountBlocks == 1) {
            bnPastTargetAvg = bnTarget;
        } else {
            // NOTE: that's not an average really...
            bnPastTargetAvg = (bnPastTargetAvg * nCountBlocks + bnTarget) / (nCountBlocks + 1);
        }

        if(nCountBlocks != nPastBlocks) {
            assert(pindex->pprev); // should never fail
            pindex = pindex->pprev;
        }
    }

    arith_uint256 bnNew(bnPastTargetAvg);

    int64_t nActualTimespan = pindexLast->GetBlockTime() - pindex->GetBlockTime();
    // NOTE: is this accurate? nActualTimespan counts it for (nPastBlocks - 1) blocks only...
    int64_t nTargetTimespan = nPastBlocks * params.nPowTargetSpacing;

    if (nActualTimespan < nTargetTimespan/3)
        nActualTimespan = nTargetTimespan/3;
    if (nActualTimespan > nTargetTimespan*3)
        nActualTimespan = nTargetTimespan*3;

    // Retarget
    bnNew *= nActualTimespan;
    bnNew /= nTargetTimespan;

    if (bnNew > bnPowLimit) {
        bnNew = bnPowLimit;
    }

    return bnNew.GetCompact();
}

unsigned int GetNextWorkRequiredBTC(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
    assert(pindexLast != nullptr);
    unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();

    // Only change once per interval
    if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)
    {
        if (params.fPowAllowMinDifficultyBlocks)
        {
            // Special difficulty rule for testnet:
            // If the new block's timestamp is more than 2* 2.5 minutes
            // then allow mining of a min-difficulty block.
            if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
                return nProofOfWorkLimit;
            else
            {
                // Return the last non-special-min-difficulty-rules-block
                const CBlockIndex* pindex = pindexLast;
                while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
                    pindex = pindex->pprev;
                return pindex->nBits;
            }
        }
        return pindexLast->nBits;
    }

    // Go back by what we want to be 1 day worth of blocks
    int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval()-1);
    assert(nHeightFirst >= 0);
    const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst);
    assert(pindexFirst);

   return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);
}

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
    // this is only active on devnets
    if (pindexLast->nHeight < params.nMinimumDifficultyBlocks) {
        unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();
        return nProofOfWorkLimit;
    }

    // Most recent algo first
    if (pindexLast->nHeight + 1 >= params.nPowDGWHeight) {
        return DarkGravityWave(pindexLast, pblock, params);
    }
    else if (pindexLast->nHeight + 1 >= params.nPowKGWHeight) {
        return KimotoGravityWell(pindexLast, params);
    }
    else {
        return GetNextWorkRequiredBTC(pindexLast, pblock, params);
    }
}

// for DIFF_BTC only!
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
    if (params.fPowNoRetargeting)
        return pindexLast->nBits;

    // Limit adjustment step
    int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
    if (nActualTimespan < params.nPowTargetTimespan/4)
        nActualTimespan = params.nPowTargetTimespan/4;
    if (nActualTimespan > params.nPowTargetTimespan*4)
        nActualTimespan = params.nPowTargetTimespan*4;

    // Retarget
    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
    arith_uint256 bnNew;
    bnNew.SetCompact(pindexLast->nBits);
    bnNew *= nActualTimespan;
    bnNew /= params.nPowTargetTimespan;

    if (bnNew > bnPowLimit)
        bnNew = bnPowLimit;

    return bnNew.GetCompact();
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;

    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

    // Check range
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
        return false;

    // Check proof of work matches claimed amount
    if (UintToArith256(hash) > bnTarget)
        return false;

    return true;
}
<commit_msg>Refactor some pow functions (#3198)<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "pow.h"

#include "arith_uint256.h"
#include "chain.h"
#include "chainparams.h"
#include "primitives/block.h"
#include "uint256.h"

#include <math.h>

unsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const Consensus::Params& params) {
    const CBlockIndex *BlockLastSolved = pindexLast;
    const CBlockIndex *BlockReading = pindexLast;
    uint64_t PastBlocksMass = 0;
    int64_t PastRateActualSeconds = 0;
    int64_t PastRateTargetSeconds = 0;
    double PastRateAdjustmentRatio = double(1);
    arith_uint256 PastDifficultyAverage;
    arith_uint256 PastDifficultyAveragePrev;
    double EventHorizonDeviation;
    double EventHorizonDeviationFast;
    double EventHorizonDeviationSlow;

    uint64_t pastSecondsMin = params.nPowTargetTimespan * 0.025;
    uint64_t pastSecondsMax = params.nPowTargetTimespan * 7;
    uint64_t PastBlocksMin = pastSecondsMin / params.nPowTargetSpacing;
    uint64_t PastBlocksMax = pastSecondsMax / params.nPowTargetSpacing;

    if (BlockLastSolved == nullptr || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return UintToArith256(params.powLimit).GetCompact(); }

    for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
        if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
        PastBlocksMass++;

        PastDifficultyAverage.SetCompact(BlockReading->nBits);
        if (i > 1) {
            // handle negative arith_uint256
            if(PastDifficultyAverage >= PastDifficultyAveragePrev)
                PastDifficultyAverage = ((PastDifficultyAverage - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev;
            else
                PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - PastDifficultyAverage) / i);
        }
        PastDifficultyAveragePrev = PastDifficultyAverage;

        PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime();
        PastRateTargetSeconds = params.nPowTargetSpacing * PastBlocksMass;
        PastRateAdjustmentRatio = double(1);
        if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; }
        if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
            PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds);
        }
        EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(28.2)), -1.228));
        EventHorizonDeviationFast = EventHorizonDeviation;
        EventHorizonDeviationSlow = 1 / EventHorizonDeviation;

        if (PastBlocksMass >= PastBlocksMin) {
                if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast))
                { assert(BlockReading); break; }
        }
        if (BlockReading->pprev == nullptr) { assert(BlockReading); break; }
        BlockReading = BlockReading->pprev;
    }

    arith_uint256 bnNew(PastDifficultyAverage);
    if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
        bnNew *= PastRateActualSeconds;
        bnNew /= PastRateTargetSeconds;
    }

    if (bnNew > UintToArith256(params.powLimit)) {
        bnNew = UintToArith256(params.powLimit);
    }

    return bnNew.GetCompact();
}

unsigned int static DarkGravityWave(const CBlockIndex* pindexLast, const Consensus::Params& params) {
    /* current difficulty formula, dash - DarkGravity v3, written by Evan Duffield - evan@dash.org */
    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
    int64_t nPastBlocks = 24;

    // make sure we have at least (nPastBlocks + 1) blocks, otherwise just return powLimit
    if (!pindexLast || pindexLast->nHeight < nPastBlocks) {
        return bnPowLimit.GetCompact();
    }

    const CBlockIndex *pindex = pindexLast;
    arith_uint256 bnPastTargetAvg;

    for (unsigned int nCountBlocks = 1; nCountBlocks <= nPastBlocks; nCountBlocks++) {
        arith_uint256 bnTarget = arith_uint256().SetCompact(pindex->nBits);
        if (nCountBlocks == 1) {
            bnPastTargetAvg = bnTarget;
        } else {
            // NOTE: that's not an average really...
            bnPastTargetAvg = (bnPastTargetAvg * nCountBlocks + bnTarget) / (nCountBlocks + 1);
        }

        if(nCountBlocks != nPastBlocks) {
            assert(pindex->pprev); // should never fail
            pindex = pindex->pprev;
        }
    }

    arith_uint256 bnNew(bnPastTargetAvg);

    int64_t nActualTimespan = pindexLast->GetBlockTime() - pindex->GetBlockTime();
    // NOTE: is this accurate? nActualTimespan counts it for (nPastBlocks - 1) blocks only...
    int64_t nTargetTimespan = nPastBlocks * params.nPowTargetSpacing;

    if (nActualTimespan < nTargetTimespan/3)
        nActualTimespan = nTargetTimespan/3;
    if (nActualTimespan > nTargetTimespan*3)
        nActualTimespan = nTargetTimespan*3;

    // Retarget
    bnNew *= nActualTimespan;
    bnNew /= nTargetTimespan;

    if (bnNew > bnPowLimit) {
        bnNew = bnPowLimit;
    }

    return bnNew.GetCompact();
}

unsigned int GetNextWorkRequiredBTC(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
    assert(pindexLast != nullptr);
    unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();

    // Only change once per interval
    if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)
    {
        if (params.fPowAllowMinDifficultyBlocks)
        {
            // Special difficulty rule for testnet:
            // If the new block's timestamp is more than 2* 2.5 minutes
            // then allow mining of a min-difficulty block.
            if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
                return nProofOfWorkLimit;
            else
            {
                // Return the last non-special-min-difficulty-rules-block
                const CBlockIndex* pindex = pindexLast;
                while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
                    pindex = pindex->pprev;
                return pindex->nBits;
            }
        }
        return pindexLast->nBits;
    }

    // Go back by what we want to be 1 day worth of blocks
    int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval()-1);
    assert(nHeightFirst >= 0);
    const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst);
    assert(pindexFirst);

   return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);
}

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
    assert(pindexLast != nullptr);
    assert(pblock != nullptr);
    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);

    // this is only active on devnets
    if (pindexLast->nHeight < params.nMinimumDifficultyBlocks) {
        return bnPowLimit.GetCompact();
    }

    if (pindexLast->nHeight + 1 < params.nPowKGWHeight) {
        return GetNextWorkRequiredBTC(pindexLast, pblock, params);
    }

    // Note: GetNextWorkRequiredBTC has it's own special difficulty rule,
    // so we only apply this to post-BTC algos.
    if (params.fPowAllowMinDifficultyBlocks) {
        // recent block is more than 2 hours old
        if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + 2 * 60 * 60) {
            return bnPowLimit.GetCompact();
        }
        // recent block is more than 10 minutes old
        if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing * 4) {
            arith_uint256 bnNew = arith_uint256().SetCompact(pindexLast->nBits) * 10;
            if (bnNew > bnPowLimit) {
                return bnPowLimit.GetCompact();
            }
            return bnNew.GetCompact();
        }
    }

    if (pindexLast->nHeight + 1 < params.nPowDGWHeight) {
        return KimotoGravityWell(pindexLast, params);
    }

    return DarkGravityWave(pindexLast, params);
}

// for DIFF_BTC only!
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
    if (params.fPowNoRetargeting)
        return pindexLast->nBits;

    // Limit adjustment step
    int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
    if (nActualTimespan < params.nPowTargetTimespan/4)
        nActualTimespan = params.nPowTargetTimespan/4;
    if (nActualTimespan > params.nPowTargetTimespan*4)
        nActualTimespan = params.nPowTargetTimespan*4;

    // Retarget
    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
    arith_uint256 bnNew;
    bnNew.SetCompact(pindexLast->nBits);
    bnNew *= nActualTimespan;
    bnNew /= params.nPowTargetTimespan;

    if (bnNew > bnPowLimit)
        bnNew = bnPowLimit;

    return bnNew.GetCompact();
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;

    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

    // Check range
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
        return false;

    // Check proof of work matches claimed amount
    if (UintToArith256(hash) > bnTarget)
        return false;

    return true;
}
<|endoftext|>


<commit_before>#ifndef VARIANT_HPP
#define VARIANT_HPP

#include <type_traits>
#include <memory>
#include <cassert>
#include <stdexcept>

template<class ... T> class variant;

namespace impl {
  template<std::size_t start, class ... T>
  struct select;

  template<std::size_t start, class H, class ... T>
  struct select<start, H, T...> : select<start + 1, T...> {

    using select<start + 1, T...>::index;
    static inline constexpr std::size_t index(const H* ) { return start; }

    using select<start + 1, T...>::cast;
    static inline constexpr const H& cast(const H& value) { return value; }
    static inline constexpr H&& cast(H&& value) { return std::move(value); }

  };

  template<std::size_t start> struct select<start> {
    static inline constexpr void index();
    static inline constexpr void cast();
  };

  template<class Variant, class Self, class Signature>
  struct dispatch;

  template<class ... T, class Self, class Visitor, class Ret, class ... Args>
  struct dispatch<variant<T...>, Self, Ret (Visitor, Args...) > {

    template<class U>
    static Ret call_thunk(Self& self, Visitor&& visitor, Args&& ... args) {
      return std::forward<Visitor>(visitor)(self.template get<U>(), std::forward<Args>(args)...);
    }

    using thunk_type = Ret (*)(Self& self, Visitor&& visitor, Args&& ... args);
    static constexpr thunk_type table[] = { call_thunk<T>... };
  };

  template<class ... T, class Self, class Visitor,  class Ret, class ... Args>
  constexpr typename dispatch<variant<T...>, Self, Ret (Visitor, Args...) >::thunk_type
  dispatch<variant<T...>, Self, Ret (Visitor, Args...) >::table[];

}

template<class ... T>
class variant {

  using storage_type = typename std::aligned_union<0, T...>::type;
  storage_type storage;

protected:
  using index_type = std::size_t;
  index_type index;

private:

  using select_type = impl::select<0, T...>;

  template<class U>
  void construct(U&& value) {
    new (&storage) typename std::decay<U>::type(std::forward<U>(value));
  }

  struct copy_construct {
    template<class U>
    void operator()(U& self, const variant& other) const {
      new (&self) U(other.template get<U>());
    }
  };

  struct copy {
    template<class U>
    void operator()(U& self, const variant& other) const {
      self = other.template get<U>();
    }
  };

  struct move {
    template<class U>
    void operator()(U& self, variant&& other) const {
      self = std::move(other.template get<U>());
    }
  };

  struct move_construct {
    template<class U>
    void operator()(U& self, variant&& other) const {
      new (&self) U(std::move(other.template get<U>()));
    }
  };

  struct destruct {
    template<class U>
    void operator()(U& self) const {
      self.~U();
    }
  };

  struct compare {

    template<class U>
    bool operator()(const U& self, const variant& other) const {
      return self == other.get<U>();
    }

  };

  struct less {

    template<class U>
    bool operator()(const U& self, const variant& other) const {
      return self < other.get<U>();
    }

  };

public:
  std::size_t type() const { return index; }

  struct bad_cast : std::runtime_error {
    bad_cast() : std::runtime_error("bad_cast") { }
  };

  template<class U, index_type R = select_type::index( ((typename std::decay<U>::type*)0) ) >
  static constexpr index_type type_index() { return R; }

  template<class U, index_type R = type_index<U>() >
  U& cast() {
    U& res = reinterpret_cast<U&>(storage);
    if( R != index ) throw bad_cast();
    return res;
  }

  template<class U, index_type R = type_index<U>() >
  const U& cast() const {
    const U& res = reinterpret_cast<const U&>(storage);
    if( R != index ) {
      throw bad_cast();
    }
    return res;
  }

  template<class U, index_type R = type_index<U>()>
  U& get() {
    U& res = reinterpret_cast<U&>(storage);
    assert(R == index);
    return res;
  }

  template<class U, index_type R = type_index<U>() >
  const U& get() const {
    const U& res = reinterpret_cast<const U&>(storage);
    assert(R == index);
    return res;
  }

  template<class U, index_type R = type_index<U>()>
  U* get_if() {
    if(!is<U>()) return nullptr;
    return &get<U>();
  }

  template<class U, index_type R = type_index<U>()>
  const U* get_if() const {
    if(!is<U>()) return nullptr;
    return &get<U>();
  }

  template<class U, index_type R = type_index<U>() >
  bool is() const noexcept {
    return R == index;
  }

  variant(const variant& other) noexcept
    : index(other.index) {
    static constexpr bool skip[] = {std::is_trivially_copy_constructible<T>::value...};

    if(skip[index]) {
      storage = other.storage;
    } else {
      apply( copy_construct(), other );
    }
  }

  variant(variant&& other) noexcept
    : index(other.index) {
    static constexpr bool skip[] = {std::is_trivially_move_constructible<T>::value...};

    if(skip[index]) {
      storage = std::move(other.storage);
    } else {
      apply( move_construct(), std::move(other) );
    }
  }

  ~variant() noexcept {
    static constexpr bool dont_skip[] = {!std::is_trivially_destructible<T>::value...};

    if(dont_skip[index]) {
      apply( destruct() );
    }

  }

  variant& operator=(const variant& other) noexcept {
    if(index == other.index) {
      apply(copy(), other);
    } else {
      this->~variant();
      index = other.index;
      apply(copy_construct(), other);
    }

    return *this;
  }

  bool operator==(const variant& other) const {
    if(type() != other.type()) return false;
    return map<bool>(compare(), other);
  }

  bool operator!=(const variant& other) const {
    return !operator==(other);
  }

  bool operator<(const variant& other) const {
    return index < other.index || (index == other.index && map<bool>(less(), other));
  }

  variant& operator=(variant&& other)  noexcept{

    if(index == other.index) {
      apply( move(), std::move(other) );
    } else {
      this->~variant();
      index = other.index;
      apply( move_construct(), std::move(other) );
    }

    return *this;
  }

  template<class U, index_type R = type_index<U>() >
  variant(U&& value) noexcept
    : index( R ) {
    construct( select_type::cast( std::forward<U>(value)) );
  }

  template<class Visitor, class ... Args>
  void apply(Visitor&& visitor, Args&& ... args) {

    impl::dispatch<variant, variant, void (Visitor, Args...)>::table[index]
      (*this, std::forward<Visitor>(visitor), std::forward<Args>(args)...);

  }

  template<class Visitor, class ... Args>
  void apply(Visitor&& visitor, Args&& ... args) const {

    impl::dispatch<variant, const variant, void (Visitor, Args...)>::table[index]
      (*this, std::forward<Visitor>(visitor), std::forward<Args>(args)...);

  }

  template<class Return, class Visitor, class ... Args>
  Return map(Visitor&& visitor, Args&& ... args) const {

    return impl::dispatch<variant, const variant, Return (Visitor, Args...) >::table[index]
      (*this, std::forward<Visitor>(visitor), std::forward<Args>(args)...);

  }

};

#endif
<commit_msg>variant asserts yo<commit_after>#ifndef VARIANT_HPP
#define VARIANT_HPP

#include <type_traits>
#include <memory>
#include <cassert>
#include <stdexcept>

template<class ... T> class variant;

namespace impl {
  template<std::size_t start, class ... T>
  struct select;

  template<std::size_t start, class H, class ... T>
  struct select<start, H, T...> : select<start + 1, T...> {

    using select<start + 1, T...>::index;
    static inline constexpr std::size_t index(const H* ) { return start; }

    using select<start + 1, T...>::cast;
    static inline constexpr const H& cast(const H& value) { return value; }
    static inline constexpr H&& cast(H&& value) { return std::move(value); }

  };

  template<std::size_t start> struct select<start> {
    static inline constexpr void index();
    static inline constexpr void cast();
  };

  template<class Variant, class Self, class Signature>
  struct dispatch;

  template<class ... T, class Self, class Visitor, class Ret, class ... Args>
  struct dispatch<variant<T...>, Self, Ret (Visitor, Args...) > {

    template<class U>
    static Ret call_thunk(Self& self, Visitor&& visitor, Args&& ... args) {
      return std::forward<Visitor>(visitor)(self.template get<U>(), std::forward<Args>(args)...);
    }

    using thunk_type = Ret (*)(Self& self, Visitor&& visitor, Args&& ... args);
    static constexpr thunk_type table[] = { call_thunk<T>... };
  };

  template<class ... T, class Self, class Visitor,  class Ret, class ... Args>
  constexpr typename dispatch<variant<T...>, Self, Ret (Visitor, Args...) >::thunk_type
  dispatch<variant<T...>, Self, Ret (Visitor, Args...) >::table[];

  template<class Expected, class Actual>
  static bool check_type() {
    assert((std::is_same<Expected, Actual>::value) );
    return std::is_same<Expected, Actual>::value;
  }

  template<class U, class ... T>
  static bool check_type(std::size_t index) {
    using type = bool (*)();
    static const type expand[] = {
      &check_type<U, T>...
    };

    return expand[index]();
  }
}

template<class ... T>
class variant {

  using storage_type = typename std::aligned_union<0, T...>::type;
  storage_type storage;

protected:
  using index_type = std::size_t;
  index_type index;

private:

  using select_type = impl::select<0, T...>;

  template<class U>
  void construct(U&& value) {
    new (&storage) typename std::decay<U>::type(std::forward<U>(value));
  }

  struct copy_construct {
    template<class U>
    void operator()(U& self, const variant& other) const {
      new (&self) U(other.template get<U>());
    }
  };

  struct copy {
    template<class U>
    void operator()(U& self, const variant& other) const {
      self = other.template get<U>();
    }
  };

  struct move {
    template<class U>
    void operator()(U& self, variant&& other) const {
      self = std::move(other.template get<U>());
    }
  };

  struct move_construct {
    template<class U>
    void operator()(U& self, variant&& other) const {
      new (&self) U(std::move(other.template get<U>()));
    }
  };

  struct destruct {
    template<class U>
    void operator()(U& self) const {
      self.~U();
    }
  };

  struct compare {

    template<class U>
    bool operator()(const U& self, const variant& other) const {
      return self == other.get<U>();
    }

  };

  struct less {

    template<class U>
    bool operator()(const U& self, const variant& other) const {
      return self < other.get<U>();
    }

  };

public:
  std::size_t type() const { return index; }

  struct bad_cast : std::runtime_error {
    bad_cast() : std::runtime_error("bad_cast") { }
  };

  template<class U, index_type R = select_type::index( ((typename std::decay<U>::type*)0) ) >
  static constexpr index_type type_index() { return R; }

  template<class U, index_type R = type_index<U>() >
  U& cast() {
    U& res = reinterpret_cast<U&>(storage);
    if( R != index ) throw bad_cast();
    return res;
  }

  template<class U, index_type R = type_index<U>() >
  const U& cast() const {
    const U& res = reinterpret_cast<const U&>(storage);
    if( R != index ) {
      throw bad_cast();
    }
    return res;
  }

  template<class U, index_type R = type_index<U>()>
  U& get() {
    U& res = reinterpret_cast<U&>(storage);
    assert( (impl::check_type<U, T...>(index)) );
    return res;
  }

  template<class U, index_type R = type_index<U>() >
  const U& get() const {
    const U& res = reinterpret_cast<const U&>(storage);
    assert( (impl::check_type<U, T...>(index)) );
    return res;
  }

  template<class U, index_type R = type_index<U>()>
  U* get_if() {
    if(!is<U>()) return nullptr;
    return &get<U>();
  }

  template<class U, index_type R = type_index<U>()>
  const U* get_if() const {
    if(!is<U>()) return nullptr;
    return &get<U>();
  }

  template<class U, index_type R = type_index<U>() >
  bool is() const noexcept {
    return R == index;
  }

  variant(const variant& other) noexcept
    : index(other.index) {
    static constexpr bool skip[] = {std::is_trivially_copy_constructible<T>::value...};

    if(skip[index]) {
      storage = other.storage;
    } else {
      apply( copy_construct(), other );
    }
  }

  variant(variant&& other) noexcept
    : index(other.index) {
    static constexpr bool skip[] = {std::is_trivially_move_constructible<T>::value...};

    if(skip[index]) {
      storage = std::move(other.storage);
    } else {
      apply( move_construct(), std::move(other) );
    }
  }

  ~variant() noexcept {
    static constexpr bool dont_skip[] = {!std::is_trivially_destructible<T>::value...};

    if(dont_skip[index]) {
      apply( destruct() );
    }

  }

  variant& operator=(const variant& other) noexcept {
    if(index == other.index) {
      apply(copy(), other);
    } else {
      this->~variant();
      index = other.index;
      apply(copy_construct(), other);
    }

    return *this;
  }

  bool operator==(const variant& other) const {
    if(type() != other.type()) return false;
    return map<bool>(compare(), other);
  }

  bool operator!=(const variant& other) const {
    return !operator==(other);
  }

  bool operator<(const variant& other) const {
    return index < other.index || (index == other.index && map<bool>(less(), other));
  }

  variant& operator=(variant&& other)  noexcept{

    if(index == other.index) {
      apply( move(), std::move(other) );
    } else {
      this->~variant();
      index = other.index;
      apply( move_construct(), std::move(other) );
    }

    return *this;
  }

  template<class U, index_type R = type_index<U>() >
  variant(U&& value) noexcept
    : index( R ) {
    construct( select_type::cast( std::forward<U>(value)) );
  }

  template<class Visitor, class ... Args>
  void apply(Visitor&& visitor, Args&& ... args) {

    impl::dispatch<variant, variant, void (Visitor, Args...)>::table[index]
      (*this, std::forward<Visitor>(visitor), std::forward<Args>(args)...);

  }

  template<class Visitor, class ... Args>
  void apply(Visitor&& visitor, Args&& ... args) const {

    impl::dispatch<variant, const variant, void (Visitor, Args...)>::table[index]
      (*this, std::forward<Visitor>(visitor), std::forward<Args>(args)...);

  }

  template<class Return, class Visitor, class ... Args>
  Return map(Visitor&& visitor, Args&& ... args) const {

    return impl::dispatch<variant, const variant, Return (Visitor, Args...) >::table[index]
      (*this, std::forward<Visitor>(visitor), std::forward<Args>(args)...);

  }

};

#endif
<|endoftext|>


<commit_before>#include <SDL.h>
#include <stdio.h>
#include <cstdlib>
#include <cmath>
#include "map.h"
#include "image.h"
#include "world.h"
#include <iostream>
#include <vector>

// returns chance of <eye> over <die> roll
bool roll(int die, int eye);

// Constants
#define CELL_LENGTH 16
#define COL_TILE_DESIRED 7

Map::Map()
{
}

Map::~Map()
{
    delete platformImage;
    delete potatoImage;
    delete meatImage;
    delete babyImage;
    delete moneyImage;
}

void Map::loadImages() {
    // TODO initialize into spritemaps
    platformImage = new Image( World::getRenderer(), "platform.png");
    potatoImage = new Image( World::getRenderer(), "small_potatoes.png");
    meatImage = new Image( World::getRenderer(), "Meatloaf.png");
    babyImage = new Image( World::getRenderer(), "baby.png");
    moneyImage = new Image( World::getRenderer(), "Money.png");
}

void Map::init()
{
    // Load assets
    loadImages();

    cCol = std::ceil(World::getWidth() / CELL_LENGTH);
    cRow = std::ceil(World::getHeight() / CELL_LENGTH);

    // Initialize mapGrid, a representation of Grid
    mapGrid = new MapItem*[cCol];

    // Initialize into MAP_SKY
    for (int i = 0; i < cCol; i++) {
        mapGrid[i] = new MapItem[cRow];
        for (int j = 0; j < cRow; j++) {
            mapGrid[i][j] = MAP_SKY;
        }
    }

    leftCol = 0;
    CreateMap();
    printMap();
}

void Map::CreateMap() {
    for (int i = 1; i < cCol; i++) {
        createColumn(i);
    }
}

void Map::createColumn(int col) {
    // Counting struct
    ColCount scanInfo;
    // Column to be examined.
    int prevColumn = (col - 1) % cCol;
    // Column to be written, in case we start a Barrier this time.
    int nextColumn = (col + 1) % cCol;
    // Current Column to be created.
    int currColumn = col % cCol;

    // Currently created Tile
    int tileCount = 0;

    // Clean up first.
    cleanColumn(col);

    scanColumn(prevColumn, scanInfo);

    printCount(scanInfo);

    for (int row = 0; row < cRow; row++) {
        if (mapGrid[prevColumn][row] != MAP_SKY) {

            // TODO set this Roll to be configurable
            if (roll(7, 3)) {
                if (mapGrid[prevColumn][row] == MAP_BARRIER_A) {
                    mapGrid[currColumn][row] = MAP_BARRIER_B;
                }
                else if (mapGrid[prevColumn][row] == MAP_BARRIER_B) {
                    mapGrid[currColumn][row] = MAP_BARRIER_A;
                }

                else {
                    mapGrid[currColumn][row] = mapGrid[prevColumn][row];
                }
                tileCount++;
            }
        }
    }

    // If this column has not enough tiles, give it another shot.
    for( ;tileCount < COL_TILE_DESIRED; tileCount++) {
        MapItem *newTile;

        // TODO set this Roll to be configurable
        if (roll(7, 5)) {
            newTile = &mapGrid[currColumn][rand() % cRow];
            if (*newTile == MAP_SKY) {
                *newTile = MapItem(rand() % ITEM_KIND);

                // Not gonna bother with retroactive barriering.
                if (*newTile == MAP_BARRIER_B) {
                    *newTile = MAP_SKY;
                }
            }
        }
    }
}

void Map::scanColumn(int col, ColCount &result) {
    for (int i = 0; i < ITEM_KIND; i++) {
        result.count[i] = 0;
    }
    for (int row = 0; row < cRow; row++) {
        result.count[mapGrid[col][row]]++;
    }
    result.non_sky = cCol - result.count[MAP_SKY];
}

void Map::cleanColumn(int col) {
    // Column to be written, in case we start a Barrier this time.
    int nextCol = (col + 1) % cCol;

    for (int row = 0; row < cRow; row++) {
        // If BARRIER_A, then clean the next part as well.
        if (mapGrid[col][row] == MAP_BARRIER_A) {
            mapGrid[nextCol][row] = MAP_SKY;
        }
        // If BARRIER_B, leave it alone; we don't want to be cleaning up first half.
        if (mapGrid[col][row] != MAP_BARRIER_B) {
            mapGrid[col][row] = MAP_SKY;
        }
    }
}

void Map::newGame()
{
    printf("Map: New Game Init\n");
}

// Compute where at what screen coordinate the Grid Cell must be drawn.
void Map::gridToScreen(int gridX, int gridY, int &screenX, int &screenY) {
    // Nominal - "original" location of the grid; i.e., without any offset.
    float nominalX, nominalY;
    // Adjusted - location of the draw after the alignment to current location.
    float adjustedX, adjustedY;
    nominalX = gridX * 16.0f;
    nominalY = gridY * 16.0f;

    // For now;
    adjustedX = nominalX * 1.0f;
    adjustedY = nominalY * 1.0f;

    World::worldToScreen(adjustedX, adjustedY, screenX, screenY);
}

void Map::draw(SDL_Renderer *renderer)
{
    Image *toDraw;
    int screenX, screenY;

    for (int x = 0; x < cCol; x++) {
        for (int y = 0; y < cRow; y++) {
            switch (mapGrid[x][y]) {
                // Collectible
                case MAP_BARRIER_A:
                    toDraw = platformImage;
                    break;
                case MAP_POTATO:
                    toDraw = potatoImage;
                    break;
                case MAP_MONEY:
                    toDraw = moneyImage;
                    break;
                case MAP_MEATLOAF:
                    toDraw = meatImage;
                    break;

                    // Animation
                case MAP_SIGN:
                case MAP_WHITESTART:
                case MAP_REDSTAR:
                case MAP_BLUESTAR:
                    break;

                    // SKY
                default:
                    toDraw = NULL;
                    break;
            }

            //kgridToScreen(int gridX, int gridY, int &screenX, int &screenY);
            gridToScreen(x, y, screenX, screenY);

            //printf("%d, %d\n", screenX, screenY);
            if (toDraw != NULL) {
                toDraw->draw(renderer, screenX, screenY);
            }
        }
    }
}

void Map::update(int elapsed) {
    // data structure - this is a case where a linked list(vector?) would work

    // TODO 1. shift horizontally
    // TODO 2. determine if still in display
    // TODO 3. dispose
}

int Map::collide(int x,int y,int w,int h)
{
    return MAP_SKY;
}

int Map::collect(int x,int y,int w,int h)
{

    return 0;
}
// Console Print
void Map::printMap() {
    printf("cCol: %d, cRow: %d\n", cCol, cRow);
    for (int i = 0; i < cRow; i++) {
        printf("[");
        for (int j = 0; j < cCol; j++) {
            printf(" %d ", mapGrid[j][i]);
        }
        printf("]\n");
    }
}

// Console Print
void Map::printCount(ColCount &c) {
    printf("[");
    for (int i = 0; i < ITEM_KIND; i++) {
        printf(" %d ", c.count[i]);
    }
    printf("]\n");
}

// Helper function: returns true for eye / die.
bool roll(int die, int eye) {
    return std::rand() % die < eye;
}

<commit_msg>shifting map to left in constant speed(not yet waiting for elapsed time)<commit_after>#include <SDL.h>
#include <stdio.h>
#include <cstdlib>
#include <cmath>
#include "map.h"
#include "image.h"
#include "world.h"
#include <iostream>
#include <vector>

// returns chance of <eye> over <die> roll
bool roll(int die, int eye);

#define CELL_LENGTH 16
#define COL_TILE_DESIRED 7
#define TRUMP_SPEED 0.7f

Map::Map()
{
}

Map::~Map()
{
    delete platformImage;
    delete potatoImage;
    delete meatImage;
    delete babyImage;
    delete moneyImage;
}

void Map::loadImages() {
    // TODO initialize into spritemaps
    platformImage = new Image( World::getRenderer(), "platform.png");
    potatoImage = new Image( World::getRenderer(), "small_potatoes.png");
    meatImage = new Image( World::getRenderer(), "Meatloaf.png");
    babyImage = new Image( World::getRenderer(), "baby.png");
    moneyImage = new Image( World::getRenderer(), "Money.png");
}

void Map::init()
{
    // Load assets
    loadImages();

    cCol = std::ceil(World::getWidth() / CELL_LENGTH);
    cRow = std::ceil(World::getHeight() / CELL_LENGTH);

    // Initialize mapGrid, a representation of Grid
    mapGrid = new MapItem*[cCol];

    // Initialize into MAP_SKY
    for (int i = 0; i < cCol; i++) {
        mapGrid[i] = new MapItem[cRow];
        for (int j = 0; j < cRow; j++) {
            mapGrid[i][j] = MAP_SKY;
        }
    }

    leftCol = 0;
    CreateMap();
    printMap();
}

void Map::CreateMap() {
    for (int i = 1; i < cCol; i++) {
        createColumn(i);
    }
}

void Map::createColumn(int col) {
    // Counting struct
    ColCount scanInfo;
    // Column to be examined.
    int prevColumn = (col - 1) % cCol;
    // Column to be written, in case we start a Barrier this time.
    int nextColumn = (col + 1) % cCol;
    // Current Column to be created.
    int currColumn = col % cCol;

    // Currently created Tile
    int tileCount = 0;

    // Clean up first.
    cleanColumn(col);

    scanColumn(prevColumn, scanInfo);

    printCount(scanInfo);

    for (int row = 0; row < cRow; row++) {
        if (mapGrid[prevColumn][row] != MAP_SKY) {

            // TODO set this Roll to be configurable
            if (roll(7, 3)) {
                if (mapGrid[prevColumn][row] == MAP_BARRIER_A) {
                    mapGrid[currColumn][row] = MAP_BARRIER_B;
                }
                else if (mapGrid[prevColumn][row] == MAP_BARRIER_B) {
                    mapGrid[currColumn][row] = MAP_BARRIER_A;
                }

                else {
                    mapGrid[currColumn][row] = mapGrid[prevColumn][row];
                }
                tileCount++;
            }
        }
    }

    // If this column has not enough tiles, give it another shot.
    for( ;tileCount < COL_TILE_DESIRED; tileCount++) {
        MapItem *newTile;

        // TODO set this Roll to be configurable
        if (roll(7, 5)) {
            newTile = &mapGrid[currColumn][rand() % cRow];
            if (*newTile == MAP_SKY) {
                *newTile = MapItem(rand() % ITEM_KIND);

                // Not gonna bother with retroactive barriering.
                if (*newTile == MAP_BARRIER_B) {
                    *newTile = MAP_SKY;
                }
            }
        }
    }
}

void Map::scanColumn(int col, ColCount &result) {
    for (int i = 0; i < ITEM_KIND; i++) {
        result.count[i] = 0;
    }
    for (int row = 0; row < cRow; row++) {
        result.count[mapGrid[col][row]]++;
    }
    result.non_sky = cCol - result.count[MAP_SKY];
}

void Map::cleanColumn(int col) {
    // Column to be written, in case we start a Barrier this time.
    int nextCol = (col + 1) % cCol;

    for (int row = 0; row < cRow; row++) {
        // If BARRIER_A, then clean the next part as well.
        if (mapGrid[col][row] == MAP_BARRIER_A) {
            mapGrid[nextCol][row] = MAP_SKY;
        }
        // If BARRIER_B, leave it alone; we don't want to be cleaning up first half.
        if (mapGrid[col][row] != MAP_BARRIER_B) {
            mapGrid[col][row] = MAP_SKY;
        }
    }
}

void Map::newGame()
{
    printf("Map: New Game Init\n");
}

// Compute where at what screen coordinate the Grid Cell must be drawn.
void Map::gridToScreen(int gridX, int gridY, int &screenX, int &screenY) {
    // Nominal - "original" location of the grid; i.e., without any offset.
    float nominalX, nominalY;
    // Adjusted - location of the draw after the alignment to current location.
    float adjustedX, adjustedY;
    nominalX = gridX * 16.0f;
    nominalY = gridY * 16.0f;

    // For now;
    adjustedX = (nominalX - left) * 1.0f;
    adjustedY = nominalY * 1.0f;

    if (gridX == 1 && gridY == 1) {
        printf("%f, %f\n", adjustedX, adjustedY);
    }

    World::worldToScreen(adjustedX, adjustedY, screenX, screenY);
}

void Map::draw(SDL_Renderer *renderer)
{
    Image *toDraw;
    int screenX, screenY;

    for (int x = 0; x < cCol; x++) {
        for (int y = 0; y < cRow; y++) {
            switch (mapGrid[x][y]) {
                // Collectible
                case MAP_BARRIER_A:
                    toDraw = platformImage;
                    break;
                case MAP_POTATO:
                    toDraw = potatoImage;
                    break;
                case MAP_MONEY:
                    toDraw = moneyImage;
                    break;
                case MAP_MEATLOAF:
                    toDraw = meatImage;
                    break;

                    // Animation
                case MAP_SIGN:
                case MAP_WHITESTART:
                case MAP_REDSTAR:
                case MAP_BLUESTAR:
                    break;

                    // SKY
                default:
                    toDraw = NULL;
                    break;
            }

            //kgridToScreen(int gridX, int gridY, int &screenX, int &screenY);
            gridToScreen(x, y, screenX, screenY);

            //printf("%d, %d\n", screenX, screenY);
            if (toDraw != NULL) {
                toDraw->draw(renderer, screenX, screenY);
            }
        }
    }
}

void Map::update(int elapsed) {
    // 1. Shift horizontally.
    left += TRUMP_SPEED;

    // data structure - this is a case where a linked list(vector?) would work

    // TODO 1. shift horizontally
    // TODO 2. determine if still in display
    // TODO 3. dispose
}

int Map::collide(int x,int y,int w,int h)
{
    return MAP_SKY;
}

int Map::collect(int x,int y,int w,int h)
{

    return 0;
}
// Console Print
void Map::printMap() {
    printf("cCol: %d, cRow: %d\n", cCol, cRow);
    for (int i = 0; i < cRow; i++) {
        printf("[");
        for (int j = 0; j < cCol; j++) {
            printf(" %d ", mapGrid[j][i]);
        }
        printf("]\n");
    }
}

// Console Print
void Map::printCount(ColCount &c) {
    printf("[");
    for (int i = 0; i < ITEM_KIND; i++) {
        printf(" %d ", c.count[i]);
    }
    printf("]\n");
}

// Helper function: returns true for eye / die.
bool roll(int die, int eye) {
    return std::rand() % die < eye;
}

<|endoftext|>