<commit_before>/* FasTC
 * Copyright (c) 2013 University of North Carolina at Chapel Hill.
 * All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for educational, research, and non-profit purposes, without
 * fee, and without a written agreement is hereby granted, provided that the
 * above copyright notice, this paragraph, and the following four paragraphs
 * appear in all copies.
 *
 * Permission to incorporate this software into commercial products may be
 * obtained by contacting the authors or the Office of Technology Development
 * at the University of North Carolina at Chapel Hill <otd@unc.edu>.
 *
 * This software program and documentation are copyrighted by the University of
 * North Carolina at Chapel Hill. The software program and documentation are
 * supplied "as is," without any accompanying services from the University of
 * North Carolina at Chapel Hill or the authors. The University of North
 * Carolina at Chapel Hill and the authors do not warrant that the operation of
 * the program will be uninterrupted or error-free. The end-user understands
 * that the program was developed for research purposes and is advised not to
 * rely exclusively on the program for any reason.
 *
 * IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE
 * AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,
 * OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF
 * THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA
 * AT CHAPEL HILL OR THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 * THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY
 * DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY
 * STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON
 * AN "AS IS" BASIS, AND THE UNIVERSITY  OF NORTH CAROLINA AT CHAPEL HILL AND
 * THE AUTHORS HAVE NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
 * ENHANCEMENTS, OR MODIFICATIONS.
 *
 * Please send all BUG REPORTS to <pavel@cs.unc.edu>.
 *
 * The authors may be contacted via:
 *
 * Pavel Krajcevski
 * Dept of Computer Science
 * 201 S Columbia St
 * Frederick P. Brooks, Jr. Computer Science Bldg
 * Chapel Hill, NC 27599-3175
 * USA
 *
 * <http://gamma.cs.unc.edu/FasTC/>
 */

#include "gtest/gtest.h"
#include "Image.h"
#include "Pixel.h"

TEST(Image, NonSpecificConstructor) {
  PVRTCC::Pixel p;

  PVRTCC::Image img (4, 4);
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      EXPECT_TRUE(img(i, j) == p);
    }
  }
}

TEST(Image, SpecificConstructor) {
  PVRTCC::Pixel pxs[16];
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      pxs[j*4 + i].R() = i;
      pxs[j*4 + i].G() = j;
    }
  }

  PVRTCC::Image img(4, 4, pxs);
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      EXPECT_TRUE(img(i, j) == pxs[j*4 + i]);
    }
  }
}

TEST(Image, CopyConstructor) {
  PVRTCC::Pixel pxs[16];
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      pxs[j*4 + i].R() = i;
      pxs[j*4 + i].G() = j;
    }
  }

  PVRTCC::Image img(4, 4, pxs);
  PVRTCC::Image img2(img);
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      EXPECT_TRUE(img2(i, j) == pxs[j*4 + i]);
    }
  }
}

TEST(Image, AssignmentOperator) {
  PVRTCC::Pixel pxs[16];
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      pxs[j*4 + i].R() = i;
      pxs[j*4 + i].G() = j;
    }
  }

  PVRTCC::Image img(4, 4, pxs);
  PVRTCC::Image img2 = img;
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      EXPECT_TRUE(img2(i, j) == pxs[j*4 + i]);
    }
  }
}

TEST(Image, BilinearUpscale) {
  PVRTCC::Pixel pxs[16];
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      pxs[j*4 + i].R() = i*2;
      pxs[j*4 + i].G() = j*2;
    }
  }

  PVRTCC::Image img(4, 4, pxs);
  img.BilinearUpscale(1);
  EXPECT_EQ(img.GetWidth(), static_cast<uint32>(8));
  EXPECT_EQ(img.GetHeight(), static_cast<uint32>(8));

  for(uint32 i = 0; i < img.GetWidth(); i++) {
    for(uint32 j = 0; j < img.GetHeight(); j++) {
      if(i == 0) {
        EXPECT_EQ(img(i, j).R(), i);
      } else {
        EXPECT_EQ(img(i, j).R(), i-1);
      }

      if(j == 0) {
        EXPECT_EQ(img(i, j).G(), j);
      } else {
        EXPECT_EQ(img(i, j).G(), j-1);
      }
    }
  }
}

TEST(Image, BilinearUpscaleWrapped) {
  PVRTCC::Pixel pxs[16];

  // Make sure that our bit depth is less than full...
  for(int i = 0; i < 16; i++) {
    const uint8 newBitDepth[4] = { 6, 5, 6, 5 };
    pxs[i].ChangeBitDepth(newBitDepth);
  }

  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      pxs[j*4 + i].R() = i*4;
      pxs[j*4 + i].G() = j*4;
    }
  }

  PVRTCC::Image img(4, 4, pxs);
  img.BilinearUpscale(2, PVRTCC::eWrapMode_Wrap);
  EXPECT_EQ(img.GetWidth(), static_cast<uint32>(16));
  EXPECT_EQ(img.GetHeight(), static_cast<uint32>(16));

  for(uint32 i = 0; i < img.GetWidth(); i++) {
    for(uint32 j = 0; j < img.GetHeight(); j++) {
      const PVRTCC::Pixel &p = img(i, j);

      // First make sure that the bit depth didn't change
      uint8 depth[4];
      p.GetBitDepth(depth);
      EXPECT_EQ(depth[0], 6);
      EXPECT_EQ(depth[1], 5);
      EXPECT_EQ(depth[2], 6);
      EXPECT_EQ(depth[3], 5);

      // Now make sure that the values are correct.
      if(i == 0) {
        EXPECT_EQ(p.R(), 6);
      } else if(i == 1) {
        EXPECT_EQ(p.R(), 3);
      } else if(i == 15) {
        EXPECT_EQ(p.R(), 9);
      } else {
        EXPECT_EQ(p.R(), i-2);
      }

      if(j == 0) {
        EXPECT_EQ(p.G(), 6);
      } else if(j == 1) {
        EXPECT_EQ(p.G(), 3);
      } else if(j == 15) {
        EXPECT_EQ(p.G(), 9);
      } else {
        EXPECT_EQ(p.G(), j-2);
      }
    }
  }
}

TEST(Image, ChangeBitDepth) {
  PVRTCC::Image img(4, 4);

  uint8 testDepth[4] = { 2, 3, 5, 0 };
  img.ChangeBitDepth(testDepth);

  uint8 depth[4];
  for(uint32 j = 0; j < img.GetHeight(); j++) {
    for(uint32 i = 0; i < img.GetWidth(); i++) {
      img(i, j).GetBitDepth(depth);

      for(int d = 0; d < 4; d++) {
        EXPECT_EQ(testDepth[d], depth[d]);
      }
    }
  }
}
<commit_msg>Add a test to make sure that after a bilerp the pixels that should remain unaffected do in fact remain unaffected.<commit_after>/* FasTC
 * Copyright (c) 2013 University of North Carolina at Chapel Hill.
 * All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for educational, research, and non-profit purposes, without
 * fee, and without a written agreement is hereby granted, provided that the
 * above copyright notice, this paragraph, and the following four paragraphs
 * appear in all copies.
 *
 * Permission to incorporate this software into commercial products may be
 * obtained by contacting the authors or the Office of Technology Development
 * at the University of North Carolina at Chapel Hill <otd@unc.edu>.
 *
 * This software program and documentation are copyrighted by the University of
 * North Carolina at Chapel Hill. The software program and documentation are
 * supplied "as is," without any accompanying services from the University of
 * North Carolina at Chapel Hill or the authors. The University of North
 * Carolina at Chapel Hill and the authors do not warrant that the operation of
 * the program will be uninterrupted or error-free. The end-user understands
 * that the program was developed for research purposes and is advised not to
 * rely exclusively on the program for any reason.
 *
 * IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE
 * AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,
 * OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF
 * THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA
 * AT CHAPEL HILL OR THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 * THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY
 * DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY
 * STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON
 * AN "AS IS" BASIS, AND THE UNIVERSITY  OF NORTH CAROLINA AT CHAPEL HILL AND
 * THE AUTHORS HAVE NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
 * ENHANCEMENTS, OR MODIFICATIONS.
 *
 * Please send all BUG REPORTS to <pavel@cs.unc.edu>.
 *
 * The authors may be contacted via:
 *
 * Pavel Krajcevski
 * Dept of Computer Science
 * 201 S Columbia St
 * Frederick P. Brooks, Jr. Computer Science Bldg
 * Chapel Hill, NC 27599-3175
 * USA
 *
 * <http://gamma.cs.unc.edu/FasTC/>
 */

#include "gtest/gtest.h"
#include "Image.h"
#include "Pixel.h"
#include "TestUtils.h"

#include <cstdlib>

TEST(Image, NonSpecificConstructor) {
  PVRTCC::Pixel p;

  PVRTCC::Image img (4, 4);
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      EXPECT_TRUE(img(i, j) == p);
    }
  }
}

TEST(Image, SpecificConstructor) {
  PVRTCC::Pixel pxs[16];
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      pxs[j*4 + i].R() = i;
      pxs[j*4 + i].G() = j;
    }
  }

  PVRTCC::Image img(4, 4, pxs);
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      EXPECT_TRUE(img(i, j) == pxs[j*4 + i]);
    }
  }
}

TEST(Image, CopyConstructor) {
  PVRTCC::Pixel pxs[16];
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      pxs[j*4 + i].R() = i;
      pxs[j*4 + i].G() = j;
    }
  }

  PVRTCC::Image img(4, 4, pxs);
  PVRTCC::Image img2(img);
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      EXPECT_TRUE(img2(i, j) == pxs[j*4 + i]);
    }
  }
}

TEST(Image, AssignmentOperator) {
  PVRTCC::Pixel pxs[16];
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      pxs[j*4 + i].R() = i;
      pxs[j*4 + i].G() = j;
    }
  }

  PVRTCC::Image img(4, 4, pxs);
  PVRTCC::Image img2 = img;
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      EXPECT_TRUE(img2(i, j) == pxs[j*4 + i]);
    }
  }
}

TEST(Image, BilinearUpscale) {
  PVRTCC::Pixel pxs[16];
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      pxs[j*4 + i].R() = i*2;
      pxs[j*4 + i].G() = j*2;
    }
  }

  PVRTCC::Image img(4, 4, pxs);
  img.BilinearUpscale(1);
  EXPECT_EQ(img.GetWidth(), static_cast<uint32>(8));
  EXPECT_EQ(img.GetHeight(), static_cast<uint32>(8));

  for(uint32 i = 0; i < img.GetWidth(); i++) {
    for(uint32 j = 0; j < img.GetHeight(); j++) {
      if(i == 0) {
        EXPECT_EQ(img(i, j).R(), i);
      } else {
        EXPECT_EQ(img(i, j).R(), i-1);
      }

      if(j == 0) {
        EXPECT_EQ(img(i, j).G(), j);
      } else {
        EXPECT_EQ(img(i, j).G(), j-1);
      }
    }
  }
}

TEST(Image, BilinearUpscaleMaintainsPixels) {

  srand(0xabd1ca7e);

  const uint32 w = 4;
  const uint32 h = 4;

  PVRTCC::Pixel pxs[16];
  for(int i = 0; i < w; i++) {
    for(int j = 0; j < h; j++) {
      pxs[j*w + i].R() = rand() % 256;
      pxs[j*w + i].G() = rand() % 256;
      pxs[j*w + i].B() = rand() % 256;
      pxs[j*w + i].A() = rand() % 256;
    }
  }

  PVRTCC::Image img(w, h, pxs);
  img.BilinearUpscale(2);
  EXPECT_EQ(img.GetWidth(), w << 2);
  EXPECT_EQ(img.GetHeight(), h << 2);

  for(uint32 i = 2; i < img.GetWidth(); i+=4) {
    for(uint32 j = 2; j < img.GetHeight(); j+=4) {
      PVRTCC::Pixel p = img(i, j);
      uint32 idx = ((j - 2) / 4) * w + ((i-2)/4);
      EXPECT_EQ(PixelPrinter(p.PackRGBA()), PixelPrinter(pxs[idx].PackRGBA()));
    }
  }
}

TEST(Image, BilinearUpscaleWrapped) {
  PVRTCC::Pixel pxs[16];

  // Make sure that our bit depth is less than full...
  for(int i = 0; i < 16; i++) {
    const uint8 newBitDepth[4] = { 6, 5, 6, 5 };
    pxs[i].ChangeBitDepth(newBitDepth);
  }

  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      pxs[j*4 + i].R() = i*4;
      pxs[j*4 + i].G() = j*4;
    }
  }

  PVRTCC::Image img(4, 4, pxs);
  img.BilinearUpscale(2, PVRTCC::eWrapMode_Wrap);
  EXPECT_EQ(img.GetWidth(), static_cast<uint32>(16));
  EXPECT_EQ(img.GetHeight(), static_cast<uint32>(16));

  for(uint32 i = 0; i < img.GetWidth(); i++) {
    for(uint32 j = 0; j < img.GetHeight(); j++) {
      const PVRTCC::Pixel &p = img(i, j);

      // First make sure that the bit depth didn't change
      uint8 depth[4];
      p.GetBitDepth(depth);
      EXPECT_EQ(depth[0], 6);
      EXPECT_EQ(depth[1], 5);
      EXPECT_EQ(depth[2], 6);
      EXPECT_EQ(depth[3], 5);

      // Now make sure that the values are correct.
      if(i == 0) {
        EXPECT_EQ(p.R(), 6);
      } else if(i == 1) {
        EXPECT_EQ(p.R(), 3);
      } else if(i == 15) {
        EXPECT_EQ(p.R(), 9);
      } else {
        EXPECT_EQ(p.R(), i-2);
      }

      if(j == 0) {
        EXPECT_EQ(p.G(), 6);
      } else if(j == 1) {
        EXPECT_EQ(p.G(), 3);
      } else if(j == 15) {
        EXPECT_EQ(p.G(), 9);
      } else {
        EXPECT_EQ(p.G(), j-2);
      }
    }
  }
}

TEST(Image, ChangeBitDepth) {
  PVRTCC::Image img(4, 4);

  uint8 testDepth[4] = { 2, 3, 5, 0 };
  img.ChangeBitDepth(testDepth);

  uint8 depth[4];
  for(uint32 j = 0; j < img.GetHeight(); j++) {
    for(uint32 i = 0; i < img.GetWidth(); i++) {
      img(i, j).GetBitDepth(depth);

      for(int d = 0; d < 4; d++) {
        EXPECT_EQ(testDepth[d], depth[d]);
      }
    }
  }
}
<|endoftext|>


<commit_before>#include "AliGFWWeights.h"
#include "TMath.h"
AliGFWWeights::AliGFWWeights():
  fDataFilled(kFALSE),
  fMCFilled(kFALSE),
  fW_data(0),
  fW_mcrec(0),
  fW_mcgen(0),
  fEffInt(0),
  fAccInt(0),
  fNbinsPt(0),
  fbinsPt(0)
{
};
AliGFWWeights::~AliGFWWeights()
{
  delete fW_data;
  delete fW_mcrec;
  delete fW_mcgen;
  delete fEffInt;
  delete fAccInt;
  if(fbinsPt) delete [] fbinsPt;
};
void AliGFWWeights::SetPtBins(Int_t Nbins, Double_t *bins) {
  if(fbinsPt) delete [] fbinsPt;
  fNbinsPt = Nbins;
  fbinsPt = new Double_t[fNbinsPt+1];
  for(Int_t i=0;i<=fNbinsPt;++i) fbinsPt[i] = bins[i];
};
void AliGFWWeights::Init(Bool_t AddData, Bool_t AddMC)
{
  fW_data = new TObjArray();
  fW_data->SetName("AliGFWWeights_Data");
  fW_mcrec = new TObjArray();
  fW_mcrec->SetName("AliGFWWeights_MCRec");
  fW_mcgen = new TObjArray();
  fW_mcgen->SetName("AliGFWWeights_MCGen");
  fW_data->SetOwner(kTRUE);
  fW_mcrec->SetOwner(kTRUE);
  fW_mcgen->SetOwner(kTRUE);
  fDataFilled = kFALSE;
  fMCFilled = kFALSE;
  if(!fbinsPt) { //If pT bins not initialized, set to default (-1 to 1e6) to accept everything
    fNbinsPt=1;
    fbinsPt = new Double_t[2];
    fbinsPt[0] = -1;
    fbinsPt[1] = 1e6;
  };
  if(AddData) {
    const char *tnd = GetBinName(0,0,Form("data_%s",this->GetName()));
    fW_data->Add(new TH3D(tnd,";#varphi;#eta;v_{z}",60,0,TMath::TwoPi(),64,-1.6,1.6,40,-10,10));
  };
  if(AddMC) {
    const char *tnr = GetBinName(0,0,"mcrec"); //all integrated over cent. anyway
    const char *tng = GetBinName(0,0,"mcgen"); //all integrated over cent. anyway
    fW_mcrec->Add(new TH3D(tnr,";#it{p}_{T};#eta;v_{z}",fNbinsPt,0,20,64,-1.6,1.6,40,-10,10));
    fW_mcgen->Add(new TH3D(tng,";#it{p}_{T};#eta;v_{z}",fNbinsPt,0,20,64,-1.6,1.6,40,-10,10));
    ((TH3D*)fW_mcrec->At(fW_mcrec->GetEntries()-1))->GetXaxis()->Set(fNbinsPt,fbinsPt);
    ((TH3D*)fW_mcgen->At(fW_mcgen->GetEntries()-1))->GetXaxis()->Set(fNbinsPt,fbinsPt);
  };
};

void AliGFWWeights::Fill(Double_t phi, Double_t eta, Double_t vz, Double_t pt, Double_t cent, Int_t htype) {
  TObjArray *tar=0;
  const char *pf="";
  if(htype==0) { tar = fW_data; pf = Form("data_%s",this->GetName()); };
  if(htype==1) { tar = fW_mcrec; pf = "mcrec"; };
  if(htype==2) { tar = fW_mcgen; pf = "mcgen"; };
  if(!tar) return;
  TH3D *th3 = (TH3D*)tar->FindObject(GetBinName(0,0,pf)); //pT bin 0, V0M bin 0, since all integrated
  if(!th3) {
    if(!htype) tar->Add(new TH3D(GetBinName(0,0,pf),";#varphi;#eta;v_{z}",60,0,TMath::TwoPi(),64,-1.6,1.6,40,-10,10)); //0,0 since all integrated
    th3 = (TH3D*)tar->At(tar->GetEntries()-1);
  };
  th3->Fill(htype?pt:phi,eta,vz);
};
Double_t AliGFWWeights::GetWeight(Double_t phi, Double_t eta, Double_t vz, Double_t pt, Double_t cent, Int_t htype) {
  TObjArray *tar=0;
  const char *pf="";
  if(htype==0) { tar = fW_data; pf = "data"; };
  if(htype==1) { tar = fW_mcrec; pf = "mcrec"; };
  if(htype==2) { tar = fW_mcgen; pf = "mcgen"; };
  if(!tar) return 1;
  TH3D *th3 = (TH3D*)tar->FindObject(GetBinName(0,0,pf));
  if(!th3) return 1;//-1;
  Int_t xind = th3->GetXaxis()->FindBin(htype?pt:phi);
  Int_t etaind = th3->GetYaxis()->FindBin(eta);
  Int_t vzind = th3->GetZaxis()->FindBin(vz);
  Double_t weight = th3->GetBinContent(xind, etaind, vzind);
  if(weight!=0) return 1./weight;
  return 1;
};
Double_t AliGFWWeights::FindMax(TH3D *inh, Int_t &ix, Int_t &iy, Int_t &iz) {
  Double_t maxv=inh->GetBinContent(1,1,1);
  for(Int_t i=1;i<=inh->GetNbinsX();i++)
    for(Int_t j=1;j<=inh->GetNbinsY();j++)
      for(Int_t k=1;k<=inh->GetNbinsZ();k++)
	if(inh->GetBinContent(i,j,k)>maxv) {
	  ix=i;
	  iy=j;
	  iz=k;
	  maxv=inh->GetBinContent(i,j,k);
	};
  return maxv;
};
void AliGFWWeights::MCToEfficiency() {
  if(fW_mcgen->GetEntries()<1) {
    printf("MC gen. array empty. This is probably because effs. have been calculated and the generated particle histograms have been cleared out!\n");
    return;
  };
  for(Int_t i=0;i<fW_mcrec->GetEntries();i++) {
    TH3D *hr = (TH3D*)fW_mcrec->At(i);
    TH3D *hg = (TH3D*)fW_mcgen->At(i);
    hr->Sumw2();
    hg->Sumw2();
    hr->Divide(hg);
  };
  fW_mcgen->Clear();
};
void AliGFWWeights::CreateNUA(Bool_t IntegrateOverCentAndPt) {
  if(!IntegrateOverCentAndPt) {
    printf("Method is outdated! NUA is integrated over centrality and pT. Quit now, or the behaviour will be bad\n");
    return;
  };
  TH3D *h3;
  TH1D *h1;
  if(fW_data->GetEntries()<1) return;
  if(IntegrateOverCentAndPt) {
    if(fAccInt) delete fAccInt;
    fAccInt = (TH3D*)fW_data->At(0)->Clone("IntegratedAcceptance");
    fAccInt->RebinY(2);
    fAccInt->RebinZ(5);
    fAccInt->Sumw2();
    for(Int_t etai=1;etai<=fAccInt->GetNbinsY();etai++) {
      fAccInt->GetYaxis()->SetRange(etai,etai);
      if(fAccInt->Integral()<1) continue;
      for(Int_t vzi=1;vzi<=fAccInt->GetNbinsZ();vzi++) {
	fAccInt->GetZaxis()->SetRange(vzi,vzi);
	if(fAccInt->Integral()<1) continue;
	h1 = (TH1D*)fAccInt->Project3D("x");
	Double_t maxv = h1->GetMaximum();
	for(Int_t phii=1;phii<=h1->GetNbinsX();phii++)
	  fAccInt->SetBinContent(phii,etai,vzi,fAccInt->GetBinContent(phii,etai,vzi)/maxv);
	delete h1;
      };
      fAccInt->GetZaxis()->SetRange(1,fAccInt->GetNbinsZ());
    };
    fAccInt->GetYaxis()->SetRange(1,fAccInt->GetNbinsY());
    return;
  };
};
void AliGFWWeights::CreateNUE(Bool_t IntegrateOverCentrality) {
  if(!IntegrateOverCentrality) {
    printf("Method is outdated! NUE is integrated over centrality. Quit now, or the behaviour will be bad\n");
    return;
  };
  TH3D *num=0;
  TH3D *den=0;
  if(fW_mcrec->GetEntries()<1 || fW_mcgen->GetEntries()<1) return;
  if(IntegrateOverCentrality) {
    num=(TH3D*)fW_mcrec->At(0);//->Clone(Form("temp_%s",fW_mcrec->At(0)->GetName()));
    den=(TH3D*)fW_mcgen->At(0);//->Clone(Form("temp_%s",fW_mcgen->At(0)->GetName()));
    num->Sumw2();
    den->Sumw2();
    num->RebinY(2);
    den->RebinY(2);
    num->RebinZ(5);
    den->RebinZ(5);
    fEffInt = (TH3D*)num->Clone("Efficiency_Integrated");
    fEffInt->Divide(den);
    return;
  };
};
void AliGFWWeights::ReadAndMerge(const char *filelinks) {
  FILE *flist = fopen(filelinks,"r");
  char str[150];
  Int_t nFiles=0;
  while(fscanf(flist,"%s\n",str)==1) nFiles++;
  rewind(flist);
  if(nFiles==0) {
    printf("No files to read!\n");
    return;
  };
  if(!fW_data) {
    fW_data = new TObjArray();
    fW_data->SetName("Weights_Data");
    fW_data->SetOwner(kTRUE);
  };
  if(!fW_mcrec) {
    fW_mcrec = new TObjArray();
    fW_mcrec->SetName("Weights_MCRec");
    fW_mcrec->SetOwner(kTRUE);
  };
  if(!fW_mcgen) {
    fW_mcgen = new TObjArray();
    fW_mcgen->SetName("Weights_MCGen");
    fW_mcgen->SetOwner(kTRUE);
  };
  fDataFilled = kFALSE;
  fMCFilled = kFALSE;
  TFile *tf=0;
  for(Int_t i=0;i<nFiles;i++) {
    Int_t trash = fscanf(flist,"%s\n",str);
    tf = new TFile(str,"READ");
    if(tf->IsZombie()) {
      printf("Could not open file %s!\n",str);
      tf->Close();
      continue;
    };
    TList *tl = (TList*)tf->Get("OutputList");
    AliGFWWeights *tw = (AliGFWWeights*)tl->FindObject(this->GetName());
    if(!tw) {
      printf("Could not fetch weights object from %s\n",str);
      tf->Close();
      continue;
    };
    AddArray(fW_data,tw->GetDataArray());
    AddArray(fW_mcrec,tw->GetRecArray());
    AddArray(fW_mcgen,tw->GetGenArray());
    tf->Close();
    delete tw;
  };
};
void AliGFWWeights::AddArray(TObjArray *targ, TObjArray *sour) {
  if(!sour) {
    printf("Source array does not exist!\n");
    return;
  };
  for(Int_t i=0;i<sour->GetEntries();i++) {
    TH3D *sourh = (TH3D*)sour->At(i);
    TH3D *targh = (TH3D*)targ->FindObject(sourh->GetName());
    if(!targh) {
      targh = (TH3D*)sourh->Clone(sourh->GetName());
      targh->SetDirectory(0);
      targ->Add(targh);
    } else
      targh->Add(sourh);
  };
};
Long64_t AliGFWWeights::Merge(TCollection *collist) {
  Long64_t nmerged=0;
  if(!fW_data) {
    fW_data = new TObjArray();
    fW_data->SetName("Weights_Data");
    fW_data->SetOwner(kTRUE);
  };
  if(!fW_mcrec) {
    fW_mcrec = new TObjArray();
    fW_mcrec->SetName("Weights_MCRec");
    fW_mcrec->SetOwner(kTRUE);
  };
  if(!fW_mcgen) {
    fW_mcgen = new TObjArray();
    fW_mcgen->SetName("Weights_MCGen");
    fW_mcgen->SetOwner(kTRUE);
  };
  AliGFWWeights *l_w = 0;
  TIter all_w(collist);
  while (l_w = (AliGFWWeights*) all_w()) {
    AddArray(fW_data,l_w->GetDataArray());
    AddArray(fW_mcrec,tw->GetRecArray());
    AddArray(fW_mcgen,tw->GetGenArray());
    nmerged++;
  };
  return nmerged;
};
<commit_msg>Fixed the wrong variable name in AliGFWWeights<commit_after>#include "AliGFWWeights.h"
#include "TMath.h"
AliGFWWeights::AliGFWWeights():
  fDataFilled(kFALSE),
  fMCFilled(kFALSE),
  fW_data(0),
  fW_mcrec(0),
  fW_mcgen(0),
  fEffInt(0),
  fAccInt(0),
  fNbinsPt(0),
  fbinsPt(0)
{
};
AliGFWWeights::~AliGFWWeights()
{
  delete fW_data;
  delete fW_mcrec;
  delete fW_mcgen;
  delete fEffInt;
  delete fAccInt;
  if(fbinsPt) delete [] fbinsPt;
};
void AliGFWWeights::SetPtBins(Int_t Nbins, Double_t *bins) {
  if(fbinsPt) delete [] fbinsPt;
  fNbinsPt = Nbins;
  fbinsPt = new Double_t[fNbinsPt+1];
  for(Int_t i=0;i<=fNbinsPt;++i) fbinsPt[i] = bins[i];
};
void AliGFWWeights::Init(Bool_t AddData, Bool_t AddMC)
{
  fW_data = new TObjArray();
  fW_data->SetName("AliGFWWeights_Data");
  fW_mcrec = new TObjArray();
  fW_mcrec->SetName("AliGFWWeights_MCRec");
  fW_mcgen = new TObjArray();
  fW_mcgen->SetName("AliGFWWeights_MCGen");
  fW_data->SetOwner(kTRUE);
  fW_mcrec->SetOwner(kTRUE);
  fW_mcgen->SetOwner(kTRUE);
  fDataFilled = kFALSE;
  fMCFilled = kFALSE;
  if(!fbinsPt) { //If pT bins not initialized, set to default (-1 to 1e6) to accept everything
    fNbinsPt=1;
    fbinsPt = new Double_t[2];
    fbinsPt[0] = -1;
    fbinsPt[1] = 1e6;
  };
  if(AddData) {
    const char *tnd = GetBinName(0,0,Form("data_%s",this->GetName()));
    fW_data->Add(new TH3D(tnd,";#varphi;#eta;v_{z}",60,0,TMath::TwoPi(),64,-1.6,1.6,40,-10,10));
  };
  if(AddMC) {
    const char *tnr = GetBinName(0,0,"mcrec"); //all integrated over cent. anyway
    const char *tng = GetBinName(0,0,"mcgen"); //all integrated over cent. anyway
    fW_mcrec->Add(new TH3D(tnr,";#it{p}_{T};#eta;v_{z}",fNbinsPt,0,20,64,-1.6,1.6,40,-10,10));
    fW_mcgen->Add(new TH3D(tng,";#it{p}_{T};#eta;v_{z}",fNbinsPt,0,20,64,-1.6,1.6,40,-10,10));
    ((TH3D*)fW_mcrec->At(fW_mcrec->GetEntries()-1))->GetXaxis()->Set(fNbinsPt,fbinsPt);
    ((TH3D*)fW_mcgen->At(fW_mcgen->GetEntries()-1))->GetXaxis()->Set(fNbinsPt,fbinsPt);
  };
};

void AliGFWWeights::Fill(Double_t phi, Double_t eta, Double_t vz, Double_t pt, Double_t cent, Int_t htype) {
  TObjArray *tar=0;
  const char *pf="";
  if(htype==0) { tar = fW_data; pf = Form("data_%s",this->GetName()); };
  if(htype==1) { tar = fW_mcrec; pf = "mcrec"; };
  if(htype==2) { tar = fW_mcgen; pf = "mcgen"; };
  if(!tar) return;
  TH3D *th3 = (TH3D*)tar->FindObject(GetBinName(0,0,pf)); //pT bin 0, V0M bin 0, since all integrated
  if(!th3) {
    if(!htype) tar->Add(new TH3D(GetBinName(0,0,pf),";#varphi;#eta;v_{z}",60,0,TMath::TwoPi(),64,-1.6,1.6,40,-10,10)); //0,0 since all integrated
    th3 = (TH3D*)tar->At(tar->GetEntries()-1);
  };
  th3->Fill(htype?pt:phi,eta,vz);
};
Double_t AliGFWWeights::GetWeight(Double_t phi, Double_t eta, Double_t vz, Double_t pt, Double_t cent, Int_t htype) {
  TObjArray *tar=0;
  const char *pf="";
  if(htype==0) { tar = fW_data; pf = "data"; };
  if(htype==1) { tar = fW_mcrec; pf = "mcrec"; };
  if(htype==2) { tar = fW_mcgen; pf = "mcgen"; };
  if(!tar) return 1;
  TH3D *th3 = (TH3D*)tar->FindObject(GetBinName(0,0,pf));
  if(!th3) return 1;//-1;
  Int_t xind = th3->GetXaxis()->FindBin(htype?pt:phi);
  Int_t etaind = th3->GetYaxis()->FindBin(eta);
  Int_t vzind = th3->GetZaxis()->FindBin(vz);
  Double_t weight = th3->GetBinContent(xind, etaind, vzind);
  if(weight!=0) return 1./weight;
  return 1;
};
Double_t AliGFWWeights::FindMax(TH3D *inh, Int_t &ix, Int_t &iy, Int_t &iz) {
  Double_t maxv=inh->GetBinContent(1,1,1);
  for(Int_t i=1;i<=inh->GetNbinsX();i++)
    for(Int_t j=1;j<=inh->GetNbinsY();j++)
      for(Int_t k=1;k<=inh->GetNbinsZ();k++)
	if(inh->GetBinContent(i,j,k)>maxv) {
	  ix=i;
	  iy=j;
	  iz=k;
	  maxv=inh->GetBinContent(i,j,k);
	};
  return maxv;
};
void AliGFWWeights::MCToEfficiency() {
  if(fW_mcgen->GetEntries()<1) {
    printf("MC gen. array empty. This is probably because effs. have been calculated and the generated particle histograms have been cleared out!\n");
    return;
  };
  for(Int_t i=0;i<fW_mcrec->GetEntries();i++) {
    TH3D *hr = (TH3D*)fW_mcrec->At(i);
    TH3D *hg = (TH3D*)fW_mcgen->At(i);
    hr->Sumw2();
    hg->Sumw2();
    hr->Divide(hg);
  };
  fW_mcgen->Clear();
};
void AliGFWWeights::CreateNUA(Bool_t IntegrateOverCentAndPt) {
  if(!IntegrateOverCentAndPt) {
    printf("Method is outdated! NUA is integrated over centrality and pT. Quit now, or the behaviour will be bad\n");
    return;
  };
  TH3D *h3;
  TH1D *h1;
  if(fW_data->GetEntries()<1) return;
  if(IntegrateOverCentAndPt) {
    if(fAccInt) delete fAccInt;
    fAccInt = (TH3D*)fW_data->At(0)->Clone("IntegratedAcceptance");
    fAccInt->RebinY(2);
    fAccInt->RebinZ(5);
    fAccInt->Sumw2();
    for(Int_t etai=1;etai<=fAccInt->GetNbinsY();etai++) {
      fAccInt->GetYaxis()->SetRange(etai,etai);
      if(fAccInt->Integral()<1) continue;
      for(Int_t vzi=1;vzi<=fAccInt->GetNbinsZ();vzi++) {
	fAccInt->GetZaxis()->SetRange(vzi,vzi);
	if(fAccInt->Integral()<1) continue;
	h1 = (TH1D*)fAccInt->Project3D("x");
	Double_t maxv = h1->GetMaximum();
	for(Int_t phii=1;phii<=h1->GetNbinsX();phii++)
	  fAccInt->SetBinContent(phii,etai,vzi,fAccInt->GetBinContent(phii,etai,vzi)/maxv);
	delete h1;
      };
      fAccInt->GetZaxis()->SetRange(1,fAccInt->GetNbinsZ());
    };
    fAccInt->GetYaxis()->SetRange(1,fAccInt->GetNbinsY());
    return;
  };
};
void AliGFWWeights::CreateNUE(Bool_t IntegrateOverCentrality) {
  if(!IntegrateOverCentrality) {
    printf("Method is outdated! NUE is integrated over centrality. Quit now, or the behaviour will be bad\n");
    return;
  };
  TH3D *num=0;
  TH3D *den=0;
  if(fW_mcrec->GetEntries()<1 || fW_mcgen->GetEntries()<1) return;
  if(IntegrateOverCentrality) {
    num=(TH3D*)fW_mcrec->At(0);//->Clone(Form("temp_%s",fW_mcrec->At(0)->GetName()));
    den=(TH3D*)fW_mcgen->At(0);//->Clone(Form("temp_%s",fW_mcgen->At(0)->GetName()));
    num->Sumw2();
    den->Sumw2();
    num->RebinY(2);
    den->RebinY(2);
    num->RebinZ(5);
    den->RebinZ(5);
    fEffInt = (TH3D*)num->Clone("Efficiency_Integrated");
    fEffInt->Divide(den);
    return;
  };
};
void AliGFWWeights::ReadAndMerge(const char *filelinks) {
  FILE *flist = fopen(filelinks,"r");
  char str[150];
  Int_t nFiles=0;
  while(fscanf(flist,"%s\n",str)==1) nFiles++;
  rewind(flist);
  if(nFiles==0) {
    printf("No files to read!\n");
    return;
  };
  if(!fW_data) {
    fW_data = new TObjArray();
    fW_data->SetName("Weights_Data");
    fW_data->SetOwner(kTRUE);
  };
  if(!fW_mcrec) {
    fW_mcrec = new TObjArray();
    fW_mcrec->SetName("Weights_MCRec");
    fW_mcrec->SetOwner(kTRUE);
  };
  if(!fW_mcgen) {
    fW_mcgen = new TObjArray();
    fW_mcgen->SetName("Weights_MCGen");
    fW_mcgen->SetOwner(kTRUE);
  };
  fDataFilled = kFALSE;
  fMCFilled = kFALSE;
  TFile *tf=0;
  for(Int_t i=0;i<nFiles;i++) {
    Int_t trash = fscanf(flist,"%s\n",str);
    tf = new TFile(str,"READ");
    if(tf->IsZombie()) {
      printf("Could not open file %s!\n",str);
      tf->Close();
      continue;
    };
    TList *tl = (TList*)tf->Get("OutputList");
    AliGFWWeights *tw = (AliGFWWeights*)tl->FindObject(this->GetName());
    if(!tw) {
      printf("Could not fetch weights object from %s\n",str);
      tf->Close();
      continue;
    };
    AddArray(fW_data,tw->GetDataArray());
    AddArray(fW_mcrec,tw->GetRecArray());
    AddArray(fW_mcgen,tw->GetGenArray());
    tf->Close();
    delete tw;
  };
};
void AliGFWWeights::AddArray(TObjArray *targ, TObjArray *sour) {
  if(!sour) {
    printf("Source array does not exist!\n");
    return;
  };
  for(Int_t i=0;i<sour->GetEntries();i++) {
    TH3D *sourh = (TH3D*)sour->At(i);
    TH3D *targh = (TH3D*)targ->FindObject(sourh->GetName());
    if(!targh) {
      targh = (TH3D*)sourh->Clone(sourh->GetName());
      targh->SetDirectory(0);
      targ->Add(targh);
    } else
      targh->Add(sourh);
  };
};
Long64_t AliGFWWeights::Merge(TCollection *collist) {
  Long64_t nmerged=0;
  if(!fW_data) {
    fW_data = new TObjArray();
    fW_data->SetName("Weights_Data");
    fW_data->SetOwner(kTRUE);
  };
  if(!fW_mcrec) {
    fW_mcrec = new TObjArray();
    fW_mcrec->SetName("Weights_MCRec");
    fW_mcrec->SetOwner(kTRUE);
  };
  if(!fW_mcgen) {
    fW_mcgen = new TObjArray();
    fW_mcgen->SetName("Weights_MCGen");
    fW_mcgen->SetOwner(kTRUE);
  };
  AliGFWWeights *l_w = 0;
  TIter all_w(collist);
  while (l_w = ((AliGFWWeights*) all_w())) {
    AddArray(fW_data,l_w->GetDataArray());
    AddArray(fW_mcrec,l_w->GetRecArray());
    AddArray(fW_mcgen,l_w->GetGenArray());
    nmerged++;
  };
  return nmerged;
};
<|endoftext|>


<commit_before>/******************************************************************************
 * This file is part of dirtsand.                                             *
 *                                                                            *
 * dirtsand is free software: you can redistribute it and/or modify           *
 * it under the terms of the GNU Affero General Public License as             *
 * published by the Free Software Foundation, either version 3 of the         *
 * License, or (at your option) any later version.                            *
 *                                                                            *
 * dirtsand 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 Affero General Public License for more details.                        *
 *                                                                            *
 * You should have received a copy of the GNU Affero General Public License   *
 * along with dirtsand.  If not, see <http://www.gnu.org/licenses/>.          *
 ******************************************************************************/

#include "AvSeekMsg.h"

void MOUL::AvSeekMsg::read(DS::Stream* stream)
{
    AvTaskMsg::read(stream);

    m_seekPoint.read(stream);
    if (!m_seekPoint.isNull()) {
        m_targetPos = stream->read<DS::Vector3>();
        m_targetLook = stream->read<DS::Vector3>();
    }
    m_duration = stream->read<float>();
    m_smartSeek = stream->read<bool>();
    m_animName = stream->readSafeString();
    m_alignType = stream->read<uint16_t>();
    m_noSeek = stream->read<bool>();
    m_flags = stream->read<uint8_t>();
    m_finishKey.read(stream);
}

void MOUL::AvSeekMsg::write(DS::Stream* stream) const
{
    AvTaskMsg::write(stream);

    m_seekPoint.write(stream);
    if (!m_seekPoint.isNull()) {
        stream->write<DS::Vector3>(m_targetPos);
        stream->write<DS::Vector3>(m_targetLook);
    }
    stream->write<float>(m_duration);
    stream->write<bool>(m_smartSeek);
    stream->writeSafeString(m_animName);
    stream->write<uint16_t>(m_alignType);
    stream->write<bool>(m_noSeek);
    stream->write<uint8_t>(m_flags);
    m_finishKey.write(stream);
}

void MOUL::AvOneShotMsg::read(DS::Stream* stream)
{
    AvSeekMsg::read(stream);

    m_oneShotAnimName = stream->readSafeString();
    m_drivable = stream->read<bool>();
    m_reversible = stream->read<bool>();
}

void MOUL::AvOneShotMsg::write(DS::Stream* stream) const
{
    AvSeekMsg::write(stream);

    stream->writeSafeString(m_oneShotAnimName);
    stream->write<bool>(m_drivable);
    stream->write<bool>(m_reversible);
}
<commit_msg>Fix typo when reading/writing AvSeekMsg<commit_after>/******************************************************************************
 * This file is part of dirtsand.                                             *
 *                                                                            *
 * dirtsand is free software: you can redistribute it and/or modify           *
 * it under the terms of the GNU Affero General Public License as             *
 * published by the Free Software Foundation, either version 3 of the         *
 * License, or (at your option) any later version.                            *
 *                                                                            *
 * dirtsand 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 Affero General Public License for more details.                        *
 *                                                                            *
 * You should have received a copy of the GNU Affero General Public License   *
 * along with dirtsand.  If not, see <http://www.gnu.org/licenses/>.          *
 ******************************************************************************/

#include "AvSeekMsg.h"

void MOUL::AvSeekMsg::read(DS::Stream* stream)
{
    AvTaskMsg::read(stream);

    m_seekPoint.read(stream);
    if (m_seekPoint.isNull()) {
        m_targetPos = stream->read<DS::Vector3>();
        m_targetLook = stream->read<DS::Vector3>();
    }
    m_duration = stream->read<float>();
    m_smartSeek = stream->read<bool>();
    m_animName = stream->readSafeString();
    m_alignType = stream->read<uint16_t>();
    m_noSeek = stream->read<bool>();
    m_flags = stream->read<uint8_t>();
    m_finishKey.read(stream);
}

void MOUL::AvSeekMsg::write(DS::Stream* stream) const
{
    AvTaskMsg::write(stream);

    m_seekPoint.write(stream);
    if (m_seekPoint.isNull()) {
        stream->write<DS::Vector3>(m_targetPos);
        stream->write<DS::Vector3>(m_targetLook);
    }
    stream->write<float>(m_duration);
    stream->write<bool>(m_smartSeek);
    stream->writeSafeString(m_animName);
    stream->write<uint16_t>(m_alignType);
    stream->write<bool>(m_noSeek);
    stream->write<uint8_t>(m_flags);
    m_finishKey.write(stream);
}

void MOUL::AvOneShotMsg::read(DS::Stream* stream)
{
    AvSeekMsg::read(stream);

    m_oneShotAnimName = stream->readSafeString();
    m_drivable = stream->read<bool>();
    m_reversible = stream->read<bool>();
}

void MOUL::AvOneShotMsg::write(DS::Stream* stream) const
{
    AvSeekMsg::write(stream);

    stream->writeSafeString(m_oneShotAnimName);
    stream->write<bool>(m_drivable);
    stream->write<bool>(m_reversible);
}
<|endoftext|>


<commit_before>
#include "../../Flare.h"
#include "FlareShipStatus.h"

#define LOCTEXT_NAMESPACE "FlareShipStatus"

/*----------------------------------------------------
	Construct
----------------------------------------------------*/

void SFlareShipStatus::Construct(const FArguments& InArgs)
{
	TargetShip = InArgs._Ship;

	ChildSlot
	.VAlign(VAlign_Fill)
	.HAlign(HAlign_Fill)
	.Padding(FMargin(8))
	[
		SNew(SHorizontalBox)

		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage)
			.Image(FFlareStyleSet::GetIcon("Temperature"))
			.ColorAndOpacity(FLinearColor::Red)
			.Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Temperature)
		]

		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage)
			.Image(FFlareStyleSet::GetIcon("Power"))
			.ColorAndOpacity(FLinearColor::Red)
			.Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Power)
		]

		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage)
			.Image(FFlareStyleSet::GetIcon("Propulsion"))
			.ColorAndOpacity(FLinearColor::Red)
			.Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Propulsion)
		]

		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage)
			.Image(FFlareStyleSet::GetIcon("RCS"))
			.ColorAndOpacity(FLinearColor::Red)
			.Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_RCS)
		]

		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage)
			.Image(FFlareStyleSet::GetIcon("LifeSupport"))
			.ColorAndOpacity(FLinearColor::Red)
			.Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_LifeSupport)
		]

		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage)
			.Image(FFlareStyleSet::GetIcon("Shell"))
			.ColorAndOpacity(FLinearColor::Red)
			.Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Weapon)
		]
	];
}

/*----------------------------------------------------
	Interaction
----------------------------------------------------*/

void SFlareShipStatus::SetTargetShip(IFlareShipInterface* Target)
{
	TargetShip = Target;
}

/*----------------------------------------------------
	Callbacks
----------------------------------------------------*/

EVisibility SFlareShipStatus::IsVisible(EFlareSubsystem::Type Type) const
{
	if (TargetShip)
	{
		return ((TargetShip->GetSubsystemHealth(Type) <= 0.3f) ? EVisibility::Visible : EVisibility::Collapsed);
	}
	{
		return EVisibility::Collapsed;
	}
}

#undef LOCTEXT_NAMESPACE
<commit_msg>Nicer color for disabled systems in menus<commit_after>
#include "../../Flare.h"
#include "FlareShipStatus.h"

#define LOCTEXT_NAMESPACE "FlareShipStatus"

/*----------------------------------------------------
	Construct
----------------------------------------------------*/

void SFlareShipStatus::Construct(const FArguments& InArgs)
{
	TargetShip = InArgs._Ship;
	FLinearColor Color(1.0, 0.05, 0, 1.0);

	ChildSlot
	.VAlign(VAlign_Fill)
	.HAlign(HAlign_Fill)
	.Padding(FMargin(8))
	[
		SNew(SHorizontalBox)

		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage)
			.Image(FFlareStyleSet::GetIcon("Temperature"))
			.ColorAndOpacity(Color)
			.Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Temperature)
		]

		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage)
			.Image(FFlareStyleSet::GetIcon("Power"))
			.ColorAndOpacity(Color)
			.Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Power)
		]

		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage)
			.Image(FFlareStyleSet::GetIcon("Propulsion"))
			.ColorAndOpacity(Color)
			.Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Propulsion)
		]

		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage)
			.Image(FFlareStyleSet::GetIcon("RCS"))
			.ColorAndOpacity(Color)
			.Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_RCS)
		]

		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage)
			.Image(FFlareStyleSet::GetIcon("LifeSupport"))
			.ColorAndOpacity(Color)
			.Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_LifeSupport)
		]

		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage)
			.Image(FFlareStyleSet::GetIcon("Shell"))
			.ColorAndOpacity(Color)
			.Visibility(this, &SFlareShipStatus::IsVisible, EFlareSubsystem::SYS_Weapon)
		]
	];
}

/*----------------------------------------------------
	Interaction
----------------------------------------------------*/

void SFlareShipStatus::SetTargetShip(IFlareShipInterface* Target)
{
	TargetShip = Target;
}

/*----------------------------------------------------
	Callbacks
----------------------------------------------------*/

EVisibility SFlareShipStatus::IsVisible(EFlareSubsystem::Type Type) const
{
	if (TargetShip)
	{
		return ((TargetShip->GetSubsystemHealth(Type) <= 0.3f) ? EVisibility::Visible : EVisibility::Collapsed);
	}
	{
		return EVisibility::Collapsed;
	}
}

#undef LOCTEXT_NAMESPACE
<|endoftext|>


<commit_before>#include <assert.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <iostream>
#include "Create.h"
#include "File.h"
#include "Map.h"
#include "Node.h"
#include "stdlib.h"
#include "utils.h"
namespace Maps
{
  Map::Map(): Map(DEFAULT_MAP_SIZE) {
    setID(0);
    for (auto &i: grid) { i = new Node; }
    buildMoveData();
  }

  Map::Map(int mapSize): grid{mapSize*mapSize, nullptr}
  , mapSize{mapSize} {
    setID(0);
  }

  Map::~Map() {
    deleteGrid();
  }

  void Map::activate() {
    for ( auto &node : grid ) {
      node->activate();
    }
  }

  void Map::setNode(int xInd, int yInd, Node* node) {
    // Reference to node ptr being replaced
    Node *&alreadyThere = grid.at(yInd*mapSize + xInd);
    delete alreadyThere; // Deletes the node that might be there
    alreadyThere = node;
   }

  void Map::buildMoveData() {
    for ( int yIndex( 0 ); yIndex < mapSize; yIndex++ ) {
      for ( int xIndex( 0 ); xIndex < mapSize; xIndex++ ) {
        // Add node links to the current node
        Node &currentNode = *getNode(xIndex, yIndex);
        if ( yIndex < mapSize-1 ) { // Build north
          Node *north = getNode(xIndex, yIndex+1);
          currentNode.setNodeLink(Dir::North, north);
        }
        if ( xIndex < mapSize-1 ) { // build east
          Node *east = getNode(xIndex+1, yIndex);
          currentNode.setNodeLink(Dir::East, east);
        }
        if ( xIndex > 0 ) { // build west
          Node *west = getNode(xIndex-1, yIndex);
          currentNode.setNodeLink(Dir::West, west);
        }
        if ( yIndex > 0 ) { // build south
          Node *south = getNode(xIndex, yIndex-1);
          currentNode.setNodeLink(Dir::South, south);
        }
      }
    }
  }

  Node* Map::getNode(int xInd, int yInd) {
    assert(xInd < mapSize && yInd < mapSize);
    assert(grid.at(yInd*mapSize + xInd) != nullptr);
    return grid.at(yInd*mapSize + xInd);
  }

  void Map::deleteGrid() {
    for (int i(0); i < grid.size(); ++i) {
      delete grid.at(i);
    }
  }

  pairType Map::toTree() {
    using namespace boost::property_tree;
    ptree tree;
    tree.push_back(XML_VAR_PAIR(mapSize));
    // Should a location be saved?
    for (Node* node : grid) {
      tree.push_back(node->toTree());
    }

    return ptree::value_type("Map", tree);
  }

  void Map::fromTree(const pairType &p) {
    const treeType &tree = p.second;

    { // Get the mapSize first:
      auto mapSizeIterator = tree.find("mapSize");
      const std::string &data = mapSizeIterator->second.data();
      mapSize = std::stoi(data);
      deleteGrid();
      grid = std::vector<Node*>(mapSize*mapSize, nullptr);
    }

    auto it = tree.begin();
    int nodeNumber = 0;
    while (it != tree.end()) {
      const std::string &key = it->first;
      const std::string &data = it->second.data();
      if (key == "Node") {
        // Sets the next node from xml
        // Note that since x,y is not recorded in the xml,
        // nodes can only be loaded in the order they were saved
        grid.at(nodeNumber) = Create::newNode(*it);
        nodeNumber++;
      }
      it++;
    }
    // So that the player can move around in the map.
    buildMoveData();
  }

  void Map::save() {
      startSave("Map");

      endSave();
  }

  void Map::load() {
      startLoad("Map");

      endLoad();
  }

} // End namespace Maps
<commit_msg>Map LS<commit_after>#include <assert.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <iostream>
#include "Create.h"
#include "File.h"
#include "Map.h"
#include "Node.h"
#include "stdlib.h"
#include "utils.h"
namespace Maps
{
  Map::Map(): Map(DEFAULT_MAP_SIZE) {
    setID(0);
    for (auto &i: grid) { i = new Node; }
    buildMoveData();
  }

  Map::Map(int mapSize): grid{mapSize*mapSize, nullptr}
  , mapSize{mapSize} {
    setID(0);
  }

  Map::~Map() {
    deleteGrid();
  }

  void Map::activate() {
    for ( auto &node : grid ) {
      node->activate();
    }
  }

  void Map::setNode(int xInd, int yInd, Node* node) {
    // Reference to node ptr being replaced
    Node *&alreadyThere = grid.at(yInd*mapSize + xInd);
    delete alreadyThere; // Deletes the node that might be there
    alreadyThere = node;
   }

  void Map::buildMoveData() {
    for ( int yIndex( 0 ); yIndex < mapSize; yIndex++ ) {
      for ( int xIndex( 0 ); xIndex < mapSize; xIndex++ ) {
        // Add node links to the current node
        Node &currentNode = *getNode(xIndex, yIndex);
        if ( yIndex < mapSize-1 ) { // Build north
          Node *north = getNode(xIndex, yIndex+1);
          currentNode.setNodeLink(Dir::North, north);
        }
        if ( xIndex < mapSize-1 ) { // build east
          Node *east = getNode(xIndex+1, yIndex);
          currentNode.setNodeLink(Dir::East, east);
        }
        if ( xIndex > 0 ) { // build west
          Node *west = getNode(xIndex-1, yIndex);
          currentNode.setNodeLink(Dir::West, west);
        }
        if ( yIndex > 0 ) { // build south
          Node *south = getNode(xIndex, yIndex-1);
          currentNode.setNodeLink(Dir::South, south);
        }
      }
    }
  }

  Node* Map::getNode(int xInd, int yInd) {
    assert(xInd < mapSize && yInd < mapSize);
    assert(grid.at(yInd*mapSize + xInd) != nullptr);
    return grid.at(yInd*mapSize + xInd);
  }

  void Map::deleteGrid() {
    for (int i(0); i < grid.size(); ++i) {
      delete grid.at(i);
    }
  }

  pairType Map::toTree() {
    using namespace boost::property_tree;
    ptree tree;
    tree.push_back(XML_VAR_PAIR(mapSize));
    // Should a location be saved?
    for (Node* node : grid) {
      tree.push_back(node->toTree());
    }

    return ptree::value_type("Map", tree);
  }

  void Map::fromTree(const pairType &p) {
    const treeType &tree = p.second;

    { // Get the mapSize first:
      auto mapSizeIterator = tree.find("mapSize");
      const std::string &data = mapSizeIterator->second.data();
      mapSize = std::stoi(data);
      deleteGrid();
      grid = std::vector<Node*>(mapSize*mapSize, nullptr);
    }

    auto it = tree.begin();
    int nodeNumber = 0;
    while (it != tree.end()) {
      const std::string &key = it->first;
      const std::string &data = it->second.data();
      if (key == "Node") {
        // Sets the next node from xml
        // Note that since x,y is not recorded in the xml,
        // nodes can only be loaded in the order they were saved
        grid.at(nodeNumber) = Create::newNode(*it);
        nodeNumber++;
      }
      it++;
    }
    // So that the player can move around in the map.
    buildMoveData();
  }

  void Map::save() {
      startSave("Map");

      // Save the nodes
      SAVE(mapSize);
      for (int i = 0; i < grid.size(); i++) {
          grid.at(i)->save();
      }

      endSave();
  }

  void Map::load() {
      startLoad("Map");

      // Load the nodes
      LOAD(mapSize);
      grid = std::vector<Node*>(mapSize * mapSize, nullptr);
      for (int i = 0; i < grid.size(); i++) {
          grid.at(i) = Create::loadNewNode();
      }
      buildMoveData(); // Get map ready for use.

      endLoad();
  }

} // End namespace Maps
<|endoftext|>


<commit_before>/**
* @file Main.cpp
*/
#include "GLFWEW.h"
#include <glm/gtc/matrix_transform.hpp>
#include <iostream>
#include <vector>

/// 3DxN^[^.
struct Vector3
{
  float x, y, z;
};

/// RGBAJ[^.
struct Color
{
  float r, g, b, a;
};

/// _f[^^.
struct Vertex
{
  Vector3 position; ///< W
  Color color; ///< F
};

/// _f[^.
const Vertex vertices[] = {
  { {-0.5f, -0.3f, 0.5f}, {0.0f, 1.0f, 0.0f, 1.0f} },
  { { 0.3f, -0.3f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f} },
  { { 0.3f,  0.5f, 0.5f}, {1.0f, 0.0f, 0.0f, 1.0f} },
  { {-0.5f,  0.5f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f} },

  { {-0.3f,  0.3f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f} },
  { {-0.3f, -0.5f, 0.1f}, {0.0f, 1.0f, 1.0f, 1.0f} },
  { { 0.5f, -0.5f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f} },
  { { 0.5f, -0.5f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f} },
  { { 0.5f,  0.3f, 0.1f}, {1.0f, 1.0f, 0.0f, 1.0f} },
  { {-0.3f,  0.3f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f} },
};

/// CfbNXf[^.
const GLuint indices[] = {
  0, 1, 2, 2, 3, 0,
  4, 5, 6, 7, 8, 9,
};

/// _VF[_.
static const char* vsCode =
"#version 410 \n"
"layout(location=0) in vec3 vPosition;"
"layout(location=1) in vec4 vColor;"
"layout(location=0) out vec4 outColor;"
"uniform mat4x4 matMVP;"
"void main() {"
"  outColor = vColor;"
"  gl_Position = matMVP * vec4(vPosition, 1.0);"
"}";

/// tOgVF[_.
static const char* fsCode =
"#version 410 \n"
"layout(location=0) in vec4 inColor;"
"out vec4 fragColor;"
"void main() {"
"  fragColor = inColor;"
"}";

/**
* Vertex Buffer Object쐬.
*
* @param size _f[^̃TCY.
* @param data _f[^ւ̃|C^.
*
* @return 쐬VBO.
*/
GLuint CreateVBO(GLsizeiptr size, const GLvoid* data)
{
  GLuint vbo = 0;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
  glBindBuffer(GL_ARRAY_BUFFER, 0);
  return vbo;
}

/**
* Index Buffer Object쐬.
*
* @param size CfbNXf[^̃TCY.
* @param data CfbNXf[^ւ̃|C^.
*
* @return 쐬IBO.
*/
GLuint CreateIBO(GLsizeiptr size, const GLvoid* data)
{
  GLuint ibo = 0;
  glGenBuffers(1, &ibo);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
  glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  return ibo;
}

/**
* _Agr[gݒ肷.
*
* @param index _Agr[g̃CfbNX.
* @param cls   _f[^^.
* @param mbr   _Agr[gɐݒ肷cls̃oϐ.
*/
#define SetVertexAttribPointer(index, cls, mbr) SetVertexAttribPointerI( \
  index, \
  sizeof(cls::mbr) / sizeof(float), \
  sizeof(cls), \
  reinterpret_cast<GLvoid*>(offsetof(cls, mbr)))

void SetVertexAttribPointerI(GLuint index, GLint size, GLsizei stride, const GLvoid* pointer)
{
  glEnableVertexAttribArray(index);
  glVertexAttribPointer(index, size, GL_FLOAT, GL_FALSE, stride, pointer);
}

/**
* Vertex Array Object쐬.
*
* @param vbo VAOɊ֘AtVBO.
* @param ibo VAOɊ֘AtIBO.
*
* @return 쐬VAO.
*/
GLuint CreateVAO(GLuint vbo, GLuint ibo)
{
  GLuint vao = 0;
  glGenVertexArrays(1, &vao);
  glBindVertexArray(vao);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
  SetVertexAttribPointer(0, Vertex, position);
  SetVertexAttribPointer(1, Vertex, color);
  glBindVertexArray(0);
  glDeleteBuffers(1, &vbo);
  glDeleteBuffers(1, &ibo);
  return vao;
}

/**
* VF[_R[hRpC.
*
* @param type VF[_̎.
* @param string VF[_R[hւ̃|C^.
*
* @return 쐬VF[_IuWFNg.
*/
GLuint CompileShader(GLenum type, const GLchar* string)
{
  GLuint shader = glCreateShader(type);
  glShaderSource(shader, 1, &string, nullptr);
  glCompileShader(shader);
  GLint compiled = 0;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
  if (!compiled) {
    GLint infoLen = 0;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
    if (infoLen) {
      std::vector<char> buf;
      buf.resize(infoLen);
      if (static_cast<int>(buf.size()) >= infoLen) {
        glGetShaderInfoLog(shader, infoLen, NULL, buf.data());
        std::cerr << "ERROR: VF[_̃RpCɎsn" << buf.data() << std::endl;
      }
    }
    glDeleteShader(shader);
    return 0;
  }
  return shader;
}

/**
* vOIuWFNg쐬.
*
* @param vsCode _VF[_R[hւ̃|C^.
* @param fsCode tOgVF[_R[hւ̃|C^.
*
* @return 쐬vOIuWFNg.
*/
GLuint CreateShaderProgram(const GLchar* vsCode, const GLchar* fsCode)
{
  GLuint vs = CompileShader(GL_VERTEX_SHADER, vsCode);
  GLuint fs = CompileShader(GL_FRAGMENT_SHADER, fsCode);
  if (!vs || !fs) {
    return 0;
  }
  GLuint program = glCreateProgram();
  glAttachShader(program, fs);
  glDeleteShader(fs);
  glAttachShader(program, vs);
  glDeleteShader(vs);
  glLinkProgram(program);
  GLint linkStatus = GL_FALSE;
  glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
  if (linkStatus != GL_TRUE) {
    GLint infoLen = 0;
    glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen);
    if (infoLen) {
      std::vector<char> buf;
      buf.resize(infoLen);
      if (static_cast<int>(buf.size()) >= infoLen) {
        glGetProgramInfoLog(program, infoLen, NULL, buf.data());
        std::cerr << "ERROR: VF[_̃NɎsn"<< buf.data() << std::endl;
      }
    }
    glDeleteProgram(program);
    return 0;
  }
  return program;
}

/// Gg[|Cg.
int main()
{
  GLFWEW::Window& window = GLFWEW::Window::Instance();
  if (!window.Init(800, 600, "OpenGL Tutorial")) {
    return 1;
  }

  const GLuint vbo = CreateVBO(sizeof(vertices), vertices);
  const GLuint ibo = CreateIBO(sizeof(indices), indices);
  const GLuint vao = CreateVAO(vbo, ibo);
  const GLuint shaderProgram = CreateShaderProgram(vsCode, fsCode);
  if (!vbo || !ibo || !vao || !shaderProgram) {
    return 1;
  }

  // C[v.
  while (!window.ShouldClose()) {
    glClearColor(0.1f, 0.3f, 0.5f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // _]ړ.
    static float degree = 0.0f;
    degree += 0.1f;
    if (degree >= 360.0f) { degree -= 360.0f; }
    const glm::vec3 viewPos = glm::rotate(glm::mat4(), glm::radians(degree), glm::vec3(0, 1, 0)) * glm::vec4(2, 3, 3, 1);

    glUseProgram(shaderProgram);
    const GLint matMVPLoc = glGetUniformLocation(shaderProgram, "matMVP");
    if (matMVPLoc >= 0) {
      const glm::mat4x4 matProj =
        glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f);
      const glm::mat4x4 matView =
        glm::lookAt(viewPos, glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
      const glm::mat4x4 matMVP = matProj * matView;
      glUniformMatrix4fv(matMVPLoc, 1, GL_FALSE, &matMVP[0][0]);
    }
    glBindVertexArray(vao);
    glDrawElements(
      GL_TRIANGLES, sizeof(indices)/sizeof(indices[0]),
      GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(0));

    window.SwapBuffers();
  }

  glDeleteProgram(shaderProgram);
  glDeleteVertexArrays(1, &vao);

  return 0;
}<commit_msg>第03回9章まで実装.<commit_after>/**
* @file Main.cpp
*/
#include "GLFWEW.h"
#include <glm/gtc/matrix_transform.hpp>
#include <iostream>
#include <vector>

/// 3DxN^[^.
struct Vector3
{
  float x, y, z;
};

/// RGBAJ[^.
struct Color
{
  float r, g, b, a;
};

/// _f[^^.
struct Vertex
{
  Vector3 position; ///< W
  Color color; ///< F
};

/// _f[^.
const Vertex vertices[] = {
  { {-0.5f, -0.3f, 0.5f}, {0.0f, 1.0f, 0.0f, 1.0f} },
  { { 0.3f, -0.3f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f} },
  { { 0.3f,  0.5f, 0.5f}, {1.0f, 0.0f, 0.0f, 1.0f} },
  { {-0.5f,  0.5f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f} },

  { {-0.3f,  0.3f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f} },
  { {-0.3f, -0.5f, 0.1f}, {0.0f, 1.0f, 1.0f, 1.0f} },
  { { 0.5f, -0.5f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f} },
  { { 0.5f, -0.5f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f} },
  { { 0.5f,  0.3f, 0.1f}, {1.0f, 1.0f, 0.0f, 1.0f} },
  { {-0.3f,  0.3f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f} },
};

/// CfbNXf[^.
const GLuint indices[] = {
  0, 1, 2, 2, 3, 0,
  4, 5, 6, 7, 8, 9,
};

/// _VF[_.
static const char* vsCode =
"#version 410 \n"
"layout(location=0) in vec3 vPosition;"
"layout(location=1) in vec4 vColor;"
"layout(location=0) out vec4 outColor;"
"uniform mat4x4 matMVP;"
"void main() {"
"  outColor = vColor;"
"  gl_Position = matMVP * vec4(vPosition, 1.0);"
"}";

/// tOgVF[_.
static const char* fsCode =
"#version 410 \n"
"layout(location=0) in vec4 inColor;"
"out vec4 fragColor;"
"void main() {"
"  fragColor = inColor;"
"}";

/**
* Vertex Buffer Object쐬.
*
* @param size _f[^̃TCY.
* @param data _f[^ւ̃|C^.
*
* @return 쐬VBO.
*/
GLuint CreateVBO(GLsizeiptr size, const GLvoid* data)
{
  GLuint vbo = 0;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
  glBindBuffer(GL_ARRAY_BUFFER, 0);
  return vbo;
}

/**
* Index Buffer Object쐬.
*
* @param size CfbNXf[^̃TCY.
* @param data CfbNXf[^ւ̃|C^.
*
* @return 쐬IBO.
*/
GLuint CreateIBO(GLsizeiptr size, const GLvoid* data)
{
  GLuint ibo = 0;
  glGenBuffers(1, &ibo);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
  glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  return ibo;
}

/**
* _Agr[gݒ肷.
*
* @param index _Agr[g̃CfbNX.
* @param cls   _f[^^.
* @param mbr   _Agr[gɐݒ肷cls̃oϐ.
*/
#define SetVertexAttribPointer(index, cls, mbr) SetVertexAttribPointerI( \
  index, \
  sizeof(cls::mbr) / sizeof(float), \
  sizeof(cls), \
  reinterpret_cast<GLvoid*>(offsetof(cls, mbr)))

void SetVertexAttribPointerI(GLuint index, GLint size, GLsizei stride, const GLvoid* pointer)
{
  glEnableVertexAttribArray(index);
  glVertexAttribPointer(index, size, GL_FLOAT, GL_FALSE, stride, pointer);
}

/**
* Vertex Array Object쐬.
*
* @param vbo VAOɊ֘AtVBO.
* @param ibo VAOɊ֘AtIBO.
*
* @return 쐬VAO.
*/
GLuint CreateVAO(GLuint vbo, GLuint ibo)
{
  GLuint vao = 0;
  glGenVertexArrays(1, &vao);
  glBindVertexArray(vao);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
  SetVertexAttribPointer(0, Vertex, position);
  SetVertexAttribPointer(1, Vertex, color);
  glBindVertexArray(0);
  glDeleteBuffers(1, &vbo);
  glDeleteBuffers(1, &ibo);
  return vao;
}

/**
* VF[_R[hRpC.
*
* @param type VF[_̎.
* @param string VF[_R[hւ̃|C^.
*
* @return 쐬VF[_IuWFNg.
*/
GLuint CompileShader(GLenum type, const GLchar* string)
{
  GLuint shader = glCreateShader(type);
  glShaderSource(shader, 1, &string, nullptr);
  glCompileShader(shader);
  GLint compiled = 0;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
  if (!compiled) {
    GLint infoLen = 0;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
    if (infoLen) {
      std::vector<char> buf;
      buf.resize(infoLen);
      if (static_cast<int>(buf.size()) >= infoLen) {
        glGetShaderInfoLog(shader, infoLen, NULL, buf.data());
        std::cerr << "ERROR: VF[_̃RpCɎsn" << buf.data() << std::endl;
      }
    }
    glDeleteShader(shader);
    return 0;
  }
  return shader;
}

/**
* vOIuWFNg쐬.
*
* @param vsCode _VF[_R[hւ̃|C^.
* @param fsCode tOgVF[_R[hւ̃|C^.
*
* @return 쐬vOIuWFNg.
*/
GLuint CreateShaderProgram(const GLchar* vsCode, const GLchar* fsCode)
{
  GLuint vs = CompileShader(GL_VERTEX_SHADER, vsCode);
  GLuint fs = CompileShader(GL_FRAGMENT_SHADER, fsCode);
  if (!vs || !fs) {
    return 0;
  }
  GLuint program = glCreateProgram();
  glAttachShader(program, fs);
  glDeleteShader(fs);
  glAttachShader(program, vs);
  glDeleteShader(vs);
  glLinkProgram(program);
  GLint linkStatus = GL_FALSE;
  glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
  if (linkStatus != GL_TRUE) {
    GLint infoLen = 0;
    glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen);
    if (infoLen) {
      std::vector<char> buf;
      buf.resize(infoLen);
      if (static_cast<int>(buf.size()) >= infoLen) {
        glGetProgramInfoLog(program, infoLen, NULL, buf.data());
        std::cerr << "ERROR: VF[_̃NɎsn"<< buf.data() << std::endl;
      }
    }
    glDeleteProgram(program);
    return 0;
  }
  return program;
}

/// Gg[|Cg.
int main()
{
  GLFWEW::Window& window = GLFWEW::Window::Instance();
  if (!window.Init(800, 600, "OpenGL Tutorial")) {
    return 1;
  }

  const GLuint vbo = CreateVBO(sizeof(vertices), vertices);
  const GLuint ibo = CreateIBO(sizeof(indices), indices);
  const GLuint vao = CreateVAO(vbo, ibo);
  const GLuint shaderProgram = CreateShaderProgram(vsCode, fsCode);
  if (!vbo || !ibo || !vao || !shaderProgram) {
    return 1;
  }

  glEnable(GL_DEPTH_TEST);

  // C[v.
  while (!window.ShouldClose()) {
    glClearColor(0.1f, 0.3f, 0.5f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // _]ړ.
    static float degree = 0.0f;
    degree += 0.1f;
    if (degree >= 360.0f) { degree -= 360.0f; }
    const glm::vec3 viewPos = glm::rotate(glm::mat4(), glm::radians(degree), glm::vec3(0, 1, 0)) * glm::vec4(2, 3, 3, 1);

    glUseProgram(shaderProgram);
    const GLint matMVPLoc = glGetUniformLocation(shaderProgram, "matMVP");
    if (matMVPLoc >= 0) {
      const glm::mat4x4 matProj =
        glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f);
      const glm::mat4x4 matView =
        glm::lookAt(viewPos, glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
      const glm::mat4x4 matMVP = matProj * matView;
      glUniformMatrix4fv(matMVPLoc, 1, GL_FALSE, &matMVP[0][0]);
    }
    glBindVertexArray(vao);
    glDrawElements(
      GL_TRIANGLES, sizeof(indices)/sizeof(indices[0]),
      GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(0));

    window.SwapBuffers();
  }

  glDeleteProgram(shaderProgram);
  glDeleteVertexArrays(1, &vao);

  return 0;
}<|endoftext|>


<commit_before>/**
 * Copyright (C) 2005-2008 Christoph Rupp (chris@crupp.de).
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * See files COPYING.* for License information.
 */

#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
#include <ham/hamsterdb.h>
#include "../src/os.h"
#include "os.hpp"

#if WIN32
#   include <windows.h>
#else
#   include <unistd.h>
#endif

static void HAM_CALLCONV
my_errhandler(int level, const char *message)
{
    (void)message;
}

class OsTest : public CppUnit::TestFixture
{
    CPPUNIT_TEST_SUITE(OsTest);
    CPPUNIT_TEST      (openCloseTest);
    CPPUNIT_TEST      (openReadOnlyCloseTest);
    CPPUNIT_TEST      (negativeOpenCloseTest);
    CPPUNIT_TEST      (createCloseTest);
    CPPUNIT_TEST      (createCloseOverwriteTest);
    CPPUNIT_TEST      (closeTest);
    CPPUNIT_TEST      (openExclusiveTest);
    CPPUNIT_TEST      (readWriteTest);
    CPPUNIT_TEST      (pagesizeTest);
    CPPUNIT_TEST      (mmapTest);
    CPPUNIT_TEST      (mmapReadOnlyTest);
    CPPUNIT_TEST      (multipleMmapTest);
    CPPUNIT_TEST      (negativeMmapTest);
    CPPUNIT_TEST      (seekTellTest);
    CPPUNIT_TEST      (negativeSeekTest);
    CPPUNIT_TEST      (truncateTest);
    CPPUNIT_TEST      (largefileTest);
    CPPUNIT_TEST_SUITE_END();

public:
    void setUp()
    {
        ham_set_errhandler(my_errhandler);
    }

    void tearDown()
    {
        (void)os::unlink(".test");
    }

    void openCloseTest()
    {
        ham_status_t st;
        ham_fd_t fd;

        st=os_open("Makefile.am", 0, &fd);
        CPPUNIT_ASSERT(st==0);
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

    void openReadOnlyCloseTest()
    {
        ham_status_t st;
        ham_fd_t fd;
        const char *p="# XXXXXXXXX ERROR\n";

        st=os_open("Makefile.am", HAM_READ_ONLY, &fd);
        CPPUNIT_ASSERT(st==0);
        st=os_pwrite(fd, 0, p, (ham_size_t)strlen(p));
        CPPUNIT_ASSERT(st==HAM_IO_ERROR);
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

    void negativeOpenCloseTest()
    {
        ham_status_t st;
        ham_fd_t fd;

        st=os_open("__98324kasdlf.blöd", 0, &fd);
        CPPUNIT_ASSERT(st==HAM_FILE_NOT_FOUND);
    }

    void createCloseTest()
    {
        ham_status_t st;
        ham_fd_t fd;

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT_EQUAL(0, st);
        st=os_close(fd, 0);
        CPPUNIT_ASSERT_EQUAL(0, st);
    }

    void createCloseOverwriteTest()
    {
        ham_fd_t fd;
        ham_offset_t filesize;

        for (int i=0; i<3; i++) {
            CPPUNIT_ASSERT(os_create(".test", 0, 0664, &fd)==HAM_SUCCESS);
            CPPUNIT_ASSERT(os_seek(fd, 0, HAM_OS_SEEK_END)==HAM_SUCCESS);
            CPPUNIT_ASSERT(os_tell(fd, &filesize)==HAM_SUCCESS);
            CPPUNIT_ASSERT(filesize==0);
            CPPUNIT_ASSERT(os_truncate(fd, 1024)==HAM_SUCCESS);
            CPPUNIT_ASSERT(os_seek(fd, 0, HAM_OS_SEEK_END)==HAM_SUCCESS);
            CPPUNIT_ASSERT(os_tell(fd, &filesize)==HAM_SUCCESS);
            CPPUNIT_ASSERT(filesize==1024);
            CPPUNIT_ASSERT(os_close(fd, 0)==HAM_SUCCESS);
        }
    }

    void closeTest()
    {
#ifndef WIN32  // crashs in ntdll.dll
        ham_status_t st;

        st=os_close((ham_fd_t)0x12345, 0);
        CPPUNIT_ASSERT(st==HAM_IO_ERROR);
#endif
    }

    void openExclusiveTest()
    {
        /* fails on cygwin - cygwin bug? */
#ifndef __CYGWIN__
        ham_fd_t fd, fd2;

        CPPUNIT_ASSERT_EQUAL(0, os_create(".test",
                    HAM_LOCK_EXCLUSIVE, 0664, &fd));
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_LOCK_EXCLUSIVE));

        CPPUNIT_ASSERT_EQUAL(0,
                         os_open(".test", HAM_LOCK_EXCLUSIVE, &fd));
        CPPUNIT_ASSERT_EQUAL(HAM_WOULD_BLOCK,
                os_open(".test", HAM_LOCK_EXCLUSIVE, &fd2));
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_LOCK_EXCLUSIVE));
        CPPUNIT_ASSERT_EQUAL(0,
                         os_open(".test", HAM_LOCK_EXCLUSIVE, &fd2));
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd2, HAM_LOCK_EXCLUSIVE));
        CPPUNIT_ASSERT_EQUAL(0, os_open(".test", 0, &fd2));
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd2, 0));
#endif
    }

    void readWriteTest()
    {
        int i;
        ham_status_t st;
        ham_fd_t fd;
        char buffer[128], orig[128];

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT(st==0);
        for (i=0; i<10; i++) {
            memset(buffer, i, sizeof(buffer));
            st=os_pwrite(fd, i*sizeof(buffer), buffer, sizeof(buffer));
            CPPUNIT_ASSERT(st==0);
        }
        for (i=0; i<10; i++) {
            memset(orig, i, sizeof(orig));
            memset(buffer, 0, sizeof(buffer));
            st=os_pread(fd, i*sizeof(buffer), buffer, sizeof(buffer));
            CPPUNIT_ASSERT(st==0);
            CPPUNIT_ASSERT(0==memcmp(buffer, orig, sizeof(buffer)));
        }
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

    void pagesizeTest()
    {
        ham_size_t ps=os_get_pagesize();
        CPPUNIT_ASSERT(ps!=0);
        CPPUNIT_ASSERT(ps%1024==0);
    }

    void mmapTest()
    {
        int i;
        ham_status_t st;
        ham_fd_t fd, mmaph;
        ham_size_t ps=os_get_pagesize();
        ham_u8_t *p1, *p2;
        p1=(ham_u8_t *)malloc(ps);

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT(st==0);
        for (i=0; i<10; i++) {
            memset(p1, i, ps);
            st=os_pwrite(fd, i*ps, p1, ps);
            CPPUNIT_ASSERT(st==0);
        }
        for (i=0; i<10; i++) {
            memset(p1, i, ps);
            st=os_mmap(fd, &mmaph, i*ps, ps, 0, &p2);
            CPPUNIT_ASSERT(st==0);
            CPPUNIT_ASSERT(0==memcmp(p1, p2, ps));
            st=os_munmap(&mmaph, p2, ps);
            CPPUNIT_ASSERT(st==0);
        }
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
        free(p1);
    }

    void mmapReadOnlyTest()
    {
        int i;
        ham_fd_t fd, mmaph;
        ham_size_t ps=os_get_pagesize();
        ham_u8_t *p1, *p2;
        p1=(ham_u8_t *)malloc(ps);

        CPPUNIT_ASSERT_EQUAL(0, os_create(".test", 0, 0664, &fd));
        for (i=0; i<10; i++) {
            memset(p1, i, ps);
            CPPUNIT_ASSERT_EQUAL(0, os_pwrite(fd, i*ps, p1, ps));
        }
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd, 0));

        CPPUNIT_ASSERT_EQUAL(0, os_open(".test", HAM_READ_ONLY, &fd));
        for (i=0; i<10; i++) {
            memset(p1, i, ps);
            CPPUNIT_ASSERT_EQUAL(0, os_mmap(fd, &mmaph, i*ps, ps,
                    HAM_READ_ONLY, &p2));
            CPPUNIT_ASSERT_EQUAL(0, memcmp(p1, p2, ps));
            CPPUNIT_ASSERT_EQUAL(0, os_munmap(&mmaph, p2, ps));
        }
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_READ_ONLY));
        free(p1);
    }

    void multipleMmapTest()
    {
        int i;
        ham_status_t st;
        ham_fd_t fd, mmaph;
        ham_size_t ps=os_get_pagesize();
        ham_u8_t *p1, *p2;
        ham_offset_t addr=0, size;

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT(st==0);
        for (i=0; i<5; i++) {
            size=ps*(i+1);

            p1=(ham_u8_t *)malloc((size_t)size);
            memset(p1, i, (size_t)size);
            st=os_pwrite(fd, addr, p1, (ham_size_t)size);
            CPPUNIT_ASSERT(st==0);
            free(p1);
            addr+=size;
        }

        addr=0;
        for (i=0; i<5; i++) {
            size=ps*(i+1);

            p1=(ham_u8_t *)malloc((size_t)size);
            memset(p1, i, (size_t)size);
            st=os_mmap(fd, &mmaph, addr, (ham_size_t)size, 0, &p2);
            CPPUNIT_ASSERT(st==0);
            CPPUNIT_ASSERT(0==memcmp(p1, p2, (size_t)size));
            st=os_munmap(&mmaph, p2, (ham_size_t)size);
            CPPUNIT_ASSERT(st==0);
            free(p1);
            addr+=size;
        }
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

    void negativeMmapTest()
    {
        ham_fd_t fd, mmaph;
        ham_u8_t *page;

        CPPUNIT_ASSERT_EQUAL(0, os_create(".test", 0, 0664, &fd));
        // bad address && page size! - i don't know why this succeeds
        // on MacOS...
#ifndef __MACH__
        CPPUNIT_ASSERT_EQUAL(HAM_IO_ERROR,
                os_mmap(fd, &mmaph, 33, 66, 0, &page));
#endif
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd, 0));
    }

    void seekTellTest()
    {
        int i;
        ham_status_t st;
        ham_fd_t fd;
        ham_offset_t tell;

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT(st==0);
        for (i=0; i<10; i++) {
            st=os_seek(fd, i, HAM_OS_SEEK_SET);
            CPPUNIT_ASSERT(st==0);
            st=os_tell(fd, &tell);
            CPPUNIT_ASSERT(st==0);
            CPPUNIT_ASSERT(tell==(ham_offset_t)i);
        }
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

    void negativeSeekTest()
    {
        ham_status_t st;

        st=os_seek((ham_fd_t)0x12345, 0, HAM_OS_SEEK_SET);
        CPPUNIT_ASSERT(st==HAM_IO_ERROR);
    }

    void truncateTest()
    {
        int i;
        ham_status_t st;
        ham_fd_t fd;
        ham_offset_t fsize;

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT(st==0);
        for (i=0; i<10; i++) {
            st=os_truncate(fd, i*128);
            CPPUNIT_ASSERT(st==0);
            st=os_get_filesize(fd, &fsize);
            CPPUNIT_ASSERT(st==0);
            CPPUNIT_ASSERT(fsize==(ham_offset_t)(i*128));
        }
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

    void largefileTest()
    {
        int i;
        ham_status_t st;
        ham_fd_t fd;
        ham_u8_t kb[1024];
        ham_offset_t tell;

        memset(kb, 0, sizeof(kb));

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT(st==0);
        for (i=0; i<4*1024; i++) {
            st=os_pwrite(fd, i*sizeof(kb), kb, sizeof(kb));
            CPPUNIT_ASSERT(st==0);
        }
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);

        st=os_open(".test", 0, &fd);
        CPPUNIT_ASSERT(st==0);
        st=os_seek(fd, 0, HAM_OS_SEEK_END);
        CPPUNIT_ASSERT(st==0);
        st=os_tell(fd, &tell);
        CPPUNIT_ASSERT(st==0);
        CPPUNIT_ASSERT(tell==(ham_offset_t)1024*1024*4);
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

};

CPPUNIT_TEST_SUITE_REGISTRATION(OsTest);
<commit_msg>disable mmap-tests for platforms without mmap<commit_after>/**
 * Copyright (C) 2005-2008 Christoph Rupp (chris@crupp.de).
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * See files COPYING.* for License information.
 */

#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
#include <ham/hamsterdb.h>
#include "../src/os.h"
#include "os.hpp"

#if WIN32
#   include <windows.h>
#else
#   include <unistd.h>
#endif

static void HAM_CALLCONV
my_errhandler(int level, const char *message)
{
    (void)message;
}

class OsTest : public CppUnit::TestFixture
{
    CPPUNIT_TEST_SUITE(OsTest);
    CPPUNIT_TEST      (openCloseTest);
    CPPUNIT_TEST      (openReadOnlyCloseTest);
    CPPUNIT_TEST      (negativeOpenCloseTest);
    CPPUNIT_TEST      (createCloseTest);
    CPPUNIT_TEST      (createCloseOverwriteTest);
    CPPUNIT_TEST      (closeTest);
    CPPUNIT_TEST      (openExclusiveTest);
    CPPUNIT_TEST      (readWriteTest);
    CPPUNIT_TEST      (pagesizeTest);
#if HAVE_MMAP
    CPPUNIT_TEST      (mmapTest);
    CPPUNIT_TEST      (mmapReadOnlyTest);
    CPPUNIT_TEST      (multipleMmapTest);
    CPPUNIT_TEST      (negativeMmapTest);
#endif
    CPPUNIT_TEST      (seekTellTest);
    CPPUNIT_TEST      (negativeSeekTest);
    CPPUNIT_TEST      (truncateTest);
    CPPUNIT_TEST      (largefileTest);
    CPPUNIT_TEST_SUITE_END();

public:
    void setUp()
    {
        ham_set_errhandler(my_errhandler);
    }

    void tearDown()
    {
        (void)os::unlink(".test");
    }

    void openCloseTest()
    {
        ham_status_t st;
        ham_fd_t fd;

        st=os_open("Makefile.am", 0, &fd);
        CPPUNIT_ASSERT(st==0);
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

    void openReadOnlyCloseTest()
    {
        ham_status_t st;
        ham_fd_t fd;
        const char *p="# XXXXXXXXX ERROR\n";

        st=os_open("Makefile.am", HAM_READ_ONLY, &fd);
        CPPUNIT_ASSERT(st==0);
        st=os_pwrite(fd, 0, p, (ham_size_t)strlen(p));
        CPPUNIT_ASSERT(st==HAM_IO_ERROR);
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

    void negativeOpenCloseTest()
    {
        ham_status_t st;
        ham_fd_t fd;

        st=os_open("__98324kasdlf.blöd", 0, &fd);
        CPPUNIT_ASSERT(st==HAM_FILE_NOT_FOUND);
    }

    void createCloseTest()
    {
        ham_status_t st;
        ham_fd_t fd;

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT_EQUAL(0, st);
        st=os_close(fd, 0);
        CPPUNIT_ASSERT_EQUAL(0, st);
    }

    void createCloseOverwriteTest()
    {
        ham_fd_t fd;
        ham_offset_t filesize;

        for (int i=0; i<3; i++) {
            CPPUNIT_ASSERT(os_create(".test", 0, 0664, &fd)==HAM_SUCCESS);
            CPPUNIT_ASSERT(os_seek(fd, 0, HAM_OS_SEEK_END)==HAM_SUCCESS);
            CPPUNIT_ASSERT(os_tell(fd, &filesize)==HAM_SUCCESS);
            CPPUNIT_ASSERT(filesize==0);
            CPPUNIT_ASSERT(os_truncate(fd, 1024)==HAM_SUCCESS);
            CPPUNIT_ASSERT(os_seek(fd, 0, HAM_OS_SEEK_END)==HAM_SUCCESS);
            CPPUNIT_ASSERT(os_tell(fd, &filesize)==HAM_SUCCESS);
            CPPUNIT_ASSERT(filesize==1024);
            CPPUNIT_ASSERT(os_close(fd, 0)==HAM_SUCCESS);
        }
    }

    void closeTest()
    {
#ifndef WIN32  // crashs in ntdll.dll
        ham_status_t st;

        st=os_close((ham_fd_t)0x12345, 0);
        CPPUNIT_ASSERT(st==HAM_IO_ERROR);
#endif
    }

    void openExclusiveTest()
    {
        /* fails on cygwin - cygwin bug? */
#ifndef __CYGWIN__
        ham_fd_t fd, fd2;

        CPPUNIT_ASSERT_EQUAL(0, os_create(".test",
                    HAM_LOCK_EXCLUSIVE, 0664, &fd));
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_LOCK_EXCLUSIVE));

        CPPUNIT_ASSERT_EQUAL(0,
                         os_open(".test", HAM_LOCK_EXCLUSIVE, &fd));
        CPPUNIT_ASSERT_EQUAL(HAM_WOULD_BLOCK,
                os_open(".test", HAM_LOCK_EXCLUSIVE, &fd2));
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_LOCK_EXCLUSIVE));
        CPPUNIT_ASSERT_EQUAL(0,
                         os_open(".test", HAM_LOCK_EXCLUSIVE, &fd2));
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd2, HAM_LOCK_EXCLUSIVE));
        CPPUNIT_ASSERT_EQUAL(0, os_open(".test", 0, &fd2));
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd2, 0));
#endif
    }

    void readWriteTest()
    {
        int i;
        ham_status_t st;
        ham_fd_t fd;
        char buffer[128], orig[128];

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT(st==0);
        for (i=0; i<10; i++) {
            memset(buffer, i, sizeof(buffer));
            st=os_pwrite(fd, i*sizeof(buffer), buffer, sizeof(buffer));
            CPPUNIT_ASSERT(st==0);
        }
        for (i=0; i<10; i++) {
            memset(orig, i, sizeof(orig));
            memset(buffer, 0, sizeof(buffer));
            st=os_pread(fd, i*sizeof(buffer), buffer, sizeof(buffer));
            CPPUNIT_ASSERT(st==0);
            CPPUNIT_ASSERT(0==memcmp(buffer, orig, sizeof(buffer)));
        }
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

    void pagesizeTest()
    {
        ham_size_t ps=os_get_pagesize();
        CPPUNIT_ASSERT(ps!=0);
        CPPUNIT_ASSERT(ps%1024==0);
    }

    void mmapTest()
    {
        int i;
        ham_status_t st;
        ham_fd_t fd, mmaph;
        ham_size_t ps=os_get_pagesize();
        ham_u8_t *p1, *p2;
        p1=(ham_u8_t *)malloc(ps);

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT(st==0);
        for (i=0; i<10; i++) {
            memset(p1, i, ps);
            st=os_pwrite(fd, i*ps, p1, ps);
            CPPUNIT_ASSERT(st==0);
        }
        for (i=0; i<10; i++) {
            memset(p1, i, ps);
            st=os_mmap(fd, &mmaph, i*ps, ps, 0, &p2);
            CPPUNIT_ASSERT(st==0);
            CPPUNIT_ASSERT(0==memcmp(p1, p2, ps));
            st=os_munmap(&mmaph, p2, ps);
            CPPUNIT_ASSERT(st==0);
        }
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
        free(p1);
    }

    void mmapReadOnlyTest()
    {
        int i;
        ham_fd_t fd, mmaph;
        ham_size_t ps=os_get_pagesize();
        ham_u8_t *p1, *p2;
        p1=(ham_u8_t *)malloc(ps);

        CPPUNIT_ASSERT_EQUAL(0, os_create(".test", 0, 0664, &fd));
        for (i=0; i<10; i++) {
            memset(p1, i, ps);
            CPPUNIT_ASSERT_EQUAL(0, os_pwrite(fd, i*ps, p1, ps));
        }
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd, 0));

        CPPUNIT_ASSERT_EQUAL(0, os_open(".test", HAM_READ_ONLY, &fd));
        for (i=0; i<10; i++) {
            memset(p1, i, ps);
            CPPUNIT_ASSERT_EQUAL(0, os_mmap(fd, &mmaph, i*ps, ps,
                    HAM_READ_ONLY, &p2));
            CPPUNIT_ASSERT_EQUAL(0, memcmp(p1, p2, ps));
            CPPUNIT_ASSERT_EQUAL(0, os_munmap(&mmaph, p2, ps));
        }
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_READ_ONLY));
        free(p1);
    }

    void multipleMmapTest()
    {
        int i;
        ham_status_t st;
        ham_fd_t fd, mmaph;
        ham_size_t ps=os_get_pagesize();
        ham_u8_t *p1, *p2;
        ham_offset_t addr=0, size;

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT(st==0);
        for (i=0; i<5; i++) {
            size=ps*(i+1);

            p1=(ham_u8_t *)malloc((size_t)size);
            memset(p1, i, (size_t)size);
            st=os_pwrite(fd, addr, p1, (ham_size_t)size);
            CPPUNIT_ASSERT(st==0);
            free(p1);
            addr+=size;
        }

        addr=0;
        for (i=0; i<5; i++) {
            size=ps*(i+1);

            p1=(ham_u8_t *)malloc((size_t)size);
            memset(p1, i, (size_t)size);
            st=os_mmap(fd, &mmaph, addr, (ham_size_t)size, 0, &p2);
            CPPUNIT_ASSERT(st==0);
            CPPUNIT_ASSERT(0==memcmp(p1, p2, (size_t)size));
            st=os_munmap(&mmaph, p2, (ham_size_t)size);
            CPPUNIT_ASSERT(st==0);
            free(p1);
            addr+=size;
        }
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

    void negativeMmapTest()
    {
        ham_fd_t fd, mmaph;
        ham_u8_t *page;

        CPPUNIT_ASSERT_EQUAL(0, os_create(".test", 0, 0664, &fd));
        // bad address && page size! - i don't know why this succeeds
        // on MacOS...
#ifndef __MACH__
        CPPUNIT_ASSERT_EQUAL(HAM_IO_ERROR,
                os_mmap(fd, &mmaph, 33, 66, 0, &page));
#endif
        CPPUNIT_ASSERT_EQUAL(0, os_close(fd, 0));
    }

    void seekTellTest()
    {
        int i;
        ham_status_t st;
        ham_fd_t fd;
        ham_offset_t tell;

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT(st==0);
        for (i=0; i<10; i++) {
            st=os_seek(fd, i, HAM_OS_SEEK_SET);
            CPPUNIT_ASSERT(st==0);
            st=os_tell(fd, &tell);
            CPPUNIT_ASSERT(st==0);
            CPPUNIT_ASSERT(tell==(ham_offset_t)i);
        }
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

    void negativeSeekTest()
    {
        ham_status_t st;

        st=os_seek((ham_fd_t)0x12345, 0, HAM_OS_SEEK_SET);
        CPPUNIT_ASSERT(st==HAM_IO_ERROR);
    }

    void truncateTest()
    {
        int i;
        ham_status_t st;
        ham_fd_t fd;
        ham_offset_t fsize;

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT(st==0);
        for (i=0; i<10; i++) {
            st=os_truncate(fd, i*128);
            CPPUNIT_ASSERT(st==0);
            st=os_get_filesize(fd, &fsize);
            CPPUNIT_ASSERT(st==0);
            CPPUNIT_ASSERT(fsize==(ham_offset_t)(i*128));
        }
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

    void largefileTest()
    {
        int i;
        ham_status_t st;
        ham_fd_t fd;
        ham_u8_t kb[1024];
        ham_offset_t tell;

        memset(kb, 0, sizeof(kb));

        st=os_create(".test", 0, 0664, &fd);
        CPPUNIT_ASSERT(st==0);
        for (i=0; i<4*1024; i++) {
            st=os_pwrite(fd, i*sizeof(kb), kb, sizeof(kb));
            CPPUNIT_ASSERT(st==0);
        }
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);

        st=os_open(".test", 0, &fd);
        CPPUNIT_ASSERT(st==0);
        st=os_seek(fd, 0, HAM_OS_SEEK_END);
        CPPUNIT_ASSERT(st==0);
        st=os_tell(fd, &tell);
        CPPUNIT_ASSERT(st==0);
        CPPUNIT_ASSERT(tell==(ham_offset_t)1024*1024*4);
        st=os_close(fd, 0);
        CPPUNIT_ASSERT(st==0);
    }

};

CPPUNIT_TEST_SUITE_REGISTRATION(OsTest);
<|endoftext|>


<commit_before>#include "mitkMovieGenerator.h"
#include <GL/gl.h>

#ifdef WIN32
	#include "mitkMovieGeneratorWin32.h"
#endif
#ifndef GL_BGR
	#define GL_BGR GL_BGR_EXT
#endif

mitk::MovieGenerator::Pointer mitk::MovieGenerator::New()
{
  Pointer smartPtr;
  MovieGenerator *rawPtr = ::itk::ObjectFactory<MovieGenerator>::Create();
  if(rawPtr == NULL) {
    #ifdef WIN32
      MovieGeneratorWin32::Pointer wp = MovieGeneratorWin32::New();
      return wp;
      //rawPtr = (MovieGenerator*)MovieGeneratorWin32::New();
    #endif
  }
  smartPtr = rawPtr;
  rawPtr->UnRegister();
  return smartPtr;
}

bool mitk::MovieGenerator::WriteMovie()
{
	bool ok = false;
	if (m_stepper) {
		m_stepper->First();
		ok = InitGenerator();
		if (!ok) return false;
		int imgSize = 3 * m_width * m_height;
		printf( "Video size = %i x %i\n", m_width, m_height );
		GLbyte *data = new GLbyte[imgSize];
		for (int i=0; i<m_stepper->GetSteps(); i++) {
			if (m_renderer) m_renderer->MakeCurrent();
			glReadPixels( 0, 0, m_width, m_height, GL_BGR, GL_UNSIGNED_BYTE, (void*)data );
			AddFrame( data );
			m_stepper->Next();
		}
		ok = TerminateGenerator();
		delete[] data;
	}
	return ok;
}<commit_msg>FIX: Crash under Linux<commit_after>#include "mitkMovieGenerator.h"
#include <GL/gl.h>

#ifdef WIN32
	#include "mitkMovieGeneratorWin32.h"
#endif
#ifndef GL_BGR
	#define GL_BGR GL_BGR_EXT
#endif

mitk::MovieGenerator::Pointer mitk::MovieGenerator::New()
{
  Pointer smartPtr;
  MovieGenerator *rawPtr = ::itk::ObjectFactory<MovieGenerator>::Create();
  if(rawPtr == NULL) {
    #ifdef WIN32
      MovieGeneratorWin32::Pointer wp = MovieGeneratorWin32::New();
      return wp;
    #endif
  }
  smartPtr = rawPtr;
  if(rawPtr != NULL) rawPtr->UnRegister();
  return smartPtr;
}

bool mitk::MovieGenerator::WriteMovie()
{
	bool ok = false;
	if (m_stepper) {
		m_stepper->First();
		ok = InitGenerator();
		if (!ok) return false;
		int imgSize = 3 * m_width * m_height;
		printf( "Video size = %i x %i\n", m_width, m_height );
		GLbyte *data = new GLbyte[imgSize];
		for (int i=0; i<m_stepper->GetSteps(); i++) {
			if (m_renderer) m_renderer->MakeCurrent();
			glReadPixels( 0, 0, m_width, m_height, GL_BGR, GL_UNSIGNED_BYTE, (void*)data );
			AddFrame( data );
			m_stepper->Next();
		}
		ok = TerminateGenerator();
		delete[] data;
	}
	return ok;
}<|endoftext|>


<commit_before>
#include "AudioData.h"
#include "WavParser.h"
#include "AudioPlaybackStream.h"
#include "AudioStreamBuffer.h"
#include "AudioMixer.h"
#include "EngineTrack.h"
#include "EngineSample.h"
#include "Initializer.h"
#include "OALWrapper/OAL_Funcs.h"
#include "SDL_timer.h"
#include <iostream>
#include <vector>

#ifdef _WIN32
#include <direct.h>
#else
#include <unistd.h>
#endif

int main( int argc, char *argv[] )
{
    // fix up working directory
    {
        char temp[128] = {};
        const char *dir = getcwd(temp, sizeof(temp));
        const char *bin_pos = strstr(dir, "bin");
        const char *build_pos = strstr(dir, "build");
        if (bin_pos)
        {
            chdir("..");
        }
        else if (build_pos)
        {
            chdir("../..");
        }
    }
    // OAL_SetupLogging(true,eOAL_LogOutput_File,eOAL_LogVerbose_High);

    cOAL_Init_Params oal_parms;
    oal_parms.mlStreamingBufferSize = 8192;
    if (OAL_Init(oal_parms)==false)
    {
        printf ("Failed - Check your OpenAL installation\n");
        return 0;
    }
    else
    {
        printf ("Success\n");
    }

    AudioMixer<16> mixer;
    std::vector<std::unique_ptr<AudioStreamBuffer>> streamBuffers;

    std::unique_ptr<EngineTrack> ambientRain(Initializer::InitializeTrack("tracks/ambient_rain.track"));
    if (!ambientRain)
    {
        return -1;
    }

    for (auto &sample : ambientRain->getSamples())
    {
        const AudioSample *audioSample = sample.getSample();
        streamBuffers.emplace_back(new AudioStreamBuffer(audioSample->getBitsPerSample()));
        streamBuffers.back()->PushSamples(audioSample->getSamples(), audioSample->getNumSamples());
        mixer.ConnectInputStream(streamBuffers.back().get());
    }

    AudioStreamBuffer mixerOutput(16, true);
    mixer.ConnectOutputStream(&mixerOutput);

    mixer.Mix();

    AudioPlaybackStream stream(16);
    stream.SetInputStream(&mixerOutput);
    stream.InitStream(1, 44100, AL_FORMAT_MONO16);

    while (stream.IsPlaying())
    {
        if (mixerOutput.GetNumSamples() <= oal_parms.mlStreamingBufferSize)
        {
            for (int i = 0; i < (int)streamBuffers.size(); ++i)
            {
                const AudioSample *audioSample = ambientRain->GetEngineSample(i).getSample();
                streamBuffers[i]->PushSamples(audioSample->getSamples(), audioSample->getNumSamples());
                std::cout << streamBuffers[i]->GetNumSamples() << std::endl;
            }
            mixer.Mix();
        }
        else
        {
            SDL_Delay(10);
        }
        // sleep if you want
    }

    stream.DestroyStream();
    OAL_Close();
    return 0;
}
<commit_msg>made input buffers push samples independently to prevent long samples from building up large buffers<commit_after>
#include "AudioData.h"
#include "WavParser.h"
#include "AudioPlaybackStream.h"
#include "AudioStreamBuffer.h"
#include "AudioMixer.h"
#include "EngineTrack.h"
#include "EngineSample.h"
#include "Initializer.h"
#include "OALWrapper/OAL_Funcs.h"
#include "SDL_timer.h"
#include <iostream>
#include <vector>

#ifdef _WIN32
#include <direct.h>
#else
#include <unistd.h>
#endif

int main( int argc, char *argv[] )
{
    // fix up working directory
    {
        char temp[128] = {};
        const char *dir = getcwd(temp, sizeof(temp));
        const char *bin_pos = strstr(dir, "bin");
        const char *build_pos = strstr(dir, "build");
        if (bin_pos)
        {
            chdir("..");
        }
        else if (build_pos)
        {
            chdir("../..");
        }
    }
    // OAL_SetupLogging(true,eOAL_LogOutput_File,eOAL_LogVerbose_High);

    cOAL_Init_Params oal_parms;
    oal_parms.mlStreamingBufferSize = 8192;
    if (OAL_Init(oal_parms)==false)
    {
        printf ("Failed - Check your OpenAL installation\n");
        return 0;
    }
    else
    {
        printf ("Success\n");
    }

    AudioMixer<16> mixer;
    std::vector<std::unique_ptr<AudioStreamBuffer>> streamBuffers;

    std::unique_ptr<EngineTrack> ambientRain(Initializer::InitializeTrack("tracks/ambient_rain.track"));
    if (!ambientRain)
    {
        return -1;
    }

    for (auto &sample : ambientRain->getSamples())
    {
        const AudioSample *audioSample = sample.getSample();
        streamBuffers.emplace_back(new AudioStreamBuffer(audioSample->getBitsPerSample()));
        streamBuffers.back()->PushSamples(audioSample->getSamples(), audioSample->getNumSamples());
        mixer.ConnectInputStream(streamBuffers.back().get());
    }

    AudioStreamBuffer mixerOutput(16, true);
    mixer.ConnectOutputStream(&mixerOutput);

    mixer.Mix();

    AudioPlaybackStream stream(16);
    stream.SetInputStream(&mixerOutput);
    stream.InitStream(1, 44100, AL_FORMAT_MONO16);

    while (stream.IsPlaying())
    {
        for (int i = 0; i < (int)streamBuffers.size(); ++i)
        {
            auto &buffer = streamBuffers[i];

            if (buffer->GetNumSamples() <= oal_parms.mlStreamingBufferSize)
            {
                const auto *audioSample = ambientRain->GetEngineSample(i).getSample();
                buffer->PushSamples(audioSample->getSamples(), audioSample->getNumSamples());
                std::cout << buffer->GetNumSamples() << std::endl;
            }
        }
        if (mixerOutput.GetNumSamples() <= oal_parms.mlStreamingBufferSize)
        {
            mixer.Mix();
            std::cout << "mixing" << std::endl;
            for (auto &buffer : streamBuffers)
            {
                std::cout << buffer->GetNumSamples() << std::endl;
            }
        }
        else
        {
            SDL_Delay(10);
        }
        // sleep if you want
    }

    stream.DestroyStream();
    OAL_Close();
    return 0;
}
<|endoftext|>