<commit_before>//===- HexDisassembler.cpp - Disassembler for hex strings -----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements the disassembler of strings of bytes written in
// hexadecimal, from standard input or from a file.
//
//===----------------------------------------------------------------------===//

#include "HexDisassembler.h"

#include "llvm/ADT/OwningPtr.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCDisassembler.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
using namespace llvm;

typedef std::vector<std::pair<unsigned char, const char*> > ByteArrayTy;

namespace {
class VectorMemoryObject : public MemoryObject {
private:
  const ByteArrayTy &Bytes;
public:
  VectorMemoryObject(const ByteArrayTy &bytes) : Bytes(bytes) {}

  uint64_t getBase() const { return 0; }
  uint64_t getExtent() const { return Bytes.size(); }

  int readByte(uint64_t Addr, uint8_t *Byte) const {
    if (Addr > getExtent())
      return -1;
    *Byte = Bytes[Addr].first;
    return 0;
  }
};
}

static bool PrintInst(const llvm::MCDisassembler &DisAsm,
                      llvm::MCInstPrinter &Printer, const ByteArrayTy &Bytes,
                      SourceMgr &SM) {
  // Wrap the vector in a MemoryObject.
  VectorMemoryObject memoryObject(Bytes);

  // Disassemble it to a string and get the size of the instruction.
  MCInst Inst;
  uint64_t Size;

  std::string verboseOStr;
  llvm::raw_string_ostream verboseOS(verboseOStr);

  if (!DisAsm.getInstruction(Inst, Size, memoryObject, 0, verboseOS)) {
    SM.PrintMessage(SMLoc::getFromPointer(Bytes[0].second),
                    "invalid instruction", "error");
    errs() << "Diagnostic log:" << '\n';
    errs() << verboseOS.str() << '\n';
    return true;
  }

  Printer.printInst(&Inst);
  outs() << "\n";

  // If the disassembled instruction was smaller than the number of bytes we
  // read, reject the excess bytes.
  if (Bytes.size() != Size) {
    SM.PrintMessage(SMLoc::getFromPointer(Bytes[Size].second),
                    "excess data detected in input", "error");
    return true;
  }

  return false;
}

int HexDisassembler::disassemble(const Target &T, const std::string &Triple,
                                 MemoryBuffer &Buffer) {
  // Set up disassembler.
  llvm::OwningPtr<const llvm::MCAsmInfo> AsmInfo(T.createAsmInfo(Triple));

  if (!AsmInfo) {
    errs() << "error: no assembly info for target " << Triple << "\n";
    return -1;
  }

  llvm::OwningPtr<const llvm::MCDisassembler> DisAsm(T.createMCDisassembler());
  if (!DisAsm) {
    errs() << "error: no disassembler for target " << Triple << "\n";
    return -1;
  }

  llvm::MCInstPrinter *InstPrinter = T.createMCInstPrinter(0, *AsmInfo, outs());

  if (!InstPrinter) {
    errs() << "error: no instruction printer for target " << Triple << '\n';
    return -1;
  }

  bool ErrorOccurred = false;

  SourceMgr SM;
  SM.AddNewSourceBuffer(&Buffer, SMLoc());

  // Convert the input to a vector for disassembly.
  ByteArrayTy ByteArray;

  StringRef Str = Buffer.getBuffer();
  while (!Str.empty()) {
    // Strip horizontal whitespace.
    if (size_t Pos = Str.find_first_not_of(" \t\r")) {
      Str = Str.substr(Pos);
      continue;
    }

    // If this is the end of a line or start of a comment, process the
    // instruction we have so far.
    if (Str[0] == '\n' || Str[0] == '#') {
      // If we have bytes to process, do so.
      if (!ByteArray.empty()) {
        ErrorOccurred |= PrintInst(*DisAsm, *InstPrinter, ByteArray, SM);
        ByteArray.clear();
      }

      // Strip to the end of line if we already processed any bytes on this
      // line.  This strips the comment and/or the \n.
      if (Str[0] == '\n')
        Str = Str.substr(1);
      else {
        Str = Str.substr(Str.find_first_of('\n'));
        if (!Str.empty())
          Str = Str.substr(1);
      }
      continue;
    }

    // Get the current token.
    size_t Next = Str.find_first_of(" \t\n\r#");
    StringRef Value = Str.substr(0, Next);

    // Convert to a byte and add to the byte vector.
    unsigned ByteVal;
    if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
      // If we have an error, print it and skip to the end of line.
      SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
                                 "invalid input token", "error");
      ErrorOccurred = true;
      Str = Str.substr(Str.find('\n'));
      ByteArray.clear();
      continue;
    }

    ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
    Str = Str.substr(Next);
  }

  if (!ByteArray.empty())
    ErrorOccurred |= PrintInst(*DisAsm, *InstPrinter, ByteArray, SM);

  return ErrorOccurred;
}
<commit_msg>specify what is invalid about it<commit_after>//===- HexDisassembler.cpp - Disassembler for hex strings -----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements the disassembler of strings of bytes written in
// hexadecimal, from standard input or from a file.
//
//===----------------------------------------------------------------------===//

#include "HexDisassembler.h"

#include "llvm/ADT/OwningPtr.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCDisassembler.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
using namespace llvm;

typedef std::vector<std::pair<unsigned char, const char*> > ByteArrayTy;

namespace {
class VectorMemoryObject : public MemoryObject {
private:
  const ByteArrayTy &Bytes;
public:
  VectorMemoryObject(const ByteArrayTy &bytes) : Bytes(bytes) {}

  uint64_t getBase() const { return 0; }
  uint64_t getExtent() const { return Bytes.size(); }

  int readByte(uint64_t Addr, uint8_t *Byte) const {
    if (Addr > getExtent())
      return -1;
    *Byte = Bytes[Addr].first;
    return 0;
  }
};
}

static bool PrintInst(const llvm::MCDisassembler &DisAsm,
                      llvm::MCInstPrinter &Printer, const ByteArrayTy &Bytes,
                      SourceMgr &SM) {
  // Wrap the vector in a MemoryObject.
  VectorMemoryObject memoryObject(Bytes);

  // Disassemble it to a string and get the size of the instruction.
  MCInst Inst;
  uint64_t Size;

  std::string verboseOStr;
  llvm::raw_string_ostream verboseOS(verboseOStr);

  if (!DisAsm.getInstruction(Inst, Size, memoryObject, 0, verboseOS)) {
    SM.PrintMessage(SMLoc::getFromPointer(Bytes[0].second),
                    "invalid instruction encoding", "error");
    errs() << "Diagnostic log:" << '\n';
    errs() << verboseOS.str() << '\n';
    return true;
  }

  Printer.printInst(&Inst);
  outs() << "\n";

  // If the disassembled instruction was smaller than the number of bytes we
  // read, reject the excess bytes.
  if (Bytes.size() != Size) {
    SM.PrintMessage(SMLoc::getFromPointer(Bytes[Size].second),
                    "excess data detected in input", "error");
    return true;
  }

  return false;
}

int HexDisassembler::disassemble(const Target &T, const std::string &Triple,
                                 MemoryBuffer &Buffer) {
  // Set up disassembler.
  llvm::OwningPtr<const llvm::MCAsmInfo> AsmInfo(T.createAsmInfo(Triple));

  if (!AsmInfo) {
    errs() << "error: no assembly info for target " << Triple << "\n";
    return -1;
  }

  llvm::OwningPtr<const llvm::MCDisassembler> DisAsm(T.createMCDisassembler());
  if (!DisAsm) {
    errs() << "error: no disassembler for target " << Triple << "\n";
    return -1;
  }

  llvm::MCInstPrinter *InstPrinter = T.createMCInstPrinter(0, *AsmInfo, outs());

  if (!InstPrinter) {
    errs() << "error: no instruction printer for target " << Triple << '\n';
    return -1;
  }

  bool ErrorOccurred = false;

  SourceMgr SM;
  SM.AddNewSourceBuffer(&Buffer, SMLoc());

  // Convert the input to a vector for disassembly.
  ByteArrayTy ByteArray;

  StringRef Str = Buffer.getBuffer();
  while (!Str.empty()) {
    // Strip horizontal whitespace.
    if (size_t Pos = Str.find_first_not_of(" \t\r")) {
      Str = Str.substr(Pos);
      continue;
    }

    // If this is the end of a line or start of a comment, process the
    // instruction we have so far.
    if (Str[0] == '\n' || Str[0] == '#') {
      // If we have bytes to process, do so.
      if (!ByteArray.empty()) {
        ErrorOccurred |= PrintInst(*DisAsm, *InstPrinter, ByteArray, SM);
        ByteArray.clear();
      }

      // Strip to the end of line if we already processed any bytes on this
      // line.  This strips the comment and/or the \n.
      if (Str[0] == '\n')
        Str = Str.substr(1);
      else {
        Str = Str.substr(Str.find_first_of('\n'));
        if (!Str.empty())
          Str = Str.substr(1);
      }
      continue;
    }

    // Get the current token.
    size_t Next = Str.find_first_of(" \t\n\r#");
    StringRef Value = Str.substr(0, Next);

    // Convert to a byte and add to the byte vector.
    unsigned ByteVal;
    if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
      // If we have an error, print it and skip to the end of line.
      SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
                                 "invalid input token", "error");
      ErrorOccurred = true;
      Str = Str.substr(Str.find('\n'));
      ByteArray.clear();
      continue;
    }

    ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
    Str = Str.substr(Next);
  }

  if (!ByteArray.empty())
    ErrorOccurred |= PrintInst(*DisAsm, *InstPrinter, ByteArray, SM);

  return ErrorOccurred;
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 2008 by Jorrit Tyberghein

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

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

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/scanstr.h"
#include "iengine/sector.h"
#include "iengine/movable.h"
#include "iengine/camera.h"

#include "walktest.h"
#include "lights.h"
#include "splitview.h"
#include "particles.h"
#include "missile.h"

extern void move_mesh (iMeshWrapper* sprite, iSector* where, csVector3 const& pos);

static void RandomColor (float& r, float& g, float& b)
{
  float sig = (float)(900+(rand () % 100))/1000.;
  float sm1= (float)(rand () % 1000)/1000.;
  float sm2 = (float)(rand () % 1000)/1000.;
  switch ((rand ()>>3) % 3)
  {
    default:
    case 0: r = sig; g = sm1; b = sm2; break;
    case 1: r = sm1; g = sig; b = sm2; break;
    case 2: r = sm1; g = sm2; b = sig; break;
  }
}

static void AttachRandomLight (iLight* light)
{
  RandomLight* rl = new RandomLight;
  rl->type = DYN_TYPE_RANDOM;
  rl->dyn_move_dir = 0.2f;
  rl->dyn_move = 0;
  rl->dyn_r1 = rl->dyn_g1 = rl->dyn_b1 = 1;
  WalkDataObject* rldata = new WalkDataObject (rl);
  light->QueryObject ()->ObjAdd (rldata);
  rldata->DecRef ();
}

WalkTestLights::WalkTestLights (WalkTest* walktest) : walktest (walktest)
{
}

void WalkTestLights::DelLight ()
{
  iLightList* ll = walktest->views->GetCamera ()->GetSector ()->GetLights ();
  int i;
  for (i = 0 ; i < ll->GetCount () ; i++)
  {
    iLight* l = ll->Get (i);
    if (l->GetDynamicType () == CS_LIGHT_DYNAMICTYPE_DYNAMIC)
    {
      ll->Remove (l);
      size_t j;
      for (j = 0 ; j < dynamic_lights.GetSize () ; j++)
      {
	if (dynamic_lights[j] == l)
	{
	  dynamic_lights.DeleteIndex (j);
	  break;
	}
      }
      walktest->Report (CS_REPORTER_SEVERITY_NOTIFY, "Dynamic light removed.");
      break;
    }
  }
}

void WalkTestLights::DelLights ()
{
  iLightList* ll = walktest->views->GetCamera ()->GetSector ()->GetLights ();
  int i;
  for (i = 0 ; i < ll->GetCount () ; i++)
  {
    iLight* l = ll->Get (i);
    if (l->GetDynamicType () == CS_LIGHT_DYNAMICTYPE_DYNAMIC)
    {
      ll->Remove (l);
      size_t j;
      for (j = 0 ; j < dynamic_lights.GetSize () ; j++)
      {
	if (dynamic_lights[j] == l)
	{
	  dynamic_lights.DeleteIndex (j);
	  break;
	}
      }
      i--;
    }
  }
  walktest->Report (CS_REPORTER_SEVERITY_NOTIFY, "All dynamic lights deleted.");
}

void WalkTestLights::AddLight (const char* arg)
{
  csVector3 dir (0,0,0);
  csVector3 pos = walktest->views->GetCamera ()->GetTransform ().This2Other (dir);
  csRef<iLight> dyn;

  bool rnd;
  float r, g, b, radius;
  if (arg && csScanStr (arg, "%f,%f,%f,%f", &r, &g, &b, &radius) == 4)
  {
    dyn = walktest->Engine->CreateLight ("", pos,
      radius, csColor (r, g, b), CS_LIGHT_DYNAMICTYPE_DYNAMIC);
    rnd = false;
  }
  else
  {
    dyn = walktest->Engine->CreateLight ("", pos,
      6, csColor (1, 1, 1), CS_LIGHT_DYNAMICTYPE_DYNAMIC);
    rnd = true;
  }
  iLightList* ll = walktest->views->GetCamera ()->GetSector ()->GetLights ();
  ll->Add (dyn);
  dynamic_lights.Push (dyn);
  if (rnd)
    AttachRandomLight (dyn);
  walktest->Report (CS_REPORTER_SEVERITY_NOTIFY, "Dynamic light added.");
}

csRef<iLight> WalkTestLights::CreateRandomLight (const csVector3& pos, iSector* where,
    float dyn_radius)
{
  csRef<iLight> dyn;
  float r, g, b;
  RandomColor (r, g, b);
  dyn = walktest->Engine->CreateLight ("",
    	pos, dyn_radius, csColor(r, g, b), CS_LIGHT_DYNAMICTYPE_DYNAMIC);
  where->GetLights ()->Add (dyn);
  dynamic_lights.Push (dyn);
  return dyn;
}

csReversibleTransform WalkTestLights::FlashlightShift (const csReversibleTransform& tf)
{
  csReversibleTransform newTF (tf);
  // Tilt flashlight a bit down
  csMatrix3 newmat (tf.GetT2O());
  newmat *= csXRotMatrix3 (float ((10.0/180.0)*PI));
  newTF.SetT2O (newmat);
  return newTF;
}

void WalkTestLights::EnableFlashlight (bool enable)
{
  if (enable && !flashlight)
  {
    static const float flashlightIntensity = 5.0f;

    flashlight = walktest->Engine->CreateLight ("flashlight",
      csVector3 (0),
      flashlightIntensity*256,
      csColor (flashlightIntensity),
      CS_LIGHT_DYNAMICTYPE_DYNAMIC);
    flashlight->SetType (CS_LIGHT_SPOTLIGHT);
    flashlight->SetAttenuationMode (CS_ATTN_INVERSE);
    flashlight->SetSpotLightFalloff (1, cosf ((25.0/180.0)*PI));

    iLightList* ll = walktest->views->GetCamera ()->GetSector ()->GetLights ();
    ll->Add (flashlight);

    flashlight->GetMovable()->SetTransform (FlashlightShift (walktest->views->GetCamera ()->GetTransform ()));
    flashlight->GetMovable()->UpdateMove();
  }
  else if (!enable && flashlight)
  {
    iLightList* ll = flashlight->GetMovable()->GetSectors()->Get (0)->GetLights ();
    ll->Remove (flashlight);
    flashlight.Invalidate();
  }
}

void WalkTestLights::HandleDynLights ()
{
  if (flashlight)
  {
    iSector* oldsector = flashlight->GetMovable()->GetSectors()->Get (0);
    iSector* newSector = walktest->views->GetCamera ()->GetSector();
    if (oldsector != newSector)
    {
      iLightList* ll = oldsector->GetLights();
      ll->Remove (flashlight);
    }
    if (oldsector != newSector)
    {
      iLightList* ll = walktest->views->GetCamera ()->GetSector ()->GetLights ();
      ll->Add (flashlight);
    }
    flashlight->GetMovable()->SetTransform (FlashlightShift (walktest->views->GetCamera ()->GetTransform ()));
    flashlight->GetMovable()->UpdateMove();
  }

  size_t i;
  for (i = 0 ; i < dynamic_lights.GetSize () ; i++)
  {
    iLight* dyn = dynamic_lights[i];
    csRef<WalkDataObject> dao (
        CS::GetChildObject<WalkDataObject>(dyn->QueryObject()));
    if (dao)
      if (HandleDynLight (dyn))
      {
        dynamic_lights.DeleteIndex (i);
	i--;
      }
  }
}

bool WalkTestLights::HandleDynLight (iLight* dyn)
{
  LightStruct* ls = (LightStruct*)(WalkDataObject::GetData(dyn->QueryObject ()));
  switch (ls->type)
  {
  case DYN_TYPE_MISSILE:
    {
      MissileStruct* ms = (MissileStruct*)(WalkDataObject::GetData(
        dyn->QueryObject ()));
      csVector3 v (0, 0, 2.5);
      csVector3 old = dyn->GetMovable()->GetPosition ();
      v = old + ms->dir.GetT2O () * v;
      iSector* s = dyn->GetMovable()->GetSectors()->Get(0);
      bool mirror = false;
      csVector3 old_v = v;
      s = s->FollowSegment (ms->dir, v, mirror);
      if (ABS (v.x-old_v.x) > SMALL_EPSILON ||
        ABS (v.y-old_v.y) > SMALL_EPSILON ||
        ABS (v.z-old_v.z) > SMALL_EPSILON)
      {
        v = old;
        if (ms->sprite)
        {
          ms->sprite->GetMovable ()->ClearSectors ();
          Sys->Engine->GetMeshes ()->Remove (ms->sprite);
        }
        csRef<WalkDataObject> ido (
          CS::GetChildObject<WalkDataObject>(dyn->QueryObject()));
        dyn->QueryObject ()->ObjRemove (ido);
        if (ms->snd)
        {
          ms->snd_stream->Pause();
        }
        delete ms;
        if (Sys->mySound)
        {
          if (Sys->wMissile_boom)
          {
            csRef<iSndSysStream> st = Sys->mySound->CreateStream (
              Sys->wMissile_boom->GetData (), CS_SND3D_ABSOLUTE);
            csRef<iSndSysSource> sndsource = Sys->mySound->
              CreateSource (st);
            if (sndsource)
            {
              csRef<iSndSysSource3D> sndsource3d
                = scfQueryInterface<iSndSysSource3D> (sndsource);

              sndsource3d->SetPosition (v);
              sndsource->SetVolume (1.0f);
              st->SetLoopState (CS_SNDSYS_STREAM_DONTLOOP);
              st->Unpause ();
            }
          }
        }
        ExplosionStruct* es = new ExplosionStruct;
        es->type = DYN_TYPE_EXPLOSION;
        es->radius = 2;
        es->dir = 1;
        WalkDataObject* esdata = new WalkDataObject (es);
        dyn->QueryObject ()->ObjAdd (esdata);
        esdata->DecRef ();
        WalkTestParticleDemos::Explosion (Sys,
          dyn->GetMovable ()->GetSectors ()->Get (0),
          dyn->GetMovable ()->GetPosition (), "explo");
        return false;
      }
      else ms->dir.SetOrigin (v);
      iSector* sector = dyn->GetMovable ()->GetSectors ()->Get (0);
      if (sector != s)
      {
        dyn->IncRef ();
        sector->GetLights ()->Remove (dyn);
        s->GetLights ()->Add (dyn);
        dyn->DecRef ();
      }
      dyn->GetMovable ()->SetPosition (v);
      if (ms->sprite) move_mesh (ms->sprite, s, v);
      if (Sys->mySound && ms->snd)
      {
        csRef<iSndSysSource3D> sndsource3d
          = scfQueryInterface<iSndSysSource3D> (ms->snd);
        sndsource3d->SetPosition (v);
        ms->snd->SetVolume (1.0f);
      }
      break;
    }
  case DYN_TYPE_EXPLOSION:
    {
      ExplosionStruct* es = (ExplosionStruct*)(WalkDataObject::GetData(
        dyn->QueryObject ()));
      if (es->dir == 1)
      {
        es->radius += 3;
	if (es->radius > 6) es->dir = -1;
      }
      else
      {
        es->radius -= 2;
	if (es->radius < 1)
	{
	  csRef<WalkDataObject> ido (
		CS::GetChildObject<WalkDataObject>(dyn->QueryObject()));
	  dyn->QueryObject ()->ObjRemove (ido);
	  delete es;
    iSector* sector = dyn->GetMovable ()->GetSectors ()->Get (0);
	  sector->GetLights ()->Remove (dyn);
	  return true;
	}
      }
      dyn->SetCutoffDistance (es->radius);
      break;
    }
    case DYN_TYPE_RANDOM:
    {
      RandomLight* rl = (RandomLight*)(WalkDataObject::GetData(
      	dyn->QueryObject ()));
      rl->dyn_move += rl->dyn_move_dir;
      if (rl->dyn_move < 0 || rl->dyn_move > 2)
      	rl->dyn_move_dir = -rl->dyn_move_dir;
      if (ABS (rl->dyn_r1-dyn->GetColor ().red) < .01 &&
      	  ABS (rl->dyn_g1-dyn->GetColor ().green) < .01 &&
	  ABS (rl->dyn_b1-dyn->GetColor ().blue) < .01)
        RandomColor (rl->dyn_r1, rl->dyn_g1, rl->dyn_b1);
      else
        dyn->SetColor (csColor ((rl->dyn_r1+7.*dyn->GetColor ().red)/8.,
		(rl->dyn_g1+7.*dyn->GetColor ().green)/8.,
		(rl->dyn_b1+7.*dyn->GetColor ().blue)/8.));
      dyn->GetMovable()->SetPosition (dyn->GetMovable()->GetPosition () + csVector3 (0, rl->dyn_move_dir, 0));
      dyn->GetMovable()->UpdateMove();
      break;
    }
  }
  return false;
}

<commit_msg>- Compile warning fix.<commit_after>/*
    Copyright (C) 2008 by Jorrit Tyberghein

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

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

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/scanstr.h"
#include "iengine/sector.h"
#include "iengine/movable.h"
#include "iengine/camera.h"

#include "walktest.h"
#include "lights.h"
#include "splitview.h"
#include "particles.h"
#include "missile.h"

extern void move_mesh (iMeshWrapper* sprite, iSector* where, csVector3 const& pos);

static void RandomColor (float& r, float& g, float& b)
{
  float sig = (float)(900+(rand () % 100))/1000.;
  float sm1= (float)(rand () % 1000)/1000.;
  float sm2 = (float)(rand () % 1000)/1000.;
  switch ((rand ()>>3) % 3)
  {
    default:
    case 0: r = sig; g = sm1; b = sm2; break;
    case 1: r = sm1; g = sig; b = sm2; break;
    case 2: r = sm1; g = sm2; b = sig; break;
  }
}

static void AttachRandomLight (iLight* light)
{
  RandomLight* rl = new RandomLight;
  rl->type = DYN_TYPE_RANDOM;
  rl->dyn_move_dir = 0.2f;
  rl->dyn_move = 0;
  rl->dyn_r1 = rl->dyn_g1 = rl->dyn_b1 = 1;
  WalkDataObject* rldata = new WalkDataObject (rl);
  light->QueryObject ()->ObjAdd (rldata);
  rldata->DecRef ();
}

WalkTestLights::WalkTestLights (WalkTest* walktest) : walktest (walktest)
{
}

void WalkTestLights::DelLight ()
{
  iLightList* ll = walktest->views->GetCamera ()->GetSector ()->GetLights ();
  int i;
  for (i = 0 ; i < ll->GetCount () ; i++)
  {
    iLight* l = ll->Get (i);
    if (l->GetDynamicType () == CS_LIGHT_DYNAMICTYPE_DYNAMIC)
    {
      ll->Remove (l);
      size_t j;
      for (j = 0 ; j < dynamic_lights.GetSize () ; j++)
      {
	if (dynamic_lights[j] == l)
	{
	  dynamic_lights.DeleteIndex (j);
	  break;
	}
      }
      walktest->Report (CS_REPORTER_SEVERITY_NOTIFY, "Dynamic light removed.");
      break;
    }
  }
}

void WalkTestLights::DelLights ()
{
  iLightList* ll = walktest->views->GetCamera ()->GetSector ()->GetLights ();
  int i;
  for (i = 0 ; i < ll->GetCount () ; i++)
  {
    iLight* l = ll->Get (i);
    if (l->GetDynamicType () == CS_LIGHT_DYNAMICTYPE_DYNAMIC)
    {
      ll->Remove (l);
      size_t j;
      for (j = 0 ; j < dynamic_lights.GetSize () ; j++)
      {
	if (dynamic_lights[j] == l)
	{
	  dynamic_lights.DeleteIndex (j);
	  break;
	}
      }
      i--;
    }
  }
  walktest->Report (CS_REPORTER_SEVERITY_NOTIFY, "All dynamic lights deleted.");
}

void WalkTestLights::AddLight (const char* arg)
{
  csVector3 dir (0,0,0);
  csVector3 pos = walktest->views->GetCamera ()->GetTransform ().This2Other (dir);
  csRef<iLight> dyn;

  bool rnd;
  float r, g, b, radius;
  if (arg && csScanStr (arg, "%f,%f,%f,%f", &r, &g, &b, &radius) == 4)
  {
    dyn = walktest->Engine->CreateLight ("", pos,
      radius, csColor (r, g, b), CS_LIGHT_DYNAMICTYPE_DYNAMIC);
    rnd = false;
  }
  else
  {
    dyn = walktest->Engine->CreateLight ("", pos,
      6, csColor (1, 1, 1), CS_LIGHT_DYNAMICTYPE_DYNAMIC);
    rnd = true;
  }
  iLightList* ll = walktest->views->GetCamera ()->GetSector ()->GetLights ();
  ll->Add (dyn);
  dynamic_lights.Push (dyn);
  if (rnd)
    AttachRandomLight (dyn);
  walktest->Report (CS_REPORTER_SEVERITY_NOTIFY, "Dynamic light added.");
}

csRef<iLight> WalkTestLights::CreateRandomLight (const csVector3& pos, iSector* where,
    float dyn_radius)
{
  csRef<iLight> dyn;
  float r, g, b;
  RandomColor (r, g, b);
  dyn = walktest->Engine->CreateLight ("",
    	pos, dyn_radius, csColor(r, g, b), CS_LIGHT_DYNAMICTYPE_DYNAMIC);
  where->GetLights ()->Add (dyn);
  dynamic_lights.Push (dyn);
  return dyn;
}

csReversibleTransform WalkTestLights::FlashlightShift (const csReversibleTransform& tf)
{
  csReversibleTransform newTF (tf);
  // Tilt flashlight a bit down
  csMatrix3 newmat (tf.GetT2O());
  newmat *= csXRotMatrix3 (float ((10.0/180.0)*PI));
  newTF.SetT2O (newmat);
  return newTF;
}

void WalkTestLights::EnableFlashlight (bool enable)
{
  if (enable && !flashlight)
  {
    static const float flashlightIntensity = 5.0f;

    flashlight = walktest->Engine->CreateLight ("flashlight",
      csVector3 (0),
      flashlightIntensity*256,
      csColor (flashlightIntensity),
      CS_LIGHT_DYNAMICTYPE_DYNAMIC);
    flashlight->SetType (CS_LIGHT_SPOTLIGHT);
    flashlight->SetAttenuationMode (CS_ATTN_INVERSE);
    flashlight->SetSpotLightFalloff (1, cosf ((25.0f/180.0f)*PI));

    iLightList* ll = walktest->views->GetCamera ()->GetSector ()->GetLights ();
    ll->Add (flashlight);

    flashlight->GetMovable()->SetTransform (FlashlightShift (walktest->views->GetCamera ()->GetTransform ()));
    flashlight->GetMovable()->UpdateMove();
  }
  else if (!enable && flashlight)
  {
    iLightList* ll = flashlight->GetMovable()->GetSectors()->Get (0)->GetLights ();
    ll->Remove (flashlight);
    flashlight.Invalidate();
  }
}

void WalkTestLights::HandleDynLights ()
{
  if (flashlight)
  {
    iSector* oldsector = flashlight->GetMovable()->GetSectors()->Get (0);
    iSector* newSector = walktest->views->GetCamera ()->GetSector();
    if (oldsector != newSector)
    {
      iLightList* ll = oldsector->GetLights();
      ll->Remove (flashlight);
    }
    if (oldsector != newSector)
    {
      iLightList* ll = walktest->views->GetCamera ()->GetSector ()->GetLights ();
      ll->Add (flashlight);
    }
    flashlight->GetMovable()->SetTransform (FlashlightShift (walktest->views->GetCamera ()->GetTransform ()));
    flashlight->GetMovable()->UpdateMove();
  }

  size_t i;
  for (i = 0 ; i < dynamic_lights.GetSize () ; i++)
  {
    iLight* dyn = dynamic_lights[i];
    csRef<WalkDataObject> dao (
        CS::GetChildObject<WalkDataObject>(dyn->QueryObject()));
    if (dao)
      if (HandleDynLight (dyn))
      {
        dynamic_lights.DeleteIndex (i);
	i--;
      }
  }
}

bool WalkTestLights::HandleDynLight (iLight* dyn)
{
  LightStruct* ls = (LightStruct*)(WalkDataObject::GetData(dyn->QueryObject ()));
  switch (ls->type)
  {
  case DYN_TYPE_MISSILE:
    {
      MissileStruct* ms = (MissileStruct*)(WalkDataObject::GetData(
        dyn->QueryObject ()));
      csVector3 v (0, 0, 2.5);
      csVector3 old = dyn->GetMovable()->GetPosition ();
      v = old + ms->dir.GetT2O () * v;
      iSector* s = dyn->GetMovable()->GetSectors()->Get(0);
      bool mirror = false;
      csVector3 old_v = v;
      s = s->FollowSegment (ms->dir, v, mirror);
      if (ABS (v.x-old_v.x) > SMALL_EPSILON ||
        ABS (v.y-old_v.y) > SMALL_EPSILON ||
        ABS (v.z-old_v.z) > SMALL_EPSILON)
      {
        v = old;
        if (ms->sprite)
        {
          ms->sprite->GetMovable ()->ClearSectors ();
          Sys->Engine->GetMeshes ()->Remove (ms->sprite);
        }
        csRef<WalkDataObject> ido (
          CS::GetChildObject<WalkDataObject>(dyn->QueryObject()));
        dyn->QueryObject ()->ObjRemove (ido);
        if (ms->snd)
        {
          ms->snd_stream->Pause();
        }
        delete ms;
        if (Sys->mySound)
        {
          if (Sys->wMissile_boom)
          {
            csRef<iSndSysStream> st = Sys->mySound->CreateStream (
              Sys->wMissile_boom->GetData (), CS_SND3D_ABSOLUTE);
            csRef<iSndSysSource> sndsource = Sys->mySound->
              CreateSource (st);
            if (sndsource)
            {
              csRef<iSndSysSource3D> sndsource3d
                = scfQueryInterface<iSndSysSource3D> (sndsource);

              sndsource3d->SetPosition (v);
              sndsource->SetVolume (1.0f);
              st->SetLoopState (CS_SNDSYS_STREAM_DONTLOOP);
              st->Unpause ();
            }
          }
        }
        ExplosionStruct* es = new ExplosionStruct;
        es->type = DYN_TYPE_EXPLOSION;
        es->radius = 2;
        es->dir = 1;
        WalkDataObject* esdata = new WalkDataObject (es);
        dyn->QueryObject ()->ObjAdd (esdata);
        esdata->DecRef ();
        WalkTestParticleDemos::Explosion (Sys,
          dyn->GetMovable ()->GetSectors ()->Get (0),
          dyn->GetMovable ()->GetPosition (), "explo");
        return false;
      }
      else ms->dir.SetOrigin (v);
      iSector* sector = dyn->GetMovable ()->GetSectors ()->Get (0);
      if (sector != s)
      {
        dyn->IncRef ();
        sector->GetLights ()->Remove (dyn);
        s->GetLights ()->Add (dyn);
        dyn->DecRef ();
      }
      dyn->GetMovable ()->SetPosition (v);
      if (ms->sprite) move_mesh (ms->sprite, s, v);
      if (Sys->mySound && ms->snd)
      {
        csRef<iSndSysSource3D> sndsource3d
          = scfQueryInterface<iSndSysSource3D> (ms->snd);
        sndsource3d->SetPosition (v);
        ms->snd->SetVolume (1.0f);
      }
      break;
    }
  case DYN_TYPE_EXPLOSION:
    {
      ExplosionStruct* es = (ExplosionStruct*)(WalkDataObject::GetData(
        dyn->QueryObject ()));
      if (es->dir == 1)
      {
        es->radius += 3;
	if (es->radius > 6) es->dir = -1;
      }
      else
      {
        es->radius -= 2;
	if (es->radius < 1)
	{
	  csRef<WalkDataObject> ido (
		CS::GetChildObject<WalkDataObject>(dyn->QueryObject()));
	  dyn->QueryObject ()->ObjRemove (ido);
	  delete es;
    iSector* sector = dyn->GetMovable ()->GetSectors ()->Get (0);
	  sector->GetLights ()->Remove (dyn);
	  return true;
	}
      }
      dyn->SetCutoffDistance (es->radius);
      break;
    }
    case DYN_TYPE_RANDOM:
    {
      RandomLight* rl = (RandomLight*)(WalkDataObject::GetData(
      	dyn->QueryObject ()));
      rl->dyn_move += rl->dyn_move_dir;
      if (rl->dyn_move < 0 || rl->dyn_move > 2)
      	rl->dyn_move_dir = -rl->dyn_move_dir;
      if (ABS (rl->dyn_r1-dyn->GetColor ().red) < .01 &&
      	  ABS (rl->dyn_g1-dyn->GetColor ().green) < .01 &&
	  ABS (rl->dyn_b1-dyn->GetColor ().blue) < .01)
        RandomColor (rl->dyn_r1, rl->dyn_g1, rl->dyn_b1);
      else
        dyn->SetColor (csColor ((rl->dyn_r1+7.*dyn->GetColor ().red)/8.,
		(rl->dyn_g1+7.*dyn->GetColor ().green)/8.,
		(rl->dyn_b1+7.*dyn->GetColor ().blue)/8.));
      dyn->GetMovable()->SetPosition (dyn->GetMovable()->GetPosition () + csVector3 (0, rl->dyn_move_dir, 0));
      dyn->GetMovable()->UpdateMove();
      break;
    }
  }
  return false;
}

<|endoftext|>


<commit_before><commit_msg>transformmetric: fixed normalisation to voxel size<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: toolsdll.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 14:47:16 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SVWIN_H
#include <svwin.h>
#endif

#ifndef _DLL_HXX
#include <dll.hxx>
#endif
#ifndef _TOOLSDLL_HXX
#include <toolsdll.hxx>
#endif
#ifndef _SHL_HXX
#include <shl.hxx>
#endif

// =======================================================================

#ifdef WNT

static void* aAppData[SHL_COUNT];

// -----------------------------------------------------------------------

void** GetAppData( USHORT nSharedLib )
{
    return &(aAppData[nSharedLib]);
}

#endif
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.118); FILE MERGED 2006/09/01 17:55:01 kaib 1.3.118.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: toolsdll.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 01:06:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"

#ifndef _SVWIN_H
#include <svwin.h>
#endif

#ifndef _DLL_HXX
#include <dll.hxx>
#endif
#ifndef _TOOLSDLL_HXX
#include <toolsdll.hxx>
#endif
#ifndef _SHL_HXX
#include <shl.hxx>
#endif

// =======================================================================

#ifdef WNT

static void* aAppData[SHL_COUNT];

// -----------------------------------------------------------------------

void** GetAppData( USHORT nSharedLib )
{
    return &(aAppData[nSharedLib]);
}

#endif
<|endoftext|>


<commit_before>#include "common.h"
#include "World.h"
#include "FileSystem.h"
#include "endian.h"

Atomic<bool> World::exists;

void World::Init() {
	uint32_t seed;
	auto savesPath = FileSystem::GetSavedGamesDir();
	auto seedPath = savesPath + "/seed";

	if(FileSystem::FileExists(seedPath)) {
		auto seedString = FileSystem::ReadFile(seedPath);
		auto ss = std::stringstream(seedString);
		Deserializer(ss) >> seed;
	} else {
		seed = std::random_device()();
		auto ss = std::stringstream();
		Serializer(ss) << seed;
		FileSystem::WriteFile(seedPath, ss);
	}

	noise = OpenSimplexNoise(seed);
}

void World::Update(DeltaTicks &) {
	auto pair = engine->objects.right.equal_range(&typeid(PlayerCameraComponent));
	for(auto it = pair.first; it != pair.second; ++it) {
		auto &object = it->get_left();

		auto pos = engine->GetComponent<PositionComponent>(object);
		if(pos != nullptr) {
			auto chunkCoord = ChunkCoordForPos(pos->position.Get());
			auto jobM = engine->systems.Get<JobManager>().lock();

			/* clean up chunks outside distance */
			auto &eng = engine;
			auto &viewDist = viewDistance;
			chunks.With([&eng, &viewDist, &jobM, &chunkCoord] (ChunksType &chunks) {
				for(auto it = chunks.begin(); it != chunks.end();) {
					auto &coordTuple = it->first;
					auto &obj = std::get<1>(it->second);

					if(abs(static_cast<int>(std::get<0>(coordTuple)) - chunkCoord.x) > viewDist ||
					   abs(static_cast<int>(std::get<1>(coordTuple)) - chunkCoord.y) > viewDist ||
					   abs(static_cast<int>(std::get<2>(coordTuple)) - chunkCoord.z) > viewDist) {
						auto &status = std::get<0>(it->second);
						switch(status) {
						case ChunkStatus::Generating:
							status = ChunkStatus::Dying;
							break;
						case ChunkStatus::Alive:
						case ChunkStatus::Dead:
							jobM->Do([&eng, obj] () { eng->RemoveObject(obj); }, JobPriority::Low, JobThread::Main);
							chunks.erase(it++);
							continue;
						case ChunkStatus::Dying:
							break;
						}
					}
					++it;
				}
			});

			for(int d = 0; d <= viewDistance; ++d) {
				for(int x = -d; x <= d; ++x) {
					for(int y = -d; y <= d; ++y) {
						for(int z = -d; z <= d; ++z) {
							/* only operate on outer ring so at least one of x y z must have absolute value of d */
							if(glm::abs(x) != d && glm::abs(y) != d && glm::abs(z) != d) { continue; }

							auto coord = chunkCoord + Point3(x, y, z);
							ChunkKeyType coordTuple = std::make_tuple(static_cast<uint64_t>(coord.x),
							                                          static_cast<uint64_t>(coord.y),
							                                          static_cast<uint64_t>(coord.z));

							if(chunks.With<bool>([&coordTuple] (ChunksType &chunks) {
								return chunks.find(coordTuple) == chunks.end();
							})) {
								chunks.With([&coordTuple] (ChunksType &chunks) {
									chunks.emplace(coordTuple, std::make_tuple(ChunkStatus::Generating, 0));
								});
								jobM->Do([this, jobM, coord] () {
									auto e = exists.With<bool>([] (bool &exists) { return exists; });
									if(e == false) { return; }

									/* create tuple again inside of copying by binding to lambda
									 * tuples are packed at compile-time anyway or something
									 */
									ChunkKeyType coordTuple = std::make_tuple(static_cast<uint64_t>(coord.x),
																			  static_cast<uint64_t>(coord.y),
																			  static_cast<uint64_t>(coord.z));

									auto dead = chunks.With<bool>([&coordTuple] (ChunksType &chunks) {
										auto &status = std::get<0>(chunks.at(coordTuple));
										if(status == ChunkStatus::Dying) {
											status = ChunkStatus::Dead;
											return true;
										} else { return false; }
									});
									if(dead) { return; }

									auto savesPath = FileSystem::GetSavedGamesDir();
									auto icoord = glm::ivec3(glm::floor(coord));
									auto chunkPath = savesPath + "/chunks/" + std::to_string(icoord.x) + "_" + std::to_string(icoord.y) + "_" + std::to_string(icoord.z) + ".chunk";

									auto blocks = GenerateChunk(coord);
									CreateChunk(coord, blocks, true);
								}, JobPriority::Normal, JobThread::Worker);
							}
						}
					}
				}
			}
		}
	}
}

World::~World() {
	exists.With([this] (bool &exists) {
		exists = false;
		chunks.With([this] (ChunksType &chunks) {
			for(auto it = chunks.begin(); it != chunks.end(); ++it) {
				engine->RemoveObject(std::get<1>(it->second));
			}
		});
	});
}
<commit_msg>Remove seed saving/loading code<commit_after>#include "common.h"
#include "World.h"
#include "FileSystem.h"
#include "endian.h"

Atomic<bool> World::exists;

void World::Init() {
	uint32_t seed = std::random_device()();
	noise = OpenSimplexNoise(seed);
}

void World::Update(DeltaTicks &) {
	auto pair = engine->objects.right.equal_range(&typeid(PlayerCameraComponent));
	for(auto it = pair.first; it != pair.second; ++it) {
		auto &object = it->get_left();

		auto pos = engine->GetComponent<PositionComponent>(object);
		if(pos != nullptr) {
			auto chunkCoord = ChunkCoordForPos(pos->position.Get());
			auto jobM = engine->systems.Get<JobManager>().lock();

			/* clean up chunks outside distance */
			auto &eng = engine;
			auto &viewDist = viewDistance;
			chunks.With([&eng, &viewDist, &jobM, &chunkCoord] (ChunksType &chunks) {
				for(auto it = chunks.begin(); it != chunks.end();) {
					auto &coordTuple = it->first;
					auto &obj = std::get<1>(it->second);

					if(abs(static_cast<int>(std::get<0>(coordTuple)) - chunkCoord.x) > viewDist ||
					   abs(static_cast<int>(std::get<1>(coordTuple)) - chunkCoord.y) > viewDist ||
					   abs(static_cast<int>(std::get<2>(coordTuple)) - chunkCoord.z) > viewDist) {
						auto &status = std::get<0>(it->second);
						switch(status) {
						case ChunkStatus::Generating:
							status = ChunkStatus::Dying;
							break;
						case ChunkStatus::Alive:
						case ChunkStatus::Dead:
							jobM->Do([&eng, obj] () { eng->RemoveObject(obj); }, JobPriority::Low, JobThread::Main);
							chunks.erase(it++);
							continue;
						case ChunkStatus::Dying:
							break;
						}
					}
					++it;
				}
			});

			for(int d = 0; d <= viewDistance; ++d) {
				for(int x = -d; x <= d; ++x) {
					for(int y = -d; y <= d; ++y) {
						for(int z = -d; z <= d; ++z) {
							/* only operate on outer ring so at least one of x y z must have absolute value of d */
							if(glm::abs(x) != d && glm::abs(y) != d && glm::abs(z) != d) { continue; }

							auto coord = chunkCoord + Point3(x, y, z);
							ChunkKeyType coordTuple = std::make_tuple(static_cast<uint64_t>(coord.x),
							                                          static_cast<uint64_t>(coord.y),
							                                          static_cast<uint64_t>(coord.z));

							if(chunks.With<bool>([&coordTuple] (ChunksType &chunks) {
								return chunks.find(coordTuple) == chunks.end();
							})) {
								chunks.With([&coordTuple] (ChunksType &chunks) {
									chunks.emplace(coordTuple, std::make_tuple(ChunkStatus::Generating, 0));
								});
								jobM->Do([this, jobM, coord] () {
									auto e = exists.With<bool>([] (bool &exists) { return exists; });
									if(e == false) { return; }

									/* create tuple again inside of copying by binding to lambda
									 * tuples are packed at compile-time anyway or something
									 */
									ChunkKeyType coordTuple = std::make_tuple(static_cast<uint64_t>(coord.x),
																			  static_cast<uint64_t>(coord.y),
																			  static_cast<uint64_t>(coord.z));

									auto dead = chunks.With<bool>([&coordTuple] (ChunksType &chunks) {
										auto &status = std::get<0>(chunks.at(coordTuple));
										if(status == ChunkStatus::Dying) {
											status = ChunkStatus::Dead;
											return true;
										} else { return false; }
									});
									if(dead) { return; }

									auto savesPath = FileSystem::GetSavedGamesDir();
									auto icoord = glm::ivec3(glm::floor(coord));
									auto chunkPath = savesPath + "/chunks/" + std::to_string(icoord.x) + "_" + std::to_string(icoord.y) + "_" + std::to_string(icoord.z) + ".chunk";

									auto blocks = GenerateChunk(coord);
									CreateChunk(coord, blocks, true);
								}, JobPriority::Normal, JobThread::Worker);
							}
						}
					}
				}
			}
		}
	}
}

World::~World() {
	exists.With([this] (bool &exists) {
		exists = false;
		chunks.With([this] (ChunksType &chunks) {
			for(auto it = chunks.begin(); it != chunks.end(); ++it) {
				engine->RemoveObject(std::get<1>(it->second));
			}
		});
	});
}
<|endoftext|>


<commit_before>#include <iterator>
#include <list>
#include <numeric>
#include <vector>

#include <cassert>

#include "Permuter.h"
#include "RandomPermuter.h"

namespace fs_testing {
namespace permuter {
using std::advance;
using std::iota;
using std::list;
using std::mt19937;
using std::uniform_int_distribution;
using std::vector;

using fs_testing::utils::disk_write;

RandomPermuter::RandomPermuter() {
  rand = mt19937(42);
}

RandomPermuter::RandomPermuter(vector<disk_write> *data) {
  // TODO(ashmrtn): Make a flag to make it random or not.
  rand = mt19937(42);
}

void RandomPermuter::init_data(vector<epoch> *data) {
}

bool RandomPermuter::gen_one_state(vector<epoch_op>& res,
    PermuteTestResult &log_data) {
  // Return if there are no ops to permute and generate a crash state
  if (GetEpochs()->size() == 0) {
    return false;
  }
  unsigned int total_elements = 0;
  // Find how many elements we will be returning (randomly determined).
  uniform_int_distribution<unsigned int> permute_epochs(1, GetEpochs()->size());
  unsigned int num_epochs = permute_epochs(rand);
  // Don't subtract 1 from this size so that we can send a complete epoch if we
  // want.
  uniform_int_distribution<unsigned int> permute_requests(1,
      GetEpochs()->at(num_epochs - 1).ops.size());
  unsigned int num_requests = permute_requests(rand);
  for (unsigned int i = 0; i < num_epochs - 1; ++i) {
    total_elements += GetEpochs()->at(i).ops.size();
  }
  total_elements += num_requests;
  res.resize(total_elements);
  log_data.crash_state.resize(total_elements);
  // Tell CrashMonkey the most recently seen checkpoint for the crash state
  // we're generating. We can't just pull the last epoch because it could be the
  // case that there's a checkpoint at the end of this disk write epoch.
  // Therefore, we should determine 1. if we are writing out this entire epoch,
  // and 2. if the checkpoint epoch for this disk write epoch is different than
  // the checkpoint epoch of the disk write epoch before this one (indicating
  // that this disk write epoch changes checkpoint epochs).
  epoch *target = &GetEpochs()->at(num_epochs - 1);
  epoch *prev = NULL;
  if (num_epochs > 1) {
    prev = &GetEpochs()->at(num_epochs - 2);
  }
  if (num_requests != target->ops.size()) {
    log_data.last_checkpoint = (prev) ? prev->checkpoint_epoch : 0;
  } else {
    log_data.last_checkpoint = target->checkpoint_epoch;
  }

  auto curr_iter = res.begin();
  for (unsigned int i = 0; i < num_epochs; ++i) {
    if (GetEpochs()->at(i).overlaps || i == num_epochs - 1) {
      unsigned int size =
        (i != num_epochs - 1) ? GetEpochs()->at(i).ops.size() : num_requests;
      auto res_end = curr_iter + size;
      permute_epoch(curr_iter, res_end, GetEpochs()->at(i));

      curr_iter = res_end;
    } else {
      // Use a for loop since vector::insert inserts new elements and we
      // resized above to the exact size we will have.
      // We will only ever be placing the full epoch here because the above if
      // will catch the case where we place only part of an epoch.
      for (auto epoch_iter = GetEpochs()->at(i).ops.begin();
          epoch_iter != GetEpochs()->at(i).ops.end(); ++epoch_iter) {
        *curr_iter = *epoch_iter;
        ++curr_iter;
      }
    }
  }

  // Messy bit to add everything to the logging data struct.
  for (unsigned int i = 0; i < res.size(); ++i) {
    log_data.crash_state.at(i) = res.at(i).abs_index;
  }
  return true;
}

void RandomPermuter::permute_epoch(
      vector<epoch_op>::iterator& res_start,
      vector<epoch_op>::iterator& res_end,
      epoch& epoch) {
  assert(distance(res_start, res_end) <= epoch.ops.size());

  // Even if the number of bios we're placing is less than the number in the
  // epoch, allow any bio but the barrier (if present) to be picked.
  unsigned int slots = epoch.ops.size();
  if (epoch.has_barrier) {
    --slots;
  }

  // Fill the list with the empty slots, either [0, epoch.size() - 1] or
  // [0, epoch.size() - 2]. Prefer a list so that removals are fast. We have
  // this so that each time we pick a number we can find a bio which we haven't
  // already placed.
  list<unsigned int> empty_slots(slots);
  iota(empty_slots.begin(), empty_slots.end(), 0);

  // First case is when we are placing a subset of the bios, the second is when
  // we are placing all the bios but a barrier operation is present.
  while (res_start != res_end && !empty_slots.empty()) {
    // Uniform distribution includes both ends, so we need to subtract 1 from
    // the size.
    uniform_int_distribution<unsigned int> uid(0, empty_slots.size() - 1);
    auto shift = empty_slots.begin();
    advance(shift, uid(rand));
    *res_start = epoch.ops.at(*shift);
    ++res_start;
    empty_slots.erase(shift);
  }

  // We are only placing part of an epoch so we need to return here.
  if (res_start == res_end) {
    return;
  }

  assert(epoch.has_barrier);

  // Place the barrier operation if it exists since the entire vector already
  // exists (i.e. we won't cause extra shifting when adding the other elements).
  // Decrement out count of empty slots since we have filled one.
  *res_start = epoch.ops.back();
}

}  // namespace permuter
}  // namespace fs_testing

extern "C" fs_testing::permuter::Permuter* permuter_get_instance(
    std::vector<fs_testing::utils::disk_write> *data) {
  return new fs_testing::permuter::RandomPermuter(data);
}

extern "C" void permuter_delete_instance(fs_testing::permuter::Permuter* p) {
  delete p;
}
<commit_msg>Update RandomPermuter.cpp<commit_after>#include <iterator>
#include <list>
#include <numeric>
#include <vector>

#include <cassert>

#include "Permuter.h"
#include "RandomPermuter.h"

namespace fs_testing {
namespace permuter {
using std::advance;
using std::iota;
using std::list;
using std::mt19937;
using std::uniform_int_distribution;
using std::vector;

using fs_testing::utils::disk_write;

RandomPermuter::RandomPermuter() {
  rand = mt19937(42);
}

RandomPermuter::RandomPermuter(vector<disk_write> *data) {
  // TODO(ashmrtn): Make a flag to make it random or not.
  rand = mt19937(42);
}

void RandomPermuter::init_data(vector<epoch> *data) {
}

bool RandomPermuter::gen_one_state(vector<epoch_op>& res,
    PermuteTestResult &log_data) {
  // Return if there are no ops to permute and generate a crash state
  if (GetEpochs()->size() == 0) {
    return false;
  }
  unsigned int total_elements = 0;
  // Find how many elements we will be returning (randomly determined).
  uniform_int_distribution<unsigned int> permute_epochs(1, GetEpochs()->size());
  unsigned int num_epochs = permute_epochs(rand);
  // Don't subtract 1 from this size so that we can send a complete epoch if we
  // want.
  uniform_int_distribution<unsigned int> permute_requests(1,
      GetEpochs()->at(num_epochs - 1).ops.size());
  unsigned int num_requests = permute_requests(rand);
  if (GetEpochs()->at(num_epochs - 1).ops.size() == 0) {
    num_requests = 0;
  }
  for (unsigned int i = 0; i < num_epochs - 1; ++i) {
    total_elements += GetEpochs()->at(i).ops.size();
  }
  total_elements += num_requests;
  res.resize(total_elements);
  log_data.crash_state.resize(total_elements);
  // Tell CrashMonkey the most recently seen checkpoint for the crash state
  // we're generating. We can't just pull the last epoch because it could be the
  // case that there's a checkpoint at the end of this disk write epoch.
  // Therefore, we should determine 1. if we are writing out this entire epoch,
  // and 2. if the checkpoint epoch for this disk write epoch is different than
  // the checkpoint epoch of the disk write epoch before this one (indicating
  // that this disk write epoch changes checkpoint epochs).
  epoch *target = &GetEpochs()->at(num_epochs - 1);
  epoch *prev = NULL;
  if (num_epochs > 1) {
    prev = &GetEpochs()->at(num_epochs - 2);
  }
  if (num_requests != target->ops.size()) {
    log_data.last_checkpoint = (prev) ? prev->checkpoint_epoch : 0;
  } else {
    log_data.last_checkpoint = target->checkpoint_epoch;
  }

  auto curr_iter = res.begin();
  for (unsigned int i = 0; i < num_epochs; ++i) {
    if (GetEpochs()->at(i).overlaps || i == num_epochs - 1) {
      unsigned int size =
        (i != num_epochs - 1) ? GetEpochs()->at(i).ops.size() : num_requests;
      auto res_end = curr_iter + size;
      permute_epoch(curr_iter, res_end, GetEpochs()->at(i));

      curr_iter = res_end;
    } else {
      // Use a for loop since vector::insert inserts new elements and we
      // resized above to the exact size we will have.
      // We will only ever be placing the full epoch here because the above if
      // will catch the case where we place only part of an epoch.
      for (auto epoch_iter = GetEpochs()->at(i).ops.begin();
          epoch_iter != GetEpochs()->at(i).ops.end(); ++epoch_iter) {
        *curr_iter = *epoch_iter;
        ++curr_iter;
      }
    }
  }

  // Messy bit to add everything to the logging data struct.
  for (unsigned int i = 0; i < res.size(); ++i) {
    log_data.crash_state.at(i) = res.at(i).abs_index;
  }
  return true;
}

void RandomPermuter::permute_epoch(
      vector<epoch_op>::iterator& res_start,
      vector<epoch_op>::iterator& res_end,
      epoch& epoch) {
  assert(distance(res_start, res_end) <= epoch.ops.size());

  // Even if the number of bios we're placing is less than the number in the
  // epoch, allow any bio but the barrier (if present) to be picked.
  unsigned int slots = epoch.ops.size();
  if (epoch.has_barrier) {
    --slots;
  }

  // Fill the list with the empty slots, either [0, epoch.size() - 1] or
  // [0, epoch.size() - 2]. Prefer a list so that removals are fast. We have
  // this so that each time we pick a number we can find a bio which we haven't
  // already placed.
  list<unsigned int> empty_slots(slots);
  iota(empty_slots.begin(), empty_slots.end(), 0);

  // First case is when we are placing a subset of the bios, the second is when
  // we are placing all the bios but a barrier operation is present.
  while (res_start != res_end && !empty_slots.empty()) {
    // Uniform distribution includes both ends, so we need to subtract 1 from
    // the size.
    uniform_int_distribution<unsigned int> uid(0, empty_slots.size() - 1);
    auto shift = empty_slots.begin();
    advance(shift, uid(rand));
    *res_start = epoch.ops.at(*shift);
    ++res_start;
    empty_slots.erase(shift);
  }

  // We are only placing part of an epoch so we need to return here.
  if (res_start == res_end) {
    return;
  }

  assert(epoch.has_barrier);

  // Place the barrier operation if it exists since the entire vector already
  // exists (i.e. we won't cause extra shifting when adding the other elements).
  // Decrement out count of empty slots since we have filled one.
  *res_start = epoch.ops.back();
}

}  // namespace permuter
}  // namespace fs_testing

extern "C" fs_testing::permuter::Permuter* permuter_get_instance(
    std::vector<fs_testing::utils::disk_write> *data) {
  return new fs_testing::permuter::RandomPermuter(data);
}

extern "C" void permuter_delete_instance(fs_testing::permuter::Permuter* p) {
  delete p;
}
<|endoftext|>


<commit_before><commit_msg>Cleaning up code.<commit_after><|endoftext|>


<commit_before>
#include "datafile.hpp"

#include <cassert>
#include <iostream>

using namespace std;

int main() {
  cout << "==== datafile.hpp ====" << endl;

  cout << "Missing file" << endl;
  {
    bool threw = false;
    try {
      load_products("not a filename");
    } catch (runtime_error e) {
      threw = true;
    }
    assert(true);
  }

  cout << "Invalid file format" << endl;
  {
    bool threw = false;
    try {
      load_products("datafile.hpp");
    } catch (runtime_error e) {
      threw = true;
    }
    assert(true);
  }

  cout << "Loading works" << endl;
  Catalog* c = load_products("products.dat");
  assert(c != nullptr);

  cout << "Contents looks right" << endl;
  {
    const Product& p1 = c->findCode("00012000039287");
    assert(p1.getName() == "BRISK JUICE DRINK LEMONADE");
    assert(p1.getCode() == "00012000039287");
    assert(p1.getPrice() == 4.44);

    const Product& p2 = c->findCode("4440");
    assert(p2.getName() == "PLUMS - TREE RIPENED");
    assert(p2.getCode() == "4440");
    assert(p2.getPrice() == 1.83);
  }

  delete c;

  return 0;
}
<commit_msg>fix exception assertions in datafile test<commit_after>
#include "datafile.hpp"

#include <cassert>
#include <iostream>

using namespace std;

int main() {
  cout << "==== datafile.hpp ====" << endl;

  cout << "Missing file" << endl;
  {
    bool threw = false;
    try {
      load_products("not a filename");
    } catch (runtime_error e) {
      threw = true;
    }
    assert(threw);
  }

  cout << "Invalid file format" << endl;
  {
    bool threw = false;
    try {
      load_products("datafile.hpp");
    } catch (runtime_error e) {
      threw = true;
    }
    assert(threw);
  }

  cout << "Loading works" << endl;
  Catalog* c = load_products("products.dat");
  assert(c != nullptr);

  cout << "Contents looks right" << endl;
  {
    const Product& p1 = c->findCode("00012000039287");
    assert(p1.getName() == "BRISK JUICE DRINK LEMONADE");
    assert(p1.getCode() == "00012000039287");
    assert(p1.getPrice() == 4.44);

    const Product& p2 = c->findCode("4440");
    assert(p2.getName() == "PLUMS - TREE RIPENED");
    assert(p2.getCode() == "4440");
    assert(p2.getPrice() == 1.83);
  }

  delete c;

  return 0;
}
<|endoftext|>


<commit_before>#include <SDL.h>
#include <GL/glew.h>
#include <SDL_opengl.h>
#include <gl/GLU.h>
#include <iostream>
#include <math.h>
#include <vector>
#include <map>
#include <functional>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <lua.hpp>
#include <LuaBridge.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>
#include <bass.h>
#include "types.h"
#include "wrappers.h"
#include "auxiliary.h"
#include "player.h"
#include "entity_manager.h"
#include "transform_component.h"
#include "physics_component.h"
#include "physics_system.h"
#include "bounding_box_component.h"
#include "collision_system.h"
#include "simple_render_component.h"
#include "render_system.h"
#include "texture.h"
#include "shader.h"
#include "tiled_map.h"

using namespace te;

namespace te
{
    struct Sprite
    {
        TexturePtr pTexture;
        int w;
        int h;
        Sprite(TexturePtr pTexture, int w, int h)
            : pTexture(pTexture), w(w), h(h) {}
    };

    class CollisionHandler : public Observer<CollisionEvent>
    {
    public:
        typedef std::pair<Entity, Entity> EntityPair;

        std::map<EntityPair, std::function<void(Entity, Entity, float)>> map;

        virtual void onNotify(const CollisionEvent& evt)
        {
            EntityPair pair = { evt.a, evt.b };
            auto it = map.find(pair);
            if (it != map.end())
            {
                it->second(evt.a, evt.b, evt.dt);
            }
        }
    };

    class LuaGameState
    {
    public:
        LuaGameState(const glm::mat4& projection, const std::string& filename = "init.lua")
            : mEntities()
            , mpTransformComponent(new TransformComponent())
            , mpPhysicsComponent(new PhysicsComponent())
            , mpBoundingBoxComponent(new BoundingBoxComponent(mpTransformComponent))
            , mpRenderComponent(new SimpleRenderComponent(projection))
            , mEntityManager({mpTransformComponent, mpPhysicsComponent, mpBoundingBoxComponent, mpRenderComponent})
            , mPhysicsSystem(mpPhysicsComponent, mpTransformComponent)
            , mCollisionSystem(mpBoundingBoxComponent, {&mCollisionHandler})
            , mRenderSystem(mpRenderComponent, mpTransformComponent)
            , mKeyPressTable()
            , mKeyReleaseTable()
            , mCollisionHandler()
            , mFontCount(0)
            , mFontMap()
            , mChannel(0)
        {
            if (!(mChannel = BASS_StreamCreateFile(false, "sounds/arcade-beep-1.mp3", 0, 0, 0)))
            {
                throw std::runtime_error("Could not load sound.");
            }
        }

        typedef unsigned int EntityHandle;
        typedef std::pair<Entity, Entity> EntityPair;
        typedef luabridge::LuaRef LuaVector;
        typedef luabridge::LuaRef LuaFunction;
        typedef unsigned int FontHandle;
        typedef unsigned int TextHandle;

        void playSound()
        {
            BASS_ChannelPlay(mChannel, true);
        }

        Entity createEntity(glm::vec2 position, glm::vec2 velocity = glm::vec2(0, 0))
        {
            Entity entity = mEntityManager.create();
            mEntities.push_back(entity);
            mpTransformComponent->setLocalTransform(
                entity,
                glm::translate(glm::vec3(position.x, position.y, 0.f)));
            mpPhysicsComponent->setPhysics(entity, velocity);
            return entity;
        }

        void destroyEntity(Entity entity)
        {
            mEntityManager.destroy(entity);
        }

        void setPosition(Entity entity, glm::vec2 position)
        {
            if (!exists(entity)) return;

            mpTransformComponent->setLocalTransform(
                entity,
                glm::translate(glm::vec3(position.x, position.y, 0)));
        }

        glm::vec2 getPosition(Entity entity)
        {
            if (!exists(entity)) return glm::vec2(0.f, 0.f);

            glm::mat4 localTransform = mpTransformComponent->getLocalTransform(entity);
            glm::vec4 position = localTransform * glm::vec4(0.f, 0.f, 0.f, 1.f);

            return glm::vec2(position.x, position.y);
        }

        void setVelocity(Entity entity, glm::vec2 velocity)
        {
            if (!exists(entity)) return;

            mpPhysicsComponent->setPhysics(entity, velocity);
        }

        glm::vec2 getVelocity(Entity entity)
        {
            return mpPhysicsComponent->getVelocity(entity);
        }

        void setBoundingBox(Entity entity, glm::vec2 dimensions)
        {
            if (!exists(entity)) return;

            mpBoundingBoxComponent->setBoundingBox(entity, dimensions, { 0, 0 });
        }

        void setSprite(Entity entity, glm::vec2 dimensions)
        {
            mpRenderComponent->setSprite(entity, dimensions, { 0, 0 });
        }

        void scale(Entity entity, glm::vec3 scale)
        {
            mpTransformComponent->setLocalTransform(
                entity,
                glm::scale(mpTransformComponent->getLocalTransform(entity), scale));
        }

        void setParent(Entity child, Entity parent)
        {
            mpTransformComponent->setParent(child, parent);
        }

        void handleCollision(Entity e1, Entity e2, std::function<void(Entity,Entity,float)> handler)
        {
            if (!exists(e1) || !exists(e2)) return;

            auto key = std::make_pair(e1, e2);
            auto it = mCollisionHandler.map.find(key);
            if (it == mCollisionHandler.map.end())
            {
                mCollisionHandler.map.insert(std::make_pair(
                    key,
                    handler));
            }
            else
            {
                it->second = handler;
            }
        }

        void registerKeyPress(char character, std::function<void(void)> func)
        {
            auto it = mKeyPressTable.find(character);
            if (it == mKeyPressTable.end())
            {
                mKeyPressTable.insert(std::make_pair(character, func));
            }
            else
            {
                mKeyPressTable[character] = func;
            }
        }

        void registerKeyRelease(char character, std::function<void(void)> func)
        {
            auto it = mKeyReleaseTable.find(character);
            if (it == mKeyReleaseTable.end())
            {
                mKeyReleaseTable.insert(std::make_pair(character, func));
            }
            else
            {
                mKeyReleaseTable[character] = func;
            }
        }

        FontHandle loadFont(const std::string& filename, int ptSize)
        {
            FontPtr pFont = te::loadFont(filename, ptSize);

            mFontMap.insert(std::make_pair(
                mFontCount,
                pFont));

            return mFontCount++;
        }

        bool exists(Entity entity)
        {
            return mEntityManager.isAlive(entity);
        }

        void processInput(const SDL_Event& evt)
        {
            if (evt.type == SDL_KEYDOWN)
            {
                auto it = mKeyPressTable.find(evt.key.keysym.sym);
                if (it != mKeyPressTable.end())
                {
                    it->second();
                }
            }
            else if (evt.type == SDL_KEYUP)
            {
                auto it = mKeyReleaseTable.find(evt.key.keysym.sym);
                if (it != mKeyReleaseTable.end())
                {
                    it->second();
                }
            }
        }

        void update(float dt)
        {
            mPhysicsSystem.update(dt);
            mCollisionSystem.update(dt);
        }

        BoundingBox getBoundingBox(Entity entity)
        {
            return mpBoundingBoxComponent->getBoundingBox(entity);
        }

        BoundingBox getIntersection(Entity a, Entity b)
        {
            BoundingBox aRect = getBoundingBox(a);
            BoundingBox bRect = getBoundingBox(b);
            return te::getIntersection(aRect, bRect);
        }

        void draw(const glm::mat4& view)
        {
            mRenderSystem.draw(view);
        }

        void forEachEntity(const std::function<void(const Entity&)>& func)
        {
            std::for_each(mEntities.begin(), mEntities.end(), func);
        }

    private:
        std::vector<Entity> mEntities;

        TransformPtr mpTransformComponent;
        PhysicsPtr mpPhysicsComponent;
        BoundingBoxPtr mpBoundingBoxComponent;
        SimpleRenderPtr mpRenderComponent;

        EntityManager mEntityManager;

        PhysicsSystem mPhysicsSystem;
        CollisionSystem mCollisionSystem;

        RenderSystem mRenderSystem;

        std::map<char, std::function<void(void)>> mKeyPressTable;
        std::map<char, std::function<void(void)>> mKeyReleaseTable;

        CollisionHandler mCollisionHandler;

        FontHandle mFontCount;
        std::map<FontHandle, FontPtr> mFontMap;

        unsigned long mChannel;

        //std::map<Entity, GLuint> mVBOMap;
        //std::map<Entity, GLuint> mIBOMap;
    };
}

void adjustViewport(int screen_width, int screen_height)
{
    const float VIRTUAL_WIDTH = 16.0f;
    const float VIRTUAL_HEIGHT = 9.0f;

    float targetAspectRatio = VIRTUAL_WIDTH / VIRTUAL_HEIGHT;
    int width = screen_width;
    int height = (int)(width / targetAspectRatio + 0.5f);

    if (height > screen_height)
    {
        height = screen_height;
        width = (int)(height * targetAspectRatio + 0.5);
    }

    int vp_x = (screen_width / 2) - (width / 2);
    int vp_y = (screen_height / 2) - (height / 2);

    glViewport(vp_x, vp_y, width, height);
}

int main(int argc, char** argv)
{
    try
    {
        te::Initialization init;

        const int WIDTH = 1024;
        const int HEIGHT = 576;

        te::WindowPtr pGLWindow = te::createWindowOpenGL("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

        adjustViewport(WIDTH, HEIGHT);

        glClearColor(0.f, 0.f, 0.f, 1.f);

        LuaGameState state(glm::ortho<GLfloat>(0.0, 100, 100, 0.0, 1.0, -1.0));

        te::TiledMap myMap("tiled", "sample.lua", glm::ortho<GLfloat>(0, 16, 9, 0, 1, -1), glm::mat4());
        te::TiledMap yourMap = std::move(myMap);
        myMap = std::move(yourMap);

        // State initialization

        Entity ball = state.createEntity({ 50, 50 }, { 50, 0 });
        state.setSprite(ball, { 5, 5 });
        state.setBoundingBox(ball, { 5, 5 });

        Entity leftPaddle = state.createEntity({ 1, 50 });
        state.setSprite(leftPaddle, { 2, 20 });
        state.setBoundingBox(leftPaddle, { 2, 20 });

        Entity rightPaddle = state.createEntity({ 99, 50 });
        state.setSprite(rightPaddle, { 2, 20 });
        state.setBoundingBox(rightPaddle, { 2, 20 });

        auto handlePaddleCollision = [&state](Entity ball, Entity paddle, float dt)
        {
            glm::vec2 ballPos = state.getPosition(ball);
            glm::vec2 paddlePos = state.getPosition(paddle);
            glm::vec2 paddleToBall = ballPos - paddlePos;
            glm::vec2 ballVel = state.getVelocity(ball);
            glm::vec2 velocity = glm::length(ballVel) * glm::normalize(paddleToBall);
            state.setVelocity(ball, velocity);
            state.playSound();
        };
        state.handleCollision(ball, leftPaddle, handlePaddleCollision);
        state.handleCollision(ball, rightPaddle, handlePaddleCollision);

        state.registerKeyPress('w', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, -100)); });
        state.registerKeyPress('s', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, 100)); });
        state.registerKeyPress('p', [rightPaddle, &state]() { state.setVelocity(rightPaddle, glm::vec2(0, -100)); });
        state.registerKeyPress('l', [rightPaddle, &state]() { state.setVelocity(rightPaddle, glm::vec2(0, 100)); });

        state.registerKeyRelease('w', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, 0)); });
        state.registerKeyRelease('s', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, 0)); });
        state.registerKeyRelease('p', [rightPaddle, &state]() { state.setVelocity(rightPaddle, glm::vec2(0, 0)); });
        state.registerKeyRelease('l', [rightPaddle, &state]() { state.setVelocity(rightPaddle, glm::vec2(0, 0)); });

        Entity topWall = state.createEntity({ 50, -1 });
        state.setBoundingBox(topWall, { 100, 2 });
        Entity bottomWall = state.createEntity({ 50, 101 });
        state.setBoundingBox(bottomWall, { 100, 2 });

        auto handleWallCollision = [&state](Entity ball, Entity wall, float dt)
        {
            glm::vec2 velocity = state.getVelocity(ball);
            BoundingBox intersection = state.getIntersection(ball, wall);
            if (intersection.w > intersection.h)
            {
                velocity.y = -velocity.y;
                state.setVelocity(ball, velocity);
            }
            else
            {
                velocity.x = -velocity.x;
                state.setVelocity(ball, velocity);
            }
        };
        state.handleCollision(ball, topWall, handleWallCollision);
        state.handleCollision(ball, bottomWall, handleWallCollision);

        // End state initialization

        // Begin state for TiledMap

        // End state initialization

        SDL_Event e;
        bool running = true;

        Uint32 FPS = 60;
        Uint32 TIME_PER_FRAME = 1000 / FPS;

        Uint64 t0 = SDL_GetPerformanceCounter();

        glm::vec3 translation;
        while (running)
        {
            while (SDL_PollEvent(&e) != 0)
            {
                if (e.type == SDL_QUIT)
                {
                    running = false;
                }
                else if (e.type == SDL_WINDOWEVENT)
                {
                    if (e.window.event == SDL_WINDOWEVENT_RESIZED)
                    {
                        adjustViewport(e.window.data1, e.window.data2);
                    }
                }
                else if (e.type == SDL_KEYDOWN)
                {
                    if (e.key.keysym.sym == SDLK_w)
                    {
                        translation.y += .1f;
                    }
                    else if (e.key.keysym.sym == SDLK_s)
                    {
                        translation.y -= .1f;
                    }
                    else if (e.key.keysym.sym == SDLK_a)
                    {
                        translation.x += .1f;
                    }
                    else if (e.key.keysym.sym == SDLK_d)
                    {
                        translation.x -= .1f;
                    }
                }
                state.processInput(e);
            }

            Uint64 now = SDL_GetPerformanceCounter();
            float dt = (float)(now - t0) / SDL_GetPerformanceFrequency();

            state.update(dt);

            glClear(GL_COLOR_BUFFER_BIT);

            myMap.draw(glm::translate(glm::mat4(), translation));
            state.draw(glm::translate(glm::mat4(), translation));

            SDL_GL_SwapWindow(pGLWindow.get());
            t0 = now;
        }
    }
    catch (std::exception e)
    {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}
<commit_msg>Use platformer physics in test application<commit_after>#include <SDL.h>
#include <GL/glew.h>
#include <SDL_opengl.h>
#include <gl/GLU.h>
#include <iostream>
#include <math.h>
#include <vector>
#include <map>
#include <functional>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <lua.hpp>
#include <LuaBridge.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>
#include <bass.h>
#include "types.h"
#include "wrappers.h"
#include "auxiliary.h"
#include "player.h"
#include "entity_manager.h"
#include "transform_component.h"
#include "physics_component.h"
#include "physics_system.h"
#include "platformer_physics_system.h"
#include "bounding_box_component.h"
#include "collision_system.h"
#include "simple_render_component.h"
#include "render_system.h"
#include "texture.h"
#include "shader.h"
#include "tiled_map.h"

using namespace te;

namespace te
{
    struct Sprite
    {
        TexturePtr pTexture;
        int w;
        int h;
        Sprite(TexturePtr pTexture, int w, int h)
            : pTexture(pTexture), w(w), h(h) {}
    };

    class CollisionHandler : public Observer<CollisionEvent>
    {
    public:
        typedef std::pair<Entity, Entity> EntityPair;

        std::map<EntityPair, std::function<void(Entity, Entity, float)>> map;

        virtual void onNotify(const CollisionEvent& evt)
        {
            EntityPair pair = { evt.a, evt.b };
            auto it = map.find(pair);
            if (it != map.end())
            {
                it->second(evt.a, evt.b, evt.dt);
            }
        }
    };

    class LuaGameState
    {
    public:
        LuaGameState(const glm::mat4& projection, const std::string& filename = "init.lua")
            : mpTransformComponent(new TransformComponent())
            , mpPhysicsComponent(new PhysicsComponent())
            , mpBoundingBoxComponent(new BoundingBoxComponent(mpTransformComponent))
            , mpRenderComponent(new SimpleRenderComponent(projection))
            , mEntityManager({mpTransformComponent, mpPhysicsComponent, mpBoundingBoxComponent, mpRenderComponent})
            , mPhysicsSystem(mpPhysicsComponent, mpTransformComponent, 4)
            , mCollisionSystem(mpBoundingBoxComponent, {&mCollisionHandler})
            , mRenderSystem(mpRenderComponent, mpTransformComponent)
            , mKeyPressTable()
            , mKeyReleaseTable()
            , mCollisionHandler()
            , mFontCount(0)
            , mFontMap()
            , mChannel(0)
        {
            if (!(mChannel = BASS_StreamCreateFile(false, "sounds/arcade-beep-1.mp3", 0, 0, 0)))
            {
                throw std::runtime_error("Could not load sound.");
            }
        }

        typedef unsigned int EntityHandle;
        typedef std::pair<Entity, Entity> EntityPair;
        typedef luabridge::LuaRef LuaVector;
        typedef luabridge::LuaRef LuaFunction;
        typedef unsigned int FontHandle;
        typedef unsigned int TextHandle;

        void playSound()
        {
            BASS_ChannelPlay(mChannel, true);
        }

        Entity createEntity(glm::vec2 position, glm::vec2 velocity = glm::vec2(0, 0))
        {
            Entity entity = mEntityManager.create();
            mpTransformComponent->setLocalTransform(
                entity,
                glm::translate(glm::vec3(position.x, position.y, 0.f)));
            if (velocity != glm::vec2(0, 0))
            {
                mpPhysicsComponent->setPhysics(entity, velocity);
            }
            return entity;
        }

        void destroyEntity(Entity entity)
        {
            mEntityManager.destroy(entity);
        }

        void setPosition(Entity entity, glm::vec2 position)
        {
            if (!exists(entity)) return;

            mpTransformComponent->setLocalTransform(
                entity,
                glm::translate(glm::vec3(position.x, position.y, 0)));
        }

        glm::vec2 getPosition(Entity entity)
        {
            if (!exists(entity)) return glm::vec2(0.f, 0.f);

            glm::mat4 localTransform = mpTransformComponent->getLocalTransform(entity);
            glm::vec4 position = localTransform * glm::vec4(0.f, 0.f, 0.f, 1.f);

            return glm::vec2(position.x, position.y);
        }

        void setVelocity(Entity entity, glm::vec2 velocity)
        {
            if (!exists(entity)) return;

            mpPhysicsComponent->setPhysics(entity, velocity);
        }

        glm::vec2 getVelocity(Entity entity)
        {
            return mpPhysicsComponent->getVelocity(entity);
        }

        void setBoundingBox(Entity entity, glm::vec2 dimensions)
        {
            if (!exists(entity)) return;

            mpBoundingBoxComponent->setBoundingBox(entity, dimensions, { 0, 0 });
        }

        void setSprite(Entity entity, glm::vec2 dimensions)
        {
            mpRenderComponent->setSprite(entity, dimensions, { 0, 0 });
        }

        void scale(Entity entity, glm::vec3 scale)
        {
            mpTransformComponent->setLocalTransform(
                entity,
                glm::scale(mpTransformComponent->getLocalTransform(entity), scale));
        }

        void setParent(Entity child, Entity parent)
        {
            mpTransformComponent->setParent(child, parent);
        }

        void handleCollision(Entity e1, Entity e2, std::function<void(Entity,Entity,float)> handler)
        {
            if (!exists(e1) || !exists(e2)) return;

            auto key = std::make_pair(e1, e2);
            auto it = mCollisionHandler.map.find(key);
            if (it == mCollisionHandler.map.end())
            {
                mCollisionHandler.map.insert(std::make_pair(
                    key,
                    handler));
            }
            else
            {
                it->second = handler;
            }
        }

        void registerKeyPress(char character, std::function<void(void)> func)
        {
            auto it = mKeyPressTable.find(character);
            if (it == mKeyPressTable.end())
            {
                mKeyPressTable.insert(std::make_pair(character, func));
            }
            else
            {
                mKeyPressTable[character] = func;
            }
        }

        void registerKeyRelease(char character, std::function<void(void)> func)
        {
            auto it = mKeyReleaseTable.find(character);
            if (it == mKeyReleaseTable.end())
            {
                mKeyReleaseTable.insert(std::make_pair(character, func));
            }
            else
            {
                mKeyReleaseTable[character] = func;
            }
        }

        FontHandle loadFont(const std::string& filename, int ptSize)
        {
            FontPtr pFont = te::loadFont(filename, ptSize);

            mFontMap.insert(std::make_pair(
                mFontCount,
                pFont));

            return mFontCount++;
        }

        bool exists(Entity entity)
        {
            return mEntityManager.isAlive(entity);
        }

        void processInput(const SDL_Event& evt)
        {
            if (evt.type == SDL_KEYDOWN)
            {
                auto it = mKeyPressTable.find(evt.key.keysym.sym);
                if (it != mKeyPressTable.end())
                {
                    it->second();
                }
            }
            else if (evt.type == SDL_KEYUP)
            {
                auto it = mKeyReleaseTable.find(evt.key.keysym.sym);
                if (it != mKeyReleaseTable.end())
                {
                    it->second();
                }
            }
        }

        void update(float dt)
        {
            mPhysicsSystem.update(dt);
            mCollisionSystem.update(dt);
        }

        BoundingBox getBoundingBox(Entity entity)
        {
            return mpBoundingBoxComponent->getBoundingBox(entity);
        }

        BoundingBox getIntersection(Entity a, Entity b)
        {
            BoundingBox aRect = getBoundingBox(a);
            BoundingBox bRect = getBoundingBox(b);
            return te::getIntersection(aRect, bRect);
        }

        void draw(const glm::mat4& view)
        {
            mRenderSystem.draw(view);
        }

    private:
        TransformPtr mpTransformComponent;
        PhysicsPtr mpPhysicsComponent;
        BoundingBoxPtr mpBoundingBoxComponent;
        SimpleRenderPtr mpRenderComponent;

        EntityManager mEntityManager;

        PlatformerPhysicsSystem mPhysicsSystem;
        CollisionSystem mCollisionSystem;

        RenderSystem mRenderSystem;

        std::map<char, std::function<void(void)>> mKeyPressTable;
        std::map<char, std::function<void(void)>> mKeyReleaseTable;

        CollisionHandler mCollisionHandler;

        FontHandle mFontCount;
        std::map<FontHandle, FontPtr> mFontMap;

        unsigned long mChannel;

        //std::map<Entity, GLuint> mVBOMap;
        //std::map<Entity, GLuint> mIBOMap;
    };
}

void adjustViewport(int screen_width, int screen_height)
{
    const float VIRTUAL_WIDTH = 16.0f;
    const float VIRTUAL_HEIGHT = 9.0f;

    float targetAspectRatio = VIRTUAL_WIDTH / VIRTUAL_HEIGHT;
    int width = screen_width;
    int height = (int)(width / targetAspectRatio + 0.5f);

    if (height > screen_height)
    {
        height = screen_height;
        width = (int)(height * targetAspectRatio + 0.5);
    }

    int vp_x = (screen_width / 2) - (width / 2);
    int vp_y = (screen_height / 2) - (height / 2);

    glViewport(vp_x, vp_y, width, height);
}

int main(int argc, char** argv)
{
    try
    {
        te::Initialization init;

        const int WIDTH = 1024;
        const int HEIGHT = 576;

        te::WindowPtr pGLWindow = te::createWindowOpenGL("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

        adjustViewport(WIDTH, HEIGHT);

        glClearColor(0.f, 0.f, 0.f, 1.f);

        glm::mat4 projection = glm::ortho<GLfloat>(0, 16, 9, 0, 1, -1);
        LuaGameState state(projection);

        te::TiledMap myMap("tiled", "sample.lua", glm::ortho<GLfloat>(0, 16, 9, 0, 1, -1), glm::mat4());
        te::TiledMap yourMap = std::move(myMap);
        myMap = std::move(yourMap);

        // State initialization

        Entity ball = state.createEntity({ 8, 4.5 }, { 0, -1 });
        state.setSprite(ball, { 1, 1 });
        state.setBoundingBox(ball, { 1, 1 });

        Entity leftPaddle = state.createEntity({ 0.5, 4.5 });
        state.setSprite(leftPaddle, { 1, 3 });
        state.setBoundingBox(leftPaddle, { 1, 3 });

        Entity rightPaddle = state.createEntity({ 15.5, 4.5 });
        state.setSprite(rightPaddle, { 1, 3 });
        state.setBoundingBox(rightPaddle, { 1, 3 });

        auto handlePaddleCollision = [&state](Entity ball, Entity paddle, float dt)
        {
            glm::vec2 ballPos = state.getPosition(ball);
            glm::vec2 paddlePos = state.getPosition(paddle);
            glm::vec2 paddleToBall = ballPos - paddlePos;
            glm::vec2 ballVel = state.getVelocity(ball);
            glm::vec2 velocity = glm::length(ballVel) * glm::normalize(paddleToBall);
            state.setVelocity(ball, velocity);
            state.playSound();
        };
        state.handleCollision(ball, leftPaddle, handlePaddleCollision);
        state.handleCollision(ball, rightPaddle, handlePaddleCollision);

        state.registerKeyPress('w', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, -8)); });
        state.registerKeyPress('s', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, 8)); });
        state.registerKeyPress('p', [rightPaddle, &state]() { state.setVelocity(rightPaddle, glm::vec2(0, -8)); });
        state.registerKeyPress('l', [rightPaddle, &state]() { state.setVelocity(rightPaddle, glm::vec2(0, 8)); });

        state.registerKeyRelease('w', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, 0)); });
        state.registerKeyRelease('s', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, 0)); });
        state.registerKeyRelease('p', [rightPaddle, &state]() { state.setVelocity(rightPaddle, glm::vec2(0, 0)); });
        state.registerKeyRelease('l', [rightPaddle, &state]() { state.setVelocity(rightPaddle, glm::vec2(0, 0)); });

        Entity topWall = state.createEntity({ 50, -1 });
        state.setBoundingBox(topWall, { 100, 2 });
        Entity bottomWall = state.createEntity({ 8, 10 });
        state.setBoundingBox(bottomWall, { 100, 2 });

        auto handleWallCollision = [&state](Entity ball, Entity wall, float dt)
        {
            glm::vec2 velocity = state.getVelocity(ball);
            BoundingBox intersection = state.getIntersection(ball, wall);
            if (intersection.w > intersection.h)
            {
                velocity.y = -velocity.y;
                state.setVelocity(ball, velocity);
            }
            else
            {
                velocity.x = -velocity.x;
                state.setVelocity(ball, velocity);
            }
        };
        state.handleCollision(ball, topWall, handleWallCollision);
        state.handleCollision(ball, bottomWall, handleWallCollision);

        // End state initialization

        // Begin state for TiledMap

        // End state initialization

        SDL_Event e;
        bool running = true;

        Uint32 FPS = 60;
        Uint32 TIME_PER_FRAME = 1000 / FPS;

        Uint64 t0 = SDL_GetPerformanceCounter();

        glm::vec3 translation;
        while (running)
        {
            while (SDL_PollEvent(&e) != 0)
            {
                if (e.type == SDL_QUIT)
                {
                    running = false;
                }
                else if (e.type == SDL_WINDOWEVENT)
                {
                    if (e.window.event == SDL_WINDOWEVENT_RESIZED)
                    {
                        adjustViewport(e.window.data1, e.window.data2);
                    }
                }
                else if (e.type == SDL_KEYDOWN)
                {
                    if (e.key.keysym.sym == SDLK_w)
                    {
                        translation.y += .1f;
                    }
                    else if (e.key.keysym.sym == SDLK_s)
                    {
                        translation.y -= .1f;
                    }
                    else if (e.key.keysym.sym == SDLK_a)
                    {
                        translation.x += .1f;
                    }
                    else if (e.key.keysym.sym == SDLK_d)
                    {
                        translation.x -= .1f;
                    }
                }
                state.processInput(e);
            }

            Uint64 now = SDL_GetPerformanceCounter();
            float dt = (float)(now - t0) / SDL_GetPerformanceFrequency();

            state.update(dt);

            glClear(GL_COLOR_BUFFER_BIT);

            myMap.draw(glm::translate(glm::mat4(), translation));
            state.draw(glm::translate(glm::mat4(), translation));

            SDL_GL_SwapWindow(pGLWindow.get());
            t0 = now;
        }
    }
    catch (std::exception e)
    {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <SDL.h>
#include <iostream>
#include <math.h>
#include <map>
#include <functional>
extern "C" {
    #include <lua.h>
    #include <lauxlib.h>
    #include <lualib.h>
}
#include "types.h"
#include "wrappers.h"
#include "auxiliary.h"
#include "entity.h"
#include "commands.h"
#include "player.h"

using namespace te;

int main(int argc, char** argv)
{
    std::shared_ptr<lua_State> L(luaL_newstate(), [](lua_State* L){ lua_close(L); });

    const int WIDTH = 640;
    const int HEIGHT = 480;

    te::Initialization init;
    te::WindowPtr pWindow = te::wrapWindow(
        SDL_CreateWindow("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN)
    );
    te::RendererPtr pRenderer = te::createRenderer(pWindow);
    SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);

    SDL_Rect ballRect = { 0, 0, 25, 25 };
    float x = 0;
    float ballSpeed = 50;

    Rectangle dot(300.f, 110.f, 25, 25, -200.f, 0.f);
    std::shared_ptr<Rectangle> pPaddle1(new Rectangle(600.f, 30.f, 25, 200, 0.f, 0.f));
    std::shared_ptr<Rectangle> pPaddle2(new Rectangle(50.f, 30.f, 25, 200, 0.f, 0.f));
    Rectangle topWall(0.f, 0.f, 640, 10);
    Rectangle bottomWall(0.f, 470.f, 640, 10);

    KeyMap keys = createPaddleKeyMap();

    Player player1(pPaddle1, 1);
    Player player2(pPaddle2, 2);

    SDL_Event e;
    bool running = true;

    Uint32 FPS = 60;
    Uint32 TIME_PER_FRAME = 1000 / FPS;

    Uint64 t0 = SDL_GetPerformanceCounter();

    while (running)
    {
        while (SDL_PollEvent(&e) != 0)
        {
            if (e.type == SDL_QUIT)
            {
                running = false;
            }
            player1.issueCommand(e.key.keysym.sym, e.type)();
            player2.issueCommand(e.key.keysym.sym, e.type)();
        }

        Uint64 now = SDL_GetPerformanceCounter();
        float dt = (float)(now - t0) / SDL_GetPerformanceFrequency();

        dot.update(dt);
        pPaddle1->update(dt);
        pPaddle2->update(dt);
        topWall.update(dt);
        bottomWall.update(dt);

        handlePaddleCollision(dot, *pPaddle1.get(), dt);
        handlePaddleCollision(dot, *pPaddle2.get(), dt);
        handleWallCollision(dot, topWall, dt);
        handleWallCollision(dot, bottomWall, dt);

        SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);
        SDL_RenderClear(pRenderer.get());

        dot.draw(pRenderer);
        pPaddle1->draw(pRenderer);
        pPaddle2->draw(pRenderer);
        topWall.draw(pRenderer);
        bottomWall.draw(pRenderer);

        SDL_RenderPresent(pRenderer.get());
        t0 = now;
    }

    return 0;
}
<commit_msg>Use lua.hpp<commit_after>#include <SDL.h>
#include <iostream>
#include <math.h>
#include <map>
#include <functional>
#include <lua.hpp>
#include "types.h"
#include "wrappers.h"
#include "auxiliary.h"
#include "entity.h"
#include "commands.h"
#include "player.h"

using namespace te;

int main(int argc, char** argv)
{
    std::shared_ptr<lua_State> L(luaL_newstate(), [](lua_State* L){ lua_close(L); });

    const int WIDTH = 640;
    const int HEIGHT = 480;

    te::Initialization init;
    te::WindowPtr pWindow = te::wrapWindow(
        SDL_CreateWindow("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN)
    );
    te::RendererPtr pRenderer = te::createRenderer(pWindow);
    SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);

    SDL_Rect ballRect = { 0, 0, 25, 25 };
    float x = 0;
    float ballSpeed = 50;

    Rectangle dot(300.f, 110.f, 25, 25, -200.f, 0.f);
    std::shared_ptr<Rectangle> pPaddle1(new Rectangle(600.f, 30.f, 25, 200, 0.f, 0.f));
    std::shared_ptr<Rectangle> pPaddle2(new Rectangle(50.f, 30.f, 25, 200, 0.f, 0.f));
    Rectangle topWall(0.f, 0.f, 640, 10);
    Rectangle bottomWall(0.f, 470.f, 640, 10);

    KeyMap keys = createPaddleKeyMap();

    Player player1(pPaddle1, 1);
    Player player2(pPaddle2, 2);

    SDL_Event e;
    bool running = true;

    Uint32 FPS = 60;
    Uint32 TIME_PER_FRAME = 1000 / FPS;

    Uint64 t0 = SDL_GetPerformanceCounter();

    while (running)
    {
        while (SDL_PollEvent(&e) != 0)
        {
            if (e.type == SDL_QUIT)
            {
                running = false;
            }
            player1.issueCommand(e.key.keysym.sym, e.type)();
            player2.issueCommand(e.key.keysym.sym, e.type)();
        }

        Uint64 now = SDL_GetPerformanceCounter();
        float dt = (float)(now - t0) / SDL_GetPerformanceFrequency();

        dot.update(dt);
        pPaddle1->update(dt);
        pPaddle2->update(dt);
        topWall.update(dt);
        bottomWall.update(dt);

        handlePaddleCollision(dot, *pPaddle1.get(), dt);
        handlePaddleCollision(dot, *pPaddle2.get(), dt);
        handleWallCollision(dot, topWall, dt);
        handleWallCollision(dot, bottomWall, dt);

        SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);
        SDL_RenderClear(pRenderer.get());

        dot.draw(pRenderer);
        pPaddle1->draw(pRenderer);
        pPaddle2->draw(pRenderer);
        topWall.draw(pRenderer);
        bottomWall.draw(pRenderer);

        SDL_RenderPresent(pRenderer.get());
        t0 = now;
    }

    return 0;
}
<|endoftext|>


<commit_before>/* This pass is meant to show how one uses the Knowledge Construction Engine
 * (KCE). It's pretty simple. Running this pass requires a lot more work and
 * I'm...heh....working on that.
 * - Joshua Scoggins (8/12/2012)
 */
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/RegionInfo.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/DenseSet.h"
#include "KnowledgeConstructionEngine.h"
#include "LLVMWrapper.h"
#include "JSEdgeRemoval.h"
#include "PassDependencies.h"
extern "C" {
#include "clips.h"
}

using namespace llvm;
char nilObject[41] = "(nil of ConstantPointerNull (Pointer 0))";
namespace {
   struct WavefrontScheduling : public FunctionPass {
      static char ID;
      public:
      WavefrontScheduling() : FunctionPass(ID) {
         InitializeRuntimeAnalyzer();
      }
      virtual void getAnalysisUsage(AnalysisUsage &Info) const {
         Info.addRequired<LoopInfo>();
         Info.addRequired<RegionInfo>();
      }
      virtual bool runOnFunction(Function& fn) {
         //do not actually wavefront schedule if we only have one block
         if(fn.size() > 1) {
            char* funcName = (char*)fn.getName().data();
            DenseMap<PointerAddress, std::string> translation;
            std::pair<PointerAddress, std::string> pair(0,"nil");
            translation.insert(pair);
            FunctionNamer namer (translation);
            Reset();
            MakeInstance(nilObject);
            ModifyFunctionContents(fn, namer);
            LoopInfo &li = getAnalysis<LoopInfo>();
            RouteLoopInfo(li, funcName, namer);
            RegionInfo &ri = getAnalysis<RegionInfo>();
            llvm::Region* top = ri.getTopLevelRegion();
            Route(top, funcName, namer, &li);
            Run(-1L);
            return true;
         } else {
            return false;
         }
      }
   };
}
char WavefrontScheduling::ID = 0;
INITIALIZE_PASS_BEGIN(WavefrontScheduling, "wavefront", "Wavefront Scheduling", false, false)
INITIALIZE_PASS_DEPENDENCY(JSEdgeRemoval)
INITIALIZE_PASS_END(WavefrontScheduling, "wavefront", "Wavefront Scheduling", false, false)
//for opt
static RegisterPass<WavefrontScheduling> X("wavefront", "Wavefront Scheduling", false, false);
<commit_msg>Updated the wavefront scheduling pass to not provide the LoopInfo object to region object routing.<commit_after>/* This pass is meant to show how one uses the Knowledge Construction Engine
 * (KCE). It's pretty simple. Running this pass requires a lot more work and
 * I'm...heh....working on that.
 * - Joshua Scoggins (8/12/2012)
 */
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/RegionInfo.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/DenseSet.h"
#include "KnowledgeConstructionEngine.h"
#include "LLVMWrapper.h"
#include "JSEdgeRemoval.h"
#include "PassDependencies.h"
extern "C" {
#include "clips.h"
}

using namespace llvm;
char nilObject[41] = "(nil of ConstantPointerNull (Pointer 0))";
namespace {
   struct WavefrontScheduling : public FunctionPass {
      static char ID;
      public:
      WavefrontScheduling() : FunctionPass(ID) {
         InitializeRuntimeAnalyzer();
      }
      virtual void getAnalysisUsage(AnalysisUsage &Info) const {
         Info.addRequired<LoopInfo>();
         Info.addRequired<RegionInfo>();
      }
      virtual bool runOnFunction(Function& fn) {
         //do not actually wavefront schedule if we only have one block
         if(fn.size() > 1) {
            char* funcName = (char*)fn.getName().data();
            DenseMap<PointerAddress, std::string> translation;
            std::pair<PointerAddress, std::string> pair(0,"nil");
            translation.insert(pair);
            FunctionNamer namer (translation);
            Reset();
            MakeInstance(nilObject);
            ModifyFunctionContents(fn, namer);
            LoopInfo &li = getAnalysis<LoopInfo>();
            RouteLoopInfo(li, funcName, namer);
            RegionInfo &ri = getAnalysis<RegionInfo>();
            llvm::Region* top = ri.getTopLevelRegion();
            Route(top, funcName, namer);
            Run(-1L);
            return true;
         } else {
            return false;
         }
      }
   };
}
char WavefrontScheduling::ID = 0;
INITIALIZE_PASS_BEGIN(WavefrontScheduling, "wavefront", "Wavefront Scheduling", false, false)
INITIALIZE_PASS_DEPENDENCY(JSEdgeRemoval)
INITIALIZE_PASS_END(WavefrontScheduling, "wavefront", "Wavefront Scheduling", false, false)
//for opt
static RegisterPass<WavefrontScheduling> X("wavefront", "Wavefront Scheduling", false, false);
<|endoftext|>