<commit_before>#include <iostream>
#include <sstream>
#include <MidiFile.h>

using namespace std;

int highestString(int);
string toLower(string str);
float getBurden(int, int, int, int, int);

int numStrings = 6;

int tuning[] = {
    52, 47, 43, 38, 33, 28
};

string noteNames[] = {
    "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"
};

struct tab
{
    uint8_t str;
    uint8_t fret;
};

tab* tabs = nullptr;
int numNotes = 0;

int offset = -24;

int handPos = 1;

int main(int argc, char** argv)
{
    stringstream* lines = new stringstream[numStrings];

    string ifname = ""; //read in file name from argument 1
    if(argc < 2)
    {
        cout << "Drag a midi file from Windows Explorer into this window and press the enter key." << endl;
        getline(cin, ifname);

        int length = ifname.size();

        int f = 0;
        int l = length;

        if(ifname[0] == '"')
        {
            f = 1;
            l -= 1;
        }
        if(ifname[length-1] == '"')
            l -= 1;

        ifname = ifname.substr(f, l);
        length -= 2;
    }
    else
        ifname = argv[1];

    if(toLower(ifname.substr(ifname.size()-4, 4)) != ".mid")
    {
        cerr << "The file provided is not a midi file!" << endl;
        exit(1);
    }
    string ofname = ifname.substr(0, ifname.size()-4) + ".txt";

    MidiFile infile;
    infile.read(ifname);

    if (!infile.status())
    {
      cerr << "Error reading MIDI file " << ifname << endl;
      exit(1);
    }

    int track = infile.getTrackCount();
    if(track>1)
    {
        cout << "This file contains " << track << " tracks, numbered 0 through " << (track-1) << ". Which would you like to use?" << endl;
        cin >> track;
    }
    else
        track = 0;

    cout << "How many octaves do you want to shift this track up or down by?" << endl;
    cin >> offset;
    offset *= 12;

    ofstream outfile;
    outfile.open(ofname, ios::out);

    for(int i=0; i<infile[track].size(); i++)   //calculate number of notes
        if(infile[track][i].isNoteOn())
            numNotes++;

    tabs = new tab[numNotes];

    for(int i=0,n=-1; i<infile[track].size(); i++) //first pass in tab construction
    {
        if(!infile[track][i].isNoteOn())
        {
            continue;
        }

        n++;

        int pitch = (int)infile[track][i][1] + offset;
        tabs[n].str = highestString(pitch);
        tabs[n].fret = pitch - tuning[tabs[n].str];

        float minBurden;
        if(n==0)
            minBurden = 0;
        else
            minBurden = getBurden(handPos, tabs[n-1].str, tabs[n-1].fret, tabs[n].str, tabs[n].fret);

        for(int j=0; j<numStrings; j++)
        {
            if(tuning[j] < pitch)
            {
                float burden = getBurden(handPos, tabs[n-1].str, tabs[n-1].fret, j, pitch-tuning[j]);
                if(burden < minBurden)
                {
                    tabs[n].str = j;
                    tabs[n].fret = pitch-tuning[j];
                    minBurden = burden;
                }
            }
        }

        if(tabs[n].fret != 0)
        {
            if(tabs[n].fret < handPos-1)
                handPos = tabs[n].fret;
            if(tabs[n].fret > handPos+4)
                handPos = tabs[n].fret-3;
        }

        tabs[n].fret = pitch - tuning[tabs[n].str];
    }

    for(int i=0; i<numNotes; i++)   //construct strings of tabs for each string
    {
        lines[tabs[i].str] << (int)tabs[i].fret << '-';

        for(int j=0; j<numStrings; j++)
        {
            if(j != tabs[i].str)
            {
                lines[j] << "--";
            }
        }
    }

    for(int i=0; i<numStrings; i++)     //print tabs
    {
        outfile << noteNames[tuning[i]%12] << "-|" << lines[i].str() << endl;
    }

    outfile.close();

    cout << "Successfully created tabs." << endl;

    return 0;
}

float getBurden(int hand1, int str1, int fret1, int str2, int fret2)
{
    float burden = str1 - str2; //calculate burden based on switching strings
    if(burden<0)
        burden*=-1;
    burden -= 0.5f;
    if(burden<0)
        burden=0;

    if(fret2 != 0)  //prefer open strings
    {
        if(fret2 < hand1)   //calculate burden based on slight stretch
            burden += 0.5;
        if(fret2 > hand1 + 3)
            burden += 0.5;

        if(fret1 - fret2 == 4 || fret2 - fret1 == 4)    //calculate burden based on double stretch
            burden += 0.5f;

        if(fret2 < hand1 - 1)   //calculate burden based on full hand movement
            burden += hand1 - fret2;
        if(fret2 > hand1 + 4)
            burden += fret2 - hand1 + 3;
    }

    return burden;
}

int highestString(int note) //highest string that can play a given note
{
    int str = 0;
    int min_fret = INT_MAX;

    for(int i=0; i<numStrings; i++)
    {
        if(tuning[i] <= note && note - tuning[i] < min_fret)
        {
            str = i;
            min_fret = note - tuning[i];
        }
    }

    return str;
}

string toLower(string str)  //converts a string to lower case
{
    string ret = str;

    int l = ret.size();

    for(int i=0; i<l; i++)
    {
        ret[i] = tolower(ret[i]);
    }

    return ret;
}
<commit_msg>Fixed spacing with double digit fret numbers.<commit_after>#include <iostream>
#include <sstream>
#include <MidiFile.h>

using namespace std;

int highestString(int);
string toLower(string str);
float getBurden(int, int, int, int, int);

int numStrings = 6;

int tuning[] = {
    52, 47, 43, 38, 33, 28
};

string noteNames[] = {
    "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"
};

struct tab
{
    uint8_t str;
    uint8_t fret;
};

tab* tabs = nullptr;
int numNotes = 0;

int offset = -24;

int handPos = 1;

int main(int argc, char** argv)
{
    stringstream* lines = new stringstream[numStrings];

    string ifname = ""; //read in file name from argument 1
    if(argc < 2)
    {
        cout << "Drag a midi file from Windows Explorer into this window and press the enter key." << endl;
        getline(cin, ifname);

        int length = ifname.size();

        int f = 0;
        int l = length;

        if(ifname[0] == '"')
        {
            f = 1;
            l -= 1;
        }
        if(ifname[length-1] == '"')
            l -= 1;

        ifname = ifname.substr(f, l);
        length -= 2;
    }
    else
        ifname = argv[1];

    if(toLower(ifname.substr(ifname.size()-4, 4)) != ".mid")
    {
        cerr << "The file provided is not a midi file!" << endl;
        exit(1);
    }
    string ofname = ifname.substr(0, ifname.size()-4) + ".txt";

    MidiFile infile;
    infile.read(ifname);

    if (!infile.status())
    {
      cerr << "Error reading MIDI file " << ifname << endl;
      exit(1);
    }

    int track = infile.getTrackCount();
    if(track>1)
    {
        cout << "This file contains " << track << " tracks, numbered 0 through " << (track-1) << ". Which would you like to use?" << endl;
        cin >> track;
    }
    else
        track = 0;

    cout << "How many octaves do you want to shift this track up or down by?" << endl;
    cin >> offset;
    offset *= 12;

    ofstream outfile;
    outfile.open(ofname, ios::out);

    for(int i=0; i<infile[track].size(); i++)   //calculate number of notes
        if(infile[track][i].isNoteOn())
            numNotes++;

    tabs = new tab[numNotes];

    for(int i=0,n=-1; i<infile[track].size(); i++) //first pass in tab construction
    {
        if(!infile[track][i].isNoteOn())
        {
            continue;
        }

        n++;

        int pitch = (int)infile[track][i][1] + offset;
        tabs[n].str = highestString(pitch);
        tabs[n].fret = pitch - tuning[tabs[n].str];

        float minBurden;
        if(n==0)
            minBurden = 0;
        else
            minBurden = getBurden(handPos, tabs[n-1].str, tabs[n-1].fret, tabs[n].str, tabs[n].fret);

        for(int j=0; j<numStrings; j++)
        {
            if(tuning[j] < pitch)
            {
                float burden = getBurden(handPos, tabs[n-1].str, tabs[n-1].fret, j, pitch-tuning[j]);
                if(burden < minBurden)
                {
                    tabs[n].str = j;
                    tabs[n].fret = pitch-tuning[j];
                    minBurden = burden;
                }
            }
        }

        if(tabs[n].fret != 0)
        {
            if(tabs[n].fret < handPos-1)
                handPos = tabs[n].fret;
            if(tabs[n].fret > handPos+4)
                handPos = tabs[n].fret-3;
        }

        tabs[n].fret = pitch - tuning[tabs[n].str];
    }

    for(int i=0; i<numNotes; i++)   //construct strings of tabs for each string
    {
        lines[tabs[i].str] << (int)tabs[i].fret << '-';

        string after = "--";    //maintain spacing with double digit fret numbers
        if(tabs[i].fret >= 10)
            after = "---";

        for(int j=0; j<numStrings; j++)
        {
            if(j != tabs[i].str)
            {
                lines[j] << after;
            }
        }
    }

    for(int i=0; i<numStrings; i++)     //print tabs
    {
        outfile << noteNames[tuning[i]%12] << "-|" << lines[i].str() << endl;
    }

    outfile.close();

    cout << "Successfully created tabs." << endl;

    return 0;
}

float getBurden(int hand1, int str1, int fret1, int str2, int fret2)
{
    float burden = str1 - str2; //calculate burden based on switching strings
    if(burden<0)
        burden*=-1;
    burden -= 0.5f;
    if(burden<0)
        burden=0;

    if(fret2 != 0)  //prefer open strings
    {
        if(fret2 < hand1)   //calculate burden based on slight stretch
            burden += 0.5;
        if(fret2 > hand1 + 3)
            burden += 0.5;

        if(fret1 - fret2 == 4 || fret2 - fret1 == 4)    //calculate burden based on double stretch
            burden += 0.5f;

        if(fret2 < hand1 - 1)   //calculate burden based on full hand movement
            burden += hand1 - fret2;
        if(fret2 > hand1 + 4)
            burden += fret2 - hand1 + 3;
    }

    return burden;
}

int highestString(int note) //highest string that can play a given note
{
    int str = 0;
    int min_fret = INT_MAX;

    for(int i=0; i<numStrings; i++)
    {
        if(tuning[i] <= note && note - tuning[i] < min_fret)
        {
            str = i;
            min_fret = note - tuning[i];
        }
    }

    return str;
}

string toLower(string str)  //converts a string to lower case
{
    string ret = str;

    int l = ret.size();

    for(int i=0; i<l; i++)
    {
        ret[i] = tolower(ret[i]);
    }

    return ret;
}
<|endoftext|>


<commit_before>#include "main.h"
#include "game.h"
#include "font.h"
#include "sound.h"
#include "image.h"

Game game;
SDL_Point screensize={640,384};

extern "C" {
int main(int argc,char **argv);
}

int main(int argc,char **argv)
{
	SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO);
	// init window and renderer
	// TODO: query the screen and set the resolution based on the screen size.
	SDL_Window *window=SDL_CreateWindow("Super Trump Jump",SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,640,384,0);
	screensize.x=640;
	screensize.y=384;
	SDL_Renderer *renderer=SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED);

	// Init joystick
	SDL_Joystick *joy=0;
	if(SDL_NumJoysticks()>0) {
		joy=SDL_JoystickOpen(0);
	}
	if(SDL_NumJoysticks()>1) {
		joy=SDL_JoystickOpen(1);
	}

	// Init audio
	Sound::init();

	// Init image loader
	Image::init();

	// Init font loader
	Font::init();

	// TODO calculatre this with acutal time in ms.
	int elapsed=16;
	bool done=false;
	while(!done) {
		// handle events
		SDL_Event event;

		while(SDL_PollEvent(&event)) {
			if(event.type==SDL_QUIT) {
				done=true;
			// dispatch to game object.
			} else if(event.type==SDL_KEYDOWN) {
				if(event.key.keysym.sym==' ') {
					game.handleKey(' ',true);
				}
			} else if(event.type==SDL_KEYUP) {
				if(event.key.keysym.sym==' ') {
					game.handleKey(' ',false);
				}
			} else if(event.type==SDL_MOUSEBUTTONDOWN) {
				int x=event.button.x;
				int y=event.button.y;
				game.handleButton(x,y,true);
			} else if(event.type==SDL_MOUSEBUTTONUP) {
				int x=event.button.x;
				int y=event.button.y;
				game.handleButton(x,y,false);
			} else if(event.type==SDL_MOUSEMOTION) {
				int x=event.motion.x;
				int y=event.motion.y;
				game.handleMotion(x,y);
			}
		}
		// draw screen
		game.draw(renderer);

		// update game state
		game.update(elapsed);
	}
	SDL_Quit();
	return 0;
}
<commit_msg>Made random numbers more random.<commit_after>#include <SDL.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "main.h"
#include "game.h"
#include "font.h"
#include "sound.h"
#include "image.h"

Game game;
SDL_Point screensize={640,384};

extern "C" {
int main(int argc,char **argv);
}

int main(int argc,char **argv)
{
	SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO);
	// init window and renderer
	// TODO: query the screen and set the resolution based on the screen size.
	SDL_Window *window=SDL_CreateWindow("Super Trump Jump",SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,640,384,0);
	screensize.x=640;
	screensize.y=384;
	SDL_Renderer *renderer=SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED);

	// Init joystick
	SDL_Joystick *joy=0;
	if(SDL_NumJoysticks()>0) {
		joy=SDL_JoystickOpen(0);
	}
	if(SDL_NumJoysticks()>1) {
		joy=SDL_JoystickOpen(1);
	}

	// Init audio
	Sound::init();

	// Init image loader
	Image::init();

	// Init font loader
	Font::init();

	srand(time(NULL));

	// TODO calculatre this with acutal time in ms.
	int elapsed=16;
	bool done=false;
	while(!done) {
		// handle events
		SDL_Event event;

		while(SDL_PollEvent(&event)) {
			if(event.type==SDL_QUIT) {
				done=true;
			// dispatch to game object.
			} else if(event.type==SDL_KEYDOWN) {
				if(event.key.keysym.sym==' ') {
					game.handleKey(' ',true);
				}
			} else if(event.type==SDL_KEYUP) {
				if(event.key.keysym.sym==' ') {
					game.handleKey(' ',false);
				}
			} else if(event.type==SDL_MOUSEBUTTONDOWN) {
				int x=event.button.x;
				int y=event.button.y;
				game.handleButton(x,y,true);
			} else if(event.type==SDL_MOUSEBUTTONUP) {
				int x=event.button.x;
				int y=event.button.y;
				game.handleButton(x,y,false);
			} else if(event.type==SDL_MOUSEMOTION) {
				int x=event.motion.x;
				int y=event.motion.y;
				game.handleMotion(x,y);
			}
		}
		// draw screen
		game.draw(renderer);

		// update game state
		game.update(elapsed);
	}
	SDL_Quit();
	return 0;
}
<|endoftext|>


<commit_before>/**
 * Blink
 *
 * Turns on an LED on for one second,
 * then off for one second, repeatedly.
 */
#include "Arduino.h"

#include <SPI.h>

const int kSlaveSelectPin = 10;

// Set LED_BUILTIN if it is not defined by Arduino framework
// #define LED_BUILTIN 13

class SPITransaction {
 public:
  SPITransaction() {
    digitalWrite(kSlaveSelectPin, LOW);
    SPI.beginTransaction(SPISettings(50000, MSBFIRST, SPI_MODE0));
  }

  ~SPITransaction() {
    digitalWrite(kSlaveSelectPin, HIGH);
    SPI.endTransaction();
  }
};

void reset() {
  SPITransaction transaction;
  SPI.transfer(0x30);
}

byte readReg(byte addr) {
  SPITransaction transaction;

  SPI.transfer(addr | 0x80);
  byte reply = SPI.transfer(0x00);

  return reply;
}

void setup()
{
  // initialize LED digital pin as an output.
  pinMode(LED_BUILTIN, OUTPUT);

  // Initialise the Slave Select pin.
  pinMode(kSlaveSelectPin, OUTPUT);

  Serial.begin(9600);

  SPI.begin();
}

void loop()
{
  // turn the LED on (HIGH is the voltage level)
  digitalWrite(LED_BUILTIN, HIGH);

  // wait for a second
  delay(1000);

  // turn the LED off by making the voltage LOW
  digitalWrite(LED_BUILTIN, LOW);

  Serial.write("Hello world!\n");

   // wait for a second
  delay(1000);

  reset();

  Serial.println(readReg(0xf0));
  Serial.println(readReg(0xf1));
}<commit_msg>Read temperature and humidity from SHT31D<commit_after>#include "Arduino.h"

#include <SPI.h>
#include <Wire.h>

using namespace std;

const int kSlaveSelectPin = 10;

class SPITransaction {
 public:
  SPITransaction() {
    digitalWrite(kSlaveSelectPin, LOW);
    SPI.beginTransaction(SPISettings(50000, MSBFIRST, SPI_MODE0));
  }

  ~SPITransaction() {
    digitalWrite(kSlaveSelectPin, HIGH);
    SPI.endTransaction();
  }
};

class SHT31D {
  static const uint8_t kSensorAddress = 0x44;
  static const uint16_t kSoftReset = 0x30a2;
  static const uint16_t kReadSensor = 0x2400;

 public:
  void Init() {
    WriteCommand(kSoftReset);
    delay(10);
  }

  struct Reading {
    float temperature;
    float humidity;

    Reading(float temperature, float humidity)
        : temperature(temperature),
          humidity(humidity) {}
  };

 private:
  static float ConvertTemperature(uint16_t raw_temp) {
    return -45 + 175 * (float(raw_temp) / 0xffff);
  }

  static float ConvertHumidity(uint16_t raw_humidity) {
    return 100 * (float(raw_humidity) / 0xffff);
  }

  static bool WriteCommand(uint16_t command) {
    Wire.beginTransmission(kSensorAddress);
    Wire.write(command >> 8);
    Wire.write(command & 0xff);
    return Wire.endTransmission() == 0;
  }

 public:
  Reading ReadTemperatureAndHumidity() {
    WriteCommand(kReadSensor);
    delay(500);
    Wire.requestFrom(kSensorAddress, uint8_t(6));
    if (Wire.available() == 6) {
      uint16_t raw_temp = (Wire.read() << 8) | (Wire.read() & 0xff);
      uint8_t temp_crc = Wire.read();
      uint16_t raw_humidity = (Wire.read() << 8) | (Wire.read() & 0xff);
      uint8_t humidity_crc = Wire.read();
      return Reading(ConvertTemperature(raw_temp), ConvertHumidity(raw_humidity));
    }
    Serial.println("Failed to read sensor");
    return Reading(0.0f, 0.0f);
  }
};

void reset() {
  SPITransaction transaction;
  SPI.transfer(0x30);
}

byte readReg(byte addr) {
  SPITransaction transaction;

  SPI.transfer(addr | 0x80);
  byte reply = SPI.transfer(0x00);

  return reply;
}

static SHT31D sensor;

void setup() {
  // initialize LED digital pin as an output.
  pinMode(LED_BUILTIN, OUTPUT);

  // Initialise the Slave Select pin.
  pinMode(kSlaveSelectPin, OUTPUT);

  Serial.begin(9600);

  SPI.begin();
  Wire.begin();

  sensor.Init();

  delay(100);
}

void loop() {
  // turn the LED on (HIGH is the voltage level)
  digitalWrite(LED_BUILTIN, HIGH);

  // wait for a second
  delay(1000);

  // turn the LED off by making the voltage LOW
  digitalWrite(LED_BUILTIN, LOW);

  Serial.write("Hello world!\n");

   // wait for a second
  delay(1000);

  SHT31D::Reading reading = sensor.ReadTemperatureAndHumidity();
  Serial.print(reading.temperature);
  Serial.println();
  Serial.print(reading.humidity);
  Serial.println();
}<|endoftext|>


<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include <mfem.hpp>

using namespace std;
using namespace mfem;

int main(int argc, char *argv[])
{
   MPI_Session mpi;

   const char *device_config = "cpu";

   OptionsParser args(argc, argv);
   args.AddOption(&device_config, "-d", "--device",
                  "Device configuration string, see Device::Configure().");
   args.Parse();
   if (!args.Good())
   {
      if (mpi.Root()) { args.PrintUsage(cout); }
      return 1;
   }
   if (mpi.Root()) { args.PrintOptions(cout); }

   Device device(device_config);
   if (mpi.Root()) { device.Print(); }

   //-----------------------------------------------------------
   int width = 1000000;
   Vector v_r(width/2), v_i(width/2); // this initialization causes failure below
   {
      // Vector v_r(width/2), v_i(width/2); // this initialization is fine
      Vector v(width);
      v.UseDevice(true);
      v = 0.0;
      cout << mpi.WorldRank() << ": v.HostRead() = " << v.HostRead() << endl;

      v_r.MakeRef(v, 0, width/2);
      v_i.MakeRef(v, width/2, width/2);
   }
   Vector w(width);
   w.UseDevice(true);
   w = 0.0;
   cout << mpi.WorldRank() << ": w.HostRead() = " << w.HostRead() << endl;
   Vector w_r(width/2), w_i(width/2);

   MPI_Barrier(MPI_COMM_WORLD);
   cout << mpi.WorldRank() << ": == # START # ==" << endl;
   MPI_Barrier(MPI_COMM_WORLD);
   w_r.MakeRef(w, 0, width/2);        // fails
   w_i.MakeRef(w, width/2, width/2);  // fails
   // with one of the following two messages:
   // 1) Verification failed: (h_mt == maps->aliases.at(h_ptr).mem->h_mt) is false:
   //    -->
   //    ... in function: static void mfem::MemoryManager::CheckHostMemoryType_(mfem::MemoryType, void *)
   //    ... in file: general/mem_manager.cpp:1377
   // 2) alias already exists with different base/offset!
   MPI_Barrier(MPI_COMM_WORLD);
   cout << mpi.WorldRank() << ": == # END # ==" << endl;

   return 0;
}
<commit_msg>Some simplification and better reproducability (tested on Ray with device cuda).<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include <mfem.hpp>

using namespace std;
using namespace mfem;

int main(int argc, char *argv[])
{
   MPI_Session mpi;

   const char *device_config = "cpu";

   OptionsParser args(argc, argv);
   args.AddOption(&device_config, "-d", "--device",
                  "Device configuration string, see Device::Configure().");
   args.Parse();
   if (!args.Good())
   {
      if (mpi.Root()) { args.PrintUsage(cout); }
      return 1;
   }
   if (mpi.Root()) { args.PrintOptions(cout); }

   Device device(device_config);
   if (mpi.Root()) { device.Print(); }

   //-----------------------------------------------------------
   int width = 1000;
   Vector v_r, v_i; // this initialization causes failure below
   {
      // Vector v_r, v_i; // this initialization is fine
      Vector v(width);
      v.UseDevice(true);
      v = 0.0;
      cout << mpi.WorldRank() << ": v.HostRead() = " << v.HostRead() << endl;

      v_r.MakeRef(v, 0, width/2);
      v_i.MakeRef(v, width/2, width/2);
   }
   Vector w(width);
   w.UseDevice(true);
   w = 0.0;
   cout << mpi.WorldRank() << ": w.HostRead() = " << w.HostRead() << endl;
   Vector w_r, w_i;

   MPI_Barrier(MPI_COMM_WORLD);
   cout << mpi.WorldRank() << ": == # START # ==" << endl;
   MPI_Barrier(MPI_COMM_WORLD);
   w_r.MakeRef(w, 0, width/2);        // fails
   w_i.MakeRef(w, width/2, width/2);  // fails
   // with one of the following two messages:
   // 1) Verification failed: (h_mt == maps->aliases.at(h_ptr).mem->h_mt) is false:
   //    -->
   //    ... in function: static void mfem::MemoryManager::CheckHostMemoryType_(mfem::MemoryType, void *)
   //    ... in file: general/mem_manager.cpp:1377
   // 2) alias already exists with different base/offset!
   MPI_Barrier(MPI_COMM_WORLD);
   cout << mpi.WorldRank() << ": == # END # ==" << endl;

   return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TitleItemConverter.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 00:25:51 $
 *
 *  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 CHART_TITLEITEMCONVERTER_HXX
#define CHART_TITLEITEMCONVERTER_HXX

#include "ItemConverter.hxx"

#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif

#include <vector>
#include <memory>

class SdrModel;

namespace chart
{
namespace wrapper
{

class TitleItemConverter :
        public ::comphelper::ItemConverter
{
public:
    TitleItemConverter(
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::beans::XPropertySet > & rPropertySet,
        SfxItemPool& rItemPool,
        SdrModel& rDrawModel,
        ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
            ::std::auto_ptr< ::com::sun::star::awt::Size >() );

    virtual ~TitleItemConverter();

    virtual void FillItemSet( SfxItemSet & rOutItemSet ) const;
    virtual bool ApplyItemSet( const SfxItemSet & rItemSet );

protected:
    virtual const USHORT * GetWhichPairs() const;
    virtual bool GetItemPropertyName( USHORT nWhichId, ::rtl::OUString & rOutName ) const;

    virtual void FillSpecialItem( USHORT nWhichId, SfxItemSet & rOutItemSet ) const
        throw( ::com::sun::star::uno::Exception );
    virtual bool ApplySpecialItem( USHORT nWhichId, const SfxItemSet & rItemSet )
        throw( ::com::sun::star::uno::Exception );

private:
    ::std::vector< ItemConverter * >    m_aConverters;
};

} //  namespace wrapper
} //  namespace chart

// CHART_TITLEITEMCONVERTER_HXX
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.5.4); FILE MERGED 2005/10/07 11:28:42 bm 1.5.4.3: RESYNC: (1.5-1.6); FILE MERGED 2005/07/12 12:57:00 bm 1.5.4.2: use named properties for gradients etc. in chart model 2004/05/07 09:14:10 bm 1.5.4.1: enabling member-ids for all items<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TitleItemConverter.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 17:57:18 $
 *
 *  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 CHART_TITLEITEMCONVERTER_HXX
#define CHART_TITLEITEMCONVERTER_HXX

#include "ItemConverter.hxx"

#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#include <vector>
#include <memory>

class SdrModel;

namespace chart
{
namespace wrapper
{

class TitleItemConverter :
        public ::comphelper::ItemConverter
{
public:
    TitleItemConverter(
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::beans::XPropertySet > & rPropertySet,
        SfxItemPool& rItemPool,
        SdrModel& rDrawModel,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::lang::XMultiServiceFactory > & xNamedPropertyContainerFactory,
        ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
            ::std::auto_ptr< ::com::sun::star::awt::Size >() );

    virtual ~TitleItemConverter();

    virtual void FillItemSet( SfxItemSet & rOutItemSet ) const;
    virtual bool ApplyItemSet( const SfxItemSet & rItemSet );

protected:
    virtual const USHORT * GetWhichPairs() const;
    virtual bool GetItemProperty( tWhichIdType nWhichId, tPropertyNameWithMemberId & rOutProperty ) const;

    virtual void FillSpecialItem( USHORT nWhichId, SfxItemSet & rOutItemSet ) const
        throw( ::com::sun::star::uno::Exception );
    virtual bool ApplySpecialItem( USHORT nWhichId, const SfxItemSet & rItemSet )
        throw( ::com::sun::star::uno::Exception );

private:
    ::std::vector< ItemConverter * >    m_aConverters;
};

} //  namespace wrapper
} //  namespace chart

// CHART_TITLEITEMCONVERTER_HXX
#endif
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"

#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/pref_names.h"
#include "net/base/mock_host_resolver.h"

// Possible race in ChromeURLDataManager. http://crbug.com/59198
#if defined(OS_MACOSX) || defined(OS_LINUX)
#define MAYBE_TabOnRemoved DISABLED_TabOnRemoved
#else
#define MAYBE_TabOnRemoved TabOnRemoved
#endif

// Crashes on linux views. http://crbug.com/61592
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
#define MAYBE_Tabs DISABLED_Tabs
#else
#define MAYBE_Tabs Tabs
#endif

// Window resizes are not completed by the time the callback happens,
// so these tests fail on linux. http://crbug.com/72369
#if defined(OS_LINUX)
#define MAYBE_FocusWindowDoesNotExitFullscreen \
  DISABLED_FocusWindowDoesNotExitFullscreen
#define MAYBE_UpdateWindowSizeExitsFullscreen \
  DISABLED_UpdateWindowSizeExitsFullscreen
#else
#define MAYBE_FocusWindowDoesNotExitFullscreen FocusWindowDoesNotExitFullscreen
#define MAYBE_UpdateWindowSizeExitsFullscreen UpdateWindowSizeExitsFullscreen
#endif

// Times out on Mac (especially Leopard). http://crbug.com/80212
#if defined(OS_MACOSX)
#define MAYBE_CaptureVisibleTabRace FLAKY_CaptureVisibleTabRace
#else
#define MAYBE_CaptureVisibleTabRace CaptureVisibleTabRace
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
  ASSERT_TRUE(StartTestServer());

  // The test creates a tab and checks that the URL of the new tab
  // is that of the new tab page.  Make sure the pref that controls
  // this is set.
  browser()->profile()->GetPrefs()->SetBoolean(
      prefs::kHomePageIsNewTabPage, true);

  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabMove) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabEvents) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabRelativeURLs) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
                                  "test_jpeg.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
                                  "test_png.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabRace) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
                                  "test_race.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
                       MAYBE_FocusWindowDoesNotExitFullscreen) {
  browser()->window()->SetFullscreen(true);
  bool is_fullscreen = browser()->window()->IsFullscreen();
  ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_;
  ASSERT_EQ(is_fullscreen, browser()->window()->IsFullscreen());
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
                       MAYBE_UpdateWindowSizeExitsFullscreen) {
  browser()->window()->SetFullscreen(true);
  ASSERT_TRUE(RunExtensionTest("window_update/sizing")) << message_;
  ASSERT_FALSE(browser()->window()->IsFullscreen());
}

#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) {
  gfx::NativeWindow window = browser()->window()->GetNativeHandle();
  ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
  ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_;
  ASSERT_TRUE(::IsZoomed(window));
}
#endif  // OS_WIN

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) {
  ASSERT_TRUE(StartTestServer());

  browser()->profile()->GetPrefs()->SetBoolean(prefs::kIncognitoEnabled, false);

  // This makes sure that creating an incognito window fails due to pref
  // (policy) being set.
  ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedPopup) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html"))
      << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedWindow) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html"))
      << message_;
}
<commit_msg>Disable ExtensionApiTest.CaptureVisibleTabRace since it still turns the bot red, even when marked as flaky.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"

#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/pref_names.h"
#include "net/base/mock_host_resolver.h"

// Possible race in ChromeURLDataManager. http://crbug.com/59198
#if defined(OS_MACOSX) || defined(OS_LINUX)
#define MAYBE_TabOnRemoved DISABLED_TabOnRemoved
#else
#define MAYBE_TabOnRemoved TabOnRemoved
#endif

// Crashes on linux views. http://crbug.com/61592
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
#define MAYBE_Tabs DISABLED_Tabs
#else
#define MAYBE_Tabs Tabs
#endif

// Window resizes are not completed by the time the callback happens,
// so these tests fail on linux. http://crbug.com/72369
#if defined(OS_LINUX)
#define MAYBE_FocusWindowDoesNotExitFullscreen \
  DISABLED_FocusWindowDoesNotExitFullscreen
#define MAYBE_UpdateWindowSizeExitsFullscreen \
  DISABLED_UpdateWindowSizeExitsFullscreen
#else
#define MAYBE_FocusWindowDoesNotExitFullscreen FocusWindowDoesNotExitFullscreen
#define MAYBE_UpdateWindowSizeExitsFullscreen UpdateWindowSizeExitsFullscreen
#endif

// Times out on Mac (especially Leopard). http://crbug.com/80212
#if defined(OS_MACOSX)
#define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace
#else
#define MAYBE_CaptureVisibleTabRace CaptureVisibleTabRace
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
  ASSERT_TRUE(StartTestServer());

  // The test creates a tab and checks that the URL of the new tab
  // is that of the new tab page.  Make sure the pref that controls
  // this is set.
  browser()->profile()->GetPrefs()->SetBoolean(
      prefs::kHomePageIsNewTabPage, true);

  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabMove) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabEvents) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabRelativeURLs) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
                                  "test_jpeg.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
                                  "test_png.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabRace) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
                                  "test_race.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
                       MAYBE_FocusWindowDoesNotExitFullscreen) {
  browser()->window()->SetFullscreen(true);
  bool is_fullscreen = browser()->window()->IsFullscreen();
  ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_;
  ASSERT_EQ(is_fullscreen, browser()->window()->IsFullscreen());
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
                       MAYBE_UpdateWindowSizeExitsFullscreen) {
  browser()->window()->SetFullscreen(true);
  ASSERT_TRUE(RunExtensionTest("window_update/sizing")) << message_;
  ASSERT_FALSE(browser()->window()->IsFullscreen());
}

#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) {
  gfx::NativeWindow window = browser()->window()->GetNativeHandle();
  ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
  ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_;
  ASSERT_TRUE(::IsZoomed(window));
}
#endif  // OS_WIN

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) {
  ASSERT_TRUE(StartTestServer());

  browser()->profile()->GetPrefs()->SetBoolean(prefs::kIncognitoEnabled, false);

  // This makes sure that creating an incognito window fails due to pref
  // (policy) being set.
  ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedPopup) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html"))
      << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedWindow) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html"))
      << message_;
}
<|endoftext|>


<commit_before>#ifndef THREE_GEOMETRY_UTILS_HPP
#define THREE_GEOMETRY_UTILS_HPP

#include <three/core/face3.hpp>
#include <three/core/face4.hpp>

namespace three {

class GeometryUtils {
public:

  static void merge( Geometry& geometry1, Object3D& object2 ) {

    if ( object2.type() == THREE::Mesh ) {

      if ( object2.matrixAutoUpdate )
        object2.updateMatrix();

      Matrix4 matrix, matrixRotation;

      matrix = object2.matrix;
      matrixRotation.extractRotation( matrix );//, object2.scale );

      merge( geometry1, *object2.geometry, &matrix, &matrixRotation );

    } else {

      merge( geometry1, *object2.geometry );

    }

  }

  static void merge( Geometry& geometry1,
                     Geometry& geometry2,
                     const Matrix4* matrix = nullptr,
                     const Matrix4* matrixRotation = nullptr ) {

    auto vertexOffset = (int)geometry1.vertices.size();

    auto& vertices1 = geometry1.vertices;
    auto& vertices2 = geometry2.vertices;
    auto& faces1 = geometry1.faces;
    auto& faces2 = geometry2.faces;
    auto& uvs1 = geometry1.faceVertexUvs[ 0 ];
    auto& uvs2 = geometry2.faceVertexUvs[ 0 ];

    std::unordered_map<int, int> geo1MaterialsMap;

    for ( int i = 0; i < (int)geometry1.materials.size(); i ++ ) {
      const auto& id = geometry1.materials[ i ]->id;
      geo1MaterialsMap[ id ] = i;
    }

    // vertices
    concat( vertices1, vertices2 );

    if ( matrix ) {
      std::for_each( vertices1.begin() + vertexOffset, vertices1.end(),
        [&matrix] ( Vertex& v ) { matrix->multiplyVector3( v ); }
      );
    }

    // faces

    for ( size_t i = 0, il = faces2.size(); i < il; i ++ ) {

      const auto& face = faces2[ i ];

      Face faceCopy( 0, 0, 0 );//, normal, color,
      const auto& faceVertexNormals = face.vertexNormals;
      const auto& faceVertexColors = face.vertexColors;

      if ( face.type() == THREE::Face3 ) {
        faceCopy = Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
      } else if ( face.type() == THREE::Face4 ) {
        faceCopy = Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
      }

      faceCopy.normal.copy( face.normal );

      if ( matrixRotation ) matrixRotation->multiplyVector3( faceCopy.normal );

      for ( size_t j = 0, jl = faceVertexNormals.size(); j < jl; j ++ ) {

        auto normal = faceVertexNormals[ j ].clone();

        if ( matrixRotation ) matrixRotation->multiplyVector3( normal );

        faceCopy.vertexNormals[ j ] = normal;

      }

      faceCopy.color.copy( face.color );

      faceCopy.vertexColors = faceVertexColors;

      if ( face.materialIndex != -1 ) {

        auto material2 = geometry2.materials[ face.materialIndex ];
        auto materialId2 = material2->id;
        int materialIndex = 0;

        auto materialIndexIt = geo1MaterialsMap.find( materialId2 );
        if ( materialIndexIt == geo1MaterialsMap.end() ) {

          materialIndex = (int)geometry1.materials.size();
          geo1MaterialsMap[ materialId2 ] = materialIndex;

          geometry1.materials.push_back( material2 );

        }

        faceCopy.materialIndex = materialIndex;

      }

      faceCopy.centroid.copy( face.centroid );
      if ( matrix ) matrix->multiplyVector3( faceCopy.centroid );

      faces1.push_back( faceCopy );

    }

    // uvs

    concat( uvs1, uvs2 );

  }

}; // GeometryUtils

} // namespace three

#endif // THREE_GEOMETRY_UTILS_HPP

<commit_msg>Fixing geometry merging<commit_after>#ifndef THREE_GEOMETRY_UTILS_HPP
#define THREE_GEOMETRY_UTILS_HPP

#include <three/core/face3.hpp>
#include <three/core/face4.hpp>

namespace three {

class GeometryUtils {
public:

  static void merge( Geometry& geometry1, Object3D& object2 ) {

    if ( object2.type() == THREE::Mesh ) {

      if ( object2.matrixAutoUpdate )
        object2.updateMatrix();

      Matrix4 matrix, matrixRotation;

      matrix = object2.matrix;
      matrixRotation.extractRotation( matrix );//, object2.scale );

      merge( geometry1, *object2.geometry, &matrix, &matrixRotation );

    } else {

      merge( geometry1, *object2.geometry );

    }

  }

  static void merge( Geometry& geometry1,
                     Geometry& geometry2,
                     const Matrix4* matrix = nullptr,
                     const Matrix4* matrixRotation = nullptr ) {

    auto vertexOffset = (int)geometry1.vertices.size();

    auto& vertices1 = geometry1.vertices;
    auto& vertices2 = geometry2.vertices;
    auto& faces1 = geometry1.faces;
    auto& faces2 = geometry2.faces;
    auto& uvs1 = geometry1.faceVertexUvs[ 0 ];
    auto& uvs2 = geometry2.faceVertexUvs[ 0 ];

    std::unordered_map<int, int> geo1MaterialsMap;

    for ( int i = 0; i < (int)geometry1.materials.size(); i ++ ) {
      const auto& id = geometry1.materials[ i ]->id;
      geo1MaterialsMap[ id ] = i;
    }

    // vertices
    concat( vertices1, vertices2 );

    if ( matrix ) {
      std::for_each( vertices1.begin() + vertexOffset, vertices1.end(),
        [&matrix] ( Vertex& v ) { matrix->multiplyVector3( v ); }
      );
    }

    // faces

    for ( size_t i = 0, il = faces2.size(); i < il; i ++ ) {

      const auto& face = faces2[ i ];

      Face faceCopy( 0, 0, 0 );//, normal, color,
      const auto& faceVertexNormals = face.vertexNormals;
      const auto& faceVertexColors = face.vertexColors;

      if ( face.type() == THREE::Face3 ) {
        faceCopy = Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
      } else if ( face.type() == THREE::Face4 ) {
        faceCopy = Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
      }

      faceCopy.normal.copy( face.normal );

      if ( matrixRotation ) matrixRotation->multiplyVector3( faceCopy.normal );

      for ( size_t j = 0, jl = faceVertexNormals.size(); j < jl; j ++ ) {

        auto normal = faceVertexNormals[ j ].clone();

        if ( matrixRotation ) matrixRotation->multiplyVector3( normal );

        faceCopy.vertexNormals[ j ] = normal;

      }

      faceCopy.color.copy( face.color );

      faceCopy.vertexColors = faceVertexColors;

      if ( face.materialIndex != -1 ) {

        auto material2 = geometry2.materials[ face.materialIndex ];
        auto materialId2 = material2->id;
        int materialIndex = 0;

        auto materialIndexIt = geo1MaterialsMap.find( materialId2 );
        if ( materialIndexIt == geo1MaterialsMap.end() ) {

          materialIndex = (int)geometry1.materials.size();
          geo1MaterialsMap[ materialId2 ] = materialIndex;

          geometry1.materials.push_back( material2 );

        } else {
          materialIndex = materialIndexIt->second;
        }

        faceCopy.materialIndex = materialIndex;

      }

      faceCopy.centroid.copy( face.centroid );
      if ( matrix ) matrix->multiplyVector3( faceCopy.centroid );

      faces1.push_back( faceCopy );

    }

    // uvs

    concat( uvs1, uvs2 );

  }

}; // GeometryUtils

} // namespace three

#endif // THREE_GEOMETRY_UTILS_HPP

<|endoftext|>


<commit_before>// addon.cc
#include <node.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <string.h>
#include "lexer.h"

using namespace v8;

/* Type Definitions */
#define STRINGTYPE 0x03
#define COMMENTTYPE 0x01
#define KEYTYPE 0x02

/* State definitions */
#define NONESTATE 0x01
#define COMMENTSTATE 0x02
#define KEYSTATE 0x03
#define STRINGSTATE 0x04

#define VALLENGTH 100

char *v8StrToCharStar(v8::Local<v8::Value> value) {
    v8::String::Utf8Value string(value);
    char *str = (char *) malloc(string.length() + 1);
    strcpy(str, *string);
    return str;
}

void parse(const FunctionCallbackInfo<Value>& args) {
    bool escaped = false;
    char chr;
    int i;
    int ntokens;
    int state = NONESTATE;
    struct Token * tokens;
    char * po_string;
    char * buffer;

    buffer = NULL;
    tokens = NULL;
    ntokens = 0;

    Isolate* isolate = Isolate::GetCurrent();
    Local<Object> catalog_obj;
    Local<String> catalog_str;

    HandleScope scope(isolate);

    if (args.Length() < 1) {
        isolate->ThrowException(Exception::TypeError(
            String::NewFromUtf8(isolate, "Takes two arguments")));
        return;
    }

    if (!args[0]->IsString()) {
        isolate->ThrowException(Exception::TypeError(
            String::NewFromUtf8(isolate, "First argument must be a string")));
        return;
    }

    catalog_obj = Object::New(isolate);
    po_string = v8StrToCharStar(args[0]);
    catalog_str = args[0]->ToString();

    for (i = 0; i < catalog_str->Length(); i++) {
        chr = po_string[i];

        switch(state) {
            case NONESTATE:
                if (chr == '\'' || chr == '"') {
                    state = STRINGSTATE;
                    tokens = append(tokens, ntokens, STRINGTYPE, chr, NULL);
                    ++ntokens;
                } else if (chr == '#') {
                    state = COMMENTSTATE;
                    tokens = append(tokens, ntokens, COMMENTTYPE, '\0', NULL);
                    ++ntokens;
                } else if (!isspace(chr)) {
                    state = KEYSTATE;
                    buffer = append_to_buffer(NULL, chr);
                } else if (isspace(chr)) {
                    tokens = append(tokens, ntokens, KEYTYPE, '\0', buffer);
                    free(buffer);
                    buffer = NULL;
                    ++ntokens;
                }

                break;

            case COMMENTSTATE:
                if (chr == '\n') {
                    state = NONESTATE;
                } else if (chr != '\r') {
                    buffer = append_to_buffer(buffer, chr);
                }

                break;

            case STRINGSTATE:
                if(escaped) {
                    switch(chr) {
                        case 't':
                            buffer = append_to_buffer(buffer, '\t');
                            break;

                        case 'n':
                            buffer = append_to_buffer(buffer, '\n');
                            break;

                        case 'r':
                            buffer = append_to_buffer(buffer, '\r');
                            break;
                    }

                    escaped = false;

                } else {
                    if(chr == '\'' || chr == '"') {
                        state = NONESTATE;
                    } else if (chr == '\\') {
                        escaped = true;
                        break;
                    } else {
                        buffer = append_to_buffer(buffer, chr);
                    }
                    escaped = false;
                }

                break;

            case KEYSTATE:
                if(isalpha(chr) || chr == '-' || chr == '[' || chr == ']') {
                    buffer = append_to_buffer(buffer, chr);
                } else {
                    state = NONESTATE;
                    --i;
                }

                break;
        }
    }

    args.GetReturnValue().Set(catalog_obj);
    print_token_array(tokens, ntokens);
    free_token_array(tokens, ntokens);
    free(po_string);
}

void Init(Handle<Object> exports) {
    NODE_SET_METHOD(exports, "parse", parse);
}

NODE_MODULE(gettextlexer, Init)
<commit_msg>Fix string termination bug<commit_after>// addon.cc
#include <node.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <string.h>
#include "lexer.h"

using namespace v8;

/* Type Definitions */
#define STRINGTYPE 0x03
#define COMMENTTYPE 0x01
#define KEYTYPE 0x02

/* State definitions */
#define NONESTATE 0x01
#define COMMENTSTATE 0x02
#define KEYSTATE 0x03
#define STRINGSTATE 0x04

#define VALLENGTH 100

char *v8StrToCharStar(v8::Local<v8::Value> value) {
    v8::String::Utf8Value string(value);
    char *str = (char *) malloc(string.length() + 1);
    strcpy(str, *string);
    return str;
}

void parse(const FunctionCallbackInfo<Value>& args) {
    bool escaped = false;
    char chr;
    int i;
    int ntokens;
    int state = NONESTATE;
    struct Token * tokens;
    char * po_string;
    char * buffer;

    buffer = NULL;
    tokens = NULL;
    ntokens = 0;

    Isolate* isolate = Isolate::GetCurrent();
    Local<Object> catalog_obj;
    Local<String> catalog_str;

    HandleScope scope(isolate);

    if (args.Length() < 1) {
        isolate->ThrowException(Exception::TypeError(
            String::NewFromUtf8(isolate, "Takes two arguments")));
        return;
    }

    if (!args[0]->IsString()) {
        isolate->ThrowException(Exception::TypeError(
            String::NewFromUtf8(isolate, "First argument must be a string")));
        return;
    }

    catalog_obj = Object::New(isolate);
    po_string = v8StrToCharStar(args[0]);
    catalog_str = args[0]->ToString();

    for (i = 0; i < catalog_str->Length(); i++) {
        chr = po_string[i];

        switch(state) {
            case NONESTATE:
                if (chr == '\'' || chr == '"') {
                    state = STRINGSTATE;
                    tokens = append(tokens, ntokens, STRINGTYPE, chr, NULL);
                    ++ntokens;
                } else if (chr == '#') {
                    state = COMMENTSTATE;
                    tokens = append(tokens, ntokens, COMMENTTYPE, '\0', NULL);
                    ++ntokens;
                } else if (!isspace(chr)) {
                    state = KEYSTATE;
                    buffer = append_to_buffer(NULL, chr);
                } else if (isspace(chr)) {
                    tokens = append(tokens, ntokens, KEYTYPE, '\0', buffer);
                    free(buffer);
                    buffer = NULL;
                    ++ntokens;
                }

                break;

            case COMMENTSTATE:
                if (chr == '\n') {
                    state = NONESTATE;
                } else if (chr != '\r') {
                    buffer = append_to_buffer(buffer, chr);
                }

                break;

            case STRINGSTATE:
                if(escaped) {
                    switch(chr) {
                        case 't':
                            buffer = append_to_buffer(buffer, '\t');
                            break;

                        case 'n':
                            buffer = append_to_buffer(buffer, '\n');
                            break;

                        case 'r':
                            buffer = append_to_buffer(buffer, '\r');
                            break;
                    }

                    escaped = false;

                } else {
                    if(chr == quote) {
                        tokens = append(tokens, ntokens, STRINGTYPE, quote, buffer);
                        free(buffer);
                        buffer = NULL;
                        state = NONESTATE;
                        ++ntokens;
                    } else if (chr == '\\') {
                        escaped = true;
                        break;
                    } else {
                        buffer = append_to_buffer(buffer, chr);
                    }
                    escaped = false;
                }

                break;

            case KEYSTATE:
                if(isalpha(chr) || chr == '-' || chr == '[' || chr == ']') {
                    buffer = append_to_buffer(buffer, chr);
                } else {
                    state = NONESTATE;
                    --i;
                }

                break;
        }
    }

    args.GetReturnValue().Set(catalog_obj);
    print_token_array(tokens, ntokens);
    free_token_array(tokens, ntokens);
    free(po_string);
}

void Init(Handle<Object> exports) {
    NODE_SET_METHOD(exports, "parse", parse);
}

NODE_MODULE(gettextlexer, Init)
<|endoftext|>


<commit_before>/*
 * Copyright 2007-2017 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Convert C++ exception to a HTTP response.
 */

#include "Request.hxx"
#include "Instance.hxx"
#include "http_client.hxx"
#include "nfs/Error.hxx"
#include "memcached/Error.hxx"
#include "cgi/Error.hxx"
#include "fcgi/Error.hxx"
#include "was/Error.hxx"
#include "widget/Error.hxx"
#include "HttpResponseHandler.hxx"
#include "http_server/http_server.hxx"
#include "http/IncomingRequest.hxx"
#include "http/MessageHttpResponse.hxx"
#include "HttpMessageResponse.hxx"
#include "pool/pool.hxx"
#include "system/Error.hxx"
#include "util/Exception.hxx"

#include <nfsc/libnfs-raw-nfs.h>

static MessageHttpResponse
Dup(struct pool &pool, http_status_t status, const char *msg)
{
	return {status, p_strdup(&pool, msg)};
}

gcc_pure
static MessageHttpResponse
ToResponse(struct pool &pool, std::exception_ptr ep)
{
	try {
		FindRetrowNested<HttpMessageResponse>(ep);
	} catch (const HttpMessageResponse &e) {
		return Dup(pool, e.GetStatus(), e.what());
	}

	try {
		FindRetrowNested<std::system_error>(ep);
	} catch (const std::system_error &e) {
		if (e.code().category() == ErrnoCategory()) {
			switch (e.code().value()) {
			case ENOENT:
			case ENOTDIR:
				return {HTTP_STATUS_NOT_FOUND,
					"The requested file does not exist."};

			case EACCES:
			case EPERM:
				return {HTTP_STATUS_FORBIDDEN,
					"Access to the requested file denied."};
			}
		}
	}

	try {
		FindRetrowNested<WidgetError>(ep);
	} catch (const WidgetError &e) {
		switch (e.GetCode()) {
		case WidgetErrorCode::UNSPECIFIED:
			break;

		case WidgetErrorCode::WRONG_TYPE:
		case WidgetErrorCode::UNSUPPORTED_ENCODING:
			return {HTTP_STATUS_BAD_GATEWAY, "Malformed widget response"};

		case WidgetErrorCode::NO_SUCH_VIEW:
			return {HTTP_STATUS_NOT_FOUND, "No such view"};

		case WidgetErrorCode::NOT_A_CONTAINER:
			return Dup(pool, HTTP_STATUS_NOT_FOUND, e.what());

		case WidgetErrorCode::FORBIDDEN:
			return {HTTP_STATUS_FORBIDDEN, "Forbidden"};
		}
	}

	try {
		FindRetrowNested<HttpClientError>(ep);
	} catch (...) {
		return {HTTP_STATUS_BAD_GATEWAY, "Upstream server failed"};
	}

	try {
		FindRetrowNested<WasError>(ep);
	} catch (...) {
		return {HTTP_STATUS_BAD_GATEWAY, "Script failed"};
	}

	try {
		FindRetrowNested<FcgiClientError>(ep);
	} catch (...) {
		return {HTTP_STATUS_BAD_GATEWAY, "Script failed"};
	}

	try {
		FindRetrowNested<CgiError>(ep);
	} catch (...) {
		return {HTTP_STATUS_BAD_GATEWAY, "Script failed"};
	}

	try {
		FindRetrowNested<MemcachedClientError>(ep);
	} catch (...) {
		return {HTTP_STATUS_BAD_GATEWAY, "Cache server failed"};
	}

	try {
		FindRetrowNested<NfsClientError>(ep);
	} catch (const NfsClientError &e) {
		switch (e.GetCode()) {
		case NFS3ERR_NOENT:
		case NFS3ERR_NOTDIR:
			return {HTTP_STATUS_NOT_FOUND,
				"The requested file does not exist."};
		}
	}

	return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"};
}

void
Request::LogDispatchError(http_status_t status,
			  const char *msg, const char *log_msg,
			  unsigned log_level)
{
	logger(log_level, "error on '", request.uri, "': ", log_msg);

	if (instance.config.verbose_response)
		msg = p_strdup(&pool, log_msg);

	DispatchResponse(status, msg);
}

void
Request::LogDispatchError(http_status_t status, const char *log_msg,
			  unsigned log_level)
{
	LogDispatchError(status, http_status_to_string(status),
			 log_msg, log_level);
}

void
Request::LogDispatchError(std::exception_ptr ep)
{
	auto response = ToResponse(pool, ep);
	if (instance.config.verbose_response)
		response.message = p_strdup(&pool, GetFullMessage(ep).c_str());

	logger(response.status == HTTP_STATUS_INTERNAL_SERVER_ERROR ? 1 : 2,
	       "error on '", request.uri, "': ", ep);

	DispatchResponse(response.status, response.message);
}

void
Request::LogDispatchError(http_status_t status, const char *msg,
			  std::exception_ptr ep, unsigned log_level)
{
	logger(log_level, "error on '", request.uri, "': ", ep);

	if (instance.config.verbose_response)
		msg = p_strdup(&pool, GetFullMessage(ep).c_str());

	DispatchResponse(status, msg);
}
<commit_msg>bp/RError: merge several try/catch blocks<commit_after>/*
 * Copyright 2007-2017 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Convert C++ exception to a HTTP response.
 */

#include "Request.hxx"
#include "Instance.hxx"
#include "http_client.hxx"
#include "nfs/Error.hxx"
#include "memcached/Error.hxx"
#include "cgi/Error.hxx"
#include "fcgi/Error.hxx"
#include "was/Error.hxx"
#include "widget/Error.hxx"
#include "HttpResponseHandler.hxx"
#include "http_server/http_server.hxx"
#include "http/IncomingRequest.hxx"
#include "http/MessageHttpResponse.hxx"
#include "HttpMessageResponse.hxx"
#include "pool/pool.hxx"
#include "system/Error.hxx"
#include "util/Exception.hxx"

#include <nfsc/libnfs-raw-nfs.h>

static MessageHttpResponse
Dup(struct pool &pool, http_status_t status, const char *msg)
{
	return {status, p_strdup(&pool, msg)};
}

gcc_pure
static MessageHttpResponse
ToResponse(struct pool &pool, std::exception_ptr ep)
{
	try {
		FindRetrowNested<HttpMessageResponse>(ep);
	} catch (const HttpMessageResponse &e) {
		return Dup(pool, e.GetStatus(), e.what());
	}

	try {
		FindRetrowNested<std::system_error>(ep);
	} catch (const std::system_error &e) {
		if (e.code().category() == ErrnoCategory()) {
			switch (e.code().value()) {
			case ENOENT:
			case ENOTDIR:
				return {HTTP_STATUS_NOT_FOUND,
					"The requested file does not exist."};

			case EACCES:
			case EPERM:
				return {HTTP_STATUS_FORBIDDEN,
					"Access to the requested file denied."};
			}
		}
	}

	try {
		FindRetrowNested<WidgetError>(ep);
	} catch (const WidgetError &e) {
		switch (e.GetCode()) {
		case WidgetErrorCode::UNSPECIFIED:
			break;

		case WidgetErrorCode::WRONG_TYPE:
		case WidgetErrorCode::UNSUPPORTED_ENCODING:
			return {HTTP_STATUS_BAD_GATEWAY, "Malformed widget response"};

		case WidgetErrorCode::NO_SUCH_VIEW:
			return {HTTP_STATUS_NOT_FOUND, "No such view"};

		case WidgetErrorCode::NOT_A_CONTAINER:
			return Dup(pool, HTTP_STATUS_NOT_FOUND, e.what());

		case WidgetErrorCode::FORBIDDEN:
			return {HTTP_STATUS_FORBIDDEN, "Forbidden"};
		}
	}

	try {
		FindRetrowNested<HttpClientError>(ep);
	} catch (...) {
		return {HTTP_STATUS_BAD_GATEWAY, "Upstream server failed"};
	}

	try {
		FindRetrowNested<WasError>(ep);
		FindRetrowNested<FcgiClientError>(ep);
		FindRetrowNested<CgiError>(ep);
	} catch (...) {
		return {HTTP_STATUS_BAD_GATEWAY, "Script failed"};
	}

	try {
		FindRetrowNested<MemcachedClientError>(ep);
	} catch (...) {
		return {HTTP_STATUS_BAD_GATEWAY, "Cache server failed"};
	}

	try {
		FindRetrowNested<NfsClientError>(ep);
	} catch (const NfsClientError &e) {
		switch (e.GetCode()) {
		case NFS3ERR_NOENT:
		case NFS3ERR_NOTDIR:
			return {HTTP_STATUS_NOT_FOUND,
				"The requested file does not exist."};
		}
	}

	return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"};
}

void
Request::LogDispatchError(http_status_t status,
			  const char *msg, const char *log_msg,
			  unsigned log_level)
{
	logger(log_level, "error on '", request.uri, "': ", log_msg);

	if (instance.config.verbose_response)
		msg = p_strdup(&pool, log_msg);

	DispatchResponse(status, msg);
}

void
Request::LogDispatchError(http_status_t status, const char *log_msg,
			  unsigned log_level)
{
	LogDispatchError(status, http_status_to_string(status),
			 log_msg, log_level);
}

void
Request::LogDispatchError(std::exception_ptr ep)
{
	auto response = ToResponse(pool, ep);
	if (instance.config.verbose_response)
		response.message = p_strdup(&pool, GetFullMessage(ep).c_str());

	logger(response.status == HTTP_STATUS_INTERNAL_SERVER_ERROR ? 1 : 2,
	       "error on '", request.uri, "': ", ep);

	DispatchResponse(response.status, response.message);
}

void
Request::LogDispatchError(http_status_t status, const char *msg,
			  std::exception_ptr ep, unsigned log_level)
{
	logger(log_level, "error on '", request.uri, "': ", ep);

	if (instance.config.verbose_response)
		msg = p_strdup(&pool, GetFullMessage(ep).c_str());

	DispatchResponse(status, msg);
}
<|endoftext|>


<commit_before>#include <string.h>

#include "base/logging.h"
#include "gfx/gl_common.h"
#include "gfx_es2/fbo.h"
#include "gfx/gl_common.h"
#include "gfx_es2/gl_state.h"

#if defined(USING_GLES2) && !defined(BLACKBERRY)
#define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER
#define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER
#define GL_RGBA8 GL_RGBA
#ifndef GL_DEPTH_COMPONENT24
#define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES
#endif
#ifndef GL_DEPTH24_STENCIL8_OES
#define GL_DEPTH24_STENCIL8_OES 0x88F0
#endif
#endif

#ifdef IOS
extern void bindDefaultFBO();
#endif

struct FBO {
	GLuint handle;
	GLuint color_texture;
	GLuint z_stencil_buffer;  // Either this is set, or the two below.
	GLuint z_buffer;
	GLuint stencil_buffer;

	int width;
	int height;
	FBOColorDepth colorDepth;
};

// On PC, we always use GL_DEPTH24_STENCIL8.
// On Android, we try to use what's available.

#ifndef USING_GLES2
FBO *fbo_ext_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) {
	FBO *fbo = new FBO();
	fbo->width = width;
	fbo->height = height;
	fbo->colorDepth = colorDepth;

	// Color texture is same everywhere
	glGenFramebuffersEXT(1, &fbo->handle);
	glGenTextures(1, &fbo->color_texture);

	// Create the surfaces.
	glBindTexture(GL_TEXTURE_2D, fbo->color_texture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	// TODO: We could opt to only create 16-bit render targets on slow devices. For later.
	switch (colorDepth) {
	case FBO_8888:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
		break;
	case FBO_4444:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL);
		break;
	case FBO_5551:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL);
		break;
	case FBO_565:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL);
		break;
	}

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	fbo->stencil_buffer = 0;
	fbo->z_buffer = 0;
	// 24-bit Z, 8-bit stencil
	glGenRenderbuffersEXT(1, &fbo->z_stencil_buffer);
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer);
	glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_STENCIL_EXT, width, height);
	//glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8, width, height);

	// Bind it all together
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle);
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, fbo->color_texture, 0);
	glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer);
	glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer);

	GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
	switch(status) {
	case GL_FRAMEBUFFER_COMPLETE_EXT:
		// ILOG("Framebuffer verified complete.");
		break;
	case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
		ELOG("GL_FRAMEBUFFER_UNSUPPORTED");
		break;
	case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
		ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT ");
		break;
	default:
		FLOG("Other framebuffer error: %i", status);
		break;
	}
	// Unbind state we don't need
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
	glBindTexture(GL_TEXTURE_2D, 0);
	return fbo;
}
#endif

FBO *fbo_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) {
	CheckGLExtensions();

#ifndef USING_GLES2
	if(!gl_extensions.FBO_ARB)
		return fbo_ext_create(width, height, num_color_textures, z_stencil, colorDepth);
#endif

	FBO *fbo = new FBO();
	fbo->width = width;
	fbo->height = height;
	fbo->colorDepth = colorDepth;

	// Color texture is same everywhere
	glGenFramebuffers(1, &fbo->handle);
	glGenTextures(1, &fbo->color_texture);

	// Create the surfaces.
	glBindTexture(GL_TEXTURE_2D, fbo->color_texture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	// TODO: We could opt to only create 16-bit render targets on slow devices. For later.
	switch (colorDepth) {
	case FBO_8888:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
		break;
	case FBO_4444:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL);
		break;
	case FBO_5551:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL);
		break;
	case FBO_565:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL);
		break;
	}

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

#ifdef USING_GLES2
	if (gl_extensions.OES_packed_depth_stencil) {
		ILOG("Creating %i x %i FBO using DEPTH24_STENCIL8", width, height);
		// Standard method
		fbo->stencil_buffer = 0;
		fbo->z_buffer = 0;
		// 24-bit Z, 8-bit stencil combined
		glGenRenderbuffers(1, &fbo->z_stencil_buffer);
		glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, width, height);

		// Bind it all together
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle);
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0);
		glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer);
	} else {
		ILOG("Creating %i x %i FBO using separate stencil", width, height);
		// TEGRA
		fbo->z_stencil_buffer = 0;
		// 16/24-bit Z, separate 8-bit stencil
		glGenRenderbuffers(1, &fbo->z_buffer);
		glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_buffer);
		glRenderbufferStorage(GL_RENDERBUFFER, gl_extensions.OES_depth24 ? GL_DEPTH_COMPONENT24 : GL_DEPTH_COMPONENT16, width, height);

		// 8-bit stencil buffer
		glGenRenderbuffers(1, &fbo->stencil_buffer);
		glBindRenderbuffer(GL_RENDERBUFFER, fbo->stencil_buffer);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, width, height);

		// Bind it all together
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle);
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0);
		glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_buffer);
		glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->stencil_buffer);
	}
#else
	fbo->stencil_buffer = 0;
	fbo->z_buffer = 0;
	// 24-bit Z, 8-bit stencil
	glGenRenderbuffers(1, &fbo->z_stencil_buffer);
	glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer);
	glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);

	// Bind it all together
	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle);
	glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0);
	glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer);
	glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer);
#endif

	GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	switch(status) {
	case GL_FRAMEBUFFER_COMPLETE:
		// ILOG("Framebuffer verified complete.");
		break;
	case GL_FRAMEBUFFER_UNSUPPORTED:
		ELOG("GL_FRAMEBUFFER_UNSUPPORTED");
		break;
	case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
		ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT ");
		break;
	default:
		FLOG("Other framebuffer error: %i", status);
		break;
	}
	// Unbind state we don't need
	glBindRenderbuffer(GL_RENDERBUFFER, 0);
	glBindTexture(GL_TEXTURE_2D, 0);
	return fbo;
}

void fbo_unbind() {
	CheckGLExtensions();

	if(gl_extensions.FBO_ARB){
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
	}else{
#ifndef USING_GLES2
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
#endif
	}
#ifdef IOS
	bindDefaultFBO();
#endif
}

void fbo_bind_as_render_target(FBO *fbo) {
	if(gl_extensions.FBO_ARB){
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle);
	}else{
#ifndef USING_GLES2
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle);
#endif
	}
}

void fbo_bind_for_read(FBO *fbo) {
	if(gl_extensions.FBO_ARB){
		glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo->handle);
	}else{
#ifndef USING_GLES2
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle);
#endif
	}
}

void fbo_bind_color_as_texture(FBO *fbo, int color) {
	if (fbo) {
		glBindTexture(GL_TEXTURE_2D, fbo->color_texture);
	}
}

void fbo_destroy(FBO *fbo) {
	if(gl_extensions.FBO_ARB){
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle);
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
		glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
		glDeleteFramebuffers(1, &fbo->handle);
		glDeleteRenderbuffers(1, &fbo->z_stencil_buffer);
	}else{
#ifndef USING_GLES2
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle);
		glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
		glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER_EXT, 0);
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
		glDeleteFramebuffersEXT(1, &fbo->handle);
		glDeleteRenderbuffersEXT(1, &fbo->z_stencil_buffer);
#endif
	}

	glDeleteTextures(1, &fbo->color_texture);
	delete fbo;
}

void fbo_get_dimensions(FBO *fbo, int *w, int *h) {
	*w = fbo->width;
	*h = fbo->height;
}

int fbo_get_color_texture(FBO *fbo) {
	return fbo->color_texture;
}
<commit_msg>Revert "Fix nasty bug in one FBO setup. Must be a common mistake that some drivers work around?"<commit_after>#include <string.h>

#include "base/logging.h"
#include "gfx/gl_common.h"
#include "gfx_es2/fbo.h"
#include "gfx/gl_common.h"
#include "gfx_es2/gl_state.h"

#if defined(USING_GLES2) && !defined(BLACKBERRY)
#define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER
#define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER
#define GL_RGBA8 GL_RGBA
#ifndef GL_DEPTH_COMPONENT24
#define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES
#endif
#ifndef GL_DEPTH24_STENCIL8_OES
#define GL_DEPTH24_STENCIL8_OES 0x88F0
#endif
#endif

#ifdef IOS
extern void bindDefaultFBO();
#endif

struct FBO {
	GLuint handle;
	GLuint color_texture;
	GLuint z_stencil_buffer;  // Either this is set, or the two below.
	GLuint z_buffer;
	GLuint stencil_buffer;

	int width;
	int height;
	FBOColorDepth colorDepth;
};

// On PC, we always use GL_DEPTH24_STENCIL8.
// On Android, we try to use what's available.

#ifndef USING_GLES2
FBO *fbo_ext_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) {
	FBO *fbo = new FBO();
	fbo->width = width;
	fbo->height = height;
	fbo->colorDepth = colorDepth;

	// Color texture is same everywhere
	glGenFramebuffersEXT(1, &fbo->handle);
	glGenTextures(1, &fbo->color_texture);

	// Create the surfaces.
	glBindTexture(GL_TEXTURE_2D, fbo->color_texture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	// TODO: We could opt to only create 16-bit render targets on slow devices. For later.
	switch (colorDepth) {
	case FBO_8888:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
		break;
	case FBO_4444:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL);
		break;
	case FBO_5551:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL);
		break;
	case FBO_565:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL);
		break;
	}

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	fbo->stencil_buffer = 0;
	fbo->z_buffer = 0;
	// 24-bit Z, 8-bit stencil
	glGenRenderbuffersEXT(1, &fbo->z_stencil_buffer);
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer);
	glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_STENCIL_EXT, width, height);
	//glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8, width, height);

	// Bind it all together
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle);
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, fbo->color_texture, 0);
	glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer);
	glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer);

	GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
	switch(status) {
	case GL_FRAMEBUFFER_COMPLETE_EXT:
		// ILOG("Framebuffer verified complete.");
		break;
	case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
		ELOG("GL_FRAMEBUFFER_UNSUPPORTED");
		break;
	case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
		ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT ");
		break;
	default:
		FLOG("Other framebuffer error: %i", status);
		break;
	}
	// Unbind state we don't need
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
	glBindTexture(GL_TEXTURE_2D, 0);
	return fbo;
}
#endif

FBO *fbo_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) {
	CheckGLExtensions();

#ifndef USING_GLES2
	if(!gl_extensions.FBO_ARB)
		return fbo_ext_create(width, height, num_color_textures, z_stencil, colorDepth);
#endif

	FBO *fbo = new FBO();
	fbo->width = width;
	fbo->height = height;
	fbo->colorDepth = colorDepth;

	// Color texture is same everywhere
	glGenFramebuffers(1, &fbo->handle);
	glGenTextures(1, &fbo->color_texture);

	// Create the surfaces.
	glBindTexture(GL_TEXTURE_2D, fbo->color_texture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	// TODO: We could opt to only create 16-bit render targets on slow devices. For later.
	switch (colorDepth) {
	case FBO_8888:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
		break;
	case FBO_4444:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL);
		break;
	case FBO_5551:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL);
		break;
	case FBO_565:
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL);
		break;
	}

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

#ifdef USING_GLES2
	if (gl_extensions.OES_packed_depth_stencil) {
		ILOG("Creating %i x %i FBO using DEPTH24_STENCIL8", width, height);
		// Standard method
		fbo->stencil_buffer = 0;
		fbo->z_buffer = 0;
		// 24-bit Z, 8-bit stencil combined
		glGenRenderbuffers(1, &fbo->z_stencil_buffer);
		glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, width, height);

		// Bind it all together
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle);
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0);
		glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer);
		glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer);
	} else {
		ILOG("Creating %i x %i FBO using separate stencil", width, height);
		// TEGRA
		fbo->z_stencil_buffer = 0;
		// 16/24-bit Z, separate 8-bit stencil
		glGenRenderbuffers(1, &fbo->z_buffer);
		glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_buffer);
		glRenderbufferStorage(GL_RENDERBUFFER, gl_extensions.OES_depth24 ? GL_DEPTH_COMPONENT24 : GL_DEPTH_COMPONENT16, width, height);

		// 8-bit stencil buffer
		glGenRenderbuffers(1, &fbo->stencil_buffer);
		glBindRenderbuffer(GL_RENDERBUFFER, fbo->stencil_buffer);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, width, height);

		// Bind it all together
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle);
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0);
		glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_buffer);
		glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->stencil_buffer);
	}
#else
	fbo->stencil_buffer = 0;
	fbo->z_buffer = 0;
	// 24-bit Z, 8-bit stencil
	glGenRenderbuffers(1, &fbo->z_stencil_buffer);
	glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer);
	glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);

	// Bind it all together
	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle);
	glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0);
	glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer);
	glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer);
#endif

	GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	switch(status) {
	case GL_FRAMEBUFFER_COMPLETE:
		// ILOG("Framebuffer verified complete.");
		break;
	case GL_FRAMEBUFFER_UNSUPPORTED:
		ELOG("GL_FRAMEBUFFER_UNSUPPORTED");
		break;
	case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
		ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT ");
		break;
	default:
		FLOG("Other framebuffer error: %i", status);
		break;
	}
	// Unbind state we don't need
	glBindRenderbuffer(GL_RENDERBUFFER, 0);
	glBindTexture(GL_TEXTURE_2D, 0);
	return fbo;
}

void fbo_unbind() {
	CheckGLExtensions();

	if(gl_extensions.FBO_ARB){
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
	}else{
#ifndef USING_GLES2
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
#endif
	}
#ifdef IOS
	bindDefaultFBO();
#endif
}

void fbo_bind_as_render_target(FBO *fbo) {
	if(gl_extensions.FBO_ARB){
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle);
	}else{
#ifndef USING_GLES2
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle);
#endif
	}
}

void fbo_bind_for_read(FBO *fbo) {
	if(gl_extensions.FBO_ARB){
		glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo->handle);
	}else{
#ifndef USING_GLES2
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle);
#endif
	}
}

void fbo_bind_color_as_texture(FBO *fbo, int color) {
	if (fbo) {
		glBindTexture(GL_TEXTURE_2D, fbo->color_texture);
	}
}

void fbo_destroy(FBO *fbo) {
	if(gl_extensions.FBO_ARB){
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle);
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
		glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
		glDeleteFramebuffers(1, &fbo->handle);
		glDeleteRenderbuffers(1, &fbo->z_stencil_buffer);
	}else{
#ifndef USING_GLES2
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle);
		glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
		glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER_EXT, 0);
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
		glDeleteFramebuffersEXT(1, &fbo->handle);
		glDeleteRenderbuffersEXT(1, &fbo->z_stencil_buffer);
#endif
	}

	glDeleteTextures(1, &fbo->color_texture);
	delete fbo;
}

void fbo_get_dimensions(FBO *fbo, int *w, int *h) {
	*w = fbo->width;
	*h = fbo->height;
}

int fbo_get_color_texture(FBO *fbo) {
	return fbo->color_texture;
}
<|endoftext|>


<commit_before>/*
 * Fluffy - looking for regions of interest when running under ILDJIT.
 * Copyright, Svilen Kanev, 2011
 */

#include "feeder.h"

#include <vector>

//XXX: This is single-threaded for now. Move to TLS for multithreading.

std::vector<ADDRINT> start_counts;
std::vector<ADDRINT> stop_counts;

std::vector<ADDRINT> curr_start_counts;
std::vector<ADDRINT> curr_stop_counts;

std::vector<ADDRINT> slice_weights_times_1000;

/* ========================================================================== */
VOID FLUFFY_Init()
{
    if (KnobFluffy.Value().empty())
        return;

    ifstream annotation_file(KnobFluffy.Value().c_str());

    ADDRINT start, end, id;
    std::string command;
    char ch;
    while (true)
    {
        annotation_file >> id >> command;
        if (annotation_file.eof())
            break;
        if (command == "Start")
        {
            do { annotation_file >> ch; } while (ch != ':');
            annotation_file >> start;
            start_counts.push_back(start);
        }
        else if (command == "End")
        {
            do { annotation_file >> ch; } while (ch != ':');
            annotation_file >> end;
            stop_counts.push_back(end);
        }
        else
            ASSERTX(false);
    }
    ASSERTX(start_counts.size() == stop_counts.size());
    ADDRINT npoints = start_counts.size();

//XXX: Change protocol so we don't need to do that and this is in annotation file
    ifstream weight_file("weights");
    ASSERTX(!weight_file.fail());
    double weight;
    int jnk;
    for(ADDRINT i=0; i<npoints; i++) {
        weight_file >> weight >> jnk;
        slice_weights_times_1000.push_back((ADDRINT)(weight*1000*100));
    }

    for(ADDRINT i=0; i<npoints; i++) {
#ifdef ZESTO_PIN_DBG
        cerr << start_counts [i] << " " << stop_counts[i] << endl;
#endif
        curr_start_counts.push_back(0);
        curr_stop_counts.push_back(0);
    }
}

/* ========================================================================== */
VOID FLUFFY_StartInsn(THREADID tid, ADDRINT pc, ADDRINT phase)
{
    if ((curr_start_counts[phase]++) == start_counts[phase]) {
        PPointHandler(CONTROL_START, NULL, NULL, (VOID*)pc, tid);
    }
}

/* ========================================================================== */
VOID FLUFFY_StopInsn(THREADID tid, ADDRINT pc, ADDRINT phase)
{
    if ((curr_stop_counts[phase]++) == stop_counts[phase]) {
        PPointHandler(CONTROL_STOP, NULL, NULL, (VOID*)pc, tid);

        thread_state_t* tstate = get_tls(tid);
        tstate->slice_num++;
        tstate->slice_length = 0; //XXX: fix icount failing with all ildjit threads
        tstate->slice_weight_times_1000 = slice_weights_times_1000[phase];
    }
}

<commit_msg>Cleaned up fluffy file interface.<commit_after>/*
 * Fluffy - looking for regions of interest when running under ILDJIT.
 * Copyright, Svilen Kanev, 2011
 */

#include "feeder.h"

#include <vector>

//XXX: This is single-threaded for now. Move to TLS for multithreading.

std::vector<ADDRINT> start_counts;
std::vector<ADDRINT> stop_counts;

std::vector<ADDRINT> curr_start_counts;
std::vector<ADDRINT> curr_stop_counts;

std::vector<ADDRINT> slice_weights_times_1000;

/* ========================================================================== */
VOID FLUFFY_Init()
{
    if (KnobFluffy.Value().empty())
        return;

    ifstream annotation_file(KnobFluffy.Value().c_str());

    ADDRINT start, end, id;
    double weight;
    std::string command;
    char ch;
    while (true)
    {
        annotation_file >> id >> command;
        if (annotation_file.eof())
            break;
        if (command == "Start")
        {
            do { annotation_file >> ch; } while (ch != ':');
            annotation_file >> start;
            start_counts.push_back(start);
        }
        else if (command == "End")
        {
            do { annotation_file >> ch; } while (ch != ':');
            annotation_file >> end;
            stop_counts.push_back(end);
        }
        else if (command == "Weight")
        {
            do { annotation_file >> ch; } while (ch != ':');
            annotation_file >> weight;
            slice_weights_times_1000.push_back((ADDRINT)(weight*1000*100));
        }
        else
            ASSERTX(false);
    }
    ASSERTX(start_counts.size() == stop_counts.size());
    ADDRINT npoints = start_counts.size();

    for(ADDRINT i=0; i<npoints; i++) {
#ifdef ZESTO_PIN_DBG
        cerr << start_counts [i] << " " << stop_counts[i] << endl;
#endif
        curr_start_counts.push_back(0);
        curr_stop_counts.push_back(0);
    }
}

/* ========================================================================== */
VOID FLUFFY_StartInsn(THREADID tid, ADDRINT pc, ADDRINT phase)
{
    if ((curr_start_counts[phase]++) == start_counts[phase]) {
        PPointHandler(CONTROL_START, NULL, NULL, (VOID*)pc, tid);
    }
}

/* ========================================================================== */
VOID FLUFFY_StopInsn(THREADID tid, ADDRINT pc, ADDRINT phase)
{
    if ((curr_stop_counts[phase]++) == stop_counts[phase]) {
        PPointHandler(CONTROL_STOP, NULL, NULL, (VOID*)pc, tid);

        thread_state_t* tstate = get_tls(tid);
        tstate->slice_num++;
        tstate->slice_length = 0; //XXX: fix icount failing with all ildjit threads
        tstate->slice_weight_times_1000 = slice_weights_times_1000[phase];
    }
}

<|endoftext|>