<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep06/host_set_ipl_parms.C $                 */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2021                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

#include <stdint.h>
#include <trace/interface.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <isteps/hwpisteperror.H>
#include <isteps/istep_reasoncodes.H>
#include <initservice/isteps_trace.H>
#include <util/utilsemipersist.H>
#include <hwas/common/deconfigGard.H>
#include <arch/pvrformat.H>
#include <sys/mmio.h>
#include <console/consoleif.H>
#include <initservice/initserviceif.H>
#ifdef CONFIG_PLDM
#include <pldm/base/hb_bios_attrs.H>
#include <pldm/pldm_errl.H>
#endif
#if (defined(CONFIG_PNORDD_IS_BMCMBOX) || defined(CONFIG_PNORDD_IS_IPMI))
#include <pnor/pnorif.H>
#endif

using namespace TARGETING;
using namespace ISTEP;

namespace ISTEP_06
{
#ifdef CONFIG_PLDM
errlHndl_t getAndSetPLDMBiosAttrs(void)
{
      errlHndl_t errl = nullptr;
      do {
      std::vector<uint8_t> bios_string_table;
      std::vector<uint8_t> bios_attr_table;
      const auto sys = TARGETING::UTIL::assertGetToplevelTarget();

      ATTR_PAYLOAD_KIND_type payload_kind = PAYLOAD_KIND_UNKNOWN;

      errl = PLDM::getHypervisorMode(bios_string_table,
                                     bios_attr_table,
                                     payload_kind);

      // If we get an error, or are returned a payload_kind
      // that is not PHYP or SAPPHIRE then we do not know
      // what payload to pick. We cannot assume the payload
      // kind as booting for the incorrect hypervisor could
      // result in loss of data in NVRAM that was generated
      // by the hypervisor on previous boots.
      if(errl)
      {
          TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                     "getAndSetPLDMBiosAttrs: An error occurred getting Hypervisor Mode from the BMC" );
          break;
      }

      if(payload_kind != PAYLOAD_KIND_PHYP &&
         payload_kind != PAYLOAD_KIND_SAPPHIRE)
      {
         /*@
          * @errortype
          * @severity   ERRL_SEV_UNRECOVERABLE
          * @moduleid   MOD_SET_IPL_PARMS
          * @reasoncode RC_INVALID_PAYLOAD_KIND
          * @userdata1  Payload Kind that BMC returned
          * @userdata2  unused
          * @devdesc    Software problem, bad data from BMC
          * @custdesc   A software error occurred during system boot
          */
          errl = new ErrlEntry(ERRL_SEV_UNRECOVERABLE,
                               MOD_SET_IPL_PARMS,
                               RC_INVALID_PAYLOAD_KIND,
                               payload_kind,
                               0,
                               ErrlEntry::NO_SW_CALLOUT);
          PLDM::addBmcErrorCallouts(errl);
          break;
      }

      sys->setAttr<ATTR_PAYLOAD_KIND>(payload_kind);

      }while(0);

      return errl;
}
#endif

void* host_set_ipl_parms( void *io_pArgs )
{
    ISTEP_ERROR::IStepError l_stepError;
    errlHndl_t l_err;

    do{

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_set_ipl_parms entry" );

    // only run on non-FSP systems
    if( !INITSERVICE::spBaseServicesEnabled() )
    {
        //Read out the semi persistent area.
        Util::semiPersistData_t l_semiData;
        Util::readSemiPersistData(l_semiData);

        // If magic number set, then this is warm reboot:
        //          1) increment boot count
        if(l_semiData.magic == Util::PERSIST_MAGIC)
        {
            l_semiData.reboot_cnt++;
        }
        // else magic number is not set, then this is first, cold boot:
        //          1) set magic num, boot count
        //          2) clear all gard records of type GARD_Reconfig
        else
        {
            l_semiData.magic = Util::PERSIST_MAGIC;
            l_semiData.reboot_cnt = 0;
            //Intentionally don't change mfg_term_reboot

            l_err = HWAS::clearGardByType(HWAS::GARD_Reconfig);
            if (l_err)
            {
                TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                          "ERROR 0x%.8X: clearGardByType( )",
                          l_err->reasonCode() );
                // Create IStep error log and cross ref error that occurred
                l_stepError.addErrorDetails( l_err );
                errlCommit( l_err, ISTEP_COMP_ID );
            }
        }

        //Write update data back out
        Util::writeSemiPersistData(l_semiData);
#ifdef CONFIG_PLDM
        const auto sys = TARGETING::UTIL::assertGetToplevelTarget();
        if(!sys->getAttr<ATTR_IS_MPIPL_HB>())
        {
            l_err = getAndSetPLDMBiosAttrs();
            if(l_err)
            {
                TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                          "host_set_ipl_parms: error occurred getting/setting PLDM bios attrs");
                l_err->collectTrace("ISTEPS_TRACE",256);
                l_stepError.addErrorDetails( l_err );
                errlCommit( l_err, ISTEP_COMP_ID );
                break;
            }
        }
        else
        {
            TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                          "host_set_ipl_parms: MPIPL detected, using PLDM bios attrs values from previous boot");
        }
#endif
    }

    /* @TODO RTC 245390: Update for P10 DD 1.0 */
#if 0
    // Add a check to indicate that Nimbus DD1.0 is NOT supported
    // and prevent a boot
    PVR_t l_pvr( mmio_pvr_read() & 0xFFFFFFFF );
    if( l_pvr.isNimbusDD1() )
    {
#ifdef CONFIG_CONSOLE
        CONSOLE::displayf(CONSOLE::DEFAULT, ISTEP_COMP_NAME,
                          "P9N (Nimbus) DD1.0 is not supported in this driver");
        CONSOLE::displayf(CONSOLE::DEFAULT, ISTEP_COMP_NAME,
                          "Please update the system's processor modules");
#endif

        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                   "DD1.0 is NOT SUPPORTED anymore. "
                   "Please upgrade proc modules");
        /*@
         * @errortype
         * @moduleid     ISTEP::MOD_SET_IPL_PARMS
         * @reasoncode   ISTEP::RC_P9N_DD1_NOT_SUPPORTED
         * @userdata1    PVR of master proc
         * @devdesc      P9N (Nimbus) DD1.x is not supported
         *               in this firmware driver.  Please update
         *               your module or use a different driver
         * @custdesc     A problem occurred during the IPL
         *               of the system.
         */
        uint64_t l_dummy = 0x0;
        l_err = new ERRORLOG::ErrlEntry(
                                        ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                        ISTEP::MOD_SET_IPL_PARMS,
                                        ISTEP::RC_P9N_DD1_NOT_SUPPORTED,
                                        l_pvr.word,
                                        l_dummy);
        // Create IStep error log and cross ref error that occurred
        l_stepError.addErrorDetails( l_err );
        errlCommit( l_err, ISTEP_COMP_ID );
    }
#endif

#if (defined(CONFIG_PNORDD_IS_BMCMBOX) || defined(CONFIG_PNORDD_IS_IPMI))
    // Add a check to indicate the BMC does not support HIOMAP pnor-ipmi access
    // and the BMC firmware should be updated
    PNOR::hiomapMode l_mode = PNOR::getPnorAccessMode();
    if( l_mode != PNOR::PNOR_IPMI )
    {
#ifdef CONFIG_CONSOLE
        CONSOLE::displayf(CONSOLE::DEFAULT, ISTEP_COMP_NAME,
            "HIOMAP PNOR-IPMI not enabled, BMC firmware needs to be updated.");
#endif

        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
            "HIOMAP PNOR-IPMI not enabled, BMC firmware needs to be updated.");

#ifdef CONFIG_PNORDD_IS_BMCMBOX
        bool l_IS_BMCMBOX = true;
#else
        bool l_IS_BMCMBOX = false;
#endif

#ifdef CONFIG_PNORDD_IS_IPMI
        bool l_IS_IPMI = true;
#else
        bool l_IS_IPMI = false;
#endif

        /*@
         * @errortype
         * @moduleid     ISTEP::MOD_SET_IPL_PARMS
         * @reasoncode   ISTEP::RC_PNOR_IPMI_NOT_ENABLED
         * @userdata1    HIOMAP Mode
         * @userdata2[0-31]  CONFIG_PNORDD_IS_BMCMBOX
         * @userdata2[32:63] CONFIG_PNORDD_IS_IPMI
         * @devdesc      PNOR-IPMI not enabled, BMC firmware needs to be updated
         * @custdesc     PNOR-IPMI not enabled, BMC firmware needs to be updated
         */
        l_err = new ERRORLOG::ErrlEntry(
                                        ERRORLOG::ERRL_SEV_PREDICTIVE,
                                        ISTEP::MOD_SET_IPL_PARMS,
                                        ISTEP::RC_PNOR_IPMI_NOT_ENABLED,
                                        l_mode,
                                        TWO_UINT32_TO_UINT64(
                                            l_IS_BMCMBOX,
                                            l_IS_IPMI));

        l_err->addProcedureCallout(HWAS::EPUB_PRC_SP_CODE,
                                   HWAS::SRCI_PRIORITY_HIGH);

        l_err->collectTrace(PNOR_COMP_NAME);
        l_err->collectTrace("ISTEPS_TRACE",256);

        // Create IStep error log and cross ref error that occurred
        l_stepError.addErrorDetails( l_err );
        errlCommit( l_err, ISTEP_COMP_ID );
    }
#endif

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_set_ipl_parms exit" );

    }while(0);

    return l_stepError.getErrorHandle();
}

};
<commit_msg>Remove BMC semi-permanent HB_VOLATILE GARD_Reconfig handling<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep06/host_set_ipl_parms.C $                 */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2021                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

#include <stdint.h>
#include <trace/interface.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <isteps/hwpisteperror.H>
#include <isteps/istep_reasoncodes.H>
#include <initservice/isteps_trace.H>
#include <util/utilsemipersist.H>
#include <hwas/common/deconfigGard.H>
#include <arch/pvrformat.H>
#include <sys/mmio.h>
#include <console/consoleif.H>
#include <initservice/initserviceif.H>
#ifdef CONFIG_PLDM
#include <pldm/base/hb_bios_attrs.H>
#include <pldm/pldm_errl.H>
#endif
#if (defined(CONFIG_PNORDD_IS_BMCMBOX) || defined(CONFIG_PNORDD_IS_IPMI))
#include <pnor/pnorif.H>
#endif

using namespace TARGETING;
using namespace ISTEP;

namespace ISTEP_06
{
#ifdef CONFIG_PLDM
errlHndl_t getAndSetPLDMBiosAttrs(void)
{
      errlHndl_t errl = nullptr;
      do {
      std::vector<uint8_t> bios_string_table;
      std::vector<uint8_t> bios_attr_table;
      const auto sys = TARGETING::UTIL::assertGetToplevelTarget();

      ATTR_PAYLOAD_KIND_type payload_kind = PAYLOAD_KIND_UNKNOWN;

      errl = PLDM::getHypervisorMode(bios_string_table,
                                     bios_attr_table,
                                     payload_kind);

      // If we get an error, or are returned a payload_kind
      // that is not PHYP or SAPPHIRE then we do not know
      // what payload to pick. We cannot assume the payload
      // kind as booting for the incorrect hypervisor could
      // result in loss of data in NVRAM that was generated
      // by the hypervisor on previous boots.
      if(errl)
      {
          TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                     "getAndSetPLDMBiosAttrs: An error occurred getting Hypervisor Mode from the BMC" );
          break;
      }

      if(payload_kind != PAYLOAD_KIND_PHYP &&
         payload_kind != PAYLOAD_KIND_SAPPHIRE)
      {
         /*@
          * @errortype
          * @severity   ERRL_SEV_UNRECOVERABLE
          * @moduleid   MOD_SET_IPL_PARMS
          * @reasoncode RC_INVALID_PAYLOAD_KIND
          * @userdata1  Payload Kind that BMC returned
          * @userdata2  unused
          * @devdesc    Software problem, bad data from BMC
          * @custdesc   A software error occurred during system boot
          */
          errl = new ErrlEntry(ERRL_SEV_UNRECOVERABLE,
                               MOD_SET_IPL_PARMS,
                               RC_INVALID_PAYLOAD_KIND,
                               payload_kind,
                               0,
                               ErrlEntry::NO_SW_CALLOUT);
          PLDM::addBmcErrorCallouts(errl);
          break;
      }

      sys->setAttr<ATTR_PAYLOAD_KIND>(payload_kind);

      }while(0);

      return errl;
}
#endif

void* host_set_ipl_parms( void *io_pArgs )
{
    ISTEP_ERROR::IStepError l_stepError;

    do{

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_set_ipl_parms entry" );

    // only run on non-FSP systems
    if( !INITSERVICE::spBaseServicesEnabled() )
    {
        // Read the semi persistent area
        Util::semiPersistData_t l_semiData;
        Util::readSemiPersistData(l_semiData);

        // If magic number set, then this is re-IPL,
        // so increment reboot count
        if(l_semiData.magic == Util::PERSIST_MAGIC)
        {
            l_semiData.reboot_cnt++;
        }
        // else magic number is not set, then this is a fresh IPL
        else
        {
            l_semiData.magic = Util::PERSIST_MAGIC;
            l_semiData.reboot_cnt = 0;
            //Intentionally don't change mfg_term_reboot
        }

        // Write updated data back out
        Util::writeSemiPersistData(l_semiData);

        // Informational only
        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_set_ipl_parms "
            "l_semiData.magic=0x%X l_semiData.reboot_cnt=0x%X, l_semiData.mfg_term_reboot=0x%X",
            l_semiData.magic, l_semiData.reboot_cnt, l_semiData.mfg_term_reboot);

#ifdef CONFIG_PLDM
        errlHndl_t l_pldm_err; // needed for scope compilation
        const auto sys = TARGETING::UTIL::assertGetToplevelTarget();
        if(!sys->getAttr<ATTR_IS_MPIPL_HB>())
        {
            l_pldm_err = getAndSetPLDMBiosAttrs();
            if(l_pldm_err)
            {
                TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                          "host_set_ipl_parms: error occurred getting/setting PLDM bios attrs");
                l_pldm_err->collectTrace("ISTEPS_TRACE",256);
                l_stepError.addErrorDetails( l_pldm_err );
                errlCommit( l_pldm_err, ISTEP_COMP_ID );
                break;
            }
        }
        else
        {
            TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                          "host_set_ipl_parms: MPIPL detected, using PLDM bios attrs values from previous boot");
        }
#endif
    }

    /* @TODO RTC 245390: Update for P10 DD 1.0 */
#if 0
    // Add a check to indicate that Nimbus DD1.0 is NOT supported
    // and prevent a boot
    PVR_t l_pvr( mmio_pvr_read() & 0xFFFFFFFF );
    if( l_pvr.isNimbusDD1() )
    {
#ifdef CONFIG_CONSOLE
        CONSOLE::displayf(CONSOLE::DEFAULT, ISTEP_COMP_NAME,
                          "P9N (Nimbus) DD1.0 is not supported in this driver");
        CONSOLE::displayf(CONSOLE::DEFAULT, ISTEP_COMP_NAME,
                          "Please update the system's processor modules");
#endif

        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                   "DD1.0 is NOT SUPPORTED anymore. "
                   "Please upgrade proc modules");
        /*@
         * @errortype
         * @moduleid     ISTEP::MOD_SET_IPL_PARMS
         * @reasoncode   ISTEP::RC_P9N_DD1_NOT_SUPPORTED
         * @userdata1    PVR of master proc
         * @devdesc      P9N (Nimbus) DD1.x is not supported
         *               in this firmware driver.  Please update
         *               your module or use a different driver
         * @custdesc     A problem occurred during the IPL
         *               of the system.
         */
        uint64_t l_dummy = 0x0;
        l_err = new ERRORLOG::ErrlEntry(
                                        ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                        ISTEP::MOD_SET_IPL_PARMS,
                                        ISTEP::RC_P9N_DD1_NOT_SUPPORTED,
                                        l_pvr.word,
                                        l_dummy);
        // Create IStep error log and cross ref error that occurred
        l_stepError.addErrorDetails( l_err );
        errlCommit( l_err, ISTEP_COMP_ID );
    }
#endif

#if (defined(CONFIG_PNORDD_IS_BMCMBOX) || defined(CONFIG_PNORDD_IS_IPMI))
    // Add a check to indicate the BMC does not support HIOMAP pnor-ipmi access
    // and the BMC firmware should be updated
    errlHndl_t l_pnor_err; // needed for scope compilation
    PNOR::hiomapMode l_mode = PNOR::getPnorAccessMode();
    if( l_mode != PNOR::PNOR_IPMI )
    {
#ifdef CONFIG_CONSOLE
        CONSOLE::displayf(CONSOLE::DEFAULT, ISTEP_COMP_NAME,
            "HIOMAP PNOR-IPMI not enabled, BMC firmware needs to be updated.");
#endif

        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
            "HIOMAP PNOR-IPMI not enabled, BMC firmware needs to be updated.");

#ifdef CONFIG_PNORDD_IS_BMCMBOX
        bool l_IS_BMCMBOX = true;
#else
        bool l_IS_BMCMBOX = false;
#endif

#ifdef CONFIG_PNORDD_IS_IPMI
        bool l_IS_IPMI = true;
#else
        bool l_IS_IPMI = false;
#endif

        /*@
         * @errortype
         * @moduleid     ISTEP::MOD_SET_IPL_PARMS
         * @reasoncode   ISTEP::RC_PNOR_IPMI_NOT_ENABLED
         * @userdata1    HIOMAP Mode
         * @userdata2[0-31]  CONFIG_PNORDD_IS_BMCMBOX
         * @userdata2[32:63] CONFIG_PNORDD_IS_IPMI
         * @devdesc      PNOR-IPMI not enabled, BMC firmware needs to be updated
         * @custdesc     PNOR-IPMI not enabled, BMC firmware needs to be updated
         */
        l_pnor_err = new ERRORLOG::ErrlEntry(
                                        ERRORLOG::ERRL_SEV_PREDICTIVE,
                                        ISTEP::MOD_SET_IPL_PARMS,
                                        ISTEP::RC_PNOR_IPMI_NOT_ENABLED,
                                        l_mode,
                                        TWO_UINT32_TO_UINT64(
                                            l_IS_BMCMBOX,
                                            l_IS_IPMI));

        l_pnor_err->addProcedureCallout(HWAS::EPUB_PRC_SP_CODE,
                                   HWAS::SRCI_PRIORITY_HIGH);

        l_pnor_err->collectTrace(PNOR_COMP_NAME);
        l_pnor_err->collectTrace("ISTEPS_TRACE",256);

        // Create IStep error log and cross ref error that occurred
        l_stepError.addErrorDetails( l_pnor_err );
        errlCommit( l_pnor_err, ISTEP_COMP_ID );
    }
#endif

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_set_ipl_parms exit" );

    }while(0);

    return l_stepError.getErrorHandle();
}

};
<|endoftext|>


<commit_before>c3ce6c47-ad5b-11e7-b063-ac87a332f658<commit_msg>lets try again<commit_after>c48263e8-ad5b-11e7-9012-ac87a332f658<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   main.c
 * Author: peterharrison
 *
 * Created on 07 February 2016, 23:47
 */

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "maze.h"
#include "mazeprinter.h"
//#include "mazepathfinder.h"
#include "mazesearcher.h"
#include <glob.h>

uint8_t wallData[1024];

int ReadRealWallsFromFile(char *filename) {
  FILE *fp;

//  ClearWallData(); /* in case we do not find a file */
  if ((fp = fopen(filename, "rb")) == NULL) {
    return 1;
  }
  if (fread(wallData, 1, 256, fp) < 256) {
    fclose(fp);
    return 2;
  };

//  fseek(fp, 0L, SEEK_END);
//  long size = ftell(fp);
//  // a standard maze uses 256 bytes
//  // assume the first 256 bytes are the wall data
//  if (size >= 256) {
//    rewind(fp);
//    for (loc.col = 0; loc.col < MAZE_COLS; loc.col++) {
//      for (loc.row = 0; loc.row < MAZE_ROWS; loc.row++) {
//        wallData[loc.row][loc.col] = fgetc(fp);// & ~VISITED;
//      }
//    }
//  }
  fclose(fp);
  return 0;
}

/*
 *
 */
int main(int argc, char **argv) {
  MazeSearcher barney;
  glob_t glob_result;
  glob("./mazefiles/*", GLOB_TILDE, NULL, &glob_result);
  if (argc > 1) {
    Maze maze(16);
    int onePassCount = 0;
    int chancerCount = 0;
    printf("   FULL  MODOPEN   MODALL\n");
    barney.setSearchMethod(MazeSearcher::SEARCH_LEFT_WALL);
    for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) {
     std::cout << "\n\n\n";
      std::cout << glob_result.gl_pathv[i] << " : ";
      ReadRealWallsFromFile(glob_result.gl_pathv[i]);
//      maze.resetToEmptyMaze();
      maze.load(wallData);
      maze.copyMazeFromFileData(wallData, 256);
      maze.flood(0x77);
      barney.setRealMaze(&maze);
      barney.map()->resetToEmptyMaze();
      barney.setLocation(0x00);
      int steps = barney.searchTo(0x77);
      //steps += barney.searchTo(0x00);
      std::cout << steps << " steps   ";
      barney.map()->testForSolution();
      int costDifference = barney.map()->costDifference();
      int openCost = barney.map()->openMazeCost();
      int residual = (100*costDifference)/openCost;
      std::cout << costDifference << " [" << residual<< "] ";

      if (costDifference == 0){
        onePassCount ++;
        std::cout << "             <-----";
      }
      if (residual < 5 && residual >= 0){
        chancerCount++;
        std::cout << " ** ";
      }
      std::cout << std::endl;
      MazePrinter::printVisitedDirs(barney.map());

//    for (int i = 1; i < argc; i++) {
//      ReadRealWallsFromFile(argv[i]);
//
//      MouseInit();
//      MazeInit();
//      int stepsFull = MouseSearchToFullFlood(target);
//      MouseInit();
//      MazeInit();
//      int stepsModOpen = MouseSearchToModifiedFlood(target);
//      MouseInit();
//      MazeInit();
//      int stepsModAll = MouseSearchToModifiedFloodAll(target);
//      char x, y, z;
//      x = ' ';
//      y = ' ';
//      z = ' ';
//      if ((stepsFull < stepsModOpen) && (stepsFull < stepsModAll)) {
//        x = '*';
//        fullCount++;
//      }
//      if ((stepsModOpen < stepsFull) && (stepsModOpen < stepsModAll)) {
//        y = '*';
//        modOpenCount++;
//      }
//      if ((stepsModAll < stepsFull) && (stepsModAll < stepsModOpen)) {
//        z = '*';
//        modAllCount++;
//      }
//      if ((stepsFull >= stepsModAll) || (stepsFull >= stepsModOpen)) {
//        x = '!';
//        fullfullCount++;
//      }
//      totalMazes++;
//      printf("%7d%c  %9d%c  %9d%c  steps for %s\n", stepsFull, x, stepsModOpen, y, stepsModAll, z, argv[i]);
//      //printf ("%4d : %3d %c %3d steps for %s\n", stepsFull - stepsModAll, stepsFull, (stepsFull > stepsModAll) ? '>' : '<', stepsModAll,  argv[i]);
    }

    printf("\n%d mazes:\n", glob_result.gl_pathc);
    printf(" one Pass mazes: %3d\n", onePassCount);
    printf(" Possible chancer  mazes: %3d\n", chancerCount);

  } else {
//    char fileName[] = "mazefiles/minos03f.maz";
//    ReadRealWallsFromFile(fileName);
//    MouseInit();
//    MazeInit();
//    printf(" : %s\n", fileName);
//    int steps = MouseSearchToFullFlood(target);
//    printf("searched in %d steps\n", steps);
//    int length = IsolatePath(Home(), Goal());
//    printf("Path length is %d cells\n", length);

  }
  return (EXIT_SUCCESS);
}

<commit_msg>test all the mazes for likley one-pass goodness<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   main.c
 * Author: peterharrison
 *
 * Created on 07 February 2016, 23:47
 */

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "maze.h"
#include "mazeprinter.h"
#include "mazesearcher.h"
#include <glob.h>

uint8_t wallData[1024];

int ReadRealWallsFromFile(char *filename) {
  FILE *fp;
  if ((fp = fopen(filename, "rb")) == NULL) {
    return 1;
  }
  if (fread(wallData, 1, 256, fp) < 256) {
    fclose(fp);
    return 2;
  };
  fclose(fp);
  return 0;
}

static char *strpad(const char *string, char pad, size_t fieldSize);

char *strpad(const char *string, char pad, size_t fieldSize) {
  size_t ssize = strlen(string);
  size_t padSize = fieldSize - ssize;
  assert(padSize > 0);
  char padding[64];
  memset(padding, pad, 62);
  padding[63] = 0;
  char *padded = (char *) malloc(fieldSize + 1);
  strncpy(padded, string, fieldSize);
  strncat(padded, padding, padSize);
//  memset(padded, pad, fieldSize);
  padded[fieldSize] = 0;
//  strcpy(padded , string);
  return padded;
}

/*
 *
 */
int main(int argc, char **argv) {
  MazeSearcher barney;
  glob_t glob_result;
  glob("./mazefiles/*", GLOB_TILDE, NULL, &glob_result);
  if (argc > 1) {
    Maze maze(16);
    int onePassCount = 0;
    int chancerCount = 0;
    printf("   FULL  MODOPEN   MODALL\n");
    maze.setFloodType(Maze::RUNLENGTH_FLOOD);
    barney.setSearchMethod(MazeSearcher::SEARCH_NORMAL);
    for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) {
      std::cout << "";
      ReadRealWallsFromFile(glob_result.gl_pathv[i]);
      maze.load(wallData);
      maze.copyMazeFromFileData(wallData, 256);
      maze.flood(0x77);
      barney.setRealMaze(&maze);
      barney.map()->resetToEmptyMaze();
      barney.setLocation(0x00);
      int steps = barney.searchTo(0x77);
      steps += barney.searchTo(0x00);
      barney.map()->testForSolution();
      int costDifference = barney.map()->costDifference();
      int openCost = barney.map()->openMazeCost();
      int residual = (100 * costDifference) / openCost;

      if (residual < 5) {
//        MazePrinter::printVisitedDirs(barney.map());
        char *name = strpad(glob_result.gl_pathv[i], ' ', 43);
        std::cout << name;
        delete name;
        std::cout.width(6);
        std::cout << std::right;
        std::cout << steps << " steps";
        std::cout << " delta " << costDifference << " (" << residual << "%)";
        if (costDifference == 0) {
        onePassCount++;
            std::cout << " <---- ";
        std::cout << std::endl;
        } else if (residual < 5 && residual >= 0) {
            chancerCount++;
            std::cout << " ***** ";
        std::cout << std::endl;
          }
        }
      }

    printf("\n%d mazes:\n", glob_result.gl_pathc);
    printf(" one Pass mazes: %3d\n", onePassCount);
    printf(" Possible chancer  mazes: %3d\n", chancerCount);

  } else {
    printf(" you should provide the name of at least one maze file on the command line\n");
  }
  return (EXIT_SUCCESS);
}

<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Room;

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
		UNKNOWN,
		GRAVEYARD,
		GRAVEYARD_GATES,
		KHATHARRS_MOMS_HOUSE,
		GATES_OF_SHOGUN,
		HOUSE_OF_BLUES,
		FOGGY_FOREST
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		/*map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
		map_location[50][52] = GATES_OF_SHOGUN;
		map_location[50][53] = HOUSE_OF_BLUES;
		map_location[50][54] = FOGGY_FOREST;*/
	}

  unordered_map<RoomID, unique_ptr<Room>> rooms;
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    //Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

struct Room {
    Room(RoomID idnum, string i_description) : ID(idnum) {
        description = i_description;
    }
    virtual string describe() {
        stringstream ss;
        ss << description << "\n";
        ss << "Entities: "; for (auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
        ss << "Items: "; for (auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n";  //make this look nice later
        ss << "Obvious exits: "; for (auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
        return ss.str();
    }
    const RoomID ID; //unique id of the room
    string description; //general description of the room for the player
    vector<unique_ptr<Entity>> entities;
    vector<RoomObject> objects;
    unordered_map<string, RoomID> exits; //keys are things like "north", "down", "cave", etc.
};

struct Graveyard : public Room
{
    Graveyard() : Room(Map::Location::GRAVEYARD, "The graveyard") {}
};

typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health)
    {
        map.rooms[Map::Location::GRAVEYARD] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Graveyard description"));
        map.rooms[Map::Location::GRAVEYARD_GATES] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Graveyard gates description"));
        map.rooms[Map::Location::KHATHARRS_MOMS_HOUSE] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Moms house"));
        map.rooms[Map::Location::GATES_OF_SHOGUN] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Gates of shogun"));
        map.rooms[Map::Location::HOUSE_OF_BLUES] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Blues"));
        map.rooms[Map::Location::FOGGY_FOREST] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Forest"));
    }

    bool act(vector<string> commands) override
    {
        auto cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if (map.rooms.at(currentLocation)->exits.find(direction) == map.rooms.at(currentLocation)->exits.end())
			return false;
		currentLocation = map.rooms.at(currentLocation)->exits[direction];
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
		if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
		if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
			case Map::GATES_OF_SHOGUN:
				cout << "Here lies the Gates of the Great Shogun. Creator of A1 weaponry; able to fork stakes by a mere glare. It is said that to look into his eyes is to see your future covered in darkness. As you notice the thick red stains which cover the gates, you are reminded of the villagers' tales of sacrifices hung from these very gates. The gate has no lock. Do you enter?" << endl;
				break;
			case Map::HOUSE_OF_BLUES:
				cout << "This is a place where men shed tears and pour out emotion! Of course, after 2 or 3 pints of the finest ale. The miscreants who frequent cavernous house know the warmth of beds not their own. Doors sing with laughter and a timely cry or two. Will you enter to find love?" << endl;
				break;
			case Map::FOGGY_FOREST:
				cout << "Not much is known about this forest. Only that a wolf howls 3 times in the night, every night. And those who enter have never been known to return. Do you risk your life for adventure?" << endl;
				break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

    RoomID currentLocation;

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, function<bool(vector<string>)>> actions;

    Map map;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<commit_msg>set player default location, linked graveyard to gates<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Room;

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
		UNKNOWN,
		GRAVEYARD,
		GRAVEYARD_GATES,
		KHATHARRS_MOMS_HOUSE,
		GATES_OF_SHOGUN,
		HOUSE_OF_BLUES,
		FOGGY_FOREST
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		/*map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
		map_location[50][52] = GATES_OF_SHOGUN;
		map_location[50][53] = HOUSE_OF_BLUES;
		map_location[50][54] = FOGGY_FOREST;*/
	}

  unordered_map<RoomID, unique_ptr<Room>> rooms;
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    //Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

struct Room {
    Room(RoomID idnum, string i_description) : ID(idnum) {
        description = i_description;
    }
    virtual string describe() {
        stringstream ss;
        ss << description << "\n";
        ss << "Entities: "; for (auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
        ss << "Items: "; for (auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n";  //make this look nice later
        ss << "Obvious exits: "; for (auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
        return ss.str();
    }
    const RoomID ID; //unique id of the room
    string description; //general description of the room for the player
    vector<unique_ptr<Entity>> entities;
    vector<RoomObject> objects;
    unordered_map<string, RoomID> exits; //keys are things like "north", "down", "cave", etc.
};

struct Graveyard : public Room
{
    Graveyard() : Room(Map::Location::GRAVEYARD, "The graveyard") {}
};

typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health)
    {
        currentLocation = Map::Location::GRAVEYARD;
        map.rooms[Map::Location::GRAVEYARD] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Graveyard description"));
        map.rooms[Map::Location::GRAVEYARD]->exits["north"] = Map::Location::GRAVEYARD_GATES;
        map.rooms[Map::Location::GRAVEYARD_GATES] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Graveyard gates description"));
        map.rooms[Map::Location::KHATHARRS_MOMS_HOUSE] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Moms house"));
        map.rooms[Map::Location::GATES_OF_SHOGUN] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Gates of shogun"));
        map.rooms[Map::Location::HOUSE_OF_BLUES] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Blues"));
        map.rooms[Map::Location::FOGGY_FOREST] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Forest"));
    }

    bool act(vector<string> commands) override
    {
        auto cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if (map.rooms.at(currentLocation)->exits.find(direction) == map.rooms.at(currentLocation)->exits.end())
			return false;
		currentLocation = map.rooms.at(currentLocation)->exits[direction];
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
		if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
		if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
			case Map::GATES_OF_SHOGUN:
				cout << "Here lies the Gates of the Great Shogun. Creator of A1 weaponry; able to fork stakes by a mere glare. It is said that to look into his eyes is to see your future covered in darkness. As you notice the thick red stains which cover the gates, you are reminded of the villagers' tales of sacrifices hung from these very gates. The gate has no lock. Do you enter?" << endl;
				break;
			case Map::HOUSE_OF_BLUES:
				cout << "This is a place where men shed tears and pour out emotion! Of course, after 2 or 3 pints of the finest ale. The miscreants who frequent cavernous house know the warmth of beds not their own. Doors sing with laughter and a timely cry or two. Will you enter to find love?" << endl;
				break;
			case Map::FOGGY_FOREST:
				cout << "Not much is known about this forest. Only that a wolf howls 3 times in the night, every night. And those who enter have never been known to return. Do you risk your life for adventure?" << endl;
				break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

    RoomID currentLocation;

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, function<bool(vector<string>)>> actions;

    Map map;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<|endoftext|>


<commit_before>#include <common.h>
#include <math.h>
#include <iostream>
#include <string>

using namespace std;

device_info_t getDeviceInfo(cl::Device &d)
{
    device_info_t devInfo;

    devInfo.numCUs = (uint)d.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
    devInfo.maxWGSize = (uint)d.getInfo<CL_DEVICE_MAX_WORK_GROUP_SIZE>();
    // Limiting max work-group size to 256
    #define MAX_WG_SIZE 256
    devInfo.maxWGSize = MIN(devInfo.maxWGSize, MAX_WG_SIZE);

    devInfo.maxAllocSize = (uint)d.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>();
    devInfo.maxGlobalSize = (uint)d.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>();
    devInfo.doubleSupported = false;

    std::string extns = d.getInfo<CL_DEVICE_EXTENSIONS>();
    if((extns.find("cl_khr_fp64") != std::string::npos) || (extns.find("cl_amd_fp64") != std::string::npos))
        devInfo.doubleSupported = true;

    devInfo.deviceType = d.getInfo<CL_DEVICE_TYPE>();

    if(devInfo.deviceType == CL_DEVICE_TYPE_CPU) {
        devInfo.gloalBWIters = 20;
        devInfo.computeWgsPerCU = 512;
        devInfo.computeIters = 10;
    } else {            // GPU
        devInfo.gloalBWIters = 50;
        devInfo.computeWgsPerCU = 2048;
        devInfo.computeIters = 30;
    }
    devInfo.transferBWIters = 20;
    devInfo.kernelLatencyIters = 20000;

    return devInfo;
}

float timeInUS(cl::Event &timeEvent)
{
    cl_ulong start = timeEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() / 1000;
    cl_ulong end = timeEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>() / 1000;

    return (float)(end - start);
}

void Timer::start()
{
    tick = chrono::high_resolution_clock::now();
}

float Timer::stopAndTime()
{
    tock = chrono::high_resolution_clock::now();
    return (float)(chrono::duration_cast<chrono::microseconds>(tock - tick).count());
}

void populate(float *ptr, uint N)
{
    srand((unsigned int)time(NULL));

    for(int i=0; i<(int)N; i++)
    {
        //ptr[i] = (float)rand();
        ptr[i] = (float)i;
    }
}

void populate(double *ptr, uint N)
{
    srand((unsigned int)time(NULL));

    for(int i=0; i<(int)N; i++)
    {
        //ptr[i] = (double)rand();
        ptr[i] = (double)i;
    }
}

#define MAX_POWER   25
uint roundToPowOf2(uint number)
{
    double logd = log(number) / log(2);
    logd = floor(logd);
    logd = MIN(logd, MAX_POWER);

    return (uint)pow(2, (int)logd);
}

<commit_msg>Fix event timer precision issue<commit_after>#include <common.h>
#include <math.h>
#include <iostream>
#include <string>

using namespace std;

device_info_t getDeviceInfo(cl::Device &d)
{
    device_info_t devInfo;

    devInfo.numCUs = (uint)d.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
    devInfo.maxWGSize = (uint)d.getInfo<CL_DEVICE_MAX_WORK_GROUP_SIZE>();
    // Limiting max work-group size to 256
    #define MAX_WG_SIZE 256
    devInfo.maxWGSize = MIN(devInfo.maxWGSize, MAX_WG_SIZE);

    devInfo.maxAllocSize = (uint)d.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>();
    devInfo.maxGlobalSize = (uint)d.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>();
    devInfo.doubleSupported = false;

    std::string extns = d.getInfo<CL_DEVICE_EXTENSIONS>();
    if((extns.find("cl_khr_fp64") != std::string::npos) || (extns.find("cl_amd_fp64") != std::string::npos))
        devInfo.doubleSupported = true;

    devInfo.deviceType = d.getInfo<CL_DEVICE_TYPE>();

    if(devInfo.deviceType == CL_DEVICE_TYPE_CPU) {
        devInfo.gloalBWIters = 20;
        devInfo.computeWgsPerCU = 512;
        devInfo.computeIters = 10;
    } else {            // GPU
        devInfo.gloalBWIters = 50;
        devInfo.computeWgsPerCU = 2048;
        devInfo.computeIters = 30;
    }
    devInfo.transferBWIters = 20;
    devInfo.kernelLatencyIters = 20000;

    return devInfo;
}

float timeInUS(cl::Event &timeEvent)
{
    cl_ulong start = timeEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() / 1000;
    cl_ulong end = timeEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>() / 1000;

    return (float)((int)end - (int)start);
}

void Timer::start()
{
    tick = chrono::high_resolution_clock::now();
}

float Timer::stopAndTime()
{
    tock = chrono::high_resolution_clock::now();
    return (float)(chrono::duration_cast<chrono::microseconds>(tock - tick).count());
}

void populate(float *ptr, uint N)
{
    srand((unsigned int)time(NULL));

    for(int i=0; i<(int)N; i++)
    {
        //ptr[i] = (float)rand();
        ptr[i] = (float)i;
    }
}

void populate(double *ptr, uint N)
{
    srand((unsigned int)time(NULL));

    for(int i=0; i<(int)N; i++)
    {
        //ptr[i] = (double)rand();
        ptr[i] = (double)i;
    }
}

#define MAX_POWER   25
uint roundToPowOf2(uint number)
{
    double logd = log(number) / log(2);
    logd = floor(logd);
    logd = MIN(logd, MAX_POWER);

    return (uint)pow(2, (int)logd);
}

<|endoftext|>


<commit_before>//
//  ex11_12_13.cpp
//  Exercise 11.12 11.13
//
//  Created by pezy on 12/15/14.
//  Copyright (c) 2014 pezy. All rights reserved.
//
//  Write a program to read a sequence of strings and ints,
//  storing each into a pair. Store the pairs in a vector.
//
//  There are at least three ways to create the pairs in the program for the
//  previous exercise.
//  Write three versions of that program, creating the pairs in each way.
//  Explain which form you think is easiest to write and understand, and why.

#include <vector>
#include <utility>
#include <string>
#include <iostream>

int main()
{
    std::vector<std::pair<std::string, int>> vec;
    std::string str;
    int i;
    while (std::cin >> str >> i)
        vec.push_back(std::pair<std::string, int>(str, i));
    // vec.push_back(std::make_pair(str, i));
    // vec.push_back({str, i});
    // vec.emplace_back(str, i); //!!! easiest way.

    for (const auto& p : vec)
        std::cout << p.first << ":" << p.second << std::endl;
}<commit_msg>Update ex11_12_13.cpp<commit_after>//
//  ex11_12_13.cpp
//  Exercise 11.12 11.13
//
//  Created by pezy on 12/15/14.
//  Copyright (c) 2014 pezy. All rights reserved.
//
//  Write a program to read a sequence of strings and ints,
//  storing each into a pair. Store the pairs in a vector.
//
//  There are at least three ways to create the pairs in the program for the
//  previous exercise.
//  Write three versions of that program, creating the pairs in each way.
//  Explain which form you think is easiest to write and understand, and why.

#include <iostream>
#include <vector>
#include <string>
#include <utility>
using namespace std;

int main()
{
    vector<pair<string, int>> v;
    string s;
    int i;
    while(cin>>s>>i)
    {
        v.push_back(make_pair(s, i));
      //v.push_back(pair<string, int>(s, i));
      //v.push_back({s, i});
      //v.emplace_back(s, i);   //!!! easiest way
    }

    for(const auto &e:v)
        cout<<e.first<<" "<<e.second<<endl;
}
<|endoftext|>


<commit_before>//
//  ex12_27.cpp
//  Exercise 12.27
//

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <iterator>
#include <cctype>
#include "ex12_27.h"

using namespace std;

TextQuery::TextQuery(ifstream &is):file(new vector<string>)
{
    string line;
    while(getline(is, line))
    {
        file->push_back(line);
        int n=file->size()-1;
        istringstream in(line);
        string text, word;
        while(in>>text)
        {
            //avoid read a word followed by punctuation(such as: word,)
            remove_copy_if(text.begin(), text.end(), back_inserter(word), [](const char &ch) {return ispunct(ch);});
            auto &lines=wm[word];
            if(!lines)
                lines.reset(new set<line_no>);
            lines->insert(n);
            word.clear();
        }
    }
}

QueryResult TextQuery::query(const string &sought) const
{
    //use static just allocate once
    static shared_ptr<set<line_no>> nodata(new set<line_no>);

    auto loc=wm.find(sought);
    if(loc==wm.end())
        return QueryResult(sought, nodata, file);
    else
        return QueryResult(sought, loc->second, file);
}

ostream &print(ostream &os, const QueryResult &qr)
{
    os<<qr.sought<<" occurs "<<qr.lines->size()<<(qr.lines->size()>1 ? " times" : " time")<<endl;
    for(auto num : *qr.lines)
        os<<"\t(line "<<num+1<<") "<<qr.file->at(num)<<endl;
    return os;
}
<commit_msg>Update ex12_27_30.cpp<commit_after>//
//  ex12_27_30.cpp
//  Exercise 12.27 12.30
//

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <iterator>
#include <cctype>
#include "ex12_27_30.h"

using namespace std;

TextQuery::TextQuery(ifstream &is):file(new vector<string>)
{
    string line;
    while(getline(is, line))
    {
        file->push_back(line);
        int n=file->size()-1;
        istringstream in(line);
        string text, word;
        while(in>>text)
        {
            //avoid read a word followed by punctuation(such as: word,)
            remove_copy_if(text.begin(), text.end(), back_inserter(word), [](const char &ch) {return ispunct(ch);});
            auto &lines=wm[word];
            if(!lines)
                lines.reset(new set<line_no>);
            lines->insert(n);
            word.clear();
        }
    }
}

QueryResult TextQuery::query(const string &sought) const
{
    //use static just allocate once
    static shared_ptr<set<line_no>> nodata(new set<line_no>);

    auto loc=wm.find(sought);
    if(loc==wm.end())
        return QueryResult(sought, nodata, file);
    else
        return QueryResult(sought, loc->second, file);
}

ostream &print(ostream &os, const QueryResult &qr)
{
    os<<qr.sought<<" occurs "<<qr.lines->size()<<(qr.lines->size()>1 ? " times" : " time")<<endl;
    for(auto num : *qr.lines)
        os<<"\t(line "<<num+1<<") "<<qr.file->at(num)<<endl;
    return os;
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}
<commit_msg>licensa<commit_after>/************************************************************************/
/* Projeto Robotica                                                     */
/* School projet for my Robotics class. This program provides face      */
/* recognition and communication with serial ports.                     */
/*                                                                      */
/* main.cpp                                                             */
/*                                                                      */
/* Guilhermo T. Agranionih  <guilhermoagranionih@gmail.com>             */
/*                                                                      */
/* Copyright (c) 2015 Guilhermo T. Agranionih                           */
/*                                                                      */
/* Permission is hereby granted, free of charge, to any person          */
/* obtaining a copy of this software and associated documentation       */
/* files (the "Software"), to deal in the Software without restriction, */
/* including without limitation the rights to use, copy, modify, merge, */
/* publish, distribute, sublicense, and/or sell copies of the Software, */
/* and to permit persons to whom the Software is furnished to do so,    */
/* subject to the following conditions:                                 */
/*                                                                      */
/* The above copyright notice and this permission notice shall be       */
/* included in all copies or substantial portions of the Software.      */
/*                                                                      */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,      */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF   */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND                */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS  */
/* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN   */
/* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN    */
/* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE     */
/* SOFTWARE.                                                            */
/************************************************************************/

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <unordered_map>
#include <string>
#include <iterator>
#include <utility>
#include <stdexcept>
#include "config.hpp"

std::unordered_map<std::string, std::pair<std::string, bool>> Config::vars = {
//	{ "name",			{ "default value", is_integer} }
	{ "type",			{ "public", false } },
	{ "port",			{ "48151", true } },
	{ "timeout",			{ "10", true } },
	{ "read_buffer_size",		{ "512", true } },
	{ "max_request_size",		{ "4096", true } },
	{ "DB_Host",			{ "127.0.0.1", false } },
	{ "DB_User",			{ "jux", false } },
	{ "DB_Password",		{ "jux", false } },
	{ "DB_Port",			{ "3306", true } },
};

std::string Config::get(const std::string& name)
{
	try {
		return vars.at(name).first;
	}
	catch (const std::exception& e) {
		std::cerr << "Error in Config::get(" + name + ")\n";
		return "";
	}
}

int Config::getInt(const std::string& name)
{
	try {
		return std::stoi(vars.at(name).first);
	}
	catch (const std::exception& e) {
		std::cerr << "Error in Config::getInt(" + name + ")\n";
		return -1;
	}
}

void Config::load(const std::string& file)
{
	std::ifstream f(file);
	std::string line;
	unsigned int lineNumber = 1;
	std::string whitespaces(" \t\v\f\r");
	auto trim = [&whitespaces](const std::string& str, size_t start, size_t end) -> std::string {
		start = str.find_first_not_of(whitespaces, start);
		end = str.find_last_not_of(whitespaces, end);
		return std::string(str, start, end - start + 1);
	};

	if (!f)
		throw std::runtime_error("Couldn't open " + file + ". Aborted.");

	while (!f.eof()) {
		std::getline(f, line);
		if (line.empty())
			continue;

		size_t start = line.find_first_not_of(whitespaces);
		if (line[start] == '#')
			continue; // this line is a comment

		size_t equalSign = line.find('=');
		if (equalSign == std::string::npos || equalSign == start || equalSign == line.size() - 1) {
			std::cerr << std::to_string(lineNumber) + ": syntax error\n";
			continue;
		}

		std::string name = trim(line, start, equalSign - 1);
		if (vars.find(name) == vars.end()) {
			std::cerr << std::to_string(lineNumber) << ": " << name + ": name not valid\n";
			continue;
		}
		std::string value = trim(line, equalSign + 1, line.size() - 1);

		if (checkValue(name, value))
			vars.at(name).first = value;

		++lineNumber;
	}
}

bool Config::checkValue(const std::string& name, std::string& value)
{
	if (vars.at(name).second) {
		try {
			std::stoi(value);
		}
		catch (const std::exception& e) {
			std::cerr << name << ": must be an integer\n";
			return false;
		}
	}
	else {
		if (value.front() == '"' && value.back() == '"') {
			value.erase(value.begin());
			value.pop_back();
		}
		else {
			std::cerr << name << ": value must have leading and trailing \"\n";
			return false;
		}
	}

	return true;
}
<commit_msg>alignement<commit_after>#include <iostream>
#include <fstream>
#include <unordered_map>
#include <string>
#include <iterator>
#include <utility>
#include <stdexcept>
#include "config.hpp"

std::unordered_map<std::string, std::pair<std::string, bool>> Config::vars = {
//	{ "name",			{ "default value", is_integer} }
	{ "type",				{ "public", false } },
	{ "port",				{ "48151", true } },
	{ "timeout",			{ "10", true } },
	{ "read_buffer_size",	{ "512", true } },
	{ "max_request_size",	{ "4096", true } },
	{ "DB_Host",			{ "127.0.0.1", false } },
	{ "DB_User",			{ "jux", false } },
	{ "DB_Password",		{ "jux", false } },
	{ "DB_Port",			{ "3306", true } },
};

std::string Config::get(const std::string& name)
{
	try {
		return vars.at(name).first;
	}
	catch (const std::exception& e) {
		std::cerr << "Error in Config::get(" + name + ")\n";
		return "";
	}
}

int Config::getInt(const std::string& name)
{
	try {
		return std::stoi(vars.at(name).first);
	}
	catch (const std::exception& e) {
		std::cerr << "Error in Config::getInt(" + name + ")\n";
		return -1;
	}
}

void Config::load(const std::string& file)
{
	std::ifstream f(file);
	std::string line;
	unsigned int lineNumber = 1;
	std::string whitespaces(" \t\v\f\r");
	auto trim = [&whitespaces](const std::string& str, size_t start, size_t end) -> std::string {
		start = str.find_first_not_of(whitespaces, start);
		end = str.find_last_not_of(whitespaces, end);
		return std::string(str, start, end - start + 1);
	};

	if (!f)
		throw std::runtime_error("Couldn't open " + file + ". Aborted.");

	while (!f.eof()) {
		std::getline(f, line);
		if (line.empty())
			continue;

		size_t start = line.find_first_not_of(whitespaces);
		if (line[start] == '#')
			continue; // this line is a comment

		size_t equalSign = line.find('=');
		if (equalSign == std::string::npos || equalSign == start || equalSign == line.size() - 1) {
			std::cerr << std::to_string(lineNumber) + ": syntax error\n";
			continue;
		}

		std::string name = trim(line, start, equalSign - 1);
		if (vars.find(name) == vars.end()) {
			std::cerr << std::to_string(lineNumber) << ": " << name + ": name not valid\n";
			continue;
		}
		std::string value = trim(line, equalSign + 1, line.size() - 1);

		if (checkValue(name, value))
			vars.at(name).first = value;

		++lineNumber;
	}
}

bool Config::checkValue(const std::string& name, std::string& value)
{
	if (vars.at(name).second) {
		try {
			std::stoi(value);
		}
		catch (const std::exception& e) {
			std::cerr << name << ": must be an integer\n";
			return false;
		}
	}
	else {
		if (value.front() == '"' && value.back() == '"') {
			value.erase(value.begin());
			value.pop_back();
		}
		else {
			std::cerr << name << ": value must have leading and trailing \"\n";
			return false;
		}
	}

	return true;
}
<|endoftext|>


<commit_before>/*
 * Universidade Federal do Rio de Janeiro
 * Trabalho de Introdução à Computação Gráfica (EEL882)
 * Semestre 2013.2
 * Professor: Cláudio Esperança
 * Aluno: Pedro Angelo Medeiros Fonini
 *
 */

/*****************************************
************** STL includes **************
*****************************************/

#include <iostream>

#include <fstream>
#include <sstream>
#include <string>

#include <vector>
#include <map>

/******************************************
************** math includes **************
******************************************/

#include <cmath>

/********************************************
************** OpenGL includes **************
********************************************/

#include <GL/glew.h>
#ifdef __APPLE__
# include <OpenGL/OpenGL.h>
# include <GLUT/glut.h>
#else
# include <GL/glut.h>
#endif

#include "loadpng.h"

/****************************************
************** definitions **************
****************************************/

// version string
#define TOSTR_(x...) #x // needs to be variadic because x might contain commas
#define STRINGIFY(x) TOSTR_(x)
#ifdef OpenWAR_VERSION
# define OpenWAR_VERSION_STR STRINGIFY(OpenWAR_VERSION)
#else
# define OpenWAR_VERSION_STR "v???"
#endif

class Terr {
public:
    float x, y;
    Terr(float x, float y) : x(x), y(y) {}
    ~Terr() {}
    std::vector<int> frontiers;
};

namespace Key {
    static const unsigned char ESC = 27;
}

namespace Color {
    static const float black[] = {0, 0, 0};
    static const float dark_green[] = {0, 0, .5};
    static const float green[] = {0, 0, 1};
    static const float dark_blue[] = {0, .5, 0};
    static const float dark_cyan[] = {0, .5, .5};
    // static const float unknown_color[] = {0, .5, 1};
    static const float green[] = {0, 1, 0};
}

const double TAU = 6.283185307179586477; // tau is 2*pi
const int WORLD_LAT_QTD = 50; // TODO: make these configurable at runtime
const int WORLD_LONG_QTD = 100;

const int STONE_LONG_QTD = 3;
const float STONE_HEIGHT = .1;
const float STONE_RAD = .2;
const float STONE_IN_PERC = 0.80;
const float STONE_HOLE_PERC = 0.80;

const double WORLD_LAT_EPS = TAU/double(2*WORLD_LAT_QTD);
const double WORLD_LONG_EPS = TAU/double(WORLD_LONG_QTD);

/****************************************
************** global vars **************
****************************************/

int latitude = 0, longitude = 0;

GLuint world_tex_map, world_tex_graph, world_curr_tex;
int wtm_width = 1024, wtm_height = 1024,
    wtg_width = 1024, wtg_height = 1024;

float sph_vertices[WORLD_LONG_QTD+1][WORLD_LAT_QTD+1][3];

std::vector<Terr> graph;

/******************************************
************** GLUT routines **************
******************************************/

using namespace std;

void handle_keypress(unsigned char key, int x, int y) {
    switch (key) {
        case Key::ESC:
            /*throw escape*/; break;
        case 'a':
            longitude -= -10; // TODO: make this number depend on the zoom level
            break;
        case 'd':
            longitude += -10;
            break;
        case 's':
            latitude -= 10;
            break;
        case 'w':
            latitude += 10;
            break;
        case 'v':
            if (world_curr_tex == world_tex_map)
                world_curr_tex = world_tex_graph;
            else
                world_curr_tex = world_tex_map;
            break;
    }
    glutPostRedisplay();
}

void init_render() {

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_COLOR_MATERIAL);
    glClearColor(.14, .18, .2, 1);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_NORMALIZE);
    glEnable(GL_CULL_FACE);
    glShadeModel(GL_SMOOTH);

    world_tex_map = loadpng("imgs/earth_tex.png", wtm_width, wtm_height);
    world_tex_graph = loadpng("imgs/earth_graph.png", wtg_width, wtg_height);
    world_curr_tex = world_tex_map;

}

void handle_resize(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(
        45,                    // camera angle
        double(w) / double(h), // width-to-height ratio
        .5, 200                // near and far z clipping coordinates
    );
}

void draw_scene() {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // ambient light
    GLfloat ambient_color[] = {.5, .5, .5, 1};
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient_color);

    // positioned light
    GLfloat light_color0[] = {5, 5, 5, 1};
    GLfloat light_pos0[] = {-2, 3, 0, 1};
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light_color0);
    glLightfv(GL_LIGHT0, GL_POSITION, light_pos0);

    glTranslatef(0, 0, -3);
    glRotatef(latitude, 1, 0, 0);
    glRotatef(longitude, 0, 1, 0);

    // draw sphere representing earth
    glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, world_curr_tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    for (int j = 1; j <= WORLD_LAT_QTD; j++) {
        glBegin(GL_TRIANGLE_STRIP);
        for (int i = 0; i <= WORLD_LONG_QTD; i++) {

            glNormal3f(sph_vertices[i][j-1][0], sph_vertices[i][j-1][1],
                       sph_vertices[i][j-1][2]);
            glTexCoord2f(float(double(i)/double(WORLD_LONG_QTD)), 1-float(double(j-1)/double(WORLD_LAT_QTD)));
            glVertex3f(sph_vertices[i][j-1][0], sph_vertices[i][j-1][1],
                       sph_vertices[i][j-1][2]);

            glNormal3f(sph_vertices[i][j][0], sph_vertices[i][j][1],
                       sph_vertices[i][j][2]);
            glTexCoord2f(float(double(i)/double(WORLD_LONG_QTD)), 1-float(double(j)/double(WORLD_LAT_QTD)));
            glVertex3f(sph_vertices[i][j][0], sph_vertices[i][j][1],
                       sph_vertices[i][j][2]);

        }
        glEnd();
    }
    glDisable(GL_TEXTURE_2D);

    glutSwapBuffers();

}

/**************************************
************** main prog **************
**************************************/

int main(int argc, char** argv) {

    cout << "OpenWAR" << endl << OpenWAR_VERSION_STR << endl;
    cout << endl;

    // sphere vertices
    cout << "Calculating sphere vertices...";
    // we should be able to calculate these at compile-time, actually
    for (int j = 0; j <= WORLD_LAT_QTD; j++) {
        for (int i = 0; i <= WORLD_LONG_QTD; i++) {
            sph_vertices[i][j][0] = -sin(j*WORLD_LAT_EPS)*sin(i*WORLD_LONG_EPS);
            sph_vertices[i][j][1] = cos(j*WORLD_LAT_EPS);
            sph_vertices[i][j][2] = -sin(j*WORLD_LAT_EPS)*cos(i*WORLD_LONG_EPS);
        }
    }
    cout << endl;

    // load territories data
    cout << "Loading territories and frontiers data...";
    {
        string line;
        char filename[] = "terr_db"; // TODO: make configurable at runtime
        ifstream file (filename);
        if (!file.is_open()) {
            cerr << "Cannot open database file `" << filename << "'" << endl;
            return 1;
        }
        map<string, int> names;
        for (int count=0; getline(file, line); count++) {
            if (line.length() == 0) { count--; continue; }
            if (line[0] == '#') { count--; continue; }
            istringstream ss(line);
            string word;
            float x, y;
            ss >> word;
            names[word] = count;
            ss >> x >> y;
            graph.push_back(Terr(x/1024, 1-y/512));
        }
        file.clear();
        file.seekg(0, file.beg);
        for (int count=0; getline(file, line); count++) {
            if (line.length() == 0) { count --; continue; }
            if (line[0] == '#') { count--; continue; }
            istringstream ss(line);
            string word;
            // discard first three words (name, x coord, y coord)
            ss >> word; ss >> word; ss >> word;
            while (ss >> word)
                graph[count].frontiers.push_back(names[word]);
        }
        file.close();
    }
    cout << endl;

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(700, 700);

    glutCreateWindow("OpenWAR");
    init_render();

    glutDisplayFunc(draw_scene);
    glutKeyboardFunc(handle_keypress);
    glutReshapeFunc(handle_resize);

    // try {
    glutMainLoop();
    // }
    // catch (exception& e) {
    //     cout << "Bye." << endl;
    // }

    return 0;

}
<commit_msg>colors; and progress with the armies<commit_after>/*
 * Universidade Federal do Rio de Janeiro
 * Trabalho de Introdução à Computação Gráfica (EEL882)
 * Semestre 2013.2
 * Professor: Cláudio Esperança
 * Aluno: Pedro Angelo Medeiros Fonini
 *
 */

/*****************************************
************** STL includes **************
*****************************************/

#include <iostream>

#include <fstream>
#include <sstream>
#include <string>

#include <vector>
#include <map>

/******************************************
************** math includes **************
******************************************/

#include <cmath>

/********************************************
************** OpenGL includes **************
********************************************/

#include <GL/glew.h>
#ifdef __APPLE__
# include <OpenGL/OpenGL.h>
# include <GLUT/glut.h>
#else
# include <GL/glut.h>
#endif

#include "loadpng.h"

/****************************************
************** definitions **************
****************************************/

// version string
#define TOSTR_(x...) #x // needs to be variadic because x might contain commas
#define STRINGIFY(x) TOSTR_(x)
#ifdef OpenWAR_VERSION
# define OpenWAR_VERSION_STR STRINGIFY(OpenWAR_VERSION)
#else
# define OpenWAR_VERSION_STR "v???"
#endif

class Terr {
public:
    float x, y;
    Terr(float x, float y) : x(x), y(y) {}
    ~Terr() {}
    std::vector<int> frontiers;
};

namespace Key {
    static const unsigned char ESC = 27;
}

namespace Color {
    typedef float color[3];
    static const color black = {0, 0, 0};
    static const color dark_blue = {0, 0, .5};
    static const color blue = {0, 0, 1};
    static const color dark_green = {0, .5, 0};
    static const color dark_cyan = {0, .5, .5};
    static const color sea_blue = {0, .5, 1};
    static const color green = {0, 1, 0};
    static const color sea_green = {0, 1, .5};
    static const color cyan = {0, 1, 1};
    static const color dark_red = {.5, 0, 0};
    static const color dark_magenta = {.5, 0, .5};
    static const color purple = {.5, 0, 1};
    static const color dark_yellow = {.5, .5, 0};
    static const color gray = {.5, .5, .5};
    static const color light_blue = {.5, .5, 1};
    static const color lime = {.5, 1, 0};
    static const color light_green = {.5, 1, .5};
    static const color light_cyan = {.5, 1, 1};
    static const color red = {1, 0, 0};
    static const color pink = {1, 0, .5};
    static const color magenta = {1, 0, 1};
    static const color orange = {1, .5, 0};
    static const color light_red = {1, .5, .5};
    static const color light_magenta = {1, .5, 1};
    static const color yellow = {1, 1, 0};
    static const color light_yellow = {1, 1, .5};
    static const color white = {1, 1, 1};
}

const double TAU = 6.283185307179586477; // tau is 2*pi
const int WORLD_LAT_QTD = 50; // TODO: make these configurable at runtime
const int WORLD_LONG_QTD = 100;

const int ARMY_LONG_QTD = 6;
const float ARMY_HEIGHT = .2;
const float ARMY_RAD = .4;
const float ARMY_IN_PERC = 0.80;
const float ARMY_HOLE_PERC = 0.20;
const float ARMY_BIG_PERC = 1.2;
static const float ARMY_HS[] = {
    ARMY_HEIGHT * ARMY_HOLE_PERC,
    ARMY_HEIGHT * (1-ARMY_HOLE_PERC)
};
static const float ARMY_HS_BIG[] = {
    ARMY_HEIGHT * ARMY_HOLE_PERC * ARMY_BIG_PERC,
    ARMY_HEIGHT * (1-ARMY_HOLE_PERC) * ARMY_BIG_PERC
};

const double WORLD_LAT_EPS = TAU/double(2*WORLD_LAT_QTD);
const double WORLD_LONG_EPS = TAU/double(WORLD_LONG_QTD);
const double ARMY_LONG_EPS = TAU/double(ARMY_LONG_QTD);

/****************************************
************** global vars **************
****************************************/

int latitude = 0, longitude = 0;

GLuint world_tex_map, world_tex_graph, world_curr_tex;
int wtm_width = 1024, wtm_height = 1024,
    wtg_width = 1024, wtg_height = 1024;

float sph_vertices[WORLD_LONG_QTD+1][WORLD_LAT_QTD+1][3];
float army_vertices[ARMY_LONG_QTD+1][2][2];

std::vector<Terr> graph;

/*************************************************
************** GLUT and GL routines **************
*************************************************/

using namespace std;

void handle_keypress(unsigned char key, int x, int y) {
    switch (key) {
        case Key::ESC:
            /*throw escape*/; break;
        case 'a':
            longitude -= -10; // TODO: make this number depend on the zoom level
            break;
        case 'd':
            longitude += -10;
            break;
        case 's':
            latitude -= 10;
            break;
        case 'w':
            latitude += 10;
            break;
        case 'v':
            if (world_curr_tex == world_tex_map)
                world_curr_tex = world_tex_graph;
            else
                world_curr_tex = world_tex_map;
            break;
    }
    glutPostRedisplay();
}

void init_render() {

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_COLOR_MATERIAL);
    glClearColor(.14, .18, .2, 1);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_NORMALIZE);
//     glEnable(GL_CULL_FACE);
    glShadeModel(GL_SMOOTH);

    world_tex_map = loadpng("imgs/earth_tex.png", wtm_width, wtm_height);
    world_tex_graph = loadpng("imgs/earth_graph.png", wtg_width, wtg_height);
    world_curr_tex = world_tex_map;

}

void handle_resize(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(
        50,                    // camera angle // TODO: get this back at 45?
        double(w) / double(h), // width-to-height ratio
        .5, 200                // near and far z clipping coordinates
    );
}

void draw_army(const Color::color c) {

    glPushMatrix();
    glTranslatef(0, 0, 1);

    glColor3f(c[0], c[1], c[2]);

    // draw lower cap
    glBegin(GL_TRIANGLE_FAN);
    glNormal3f(0, 0, -1);
    glVertex3f(0, 0, ARMY_HS[0]);
    for (int i = 0; i <= ARMY_LONG_QTD; i++) {
        glNormal3f(army_vertices[i][1][0], army_vertices[i][1][1], ARMY_HS[0]);
        glVertex3f(army_vertices[i][1][0], army_vertices[i][1][1], ARMY_HS[0]);
        glNormal3f(army_vertices[i][1][0], army_vertices[i][1][1], ARMY_HS[0]);
        glVertex3f(army_vertices[i][1][0], army_vertices[i][1][1], ARMY_HS[0]);
    }
    glEnd();

    // TODO: bottom and top caps; inner wall

    // draw outer wall
    glBegin(GL_TRIANGLE_STRIP);
    for (int i = 0; i <= ARMY_LONG_QTD; i++) {
        glNormal3f(army_vertices[i][0][0], army_vertices[i][0][1], 0);
        glVertex3f(army_vertices[i][0][0], army_vertices[i][0][1], ARMY_HEIGHT);
        glNormal3f(army_vertices[i][0][0], army_vertices[i][0][1], 0);
        glVertex3f(army_vertices[i][0][0], army_vertices[i][0][1], 0);
    }
    glEnd();

    // draw upper cap
    glBegin(GL_TRIANGLE_FAN);
    glNormal3f(0, 0, 1);
    glVertex3f(0, 0, ARMY_HS[1]);
    for (int i = 0; i <= ARMY_LONG_QTD; i++) {
        glNormal3f(army_vertices[i][1][0], army_vertices[i][1][1], ARMY_HS[1]);
        glVertex3f(army_vertices[i][1][0], army_vertices[i][1][1], ARMY_HS[1]);
        glNormal3f(army_vertices[i][1][0], army_vertices[i][1][1], ARMY_HS[1]);
        glVertex3f(army_vertices[i][1][0], army_vertices[i][1][1], ARMY_HS[1]);
    }
    glEnd();

    glColor3f(1, 1, 1); // reset color

    glPopMatrix();

}

void draw_scene() {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // ambient light
    GLfloat ambient_color[] = {.5, .5, .5, 1};
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient_color);

    // positioned light
    GLfloat light_color0[] = {5, 5, 5, 1};
    GLfloat light_pos0[] = {-2, 3, 0, 1};
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light_color0);
    glLightfv(GL_LIGHT0, GL_POSITION, light_pos0);

    glTranslatef(0, 0, -3);
    glRotatef(latitude, 1, 0, 0);
    glRotatef(longitude, 0, 1, 0);

    // draw sphere representing earth
    glPushMatrix();
    glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, world_curr_tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    for (int j = 1; j <= WORLD_LAT_QTD; j++) {
        glBegin(GL_TRIANGLE_STRIP);
        for (int i = 0; i <= WORLD_LONG_QTD; i++) {

            glNormal3f(sph_vertices[i][j-1][0], sph_vertices[i][j-1][1],
                       sph_vertices[i][j-1][2]);
            glTexCoord2f(double(i)/double(WORLD_LONG_QTD),
                         1-double(j-1)/double(WORLD_LAT_QTD));
            glVertex3f(sph_vertices[i][j-1][0], sph_vertices[i][j-1][1],
                       sph_vertices[i][j-1][2]);

            glNormal3f(sph_vertices[i][j][0], sph_vertices[i][j][1],
                       sph_vertices[i][j][2]);
            glTexCoord2f(double(i)/double(WORLD_LONG_QTD),
                         1-double(j)/double(WORLD_LAT_QTD));
            glVertex3f(sph_vertices[i][j][0], sph_vertices[i][j][1],
                       sph_vertices[i][j][2]);

        }
        glEnd();
    }
    glDisable(GL_TEXTURE_2D);
    glPopMatrix();

    draw_army(Color::yellow);

    glutSwapBuffers();

}

/**************************************
************** main prog **************
**************************************/

int main(int argc, char** argv) {

    cout << "OpenWAR" << endl << OpenWAR_VERSION_STR << endl;
    cout << endl;

    // sphere vertices
    cout << "Calculating sphere vertices...";
    // we should be able to calculate these at compile-time, actually
    for (int j = 0; j <= WORLD_LAT_QTD; j++) {
        for (int i = 0; i <= WORLD_LONG_QTD; i++) {
            sph_vertices[i][j][0] = -sin(j*WORLD_LAT_EPS)*sin(i*WORLD_LONG_EPS);
            sph_vertices[i][j][1] = cos(j*WORLD_LAT_EPS);
            sph_vertices[i][j][2] = -sin(j*WORLD_LAT_EPS)*cos(i*WORLD_LONG_EPS);
        }
    }
    cout << endl;

    // army vertices
    cout << "Calculating army vertices..." << endl;
    for (int i = 0; i <= ARMY_LONG_QTD; i++) {
        army_vertices[i][0][0] = ARMY_RAD * cos(i*ARMY_LONG_EPS);
        army_vertices[i][0][1] = ARMY_RAD * sin(i*ARMY_LONG_EPS);
        army_vertices[i][1][0] = ARMY_RAD * cos(i*ARMY_LONG_EPS) * ARMY_IN_PERC;
        army_vertices[i][1][1] = ARMY_RAD * sin(i*ARMY_LONG_EPS) * ARMY_IN_PERC;
    }

    // load territories data
    cout << "Loading territories and frontiers data...";
    {
        string line;
        char filename[] = "terr_db"; // TODO: make configurable at runtime
        ifstream file (filename);
        if (!file.is_open()) {
            cerr << "Cannot open database file `" << filename << "'" << endl;
            return 1;
        }
        map<string, int> names;
        for (int count=0; getline(file, line); count++) {
            if (line.length() == 0) { count--; continue; }
            if (line[0] == '#') { count--; continue; }
            istringstream ss(line);
            string word;
            float x, y;
            ss >> word;
            names[word] = count;
            ss >> x >> y;
            graph.push_back(Terr(x/1024, 1-y/512));
        }
        file.clear(); file.seekg(0, file.beg); // for reading it again
        for (int count=0; getline(file, line); count++) {
            if (line.length() == 0) { count --; continue; }
            if (line[0] == '#') { count--; continue; }
            istringstream ss(line);
            string word;
            // discard first three words (name, x coord, y coord)
            ss >> word; ss >> word; ss >> word;
            while (ss >> word)
                graph[count].frontiers.push_back(names[word]);
        }
        file.close();
    }
    cout << endl;

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(700, 700);

    glutCreateWindow("OpenWAR");
    init_render();

    glutDisplayFunc(draw_scene);
    glutKeyboardFunc(handle_keypress);
    glutReshapeFunc(handle_resize);

    // try {
    glutMainLoop();
    // }
    // catch (exception& e) {
    //     cout << "Bye." << endl;
    // }

    return 0;

}
<|endoftext|>