<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// bwtree_index.cpp
//
// Identification: src/backend/index/bwtree_index.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "common/logger.h"
#include "index/bwtree_index.h"
#include "index/index_key.h"
#include "storage/tuple.h"

namespace peloton {
namespace index {

BWTREE_TEMPLATE_ARGUMENTS
BWTREE_INDEX_TYPE::BWTreeIndex(IndexMetadata *metadata) :
      // Base class
      Index{metadata},
      // Key "less than" relation comparator
      comparator{},
      // Key equality checker
      equals{},
      // Key hash function
      hash_func{},
      // NOTE: These two arguments need to be constructed in advance
      // and do not have trivial constructor
      container{comparator,
                equals,
                hash_func} {
  return;
}

BWTREE_TEMPLATE_ARGUMENTS
BWTREE_INDEX_TYPE::~BWTreeIndex() {
  return;
}

/*
 * InsertEntry() - insert a key-value pair into the map
 *
 * If the key value pair already exists in the map, just return false
 */
BWTREE_TEMPLATE_ARGUMENTS
bool
BWTREE_INDEX_TYPE::InsertEntry(const storage::Tuple *key,
                               const ItemPointer &location) {
  KeyType index_key;
  index_key.SetFromKey(key);

  ItemPointer *item_p = new ItemPointer{location};

  bool ret = container.Insert(index_key, item_p);
  // If insertion fails we just delete the new value and return false
  // to notify the caller
  if(ret == false) {
    delete item_p;
  }

  return ret;
}

/*
 * DeleteEntry() - Removes a key-value pair
 *
 * If the key-value pair does not exists yet in the map return false
 */
BWTREE_TEMPLATE_ARGUMENTS
bool
BWTREE_INDEX_TYPE::DeleteEntry(const storage::Tuple *key,
                               const ItemPointer &location) {
  KeyType index_key;
  index_key.SetFromKey(key);

  // Must allocate new memory here
  ItemPointer *ip_p = new ItemPointer{location};

  // In Delete() since we just use the value for comparison (i.e. read-only)
  // it is unnecessary for us to allocate memory
  bool ret = container.DeleteExchange(index_key, &ip_p);

  // IF delete succeeds then DeleteExchange() will exchange the deleted
  // value into this variable
  if(ret == true) {
    //delete ip_p;
  } else {
    // This will delete the unused memory
    delete ip_p;
  }

  return ret;
}

BWTREE_TEMPLATE_ARGUMENTS
bool
BWTREE_INDEX_TYPE::CondInsertEntry(const storage::Tuple *key,
                                   const ItemPointer &location,
                                   std::function<bool(const ItemPointer &)> predicate) {
  KeyType index_key;
  index_key.SetFromKey(key);

  ItemPointer *item_p = new ItemPointer{location};
  bool predicate_satisfied = false;

  // This function will complete them in one step
  // predicate will be set to nullptr if the predicate
  // returns true for some value
  bool ret = container.ConditionalInsert(index_key,
                                         item_p,
                                         predicate,
                                         &predicate_satisfied);

  // If predicate is not satisfied then we know insertion successes
  if(predicate_satisfied == false) {
    // So it should always succeed?
    assert(ret == true);
  } else {
    assert(ret == false);

    delete item_p;
  }

  return ret;
}

BWTREE_TEMPLATE_ARGUMENTS
void
BWTREE_INDEX_TYPE::Scan(const std::vector<Value> &values,
                        const std::vector<oid_t> &key_column_ids,
                        const std::vector<ExpressionType> &expr_types,
                        const ScanDirectionType &scan_direction,
                        std::vector<ItemPointer *> &result) {
  KeyType index_key;

  // Checkif we have leading (leftmost) column equality
  // refer : http://www.postgresql.org/docs/8.2/static/indexes-multicolumn.html
  oid_t leading_column_id = 0;
  auto key_column_ids_itr = std::find(key_column_ids.begin(),
                                      key_column_ids.end(), leading_column_id);

  // SPECIAL CASE : leading column id is one of the key column ids
  // and is involved in a equality constraint
  bool special_case = false;
  if (key_column_ids_itr != key_column_ids.end()) {
    auto offset = std::distance(key_column_ids.begin(), key_column_ids_itr);
    if (expr_types[offset] == EXPRESSION_TYPE_COMPARE_EQUAL) {
      special_case = true;
    }
  }

  LOG_TRACE("Special case : %d ", special_case);

  // This is only a placeholder that cannot be moved but can be assigned to
  auto scan_begin_itr = container.NullIterator();

  std::unique_ptr<storage::Tuple> start_key;
  bool all_constraints_are_equal = false;

  // If it is a special case, we can figure out the range to scan in the index
  if (special_case == true) {
    start_key.reset(new storage::Tuple(metadata->GetKeySchema(), true));

    // Construct the lower bound key tuple
    all_constraints_are_equal = ConstructLowerBoundTuple(
        start_key.get(), values, key_column_ids, expr_types);

    LOG_TRACE("All constraints are equal : %d ", all_constraints_are_equal);

    index_key.SetFromKey(start_key.get());
/*
    // If it is point query then we just do a GetValue() since GetValue()
    // is way more faster than scanning using iterator
    if(all_constraints_are_equal == true) {
      //printf("All constraints are equal\n");

      // This retrieves a list of ItemPointer *
      container.GetValue(index_key, result);

      return;
    }
*/
    //printf("Non special case\n");

    // This returns an iterator pointing to index_key's values
    scan_begin_itr = container.Begin(index_key);
  } else {
    scan_begin_itr = container.Begin();
  }

  switch (scan_direction) {
    case SCAN_DIRECTION_TYPE_FORWARD:
    case SCAN_DIRECTION_TYPE_BACKWARD: {
      // Scan the index entries in forward direction
      for (auto scan_itr = scan_begin_itr;
           scan_itr.IsEnd() == false;
           scan_itr++) {
        KeyType &scan_current_key = const_cast<KeyType &>(scan_itr->first);

        auto tuple =
            scan_current_key.GetTupleForComparison(metadata->GetKeySchema());

        // Compare the current key in the scan with "values" based on
        // "expression types"
        // For instance, "5" EXPR_GREATER_THAN "2" is true
        if (Compare(tuple, key_column_ids, expr_types, values) == true) {
          result.push_back(scan_itr->second);
        } else {
          // We can stop scanning if we know that all constraints are equal
          if (all_constraints_are_equal == true) {
            break;
          }
        }
      }

    } break;

    case SCAN_DIRECTION_TYPE_INVALID:
    default:
      throw Exception("Invalid scan direction \n");
      break;
  }

  return;
}

BWTREE_TEMPLATE_ARGUMENTS
void
BWTREE_INDEX_TYPE::ScanAllKeys(std::vector<ItemPointer *> &result) {
  auto it = container.Begin();

  // scan all entries
  while (it.IsEnd() == false) {
    result.push_back(it->second);
    it++;
  }

  return;
}

BWTREE_TEMPLATE_ARGUMENTS
void
BWTREE_INDEX_TYPE::ScanKey(const storage::Tuple *key,
                           std::vector<ItemPointer *> &result) {
  KeyType index_key;
  index_key.SetFromKey(key);

  // This function in BwTree fills a given vector
  container.GetValue(index_key, result);

  return;
}

BWTREE_TEMPLATE_ARGUMENTS
std::string
BWTREE_INDEX_TYPE::GetTypeName() const {
  return "BWTree";
}

// NOTE: If ints key is used as an optimization just uncommend
// the following in order to instanciation the template before it is
// linked in linking stage

/*
template class BWTreeIndex<IntsKey<1>,
                           ItemPointer *,
                           IntsComparator<1>,
                           IntsEqualityChecker<1>,
                           IntsHasher<1>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<IntsKey<2>,
                           ItemPointer *,
                           IntsComparator<2>,
                           IntsEqualityChecker<2>,
                           IntsHasher<2>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<IntsKey<3>,
                           ItemPointer *,
                           IntsComparator<3>,
                           IntsEqualityChecker<3>,
                           IntsHasher<3>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<IntsKey<4>,
                           ItemPointer *,
                           IntsComparator<4>,
                           IntsEqualityChecker<4>,
                           IntsHasher<4>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
*/

// Generic key
template class BWTreeIndex<GenericKey<4>,
                           ItemPointer *,
                           GenericComparator<4>,
                           GenericEqualityChecker<4>,
                           GenericHasher<4>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<GenericKey<8>,
                           ItemPointer *,
                           GenericComparator<8>,
                           GenericEqualityChecker<8>,
                           GenericHasher<8>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<GenericKey<16>,
                           ItemPointer *,
                           GenericComparator<16>,
                           GenericEqualityChecker<16>,
                           GenericHasher<16>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<GenericKey<64>,
                           ItemPointer *,
                           GenericComparator<64>,
                           GenericEqualityChecker<64>,
                           GenericHasher<64>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<GenericKey<256>,
                           ItemPointer *,
                           GenericComparator<256>,
                           GenericEqualityChecker<256>,
                           GenericHasher<256>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;

// Tuple key
template class BWTreeIndex<TupleKey,
                           ItemPointer *,
                           TupleKeyComparator,
                           TupleKeyEqualityChecker,
                           TupleKeyHasher,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;

}  // End index namespace
}  // End peloton namespace
<commit_msg>Change constructor such that GC Thread is not started automatically<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// bwtree_index.cpp
//
// Identification: src/backend/index/bwtree_index.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "common/logger.h"
#include "index/bwtree_index.h"
#include "index/index_key.h"
#include "storage/tuple.h"

namespace peloton {
namespace index {

BWTREE_TEMPLATE_ARGUMENTS
BWTREE_INDEX_TYPE::BWTreeIndex(IndexMetadata *metadata) :
      // Base class
      Index{metadata},
      // Key "less than" relation comparator
      comparator{},
      // Key equality checker
      equals{},
      // Key hash function
      hash_func{},
      // NOTE: These two arguments need to be constructed in advance
      // and do not have trivial constructor
      //
      // NOTE 2: We set the first parameter to false to disable automatic GC
      //
      container{false,
                comparator,
                equals,
                hash_func} {

  return;
}

BWTREE_TEMPLATE_ARGUMENTS
BWTREE_INDEX_TYPE::~BWTreeIndex() {
  return;
}

/*
 * InsertEntry() - insert a key-value pair into the map
 *
 * If the key value pair already exists in the map, just return false
 */
BWTREE_TEMPLATE_ARGUMENTS
bool
BWTREE_INDEX_TYPE::InsertEntry(const storage::Tuple *key,
                               const ItemPointer &location) {
  KeyType index_key;
  index_key.SetFromKey(key);

  ItemPointer *item_p = new ItemPointer{location};

  bool ret = container.Insert(index_key, item_p);
  // If insertion fails we just delete the new value and return false
  // to notify the caller
  if(ret == false) {
    delete item_p;
  }

  return ret;
}

/*
 * DeleteEntry() - Removes a key-value pair
 *
 * If the key-value pair does not exists yet in the map return false
 */
BWTREE_TEMPLATE_ARGUMENTS
bool
BWTREE_INDEX_TYPE::DeleteEntry(const storage::Tuple *key,
                               const ItemPointer &location) {
  KeyType index_key;
  index_key.SetFromKey(key);

  // Must allocate new memory here
  ItemPointer *ip_p = new ItemPointer{location};

  // In Delete() since we just use the value for comparison (i.e. read-only)
  // it is unnecessary for us to allocate memory
  bool ret = container.DeleteExchange(index_key, &ip_p);

  // IF delete succeeds then DeleteExchange() will exchange the deleted
  // value into this variable
  if(ret == true) {
    //delete ip_p;
  } else {
    // This will delete the unused memory
    delete ip_p;
  }

  return ret;
}

BWTREE_TEMPLATE_ARGUMENTS
bool
BWTREE_INDEX_TYPE::CondInsertEntry(const storage::Tuple *key,
                                   const ItemPointer &location,
                                   std::function<bool(const ItemPointer &)> predicate) {
  KeyType index_key;
  index_key.SetFromKey(key);

  ItemPointer *item_p = new ItemPointer{location};
  bool predicate_satisfied = false;

  // This function will complete them in one step
  // predicate will be set to nullptr if the predicate
  // returns true for some value
  bool ret = container.ConditionalInsert(index_key,
                                         item_p,
                                         predicate,
                                         &predicate_satisfied);

  // If predicate is not satisfied then we know insertion successes
  if(predicate_satisfied == false) {
    // So it should always succeed?
    assert(ret == true);
  } else {
    assert(ret == false);

    delete item_p;
  }

  return ret;
}

BWTREE_TEMPLATE_ARGUMENTS
void
BWTREE_INDEX_TYPE::Scan(const std::vector<Value> &values,
                        const std::vector<oid_t> &key_column_ids,
                        const std::vector<ExpressionType> &expr_types,
                        const ScanDirectionType &scan_direction,
                        std::vector<ItemPointer *> &result) {
  KeyType index_key;

  // Checkif we have leading (leftmost) column equality
  // refer : http://www.postgresql.org/docs/8.2/static/indexes-multicolumn.html
  oid_t leading_column_id = 0;
  auto key_column_ids_itr = std::find(key_column_ids.begin(),
                                      key_column_ids.end(), leading_column_id);

  // SPECIAL CASE : leading column id is one of the key column ids
  // and is involved in a equality constraint
  bool special_case = false;
  if (key_column_ids_itr != key_column_ids.end()) {
    auto offset = std::distance(key_column_ids.begin(), key_column_ids_itr);
    if (expr_types[offset] == EXPRESSION_TYPE_COMPARE_EQUAL) {
      special_case = true;
    }
  }

  LOG_TRACE("Special case : %d ", special_case);

  // This is only a placeholder that cannot be moved but can be assigned to
  auto scan_begin_itr = container.NullIterator();

  std::unique_ptr<storage::Tuple> start_key;
  bool all_constraints_are_equal = false;

  // If it is a special case, we can figure out the range to scan in the index
  if (special_case == true) {
    start_key.reset(new storage::Tuple(metadata->GetKeySchema(), true));

    // Construct the lower bound key tuple
    all_constraints_are_equal = ConstructLowerBoundTuple(
        start_key.get(), values, key_column_ids, expr_types);

    LOG_TRACE("All constraints are equal : %d ", all_constraints_are_equal);

    index_key.SetFromKey(start_key.get());
/*
    // If it is point query then we just do a GetValue() since GetValue()
    // is way more faster than scanning using iterator
    if(all_constraints_are_equal == true) {
      //printf("All constraints are equal\n");

      // This retrieves a list of ItemPointer *
      container.GetValue(index_key, result);

      return;
    }
*/
    //printf("Non special case\n");

    // This returns an iterator pointing to index_key's values
    scan_begin_itr = container.Begin(index_key);
  } else {
    scan_begin_itr = container.Begin();
  }

  switch (scan_direction) {
    case SCAN_DIRECTION_TYPE_FORWARD:
    case SCAN_DIRECTION_TYPE_BACKWARD: {
      // Scan the index entries in forward direction
      for (auto scan_itr = scan_begin_itr;
           scan_itr.IsEnd() == false;
           scan_itr++) {
        KeyType &scan_current_key = const_cast<KeyType &>(scan_itr->first);

        auto tuple =
            scan_current_key.GetTupleForComparison(metadata->GetKeySchema());

        // Compare the current key in the scan with "values" based on
        // "expression types"
        // For instance, "5" EXPR_GREATER_THAN "2" is true
        if (Compare(tuple, key_column_ids, expr_types, values) == true) {
          result.push_back(scan_itr->second);
        } else {
          // We can stop scanning if we know that all constraints are equal
          if (all_constraints_are_equal == true) {
            break;
          }
        }
      }

    } break;

    case SCAN_DIRECTION_TYPE_INVALID:
    default:
      throw Exception("Invalid scan direction \n");
      break;
  }

  return;
}

BWTREE_TEMPLATE_ARGUMENTS
void
BWTREE_INDEX_TYPE::ScanAllKeys(std::vector<ItemPointer *> &result) {
  auto it = container.Begin();

  // scan all entries
  while (it.IsEnd() == false) {
    result.push_back(it->second);
    it++;
  }

  return;
}

BWTREE_TEMPLATE_ARGUMENTS
void
BWTREE_INDEX_TYPE::ScanKey(const storage::Tuple *key,
                           std::vector<ItemPointer *> &result) {
  KeyType index_key;
  index_key.SetFromKey(key);

  // This function in BwTree fills a given vector
  container.GetValue(index_key, result);

  return;
}

BWTREE_TEMPLATE_ARGUMENTS
std::string
BWTREE_INDEX_TYPE::GetTypeName() const {
  return "BWTree";
}

// NOTE: If ints key is used as an optimization just uncommend
// the following in order to instanciation the template before it is
// linked in linking stage

/*
template class BWTreeIndex<IntsKey<1>,
                           ItemPointer *,
                           IntsComparator<1>,
                           IntsEqualityChecker<1>,
                           IntsHasher<1>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<IntsKey<2>,
                           ItemPointer *,
                           IntsComparator<2>,
                           IntsEqualityChecker<2>,
                           IntsHasher<2>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<IntsKey<3>,
                           ItemPointer *,
                           IntsComparator<3>,
                           IntsEqualityChecker<3>,
                           IntsHasher<3>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<IntsKey<4>,
                           ItemPointer *,
                           IntsComparator<4>,
                           IntsEqualityChecker<4>,
                           IntsHasher<4>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
*/

// Generic key
template class BWTreeIndex<GenericKey<4>,
                           ItemPointer *,
                           GenericComparator<4>,
                           GenericEqualityChecker<4>,
                           GenericHasher<4>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<GenericKey<8>,
                           ItemPointer *,
                           GenericComparator<8>,
                           GenericEqualityChecker<8>,
                           GenericHasher<8>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<GenericKey<16>,
                           ItemPointer *,
                           GenericComparator<16>,
                           GenericEqualityChecker<16>,
                           GenericHasher<16>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<GenericKey<64>,
                           ItemPointer *,
                           GenericComparator<64>,
                           GenericEqualityChecker<64>,
                           GenericHasher<64>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;
template class BWTreeIndex<GenericKey<256>,
                           ItemPointer *,
                           GenericComparator<256>,
                           GenericEqualityChecker<256>,
                           GenericHasher<256>,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;

// Tuple key
template class BWTreeIndex<TupleKey,
                           ItemPointer *,
                           TupleKeyComparator,
                           TupleKeyEqualityChecker,
                           TupleKeyHasher,
                           ItemPointerComparator,
                           ItemPointerHashFunc>;

}  // End index namespace
}  // End peloton namespace
<|endoftext|>


<commit_before>#include "cmdExecutable.h"
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>

using namespace std;

// Placing the tokens to char*
cmdExecutable::cmdExecutable(char* command)
{

    executable = strtok(command, " ");
    command = strtok(NULL, " ");

    args[0] = executable;

    int i = 1;

    while (command != NULL)
    {
        args[i] = command;

        command = strtok(NULL, " ");

        i++;
    }

    //putting NULL at the end of args
    //necessary for execvp
    args[i] = NULL;
}

cmdExecutable::~cmdExecutable()
{
    int i = 0;
    while (args[i] != 0)
    {
        delete args[i];
    }
}

bool cmdExecutable::execute()
{
    // responsible for preventing the seg fault
    // that occurs when || follows right after ;
    // when it occurs, within main, the executable
    // becomes null
    if ( executable == NULL )
    {
        return true;
    }

    if ( strcmp( executable, "test" ) == 0 || strcmp( executable, "[" ) == 0)
    {
        //cout << "input is test" << endl;

        struct stat sb;

        int pathLocation = 1;
        bool exist = false;
        bool exist2 = false;

        string temp;

        temp.append( args[1] );

        if ( temp[0] != '-'  || temp[1] == 'e' )
        {
            if ( temp[1] == 'e' )
                pathLocation = 2;

            exist = ( stat( args[pathLocation], &sb ) == 0 );

            if ( exist )
                cout << "(True)" << endl;

            else
                cout << "(False)" << endl;
        }

        else
        {

            exist = ( stat( args[2], &sb ) == 0 );

            if ( temp[1] == 'f' )
            {
                if ( exist )
                {
                    exist2 = S_ISREG( sb.st_mode );

                    if ( exist2 )
                        cout << "(True)" << endl;

                    else
                        cout << "(False)" << endl;
                }
            }

            else if ( temp[1] == 'd' )
            {
                if ( exist )
                {
                    exist2 = S_ISDIR( sb.st_mode );

                    if ( exist2 )
                        cout << "(True)" << endl;

                    else
                        cout << "(False)" << endl;

                }

            }
        }

    }
    // if the current command is exit
    // the following with exit the rshell

    // responsible for exiting the rshell
    // whenever the input is exit or exit is
    // called through the connectors
    else if (strcmp(executable, "exit") == 0)
    {
        exit(0);
    }

    // forks the process. Allows the executable
    // to take process while the "rshell" waits
    // for the fork process
    pid_t pid = fork( );

    int status;

    // first arguement is the command
    // second argument is a pointer to an array of pointers to
    // null terminated null-terminated characters

    //cout << "Executable: " << executable << endl;

    if ( pid == 0 )
    {
        execvp( executable, args );

        //if command does not successfully run
        string execvpFail = string(executable);

        execvpFail += " failed";

        perror( execvpFail.c_str() );

        exit(EXIT_FAILURE);
    }

    else if( pid < 0 )
    {
        perror( "fork failed" );
    }

    else
    {
        // waits for the process to end
        waitpid(pid, &status, 0);
    }

    if (status != 0 )
    {
        return false;
    }

    else
    {
        return true;
    }
}
<commit_msg>Added return values so doesnt run execvp<commit_after>#include "cmdExecutable.h"
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>

using namespace std;

// Placing the tokens to char*
cmdExecutable::cmdExecutable(char* command)
{

    executable = strtok(command, " ");
    command = strtok(NULL, " ");

    args[0] = executable;

    int i = 1;

    while (command != NULL)
    {
        args[i] = command;

        command = strtok(NULL, " ");

        i++;
    }

    //putting NULL at the end of args
    //necessary for execvp
    args[i] = NULL;
}

cmdExecutable::~cmdExecutable()
{
    int i = 0;
    while (args[i] != 0)
    {
        delete args[i];
    }
}

bool cmdExecutable::execute()
{
    // responsible for preventing the seg fault
    // that occurs when || follows right after ;
    // when it occurs, within main, the executable
    // becomes null
    if ( executable == NULL )
    {
        return true;
    }

    if ( strcmp( executable, "test" ) == 0 || strcmp( executable, "[" ) == 0)
    {
        //cout << "input is test" << endl;

        struct stat sb;

        int pathLocation = 1;
        bool exist = false;
        bool exist2 = false;

        string temp;

        temp.append( args[1] );

        if ( temp[0] != '-'  || temp[1] == 'e' )
        {
            if ( temp[1] == 'e' )
                pathLocation = 2;

            exist = ( stat( args[pathLocation], &sb ) == 0 );

            if ( exist )
            {
                cout << "(True)" << endl;
                return true;
            }

            else
            {
                cout << "(False)" << endl;
                return false;
            }
        }

        else
        {

            exist = ( stat( args[2], &sb ) == 0 );

            if ( temp[1] == 'f' )
            {
                if ( exist )
                {
                    exist2 = S_ISREG( sb.st_mode );

                    if ( exist2 )
                    {
                        cout << "(True)" << endl;
                        return true;
                    }
                    else
                    {
                        cout << "(False)" << endl;
                        return false;
                    }
                }
                else
                {
                    cout << "(False)" << endl;
                    return false;
                }
            }

            else if ( temp[1] == 'd' )
            {
                if ( exist )
                {
                    exist2 = S_ISDIR( sb.st_mode );

                    if ( exist2 )
                    {
                        cout << "(True)" << endl;
                        return true;
                    }

                    else
                    {
                        cout << "(False)" << endl;
                        return false;
                    }

                }
                else
                {
                    cout << "(False)" << endl;
                    return false;
                }

            }
        }

    }
    // if the current command is exit
    // the following with exit the rshell

    // responsible for exiting the rshell
    // whenever the input is exit or exit is
    // called through the connectors
    else if (strcmp(executable, "exit") == 0)
    {
        exit(0);
    }

    // forks the process. Allows the executable
    // to take process while the "rshell" waits
    // for the fork process
    pid_t pid = fork( );

    int status;

    // first arguement is the command
    // second argument is a pointer to an array of pointers to
    // null terminated null-terminated characters

    //cout << "Executable: " << executable << endl;

    if ( pid == 0 )
    {
        execvp( executable, args );

        //if command does not successfully run
        string execvpFail = string(executable);

        execvpFail += " failed";

        perror( execvpFail.c_str() );

        exit(EXIT_FAILURE);
    }

    else if( pid < 0 )
    {
        perror( "fork failed" );
    }

    else
    {
        // waits for the process to end
        waitpid(pid, &status, 0);
    }

    if (status != 0 )
    {
        return false;
    }

    else
    {
        return true;
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <numeric>

#include <folly/dynamic.h>

#include <folly/Format.h>
#include <folly/hash/Hash.h>
#include <folly/lang/Assume.h>
#include <folly/lang/Exception.h>

namespace folly {

//////////////////////////////////////////////////////////////////////

#define FOLLY_DYNAMIC_DEF_TYPEINFO(T) \
  constexpr const char* dynamic::TypeInfo<T>::name; \
  constexpr dynamic::Type dynamic::TypeInfo<T>::type; \
  //

FOLLY_DYNAMIC_DEF_TYPEINFO(std::nullptr_t)
FOLLY_DYNAMIC_DEF_TYPEINFO(bool)
FOLLY_DYNAMIC_DEF_TYPEINFO(std::string)
FOLLY_DYNAMIC_DEF_TYPEINFO(dynamic::Array)
FOLLY_DYNAMIC_DEF_TYPEINFO(double)
FOLLY_DYNAMIC_DEF_TYPEINFO(int64_t)
FOLLY_DYNAMIC_DEF_TYPEINFO(dynamic::ObjectImpl)

#undef FOLLY_DYNAMIC_DEF_TYPEINFO

const char* dynamic::typeName() const {
  return typeName(type_);
}

TypeError::TypeError(const std::string& expected, dynamic::Type actual)
    : std::runtime_error(sformat(
          "TypeError: expected dynamic type `{}', but had type `{}'",
          expected,
          dynamic::typeName(actual))) {}

TypeError::TypeError(
    const std::string& expected,
    dynamic::Type actual1,
    dynamic::Type actual2)
    : std::runtime_error(sformat(
          "TypeError: expected dynamic types `{}, but had types `{}' and `{}'",
          expected,
          dynamic::typeName(actual1),
          dynamic::typeName(actual2))) {}

TypeError::TypeError(const TypeError&) noexcept(
    std::is_nothrow_copy_constructible<std::runtime_error>::value) = default;
TypeError& TypeError::operator=(const TypeError&) noexcept(
    std::is_nothrow_copy_assignable<std::runtime_error>::value) = default;
TypeError::TypeError(TypeError&&) noexcept(
    std::is_nothrow_move_constructible<std::runtime_error>::value) = default;
TypeError& TypeError::operator=(TypeError&&) noexcept(
    std::is_nothrow_move_assignable<std::runtime_error>::value) = default;
TypeError::~TypeError() = default;

[[noreturn]] void throwTypeError_(
    std::string const& expected,
    dynamic::Type actual) {
  throw TypeError(expected, actual);
}

[[noreturn]] void throwTypeError_(
    std::string const& expected,
    dynamic::Type actual1,
    dynamic::Type actual2) {
  throw TypeError(expected, actual1, actual2);
}

// This is a higher-order preprocessor macro to aid going from runtime
// types to the compile time type system.
#define FB_DYNAMIC_APPLY(type, apply) \
  do {                                \
    switch ((type)) {                 \
      case NULLT:                     \
        apply(std::nullptr_t);        \
        break;                        \
      case ARRAY:                     \
        apply(Array);                 \
        break;                        \
      case BOOL:                      \
        apply(bool);                  \
        break;                        \
      case DOUBLE:                    \
        apply(double);                \
        break;                        \
      case INT64:                     \
        apply(int64_t);               \
        break;                        \
      case OBJECT:                    \
        apply(ObjectImpl);            \
        break;                        \
      case STRING:                    \
        apply(std::string);           \
        break;                        \
      default:                        \
        CHECK(0);                     \
        abort();                      \
    }                                 \
  } while (0)

bool dynamic::operator<(dynamic const& o) const {
  if (UNLIKELY(type_ == OBJECT || o.type_ == OBJECT)) {
    throwTypeError_("object", type_);
  }
  if (type_ != o.type_) {
    return type_ < o.type_;
  }

#define FB_X(T) return CompareOp<T>::comp(*getAddress<T>(),   \
                                          *o.getAddress<T>())
  FB_DYNAMIC_APPLY(type_, FB_X);
#undef FB_X
}

bool dynamic::operator==(dynamic const& o) const {
  if (type() != o.type()) {
    if (isNumber() && o.isNumber()) {
      auto& integ = isInt() ? *this : o;
      auto& doubl = isInt() ? o     : *this;
      return integ.asInt() == doubl.asDouble();
    }
    return false;
  }

#define FB_X(T) return *getAddress<T>() == *o.getAddress<T>();
  FB_DYNAMIC_APPLY(type_, FB_X);
#undef FB_X
}

dynamic& dynamic::operator=(dynamic const& o) {
  if (&o != this) {
    if (type_ == o.type_) {
#define FB_X(T) *getAddress<T>() = *o.getAddress<T>()
      FB_DYNAMIC_APPLY(type_, FB_X);
#undef FB_X
    } else {
      destroy();
#define FB_X(T) new (getAddress<T>()) T(*o.getAddress<T>())
      FB_DYNAMIC_APPLY(o.type_, FB_X);
#undef FB_X
      type_ = o.type_;
    }
  }
  return *this;
}

dynamic& dynamic::operator=(dynamic&& o) noexcept {
  if (&o != this) {
    if (type_ == o.type_) {
#define FB_X(T) *getAddress<T>() = std::move(*o.getAddress<T>())
      FB_DYNAMIC_APPLY(type_, FB_X);
#undef FB_X
    } else {
      destroy();
#define FB_X(T) new (getAddress<T>()) T(std::move(*o.getAddress<T>()))
      FB_DYNAMIC_APPLY(o.type_, FB_X);
#undef FB_X
      type_ = o.type_;
    }
  }
  return *this;
}

dynamic& dynamic::operator[](dynamic const& k) & {
  if (!isObject() && !isArray()) {
    throwTypeError_("object/array", type());
  }
  if (isArray()) {
    return at(k);
  }
  auto& obj = get<ObjectImpl>();
  auto ret = obj.insert({k, nullptr});
  return ret.first->second;
}

dynamic dynamic::getDefault(const dynamic& k, const dynamic& v) const& {
  auto& obj = get<ObjectImpl>();
  auto it = obj.find(k);
  return it == obj.end() ? v : it->second;
}

dynamic dynamic::getDefault(const dynamic& k, dynamic&& v) const& {
  auto& obj = get<ObjectImpl>();
  auto it = obj.find(k);
  // Avoid clang bug with ternary
  if (it == obj.end()) {
    return std::move(v);
  } else {
    return it->second;
  }
}

dynamic dynamic::getDefault(const dynamic& k, const dynamic& v) && {
  auto& obj = get<ObjectImpl>();
  auto it = obj.find(k);
  // Avoid clang bug with ternary
  if (it == obj.end()) {
    return v;
  } else {
    return std::move(it->second);
  }
}

dynamic dynamic::getDefault(const dynamic& k, dynamic&& v) && {
  auto& obj = get<ObjectImpl>();
  auto it = obj.find(k);
  return std::move(it == obj.end() ? v : it->second);
}

const dynamic* dynamic::get_ptr(dynamic const& idx) const& {
  if (auto* parray = get_nothrow<Array>()) {
    if (!idx.isInt()) {
      throwTypeError_("int64", idx.type());
    }
    if (idx < 0 || idx >= parray->size()) {
      return nullptr;
    }
    return &(*parray)[size_t(idx.asInt())];
  } else if (auto* pobject = get_nothrow<ObjectImpl>()) {
    auto it = pobject->find(idx);
    if (it == pobject->end()) {
      return nullptr;
    }
    return &it->second;
  } else {
    throwTypeError_("object/array", type());
  }
}

[[noreturn]] static void throwOutOfRangeAtMissingKey(dynamic const& idx) {
  auto msg = sformat("couldn't find key {} in dynamic object", idx.asString());
  throw_exception<std::out_of_range>(msg);
}

dynamic const& dynamic::at(dynamic const& idx) const& {
  if (auto* parray = get_nothrow<Array>()) {
    if (!idx.isInt()) {
      throwTypeError_("int64", idx.type());
    }
    if (idx < 0 || idx >= parray->size()) {
      throw_exception<std::out_of_range>("out of range in dynamic array");
    }
    return (*parray)[size_t(idx.asInt())];
  } else if (auto* pobject = get_nothrow<ObjectImpl>()) {
    auto it = pobject->find(idx);
    if (it == pobject->end()) {
      throwOutOfRangeAtMissingKey(idx);
    }
    return it->second;
  } else {
    throwTypeError_("object/array", type());
  }
}

std::size_t dynamic::size() const {
  if (auto* ar = get_nothrow<Array>()) {
    return ar->size();
  }
  if (auto* obj = get_nothrow<ObjectImpl>()) {
    return obj->size();
  }
  if (auto* str = get_nothrow<std::string>()) {
    return str->size();
  }
  throwTypeError_("array/object", type());
}

dynamic::iterator dynamic::erase(const_iterator first, const_iterator last) {
  auto& arr = get<Array>();
  return get<Array>().erase(
    arr.begin() + (first - arr.begin()),
    arr.begin() + (last - arr.begin()));
}

std::size_t dynamic::hash() const {
  switch (type()) {
  case NULLT:
    return 0xBAAAAAAD;
  case OBJECT:
  {
    // Accumulate using addition instead of using hash_range (as in the ARRAY
    // case), as we need a commutative hash operation since unordered_map's
    // iteration order is unspecified.
    auto h = std::hash<std::pair<dynamic, dynamic>>{};
    return std::accumulate(
        items().begin(),
        items().end(),
        size_t{0x0B1EC7},
        [&](auto acc, auto item) { return acc + h(item); });
    }
  case ARRAY:
    return folly::hash::hash_range(begin(), end());
  case INT64:
    return std::hash<int64_t>()(getInt());
  case DOUBLE:
    return std::hash<double>()(getDouble());
  case BOOL:
    return std::hash<bool>()(getBool());
  case STRING:
    return Hash()(getString());
  }
  assume_unreachable();
}

char const* dynamic::typeName(Type t) {
#define FB_X(T) return TypeInfo<T>::name
  FB_DYNAMIC_APPLY(t, FB_X);
#undef FB_X
}

void dynamic::destroy() noexcept {
  // This short-circuit speeds up some microbenchmarks.
  if (type_ == NULLT) {
    return;
  }

#define FB_X(T) detail::Destroy::destroy(getAddress<T>())
  FB_DYNAMIC_APPLY(type_, FB_X);
#undef FB_X
  type_ = NULLT;
  u_.nul = nullptr;
}

dynamic dynamic::merge_diff(const dynamic& source, const dynamic& target) {
  if (!source.isObject() || source.type() != target.type()) {
    return target;
  }

  dynamic diff = object;

  // added/modified keys
  for (const auto& pair : target.items()) {
    auto it = source.find(pair.first);
    if (it == source.items().end()) {
      diff[pair.first] = pair.second;
    } else {
      diff[pair.first] = merge_diff(source[pair.first], target[pair.first]);
    }
  }

  // removed keys
  for (const auto& pair : source.items()) {
    auto it = target.find(pair.first);
    if (it == target.items().end()) {
      diff[pair.first] = nullptr;
    }
  }

  return diff;
}

const dynamic* dynamic::get_ptr(json_pointer const& jsonPtr) const& {
  auto const& tokens = jsonPtr.tokens();
  if (tokens.empty()) {
    return this;
  }
  dynamic const* dyn = this;
  for (auto const& token : tokens) {
    if (!dyn) {
      return nullptr;
    }
    // special case of parsing "/": lookup key with empty name
    if (token.empty()) {
      if (dyn->isObject()) {
        dyn = dyn->get_ptr("");
        continue;
      }
      throwTypeError_("object", dyn->type());
    }
    if (auto* parray = dyn->get_nothrow<dynamic::Array>()) {
      if (token.size() > 1 && token.at(0) == '0') {
        throw std::invalid_argument(
            "Leading zero not allowed when indexing arrays");
      }
      // special case, always return non-existent
      if (token.size() == 1 && token.at(0) == '-') {
        dyn = nullptr;
        continue;
      }
      auto const idx = folly::to<size_t>(token);
      dyn = idx < parray->size() ? &(*parray)[idx] : nullptr;
      continue;
    }
    if (auto* pobject = dyn->get_nothrow<dynamic::ObjectImpl>()) {
      auto const it = pobject->find(token);
      dyn = it != pobject->end() ? &it->second : nullptr;
      continue;
    }
    throwTypeError_("object/array", dyn->type());
  }
  return dyn;
}

//////////////////////////////////////////////////////////////////////

} // namespace folly
<commit_msg>Revert D8304491: [folly] Use folly Hash to hash strings in dynamic<commit_after>/*
 * Copyright 2011-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <numeric>

#include <folly/dynamic.h>

#include <folly/Format.h>
#include <folly/hash/Hash.h>
#include <folly/lang/Assume.h>
#include <folly/lang/Exception.h>

namespace folly {

//////////////////////////////////////////////////////////////////////

#define FOLLY_DYNAMIC_DEF_TYPEINFO(T) \
  constexpr const char* dynamic::TypeInfo<T>::name; \
  constexpr dynamic::Type dynamic::TypeInfo<T>::type; \
  //

FOLLY_DYNAMIC_DEF_TYPEINFO(std::nullptr_t)
FOLLY_DYNAMIC_DEF_TYPEINFO(bool)
FOLLY_DYNAMIC_DEF_TYPEINFO(std::string)
FOLLY_DYNAMIC_DEF_TYPEINFO(dynamic::Array)
FOLLY_DYNAMIC_DEF_TYPEINFO(double)
FOLLY_DYNAMIC_DEF_TYPEINFO(int64_t)
FOLLY_DYNAMIC_DEF_TYPEINFO(dynamic::ObjectImpl)

#undef FOLLY_DYNAMIC_DEF_TYPEINFO

const char* dynamic::typeName() const {
  return typeName(type_);
}

TypeError::TypeError(const std::string& expected, dynamic::Type actual)
    : std::runtime_error(sformat(
          "TypeError: expected dynamic type `{}', but had type `{}'",
          expected,
          dynamic::typeName(actual))) {}

TypeError::TypeError(
    const std::string& expected,
    dynamic::Type actual1,
    dynamic::Type actual2)
    : std::runtime_error(sformat(
          "TypeError: expected dynamic types `{}, but had types `{}' and `{}'",
          expected,
          dynamic::typeName(actual1),
          dynamic::typeName(actual2))) {}

TypeError::TypeError(const TypeError&) noexcept(
    std::is_nothrow_copy_constructible<std::runtime_error>::value) = default;
TypeError& TypeError::operator=(const TypeError&) noexcept(
    std::is_nothrow_copy_assignable<std::runtime_error>::value) = default;
TypeError::TypeError(TypeError&&) noexcept(
    std::is_nothrow_move_constructible<std::runtime_error>::value) = default;
TypeError& TypeError::operator=(TypeError&&) noexcept(
    std::is_nothrow_move_assignable<std::runtime_error>::value) = default;
TypeError::~TypeError() = default;

[[noreturn]] void throwTypeError_(
    std::string const& expected,
    dynamic::Type actual) {
  throw TypeError(expected, actual);
}

[[noreturn]] void throwTypeError_(
    std::string const& expected,
    dynamic::Type actual1,
    dynamic::Type actual2) {
  throw TypeError(expected, actual1, actual2);
}

// This is a higher-order preprocessor macro to aid going from runtime
// types to the compile time type system.
#define FB_DYNAMIC_APPLY(type, apply) \
  do {                                \
    switch ((type)) {                 \
      case NULLT:                     \
        apply(std::nullptr_t);        \
        break;                        \
      case ARRAY:                     \
        apply(Array);                 \
        break;                        \
      case BOOL:                      \
        apply(bool);                  \
        break;                        \
      case DOUBLE:                    \
        apply(double);                \
        break;                        \
      case INT64:                     \
        apply(int64_t);               \
        break;                        \
      case OBJECT:                    \
        apply(ObjectImpl);            \
        break;                        \
      case STRING:                    \
        apply(std::string);           \
        break;                        \
      default:                        \
        CHECK(0);                     \
        abort();                      \
    }                                 \
  } while (0)

bool dynamic::operator<(dynamic const& o) const {
  if (UNLIKELY(type_ == OBJECT || o.type_ == OBJECT)) {
    throwTypeError_("object", type_);
  }
  if (type_ != o.type_) {
    return type_ < o.type_;
  }

#define FB_X(T) return CompareOp<T>::comp(*getAddress<T>(),   \
                                          *o.getAddress<T>())
  FB_DYNAMIC_APPLY(type_, FB_X);
#undef FB_X
}

bool dynamic::operator==(dynamic const& o) const {
  if (type() != o.type()) {
    if (isNumber() && o.isNumber()) {
      auto& integ = isInt() ? *this : o;
      auto& doubl = isInt() ? o     : *this;
      return integ.asInt() == doubl.asDouble();
    }
    return false;
  }

#define FB_X(T) return *getAddress<T>() == *o.getAddress<T>();
  FB_DYNAMIC_APPLY(type_, FB_X);
#undef FB_X
}

dynamic& dynamic::operator=(dynamic const& o) {
  if (&o != this) {
    if (type_ == o.type_) {
#define FB_X(T) *getAddress<T>() = *o.getAddress<T>()
      FB_DYNAMIC_APPLY(type_, FB_X);
#undef FB_X
    } else {
      destroy();
#define FB_X(T) new (getAddress<T>()) T(*o.getAddress<T>())
      FB_DYNAMIC_APPLY(o.type_, FB_X);
#undef FB_X
      type_ = o.type_;
    }
  }
  return *this;
}

dynamic& dynamic::operator=(dynamic&& o) noexcept {
  if (&o != this) {
    if (type_ == o.type_) {
#define FB_X(T) *getAddress<T>() = std::move(*o.getAddress<T>())
      FB_DYNAMIC_APPLY(type_, FB_X);
#undef FB_X
    } else {
      destroy();
#define FB_X(T) new (getAddress<T>()) T(std::move(*o.getAddress<T>()))
      FB_DYNAMIC_APPLY(o.type_, FB_X);
#undef FB_X
      type_ = o.type_;
    }
  }
  return *this;
}

dynamic& dynamic::operator[](dynamic const& k) & {
  if (!isObject() && !isArray()) {
    throwTypeError_("object/array", type());
  }
  if (isArray()) {
    return at(k);
  }
  auto& obj = get<ObjectImpl>();
  auto ret = obj.insert({k, nullptr});
  return ret.first->second;
}

dynamic dynamic::getDefault(const dynamic& k, const dynamic& v) const& {
  auto& obj = get<ObjectImpl>();
  auto it = obj.find(k);
  return it == obj.end() ? v : it->second;
}

dynamic dynamic::getDefault(const dynamic& k, dynamic&& v) const& {
  auto& obj = get<ObjectImpl>();
  auto it = obj.find(k);
  // Avoid clang bug with ternary
  if (it == obj.end()) {
    return std::move(v);
  } else {
    return it->second;
  }
}

dynamic dynamic::getDefault(const dynamic& k, const dynamic& v) && {
  auto& obj = get<ObjectImpl>();
  auto it = obj.find(k);
  // Avoid clang bug with ternary
  if (it == obj.end()) {
    return v;
  } else {
    return std::move(it->second);
  }
}

dynamic dynamic::getDefault(const dynamic& k, dynamic&& v) && {
  auto& obj = get<ObjectImpl>();
  auto it = obj.find(k);
  return std::move(it == obj.end() ? v : it->second);
}

const dynamic* dynamic::get_ptr(dynamic const& idx) const& {
  if (auto* parray = get_nothrow<Array>()) {
    if (!idx.isInt()) {
      throwTypeError_("int64", idx.type());
    }
    if (idx < 0 || idx >= parray->size()) {
      return nullptr;
    }
    return &(*parray)[size_t(idx.asInt())];
  } else if (auto* pobject = get_nothrow<ObjectImpl>()) {
    auto it = pobject->find(idx);
    if (it == pobject->end()) {
      return nullptr;
    }
    return &it->second;
  } else {
    throwTypeError_("object/array", type());
  }
}

[[noreturn]] static void throwOutOfRangeAtMissingKey(dynamic const& idx) {
  auto msg = sformat("couldn't find key {} in dynamic object", idx.asString());
  throw_exception<std::out_of_range>(msg);
}

dynamic const& dynamic::at(dynamic const& idx) const& {
  if (auto* parray = get_nothrow<Array>()) {
    if (!idx.isInt()) {
      throwTypeError_("int64", idx.type());
    }
    if (idx < 0 || idx >= parray->size()) {
      throw_exception<std::out_of_range>("out of range in dynamic array");
    }
    return (*parray)[size_t(idx.asInt())];
  } else if (auto* pobject = get_nothrow<ObjectImpl>()) {
    auto it = pobject->find(idx);
    if (it == pobject->end()) {
      throwOutOfRangeAtMissingKey(idx);
    }
    return it->second;
  } else {
    throwTypeError_("object/array", type());
  }
}

std::size_t dynamic::size() const {
  if (auto* ar = get_nothrow<Array>()) {
    return ar->size();
  }
  if (auto* obj = get_nothrow<ObjectImpl>()) {
    return obj->size();
  }
  if (auto* str = get_nothrow<std::string>()) {
    return str->size();
  }
  throwTypeError_("array/object", type());
}

dynamic::iterator dynamic::erase(const_iterator first, const_iterator last) {
  auto& arr = get<Array>();
  return get<Array>().erase(
    arr.begin() + (first - arr.begin()),
    arr.begin() + (last - arr.begin()));
}

std::size_t dynamic::hash() const {
  switch (type()) {
  case NULLT:
    return 0xBAAAAAAD;
  case OBJECT:
  {
    // Accumulate using addition instead of using hash_range (as in the ARRAY
    // case), as we need a commutative hash operation since unordered_map's
    // iteration order is unspecified.
    auto h = std::hash<std::pair<dynamic, dynamic>>{};
    return std::accumulate(
        items().begin(),
        items().end(),
        size_t{0x0B1EC7},
        [&](auto acc, auto item) { return acc + h(item); });
    }
  case ARRAY:
    return folly::hash::hash_range(begin(), end());
  case INT64:
    return std::hash<int64_t>()(getInt());
  case DOUBLE:
    return std::hash<double>()(getDouble());
  case BOOL:
    return std::hash<bool>()(getBool());
  case STRING: {
    // keep it compatible with FBString
    const auto& str = getString();
    return ::folly::hash::fnv32_buf(str.data(), str.size());
  }
  }
  assume_unreachable();
}

char const* dynamic::typeName(Type t) {
#define FB_X(T) return TypeInfo<T>::name
  FB_DYNAMIC_APPLY(t, FB_X);
#undef FB_X
}

void dynamic::destroy() noexcept {
  // This short-circuit speeds up some microbenchmarks.
  if (type_ == NULLT) {
    return;
  }

#define FB_X(T) detail::Destroy::destroy(getAddress<T>())
  FB_DYNAMIC_APPLY(type_, FB_X);
#undef FB_X
  type_ = NULLT;
  u_.nul = nullptr;
}

dynamic dynamic::merge_diff(const dynamic& source, const dynamic& target) {
  if (!source.isObject() || source.type() != target.type()) {
    return target;
  }

  dynamic diff = object;

  // added/modified keys
  for (const auto& pair : target.items()) {
    auto it = source.find(pair.first);
    if (it == source.items().end()) {
      diff[pair.first] = pair.second;
    } else {
      diff[pair.first] = merge_diff(source[pair.first], target[pair.first]);
    }
  }

  // removed keys
  for (const auto& pair : source.items()) {
    auto it = target.find(pair.first);
    if (it == target.items().end()) {
      diff[pair.first] = nullptr;
    }
  }

  return diff;
}

const dynamic* dynamic::get_ptr(json_pointer const& jsonPtr) const& {
  auto const& tokens = jsonPtr.tokens();
  if (tokens.empty()) {
    return this;
  }
  dynamic const* dyn = this;
  for (auto const& token : tokens) {
    if (!dyn) {
      return nullptr;
    }
    // special case of parsing "/": lookup key with empty name
    if (token.empty()) {
      if (dyn->isObject()) {
        dyn = dyn->get_ptr("");
        continue;
      }
      throwTypeError_("object", dyn->type());
    }
    if (auto* parray = dyn->get_nothrow<dynamic::Array>()) {
      if (token.size() > 1 && token.at(0) == '0') {
        throw std::invalid_argument(
            "Leading zero not allowed when indexing arrays");
      }
      // special case, always return non-existent
      if (token.size() == 1 && token.at(0) == '-') {
        dyn = nullptr;
        continue;
      }
      auto const idx = folly::to<size_t>(token);
      dyn = idx < parray->size() ? &(*parray)[idx] : nullptr;
      continue;
    }
    if (auto* pobject = dyn->get_nothrow<dynamic::ObjectImpl>()) {
      auto const it = pobject->find(token);
      dyn = it != pobject->end() ? &it->second : nullptr;
      continue;
    }
    throwTypeError_("object/array", dyn->type());
  }
  return dyn;
}

//////////////////////////////////////////////////////////////////////

} // namespace folly
<|endoftext|>


<commit_before>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "Node.h"
#include "core/Engine.h"
#include "SceneManager.h"
#include "Layer.h"
#include "animators/Animator.h"
#include "Camera.h"
#include "utils/Utils.h"
#include "math/MathUtils.h"
#include "Component.h"

namespace ouzel
{
    namespace scene
    {
        Node::Node()
        {

        }

        Node::~Node()
        {

        }

        void Node::visit(const Matrix4& newTransformMatrix, bool parentTransformDirty, const LayerPtr& currentLayer)
        {
            if (parentTransformDirty)
            {
                updateTransform(newTransformMatrix);
            }

            if (transformDirty)
            {
                calculateTransform();
            }

            if (currentLayer)
            {
                for (const NodePtr& child : children)
                {
                    if (child->isVisible())
                    {
                        if (child->isGlobalOrder())
                        {
                            currentLayer->addGlobalNode(child);
                        }

                        child->visit(transform, updateChildrenTransform, currentLayer);
                    }
                }
            }

            updateChildrenTransform = false;
        }

        void Node::process(const LayerPtr& currentLayer)
        {
            if (children.empty())
            {
                if (currentLayer->checkVisibility(std::static_pointer_cast<Node>(shared_from_this())))
                {
                    currentLayer->addToDrawQueue(std::static_pointer_cast<Node>(shared_from_this()));
                }
            }
            else
            {
                children.sort([](const NodePtr& a, const NodePtr& b) {
                    return a->getZ() > b->getZ();
                });

                auto i = children.begin();

                for (; i != children.end(); ++i)
                {
                    const NodePtr& node = *i;

                    if (node->getZ() < 0.0f)
                    {
                        if (!node->isGlobalOrder() && node->isVisible() && currentLayer->checkVisibility(node))
                        {
                            currentLayer->addToDrawQueue(node);
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                if (currentLayer->checkVisibility(std::static_pointer_cast<Node>(shared_from_this())))
                {
                    currentLayer->addToDrawQueue(std::static_pointer_cast<Node>(shared_from_this()));
                }

                for (; i != children.end(); ++i)
                {
                    const NodePtr& node = *i;

                    if (!node->isGlobalOrder() && node->isVisible() && currentLayer->checkVisibility(node))
                    {
                        currentLayer->addToDrawQueue(node);
                    }
                }
            }
        }

        void Node::draw(const LayerPtr& currentLayer)
        {
            if (transformDirty)
            {
                calculateTransform();
            }

            if (currentLayer)
            {
                if (currentLayer->getCamera())
                {
                    graphics::Color drawColor(color.r, color.g, color.b, static_cast<uint8_t>(color.a * opacity));

                    for (const ComponentPtr& component : components)
                    {
                        if (component->isVisible())
                        {
                            component->draw(currentLayer->getCamera()->getViewProjection(),
                                            transform,
                                            drawColor,
                                            currentLayer->getRenderTarget(),
                                            std::static_pointer_cast<Node>(shared_from_this()));
                        }
                    }
                }
            }
        }

        bool Node::addChild(const NodePtr& node)
        {
            if (NodeContainer::addChild(node))
            {
                node->updateTransform(getTransform());

                return true;
            }
            else
            {
                return false;
            }
        }

        void Node::setZ(float newZ)
        {
            z = newZ;

            // Currently z does not affect transformation
            //localTransformDirty = transformDirty = inverseTransformDirty = true;
        }

        void Node::setGlobalOrder(bool newGlobalOrder)
        {
            globalOrder = newGlobalOrder;
        }

        void Node::setPosition(const Vector2& newPosition)
        {
            position = newPosition;

            localTransformDirty = transformDirty = inverseTransformDirty = true;
        }

        void Node::setRotation(float newRotation)
        {
            rotation = newRotation;

            localTransformDirty = transformDirty = inverseTransformDirty = true;
        }

        void Node::setScale(const Vector2& newScale)
        {
            scale = newScale;

            localTransformDirty = transformDirty = inverseTransformDirty = true;
        }

        void Node::setColor(const graphics::Color& newColor)
        {
            color = newColor;
        }

        void Node::setOpacity(float newOpacity)
        {
            opacity = clamp(newOpacity, 0.0f, 1.0f);
        }

        void Node::setFlipX(bool newFlipX)
        {
            flipX = newFlipX;

            localTransformDirty = transformDirty = inverseTransformDirty = true;
        }

        void Node::setFlipY(bool newFlipY)
        {
            flipY = newFlipY;

            localTransformDirty = transformDirty = inverseTransformDirty = true;
        }

        void Node::setVisible(bool newVisible)
        {
            visible = newVisible;
        }

        bool Node::pointOn(const Vector2& worldPosition) const
        {
            Vector2 localPosition = convertWorldToLocal(worldPosition);

            for (const ComponentPtr& component : components)
            {
                if (component->pointOn(localPosition))
                {
                    return true;
                }
            }

            return false;
        }

        bool Node::shapeOverlaps(const std::vector<Vector2>& edges) const
        {
            Matrix4 inverse = getInverseTransform();

            std::vector<Vector2> transformedEdges;

            for (const Vector2& edge : edges)
            {
                Vector3 transformedEdge = edge;

                inverse.transformPoint(transformedEdge);

                transformedEdges.push_back(Vector2(transformedEdge.x, transformedEdge.y));
            }

            for (const ComponentPtr& component : components)
            {
                if (component->shapeOverlaps(transformedEdges))
                {
                    return true;
                }
            }

            return false;
        }

        const Matrix4& Node::getTransform() const
        {
            if (transformDirty)
            {
                calculateTransform();
            }

            return transform;
        }

        const Matrix4& Node::getInverseTransform() const
        {
            if (transformDirty)
            {
                calculateTransform();
            }

            if (inverseTransformDirty)
            {
                calculateInverseTransform();
            }

            return inverseTransform;
        }

        void Node::updateTransform(const Matrix4& newParentTransform)
        {
            parentTransform = newParentTransform;
            transformDirty = inverseTransformDirty = true;
        }

        Vector2 Node::convertWorldToLocal(const Vector2& worldPosition) const
        {
            Vector3 localPosition = worldPosition;

            const Matrix4& currentInverseTransform = getInverseTransform();
            currentInverseTransform.transformPoint(localPosition);

            return Vector2(localPosition.x, localPosition.y);
        }

        Vector2 Node::convertLocalToWorld(const Vector2& localPosition) const
        {
            Vector3 worldPosition = localPosition;

            const Matrix4& currentTransform = getTransform();
            currentTransform.transformPoint(worldPosition);

            return Vector2(worldPosition.x, worldPosition.y);
        }

        void Node::animate(const AnimatorPtr& animator)
        {
            stopAnimation();
            currentAnimator = animator;

            if (currentAnimator)
            {
                currentAnimator->start(std::static_pointer_cast<Node>(shared_from_this()));
            }
        }

        void Node::stopAnimation()
        {
            if (currentAnimator)
            {
                currentAnimator->stop();
                removeAnimation();
            }
        }

        void Node::removeAnimation()
        {
            currentAnimator.reset();
        }

        void Node::calculateLocalTransform() const
        {
            localTransform = Matrix4::IDENTITY;
            localTransform.translate(Vector3(position.x, position.y, 0.0f));
            localTransform.rotateZ(TAU - rotation);

            Vector3 realScale = Vector3(scale.x * (flipX ? -1.0f : 1.0f),
                                        scale.y * (flipY ? -1.0f : 1.0f),
                                        1.0f);

            localTransform.scale(realScale);

            localTransformDirty = false;
        }

        void Node::calculateTransform() const
        {
            if (localTransformDirty)
            {
                calculateLocalTransform();
            }

            transform = parentTransform * localTransform;
            transformDirty = false;

            updateChildrenTransform = true;
        }

        void Node::calculateInverseTransform() const
        {
            if (transformDirty)
            {
                calculateTransform();
            }

            inverseTransform = transform;
            inverseTransform.invert();
            inverseTransformDirty = false;
        }

        void Node::addComponent(const ComponentPtr& component)
        {
            components.push_back(component);
        }

        void Node::removeComponent(uint32_t index)
        {
            if (index >= components.size())
            {
                return;
            }

            components.erase(components.begin() + static_cast<int>(index));
        }

        void Node::removeComponent(const ComponentPtr& component)
        {
            for (auto i = components.begin(); i != components.end();)
            {
                if (*i == component)
                {
                    i = components.erase(i);
                }
                else
                {
                    ++i;
                }
            }
        }

        void Node::removeAllComponents()
        {
            components.clear();
        }

    } // namespace scene
} // namespace ouzel
<commit_msg>Rotate transform matrix only if angle is not zero<commit_after>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "Node.h"
#include "core/Engine.h"
#include "SceneManager.h"
#include "Layer.h"
#include "animators/Animator.h"
#include "Camera.h"
#include "utils/Utils.h"
#include "math/MathUtils.h"
#include "Component.h"

namespace ouzel
{
    namespace scene
    {
        Node::Node()
        {

        }

        Node::~Node()
        {

        }

        void Node::visit(const Matrix4& newTransformMatrix, bool parentTransformDirty, const LayerPtr& currentLayer)
        {
            if (parentTransformDirty)
            {
                updateTransform(newTransformMatrix);
            }

            if (transformDirty)
            {
                calculateTransform();
            }

            if (currentLayer)
            {
                for (const NodePtr& child : children)
                {
                    if (child->isVisible())
                    {
                        if (child->isGlobalOrder())
                        {
                            currentLayer->addGlobalNode(child);
                        }

                        child->visit(transform, updateChildrenTransform, currentLayer);
                    }
                }
            }

            updateChildrenTransform = false;
        }

        void Node::process(const LayerPtr& currentLayer)
        {
            if (children.empty())
            {
                if (currentLayer->checkVisibility(std::static_pointer_cast<Node>(shared_from_this())))
                {
                    currentLayer->addToDrawQueue(std::static_pointer_cast<Node>(shared_from_this()));
                }
            }
            else
            {
                children.sort([](const NodePtr& a, const NodePtr& b) {
                    return a->getZ() > b->getZ();
                });

                auto i = children.begin();

                for (; i != children.end(); ++i)
                {
                    const NodePtr& node = *i;

                    if (node->getZ() < 0.0f)
                    {
                        if (!node->isGlobalOrder() && node->isVisible() && currentLayer->checkVisibility(node))
                        {
                            currentLayer->addToDrawQueue(node);
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                if (currentLayer->checkVisibility(std::static_pointer_cast<Node>(shared_from_this())))
                {
                    currentLayer->addToDrawQueue(std::static_pointer_cast<Node>(shared_from_this()));
                }

                for (; i != children.end(); ++i)
                {
                    const NodePtr& node = *i;

                    if (!node->isGlobalOrder() && node->isVisible() && currentLayer->checkVisibility(node))
                    {
                        currentLayer->addToDrawQueue(node);
                    }
                }
            }
        }

        void Node::draw(const LayerPtr& currentLayer)
        {
            if (transformDirty)
            {
                calculateTransform();
            }

            if (currentLayer)
            {
                if (currentLayer->getCamera())
                {
                    graphics::Color drawColor(color.r, color.g, color.b, static_cast<uint8_t>(color.a * opacity));

                    for (const ComponentPtr& component : components)
                    {
                        if (component->isVisible())
                        {
                            component->draw(currentLayer->getCamera()->getViewProjection(),
                                            transform,
                                            drawColor,
                                            currentLayer->getRenderTarget(),
                                            std::static_pointer_cast<Node>(shared_from_this()));
                        }
                    }
                }
            }
        }

        bool Node::addChild(const NodePtr& node)
        {
            if (NodeContainer::addChild(node))
            {
                node->updateTransform(getTransform());

                return true;
            }
            else
            {
                return false;
            }
        }

        void Node::setZ(float newZ)
        {
            z = newZ;

            // Currently z does not affect transformation
            //localTransformDirty = transformDirty = inverseTransformDirty = true;
        }

        void Node::setGlobalOrder(bool newGlobalOrder)
        {
            globalOrder = newGlobalOrder;
        }

        void Node::setPosition(const Vector2& newPosition)
        {
            position = newPosition;

            localTransformDirty = transformDirty = inverseTransformDirty = true;
        }

        void Node::setRotation(float newRotation)
        {
            rotation = newRotation;

            localTransformDirty = transformDirty = inverseTransformDirty = true;
        }

        void Node::setScale(const Vector2& newScale)
        {
            scale = newScale;

            localTransformDirty = transformDirty = inverseTransformDirty = true;
        }

        void Node::setColor(const graphics::Color& newColor)
        {
            color = newColor;
        }

        void Node::setOpacity(float newOpacity)
        {
            opacity = clamp(newOpacity, 0.0f, 1.0f);
        }

        void Node::setFlipX(bool newFlipX)
        {
            flipX = newFlipX;

            localTransformDirty = transformDirty = inverseTransformDirty = true;
        }

        void Node::setFlipY(bool newFlipY)
        {
            flipY = newFlipY;

            localTransformDirty = transformDirty = inverseTransformDirty = true;
        }

        void Node::setVisible(bool newVisible)
        {
            visible = newVisible;
        }

        bool Node::pointOn(const Vector2& worldPosition) const
        {
            Vector2 localPosition = convertWorldToLocal(worldPosition);

            for (const ComponentPtr& component : components)
            {
                if (component->pointOn(localPosition))
                {
                    return true;
                }
            }

            return false;
        }

        bool Node::shapeOverlaps(const std::vector<Vector2>& edges) const
        {
            Matrix4 inverse = getInverseTransform();

            std::vector<Vector2> transformedEdges;

            for (const Vector2& edge : edges)
            {
                Vector3 transformedEdge = edge;

                inverse.transformPoint(transformedEdge);

                transformedEdges.push_back(Vector2(transformedEdge.x, transformedEdge.y));
            }

            for (const ComponentPtr& component : components)
            {
                if (component->shapeOverlaps(transformedEdges))
                {
                    return true;
                }
            }

            return false;
        }

        const Matrix4& Node::getTransform() const
        {
            if (transformDirty)
            {
                calculateTransform();
            }

            return transform;
        }

        const Matrix4& Node::getInverseTransform() const
        {
            if (transformDirty)
            {
                calculateTransform();
            }

            if (inverseTransformDirty)
            {
                calculateInverseTransform();
            }

            return inverseTransform;
        }

        void Node::updateTransform(const Matrix4& newParentTransform)
        {
            parentTransform = newParentTransform;
            transformDirty = inverseTransformDirty = true;
        }

        Vector2 Node::convertWorldToLocal(const Vector2& worldPosition) const
        {
            Vector3 localPosition = worldPosition;

            const Matrix4& currentInverseTransform = getInverseTransform();
            currentInverseTransform.transformPoint(localPosition);

            return Vector2(localPosition.x, localPosition.y);
        }

        Vector2 Node::convertLocalToWorld(const Vector2& localPosition) const
        {
            Vector3 worldPosition = localPosition;

            const Matrix4& currentTransform = getTransform();
            currentTransform.transformPoint(worldPosition);

            return Vector2(worldPosition.x, worldPosition.y);
        }

        void Node::animate(const AnimatorPtr& animator)
        {
            stopAnimation();
            currentAnimator = animator;

            if (currentAnimator)
            {
                currentAnimator->start(std::static_pointer_cast<Node>(shared_from_this()));
            }
        }

        void Node::stopAnimation()
        {
            if (currentAnimator)
            {
                currentAnimator->stop();
                removeAnimation();
            }
        }

        void Node::removeAnimation()
        {
            currentAnimator.reset();
        }

        void Node::calculateLocalTransform() const
        {
            localTransform = Matrix4::IDENTITY;
            localTransform.translate(Vector3(position.x, position.y, 0.0f));
            if (rotation != 0.0f) localTransform.rotateZ(-rotation);

            Vector3 realScale = Vector3(scale.x * (flipX ? -1.0f : 1.0f),
                                        scale.y * (flipY ? -1.0f : 1.0f),
                                        1.0f);

            localTransform.scale(realScale);

            localTransformDirty = false;
        }

        void Node::calculateTransform() const
        {
            if (localTransformDirty)
            {
                calculateLocalTransform();
            }

            transform = parentTransform * localTransform;
            transformDirty = false;

            updateChildrenTransform = true;
        }

        void Node::calculateInverseTransform() const
        {
            if (transformDirty)
            {
                calculateTransform();
            }

            inverseTransform = transform;
            inverseTransform.invert();
            inverseTransformDirty = false;
        }

        void Node::addComponent(const ComponentPtr& component)
        {
            components.push_back(component);
        }

        void Node::removeComponent(uint32_t index)
        {
            if (index >= components.size())
            {
                return;
            }

            components.erase(components.begin() + static_cast<int>(index));
        }

        void Node::removeComponent(const ComponentPtr& component)
        {
            for (auto i = components.begin(); i != components.end();)
            {
                if (*i == component)
                {
                    i = components.erase(i);
                }
                else
                {
                    ++i;
                }
            }
        }

        void Node::removeAllComponents()
        {
            components.clear();
        }

    } // namespace scene
} // namespace ouzel
<|endoftext|>


<commit_before>#include "ofApp.h"

//------------------------------------------------------------------------------
// name: setup()
// desc: set up the app
//------------------------------------------------------------------------------
void ofApp::setup()
{
    ofSetVerticalSync( true );
    ofBackground(0, 0, 0);

    // get singleton
    chuck = TheChucK::instance();
    // arguments
    const char * argv[] = { "the", "-v0" };

    // initialize (SHOULD HAPPEN BEFORE AUDIO STREAM STARTS)
    chuck->initialize( MY_SRATE, MY_BUFFERSIZE, MY_CHANNELS, 2, argv );

    // load image
    OFCKDB::instance()->loadImage("texture:flare-1", "flare-tng-1.png");

    // default
    m_root = new VREntity();
    // add it
    OFCKDB::instance()->setObject("root", m_root);

    // set up light
    m_light = new ofLight();
    m_light->setDiffuseColor( ofColor(100, 255, 100) );
    m_light->enable();
    m_light->setGlobalPosition( 1000, 1000, 1000 );

    // compile and run another file
    // chuck->compileFile( "ck/dot-circle.ck" );
    chuck->compileFile( "ck/flares.ck" );
    // chuck->compileFile( "ck/xform.ck" );
    // chuck->compileFile( "ck/solar.ck" );

    // setup the sound stream...
    soundStream.setup( this,
                       MY_CHANNELS,     // output
                       MY_CHANNELS,               // input
                       MY_SRATE,        // sample rate
                       MY_BUFFERSIZE,   // buffer size
                       MY_NUMBUFFERS ); // num buffer
}

//------------------------------------------------------------------------------
// name: audioIn()
// desc: audio input callback
//------------------------------------------------------------------------------
void ofApp::audioIn( float * input, int bufferSize, int nChannels )
{
    assert( bufferSize == MY_BUFFERSIZE );
    assert( nChannels == MY_CHANNELS );
    chuck->onInput( input, bufferSize );
}

//------------------------------------------------------------------------------
// name: audioOut()
// desc: audio output callback
//------------------------------------------------------------------------------
void ofApp::audioOut( float * output, int bufferSize, int nChannels )
{
    assert( bufferSize == MY_BUFFERSIZE );
    assert( nChannels == MY_CHANNELS );
    // chuck
    chuck->onOutput( output, bufferSize );
}

//------------------------------------------------------------------------------
// name: update()
// desc: update the system
//------------------------------------------------------------------------------
void ofApp::update()
{
    // set background
    ofBackground( 1, 1, 1 );

//    // entity pointer
//    VREntity * e = NULL;
//    // db
//    OFCKDB * db = OFCKDB::instance();
//    // draw list
//    map<string,VREntity *>::iterator i;
//    for( i = db->string2entity.begin(); i != db->string2entity.end(); i++ )
//    {
//        // get entity
//        e = i->second;
//        // draw it
//        e->updateAll(1/60.0f);
//    }

    // db
    OFCKDB * db = OFCKDB::instance();
    // get root
    VREntity * root = db->getObject("root");
    // update it
    root->updateAll(1/60.0f);

    // trigger displaySync to chuck
    chuck->displaySync();
}

//------------------------------------------------------------------------------
// name: draw()
// desc: draw the scene
//------------------------------------------------------------------------------
void ofApp::draw()
{
    // enable depth test
    ofEnableDepthTest();
    // set fov
    m_camera.setFov( 80 );
    // set position
    m_camera.setPosition( ofVec3f(0,0,10) );
    // look at
    m_camera.lookAt( ofVec3f(0,0,0), ofVec3f(0,1,0) );

    // start camera
    m_camera.begin();
    // render light
    m_light->enable();

//    // entity pointer
//    VREntity * e = NULL;
//    // db
//    OFCKDB * db = OFCKDB::instance();
//    // draw list
//    map<string,VREntity *>::iterator i;
//    for( i = db->string2entity.begin(); i != db->string2entity.end(); i++ )
//    {
//        // get entity
//        e = i->second;
//        // draw it
//        e->renderAll();
//    }

    // db
    OFCKDB * db = OFCKDB::instance();
    // get root
    VREntity * root = db->getObject("root");
    // update it
    root->renderAll();

    // undo light
    m_light->disable();

    // done with camera
    m_camera.end();
}

//------------------------------------------------------------------------------
// name: keyPressed()
// desc: on key pressed
//------------------------------------------------------------------------------
void ofApp::keyPressed( int key )
{
}

//------------------------------------------------------------------------------
// name: keyRelease()
// desc: on key released
//------------------------------------------------------------------------------
void ofApp::keyReleased( int key )
{
}

//------------------------------------------------------------------------------
// name: mouseMoved()
// desc: on mouse moved
//------------------------------------------------------------------------------
void ofApp::mouseMoved( int x, int y )
{
    chuck->db()->setFloat( "mouse-x", x );
    chuck->db()->setFloat( "mouse-y", y );
}

//------------------------------------------------------------------------------
// name: mouseDragged()
// desc: on mouse dragged
//------------------------------------------------------------------------------
void ofApp::mouseDragged( int x, int y, int button )
{
}

//------------------------------------------------------------------------------
// name: mousePressed()
// desc: on mouse pressed
//------------------------------------------------------------------------------
void ofApp::mousePressed( int x, int y, int button )
{
}

//------------------------------------------------------------------------------
// name: mouseReleased()
// desc: on mouse released
//------------------------------------------------------------------------------
void ofApp::mouseReleased( int x, int y, int button )
{
}

//------------------------------------------------------------------------------
// name: mouseEntered()
// desc: on mouse entered
//------------------------------------------------------------------------------
void ofApp::mouseEntered( int x, int y )
{
}

//------------------------------------------------------------------------------
// name: mouseExited()
// desc: on mouse exited
//------------------------------------------------------------------------------
void ofApp::mouseExited( int x, int y )
{
}

//------------------------------------------------------------------------------
// name: windowResized()
// desc: on window resized
//------------------------------------------------------------------------------
void ofApp::windowResized( int w, int h )
{
    // log
    cerr << "window resized w: " << w << " h: " << h << endl;
}

//------------------------------------------------------------------------------
// name: gotMessage()
// desc: on receive of message
//------------------------------------------------------------------------------
void ofApp::gotMessage( ofMessage msg )
{
}

//------------------------------------------------------------------------------
// name: dragEvent()
// desc: on drag event
//------------------------------------------------------------------------------
void ofApp::dragEvent( ofDragInfo dragInfo )
{
}
<commit_msg>default chuck example<commit_after>#include "ofApp.h"

//------------------------------------------------------------------------------
// name: setup()
// desc: set up the app
//------------------------------------------------------------------------------
void ofApp::setup()
{
    ofSetVerticalSync( true );
    ofBackground(0, 0, 0);

    // get singleton
    chuck = TheChucK::instance();
    // arguments
    const char * argv[] = { "the", "-v0" };

    // initialize (SHOULD HAPPEN BEFORE AUDIO STREAM STARTS)
    chuck->initialize( MY_SRATE, MY_BUFFERSIZE, MY_CHANNELS, 2, argv );

    // load image
    OFCKDB::instance()->loadImage("texture:flare-1", "flare-tng-1.png");

    // default
    m_root = new VREntity();
    // add it
    OFCKDB::instance()->setObject("root", m_root);

    // set up light
    m_light = new ofLight();
    m_light->setDiffuseColor( ofColor(100, 255, 100) );
    m_light->enable();
    m_light->setGlobalPosition( 1000, 1000, 1000 );

    // compile and run another file
    chuck->compileFile( "ck/solar.ck" );
    // chuck->compileFile( "ck/flares.ck" ); // need audio input
    // chuck->compileFile( "ck/dot-circle.ck" );

    // setup the sound stream...
    soundStream.setup( this,
                       MY_CHANNELS,     // output
                       0,     // input
                       MY_SRATE,        // sample rate
                       MY_BUFFERSIZE,   // buffer size
                       MY_NUMBUFFERS ); // num buffer
}

//------------------------------------------------------------------------------
// name: audioIn()
// desc: audio input callback
//------------------------------------------------------------------------------
void ofApp::audioIn( float * input, int bufferSize, int nChannels )
{
    assert( bufferSize == MY_BUFFERSIZE );
    assert( nChannels == MY_CHANNELS );
    chuck->onInput( input, bufferSize );
}

//------------------------------------------------------------------------------
// name: audioOut()
// desc: audio output callback
//------------------------------------------------------------------------------
void ofApp::audioOut( float * output, int bufferSize, int nChannels )
{
    assert( bufferSize == MY_BUFFERSIZE );
    assert( nChannels == MY_CHANNELS );
    // chuck
    chuck->onOutput( output, bufferSize );
}

//------------------------------------------------------------------------------
// name: update()
// desc: update the system
//------------------------------------------------------------------------------
void ofApp::update()
{
    // set background
    ofBackground( 1, 1, 1 );

//    // entity pointer
//    VREntity * e = NULL;
//    // db
//    OFCKDB * db = OFCKDB::instance();
//    // draw list
//    map<string,VREntity *>::iterator i;
//    for( i = db->string2entity.begin(); i != db->string2entity.end(); i++ )
//    {
//        // get entity
//        e = i->second;
//        // draw it
//        e->updateAll(1/60.0f);
//    }

    // db
    OFCKDB * db = OFCKDB::instance();
    // get root
    VREntity * root = db->getObject("root");
    // update it
    root->updateAll(1/60.0f);

    // trigger displaySync to chuck
    chuck->displaySync();
}

//------------------------------------------------------------------------------
// name: draw()
// desc: draw the scene
//------------------------------------------------------------------------------
void ofApp::draw()
{
    // enable depth test
    ofEnableDepthTest();
    // set fov
    m_camera.setFov( 80 );
    // set position
    m_camera.setPosition( ofVec3f(0,0,10) );
    // look at
    m_camera.lookAt( ofVec3f(0,0,0), ofVec3f(0,1,0) );

    // start camera
    m_camera.begin();
    // render light
    m_light->enable();

//    // entity pointer
//    VREntity * e = NULL;
//    // db
//    OFCKDB * db = OFCKDB::instance();
//    // draw list
//    map<string,VREntity *>::iterator i;
//    for( i = db->string2entity.begin(); i != db->string2entity.end(); i++ )
//    {
//        // get entity
//        e = i->second;
//        // draw it
//        e->renderAll();
//    }

    // db
    OFCKDB * db = OFCKDB::instance();
    // get root
    VREntity * root = db->getObject("root");
    // update it
    root->renderAll();

    // undo light
    m_light->disable();

    // done with camera
    m_camera.end();
}

//------------------------------------------------------------------------------
// name: keyPressed()
// desc: on key pressed
//------------------------------------------------------------------------------
void ofApp::keyPressed( int key )
{
}

//------------------------------------------------------------------------------
// name: keyRelease()
// desc: on key released
//------------------------------------------------------------------------------
void ofApp::keyReleased( int key )
{
}

//------------------------------------------------------------------------------
// name: mouseMoved()
// desc: on mouse moved
//------------------------------------------------------------------------------
void ofApp::mouseMoved( int x, int y )
{
    chuck->db()->setFloat( "mouse-x", x );
    chuck->db()->setFloat( "mouse-y", y );
}

//------------------------------------------------------------------------------
// name: mouseDragged()
// desc: on mouse dragged
//------------------------------------------------------------------------------
void ofApp::mouseDragged( int x, int y, int button )
{
}

//------------------------------------------------------------------------------
// name: mousePressed()
// desc: on mouse pressed
//------------------------------------------------------------------------------
void ofApp::mousePressed( int x, int y, int button )
{
}

//------------------------------------------------------------------------------
// name: mouseReleased()
// desc: on mouse released
//------------------------------------------------------------------------------
void ofApp::mouseReleased( int x, int y, int button )
{
}

//------------------------------------------------------------------------------
// name: mouseEntered()
// desc: on mouse entered
//------------------------------------------------------------------------------
void ofApp::mouseEntered( int x, int y )
{
}

//------------------------------------------------------------------------------
// name: mouseExited()
// desc: on mouse exited
//------------------------------------------------------------------------------
void ofApp::mouseExited( int x, int y )
{
}

//------------------------------------------------------------------------------
// name: windowResized()
// desc: on window resized
//------------------------------------------------------------------------------
void ofApp::windowResized( int w, int h )
{
    // log
    cerr << "window resized w: " << w << " h: " << h << endl;
}

//------------------------------------------------------------------------------
// name: gotMessage()
// desc: on receive of message
//------------------------------------------------------------------------------
void ofApp::gotMessage( ofMessage msg )
{
}

//------------------------------------------------------------------------------
// name: dragEvent()
// desc: on drag event
//------------------------------------------------------------------------------
void ofApp::dragEvent( ofDragInfo dragInfo )
{
}
<|endoftext|>