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

#include <essentia/algorithmfactory.h>
#include <essentia/essentiamath.h>
#include <essentia/scheduler/network.h>
#include <essentia/streaming/algorithms/poolstorage.h>

#include "credit_libav.h"

using namespace std;
using namespace essentia;
using namespace essentia::standard;

int essentia_main(string audioFilename, string outputFilename) {
  // Returns: 1 on essentia error

  try {
    essentia::init();

    cout.precision(10); // TODO ????

    // instanciate factory and create algorithms:
    AlgorithmFactory& factory = AlgorithmFactory::instance();

    Real sr = 44100.f;
    int framesize = 512;
    int hopsize = 256;

    Pool pool;

    // Algorithm instantiations
    Algorithm* audioStereo = factory.create("AudioLoader",
                                    "filename", audioFilename);

    Algorithm* monoMixer = factory.create("MonoMixer");

    Algorithm* frameCutter = factory.create("FrameCutter",
                                            "frameSize", framesize,
                                            "hopSize", hopsize,
                                            "startFromZero", true);

    Algorithm* discontinuityDetector    = factory.create("DiscontinuityDetector",
                                                         "detectionThreshold", 15,
                                                         "frameSize", framesize,
                                                         "hopSize", hopsize,
                                                         "silenceThreshold", -25);

    Algorithm* gapsDetector             = factory.create("GapsDetector",
                                                         "frameSize", framesize,
                                                         "hopSize", hopsize,
                                                         "silenceThreshold", -70); // in the first itteration of the assessment it was found
                                                                                // that low level noise was sometimes considered noise

    Algorithm* startStopCut             = factory.create("StartStopCut",
                                                         "maximumStartTime", 1, // Found song with only this margin (to double-check)
                                                         "maximumStopTime", 1);

    Algorithm* saturationDetector       = factory.create("SaturationDetector",
                                                         "frameSize", framesize,
                                                         "hopSize", hopsize,
                                                         "differentialThreshold", 0.0001,
                                                         "minimumDuration", 2.0f); // An experiment on rock songs showed that distortion is evident when
                                                                                // the median duration of the saturated regions is around 2ms

    Algorithm* truePeakDetector         = factory.create("TruePeakDetector",
                                                         "threshold", 0.0f);

    // The algorithm should skip beginings.
    Algorithm* clickDetector            = factory.create("ClickDetector",
                                                         "frameSize", framesize,
                                                         "hopSize", hopsize,
                                                         "silenceThreshold", -25, // This is too high. Just a work around to the problem on initial and final non-silent parts
                                                         "detectionThreshold", 38); // Experiments showed that a higher threshold is not eenough to detect audible clicks.

    Algorithm* loudnessEBUR128          = factory.create("LoudnessEBUR128");

    Algorithm* humDetector              = factory.create("HumDetector",
                                                         "sampleRate", sr,
                                                         "minimumDuration", 20.f,  // [seconds] We are only interested in humming tones if they are present over very long segments
                                                         "frameSize", .4,  // For this algorithm, `frameSize` `hopSoze` are expresed in seconds.
                                                         "hopSize", .2);

    Algorithm* snr                      = factory.create("SNR",
                                                         "frameSize", framesize,
                                                         "sampleRate", sr);

    Algorithm* startStopSilence         = factory.create("StartStopSilence");

    Algorithm* windowing                = factory.create("Windowing",
                                                         "size", framesize,
                                                         "zeroPadding", 0,
                                                         "type", "hann",
                                                         "normalized", false);

    Algorithm* noiseBurstDetector       = factory.create("NoiseBurstDetector");

    cout << "-------- connecting algos ---------" << endl;
    Real fs;
    int ch, br;
    std::string md5, cod;

    vector<StereoSample> audioBuffer;
    audioStereo->output("audio").set(audioBuffer);
    audioStereo->output("sampleRate").set(fs);
    audioStereo->output("numberChannels").set(ch);
    audioStereo->output("md5").set(md5);
    audioStereo->output("bit_rate").set(br);
    audioStereo->output("codec").set(cod);

    vector<Real> momentaryLoudness, shortTermLoudness;
    Real integratedLoudness, loudnessRange;
    loudnessEBUR128->input("signal").set(audioBuffer);
    loudnessEBUR128->output("momentaryLoudness").set(momentaryLoudness);
    loudnessEBUR128->output("shortTermLoudness").set(shortTermLoudness);
    loudnessEBUR128->output("integratedLoudness").set(integratedLoudness);
    loudnessEBUR128->output("loudnessRange").set(loudnessRange);

    vector<Real> audio;
    monoMixer->input("audio").set(audioBuffer);
    monoMixer->input("numberChannels").set(2);
    monoMixer->output("audio").set(audio);

    int startStopCutStart, startStopCutEnd;
    startStopCut->input("audio").set(audio);
    startStopCut->output("startCut").set(startStopCutStart);
    startStopCut->output("stopCut").set(startStopCutEnd);

    TNT::Array2D<Real> r;
    vector<Real> humFrequencies, humSaliences, humStarts, humEnds;
    humDetector->input("signal").set(audio);
    humDetector->output("r").set(r);
    humDetector->output("frequencies").set(humFrequencies);
    humDetector->output("saliences").set(humSaliences);
    humDetector->output("starts").set(humStarts);
    humDetector->output("ends").set(humEnds);

    std::vector<Real> peakLocations, truePeakDetectorOutput;
    truePeakDetector->input("signal").set(audio);
    truePeakDetector->output("peakLocations").set(peakLocations);
    truePeakDetector->output("output") .set(truePeakDetectorOutput);

    std::vector<Real> frame;
    frameCutter->input("signal").set(audio);
    frameCutter->output("frame").set(frame);

    // Time domain algorithms do not require Windowing.
    std::vector<Real> discontinuityLocations, discontinuityAmplitudes;
    discontinuityDetector->input("frame").set(frame);
    discontinuityDetector->output("discontinuityLocations").set(discontinuityLocations);
    discontinuityDetector->output("discontinuityAmplitudes").set(discontinuityAmplitudes);

    std::vector<Real> gapsDetectorStarts, gapsDetectorEnds;
    gapsDetector->input("frame").set(frame);
    gapsDetector->output("starts").set(gapsDetectorStarts);
    gapsDetector->output("ends").set(gapsDetectorEnds);

    std::vector<Real> saturationDetectorStarts, saturationDetectorEnds;
    saturationDetector->input("frame").set(frame);
    saturationDetector->output("starts").set(saturationDetectorStarts);
    saturationDetector->output("ends").set(saturationDetectorEnds);

    std::vector<Real> clickDetectorStarts, clickDetectorEnds;
    clickDetector->input("frame").set(frame);
    clickDetector->output("starts").set(clickDetectorStarts);
    clickDetector->output("ends").set(clickDetectorEnds);

    int startFrame, stopFrame;
    startStopSilence->input("frame").set(frame);
    startStopSilence->output("startFrame").set(startFrame);
    startStopSilence->output("stopFrame").set(stopFrame);

    vector<Real> noiseBurstIndexes;
    noiseBurstDetector->input("frame").set(frame);
    noiseBurstDetector->output("indexes").set(noiseBurstIndexes);

    std::vector<Real> windowedFrame;
    windowing->input("frame").set(frame);
    windowing->output("frame").set(windowedFrame);

    Real averagedSNR, instantSNR;
    std::vector<Real> spectralSNR;
    snr->input("frame").set(windowedFrame);
    snr->output("instantSNR").set(instantSNR);
    snr->output("averagedSNR").set(averagedSNR);
    snr->output("spectralSNR").set(spectralSNR);

    cout << "-------- running algos ---------" << endl;
    audioStereo->compute();

    loudnessEBUR128->compute();
    pool.add("EBUR128.integratedLoudness", integratedLoudness);
    pool.add("EBUR128.range", loudnessRange);

    monoMixer->compute();
    pool.add("duration", audio.size() / sr);

    startStopCut->compute();
    pool.add("startStopCut.start", startStopCutStart);
    pool.add("startStopCut.end", startStopCutEnd);

    humDetector->compute();
    if (humFrequencies.size() > 0) {
      pool.add("humDetector.frequencies", humFrequencies);
      pool.add("humDetector.saliences", humSaliences);
      pool.add("humDetector.starts", humStarts);
      pool.add("humDetector.ends", humEnds);
    }

    truePeakDetector->compute();
    for (uint i = 0; i < peakLocations.size(); i++)
      peakLocations[i] /= sr;

    if (peakLocations.size() > 0)
      pool.add("truePeakDetector.locations", peakLocations);

    size_t idx = 0;
    while (true) {

      // compute a frame
      frameCutter->compute();

      // if it was the last one (ie: it was empty), then we're done.
      if (!frame.size()) {
        break;
      }

      // skippint silent frames should be internally done by each algorithm
      // if (isSilent(frame)) continue;

      discontinuityDetector->compute();

      gapsDetector->compute();

      saturationDetector->compute();

      clickDetector->compute();

      noiseBurstDetector->compute();

      windowing->compute();

      snr->compute();

      startStopSilence->compute();

      if (noiseBurstIndexes.size() > 3) {
        pool.add("noiseBursts.locations", idx * hopsize / (Real)fs);
      }

      noiseBurstIndexes.clear();

      idx++;
    }

    pool.add("filename", audioFilename);

    if (discontinuityLocations.size() > 0) {
      for (uint i = 0; i < discontinuityLocations.size(); i++)
        discontinuityLocations[i] /= sr;
      pool.add("discontinuities.locations", discontinuityLocations);
      pool.add("discontinuities.amplitudes", discontinuityAmplitudes);
    }

    if (gapsDetectorStarts.size() > 0) {
      pool.add("gaps.starts", gapsDetectorStarts);
      pool.add("gaps.ends", gapsDetectorEnds);
    }

    if (saturationDetectorStarts.size() > 0) {
      pool.add("saturationDetector.starts", saturationDetectorStarts);
      pool.add("saturationDetector.ends", saturationDetectorEnds);
    }

    if (clickDetectorStarts.size() > 0) {
      pool.add("clickDetector.starts", clickDetectorStarts);
      pool.add("clickDetector.ends", clickDetectorEnds);
    }

    pool.add("snr.spectralSNR", spectralSNR);
    pool.add("snr.averagedSNR", averagedSNR);

    pool.add("startStopSilence.start", startFrame * hopsize / fs);
    pool.add("startStopSilence.end", stopFrame * hopsize / fs);

    cout << "-------- writting Yaml ---------" << endl;
    // Write to yaml file.
    Algorithm* output = standard::AlgorithmFactory::create("YamlOutput",
                                                          "filename", outputFilename);
    output->input("pool").set(pool);
    output->compute();

    delete output;
    delete frameCutter;
    delete discontinuityDetector;
    delete gapsDetector;
    delete startStopCut;
    delete saturationDetector;
    delete truePeakDetector;
    delete clickDetector;
    delete windowing;
    delete humDetector;
    delete snr;
    delete loudnessEBUR128;
    delete startStopSilence;

    essentia::shutdown();
    cout << "-------- Done! ---------" << endl;
  }
  catch (EssentiaException& e) {
    cerr << e.what() << endl;
    return 1;
  }
  return 0;

}

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

  string audioFilename, outputFilename;

  switch (argc) {
    case 3:
      audioFilename =  argv[1];
      outputFilename = argv[2];
      break;
    default:
      return -1;
  }

  return essentia_main(audioFilename, outputFilename);
}
<commit_msg>La-Cupula extractor improvement<commit_after>/*
 * Copyright (C) 2006-2016  Music Technology Group - Universitat Pompeu Fabra
 *
 * This file is part of Essentia
 *
 * Essentia is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation (FSF), either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program 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 General Public License for more
 * details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * version 3 along with this program.  If not, see http://www.gnu.org/licenses/
 */

#include <essentia/algorithmfactory.h>
#include <essentia/essentiamath.h>
#include <essentia/scheduler/network.h>
#include <essentia/streaming/algorithms/poolstorage.h>

#include "credit_libav.h"

using namespace std;
using namespace essentia;
using namespace essentia::standard;

int essentia_main(string audioFilename, string outputFilename) {
  // Returns: 1 on essentia error

  try {
    essentia::init();

    cout.precision(10); // TODO ????

    // instanciate factory and create algorithms:
    AlgorithmFactory& factory = AlgorithmFactory::instance();

    Real sr = 44100.f;
    int framesize = 512;
    int hopsize = 256;

    Pool pool;

    // Algorithm instantiations
    Algorithm* audioStereo = factory.create("AudioLoader",
                                    "filename", audioFilename);

    Algorithm* monoMixer = factory.create("MonoMixer");

    Algorithm* frameCutter = factory.create("FrameCutter",
                                            "frameSize", framesize,
                                            "hopSize", hopsize,
                                            "startFromZero", true);

    Algorithm* discontinuityDetector    = factory.create("DiscontinuityDetector",
                                                         "detectionThreshold", 15,
                                                         "frameSize", framesize,
                                                         "hopSize", hopsize,
                                                         "silenceThreshold", -25);

    Algorithm* gapsDetector             = factory.create("GapsDetector",
                                                         "frameSize", framesize,
                                                         "hopSize", hopsize,
                                                         "silenceThreshold", -70); // in the first itteration of the assessment it was found
                                                                                // that low level noise was sometimes considered noise

    Algorithm* startStopCut             = factory.create("StartStopCut",
                                                         "maximumStartTime", 1, // Found song with only this margin (to double-check)
                                                         "maximumStopTime", 1);

    Algorithm* saturationDetector       = factory.create("SaturationDetector",
                                                         "frameSize", framesize,
                                                         "hopSize", hopsize,
                                                         "differentialThreshold", 0.0001,
                                                         "minimumDuration", 2.0f); // An experiment on rock songs showed that distortion is evident when
                                                                                // the median duration of the saturated regions is around 2ms

    Algorithm* truePeakDetector         = factory.create("TruePeakDetector",
                                                         "threshold", 0.0f);

    // The algorithm should skip beginings.
    Algorithm* clickDetector            = factory.create("ClickDetector",
                                                         "frameSize", framesize,
                                                         "hopSize", hopsize,
                                                         "silenceThreshold", -25, // This is too high. Just a work around to the problem on initial and final non-silent parts
                                                         "detectionThreshold", 38); // Experiments showed that a higher threshold is not eenough to detect audible clicks.

    Algorithm* loudnessEBUR128          = factory.create("LoudnessEBUR128");

    Algorithm* humDetector              = factory.create("HumDetector",
                                                         "sampleRate", sr,
                                                         "minimumDuration", 20.f,  // [seconds] We are only interested in humming tones if they are present over very long segments
                                                         "frameSize", .4,  // For this algorithm, `frameSize` `hopSoze` are expresed in seconds.
                                                         "hopSize", .2);

    Algorithm* snr                      = factory.create("SNR",
                                                         "frameSize", framesize,
                                                         "sampleRate", sr);

    Algorithm* startStopSilence         = factory.create("StartStopSilence");

    Algorithm* windowing                = factory.create("Windowing",
                                                         "size", framesize,
                                                         "zeroPadding", 0,
                                                         "type", "hann",
                                                         "normalized", false);

    Algorithm* noiseBurstDetector       = factory.create("NoiseBurstDetector",
                                                         "threshold", 200);

    Algorithm* falseStereoDetector      = factory.create("FalseStereoDetector");

    cout << "-------- connecting algos ---------" << endl;
    Real fs;
    int ch, br;
    std::string md5, cod;

    vector<StereoSample> audioBuffer;
    audioStereo->output("audio").set(audioBuffer);
    audioStereo->output("sampleRate").set(fs);
    audioStereo->output("numberChannels").set(ch);
    audioStereo->output("md5").set(md5);
    audioStereo->output("bit_rate").set(br);
    audioStereo->output("codec").set(cod);

    vector<Real> momentaryLoudness, shortTermLoudness;
    Real integratedLoudness, loudnessRange;
    loudnessEBUR128->input("signal").set(audioBuffer);
    loudnessEBUR128->output("momentaryLoudness").set(momentaryLoudness);
    loudnessEBUR128->output("shortTermLoudness").set(shortTermLoudness);
    loudnessEBUR128->output("integratedLoudness").set(integratedLoudness);
    loudnessEBUR128->output("loudnessRange").set(loudnessRange);

    Real correlation;
    int isFalseStereo;
    falseStereoDetector->input("frame").set(audioBuffer);
    falseStereoDetector->output("isFalseStereo").set(isFalseStereo);
    falseStereoDetector->output("correlation").set(correlation);

    vector<Real> audio;
    monoMixer->input("audio").set(audioBuffer);
    monoMixer->input("numberChannels").set(2);
    monoMixer->output("audio").set(audio);

    int startStopCutStart, startStopCutEnd;
    startStopCut->input("audio").set(audio);
    startStopCut->output("startCut").set(startStopCutStart);
    startStopCut->output("stopCut").set(startStopCutEnd);

    TNT::Array2D<Real> r;
    vector<Real> humFrequencies, humSaliences, humStarts, humEnds;
    humDetector->input("signal").set(audio);
    humDetector->output("r").set(r);
    humDetector->output("frequencies").set(humFrequencies);
    humDetector->output("saliences").set(humSaliences);
    humDetector->output("starts").set(humStarts);
    humDetector->output("ends").set(humEnds);

    std::vector<Real> peakLocations, truePeakDetectorOutput;
    truePeakDetector->input("signal").set(audio);
    truePeakDetector->output("peakLocations").set(peakLocations);
    truePeakDetector->output("output") .set(truePeakDetectorOutput);

    std::vector<Real> frame;
    frameCutter->input("signal").set(audio);
    frameCutter->output("frame").set(frame);

    // Time domain algorithms do not require Windowing.
    std::vector<Real> discontinuityLocations, discontinuityAmplitudes;
    discontinuityDetector->input("frame").set(frame);
    discontinuityDetector->output("discontinuityLocations").set(discontinuityLocations);
    discontinuityDetector->output("discontinuityAmplitudes").set(discontinuityAmplitudes);

    std::vector<Real> gapsDetectorStarts, gapsDetectorEnds;
    gapsDetector->input("frame").set(frame);
    gapsDetector->output("starts").set(gapsDetectorStarts);
    gapsDetector->output("ends").set(gapsDetectorEnds);

    std::vector<Real> saturationDetectorStarts, saturationDetectorEnds;
    saturationDetector->input("frame").set(frame);
    saturationDetector->output("starts").set(saturationDetectorStarts);
    saturationDetector->output("ends").set(saturationDetectorEnds);

    std::vector<Real> clickDetectorStarts, clickDetectorEnds;
    clickDetector->input("frame").set(frame);
    clickDetector->output("starts").set(clickDetectorStarts);
    clickDetector->output("ends").set(clickDetectorEnds);

    int startFrame, stopFrame;
    startStopSilence->input("frame").set(frame);
    startStopSilence->output("startFrame").set(startFrame);
    startStopSilence->output("stopFrame").set(stopFrame);

    vector<Real> noiseBurstIndexes;
    noiseBurstDetector->input("frame").set(frame);
    noiseBurstDetector->output("indexes").set(noiseBurstIndexes);

    std::vector<Real> windowedFrame;
    windowing->input("frame").set(frame);
    windowing->output("frame").set(windowedFrame);

    Real averagedSNR, instantSNR;
    std::vector<Real> spectralSNR;
    snr->input("frame").set(windowedFrame);
    snr->output("instantSNR").set(instantSNR);
    snr->output("averagedSNR").set(averagedSNR);
    snr->output("spectralSNR").set(spectralSNR);

    cout << "-------- running algos ---------" << endl;
    audioStereo->compute();

    pool.set("filename", audioFilename);

    pool.set("duration", audio.size() / sr);

    pool.set("filename", audioFilename);

    loudnessEBUR128->compute();
    pool.set("EBUR128.integratedLoudness", integratedLoudness);
    pool.set("EBUR128.range", loudnessRange);

    falseStereoDetector->compute();
    pool.set("channelsCorrelation", correlation);

    monoMixer->compute();

    startStopCut->compute();
    pool.set("startStopCut.start", startStopCutStart);
    pool.set("startStopCut.end", startStopCutEnd);

    humDetector->compute();
    if (humFrequencies.size() > 0) {
      pool.set("humDetector.present", true);
      pool.set("humDetector.frequencies", humFrequencies);
      pool.set("humDetector.saliences", humSaliences);
      pool.set("humDetector.starts", humStarts);
      pool.set("humDetector.ends", humEnds);
    } else {
      pool.set("humDetector.present", false);
    }

    truePeakDetector->compute();
    for (uint i = 0; i < peakLocations.size(); i++)
      peakLocations[i] /= sr;

    if (peakLocations.size() > 0) {
      pool.set("truePeakDetector.present", true);
      pool.set("truePeakDetector.locations", peakLocations);
    } else {
      pool.set("truePeakDetector.present", false);
    }

    vector<Real> noiseBursts;

    size_t idx = 0;
    while (true) {

      // compute a frame
      frameCutter->compute();

      // if it was the last one (ie: it was empty), then we're done.
      if (!frame.size()) {
        break;
      }

      // skippint silent frames should be internally done by each algorithm
      // if (isSilent(frame)) continue;

      discontinuityDetector->compute();

      gapsDetector->compute();

      saturationDetector->compute();

      clickDetector->compute();

      noiseBurstDetector->compute();

      windowing->compute();

      snr->compute();

      startStopSilence->compute();

      if (noiseBurstIndexes.size() > 3) {
        noiseBursts.push_back(idx * hopsize / (Real)fs);
      }

      noiseBurstIndexes.clear();

      idx++;
    }

    if (noiseBursts.size() > 0) {
      pool.set("noiseBursts.present", true);
      pool.set("noiseBursts.locations", noiseBursts);
    } else {
    pool.set("noiseBursts.present", false);
    }

    if (discontinuityLocations.size() > 0) {
      pool.set("discontinuities.present", true);
      for (uint i = 0; i < discontinuityLocations.size(); i++)
        discontinuityLocations[i] /= sr;
      pool.set("discontinuities.locations", discontinuityLocations);
      pool.set("discontinuities.amplitudes", discontinuityAmplitudes);
    } else {
      pool.set("discontinuities.present", false);
    }

    if (gapsDetectorStarts.size() > 0) {
      pool.set("gaps.present", true);
      pool.set("gaps.starts", gapsDetectorStarts);
      pool.set("gaps.ends", gapsDetectorEnds);
    } else {
      pool.set("gaps.present", false);
    }

    if (saturationDetectorStarts.size() > 0) {
      pool.set("saturationDetector.present", true);
      pool.set("saturationDetector.starts", saturationDetectorStarts);
      pool.set("saturationDetector.ends", saturationDetectorEnds);
    } else {
      pool.set("saturationDetector.present", false);
    }

    if (clickDetectorStarts.size() > 0) {
      pool.set("clickDetector.present", true);
      pool.set("clickDetector.starts", clickDetectorStarts);
      pool.set("clickDetector.ends", clickDetectorEnds);
    } else {
      pool.set("clickDetector.present", false);
    }

    // Spectral SNR is not very relevant.
    // pool.set("snr.spectralSNR", spectralSNR);
    pool.set("snr.averagedSNR", averagedSNR);

    pool.set("startStopSilence.start", startFrame * hopsize / fs);
    pool.set("startStopSilence.end", stopFrame * hopsize / fs);

    cout << "-------- writting Yaml ---------" << endl;
    // Write to yaml file.
    Algorithm* output = standard::AlgorithmFactory::create("YamlOutput",
                                                          "filename", outputFilename);
    output->input("pool").set(pool);
    output->compute();

    delete output;
    delete frameCutter;
    delete discontinuityDetector;
    delete gapsDetector;
    delete startStopCut;
    delete saturationDetector;
    delete truePeakDetector;
    delete clickDetector;
    delete windowing;
    delete humDetector;
    delete snr;
    delete loudnessEBUR128;
    delete startStopSilence;

    essentia::shutdown();
    cout << "-------- Done! ---------" << endl;
  }
  catch (EssentiaException& e) {
    cerr << e.what() << endl;
    return 1;
  }
  return 0;

}

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

  string audioFilename, outputFilename;

  switch (argc) {
    case 3:
      audioFilename =  argv[1];
      outputFilename = argv[2];
      break;
    default:
      return -1;
  }

  return essentia_main(audioFilename, outputFilename);
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -I%p | FileCheck %s

// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here

// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::StoredValueRef V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::StoredValueRef) boxes [(const char *) "Root"]
typedef enum {k1,k2} enumName;
enumName var
// CHECK: (enumName) (::k1) : (int) 0
// End PR #98146
<commit_msg>Correct comment.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -I%p | FileCheck %s

// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here

// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::StoredValueRef V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::StoredValueRef) boxes [(const char *) "Root"]
// End PR #98146
typedef enum {k1,k2} enumName;
enumName var
// CHECK: (enumName) (::k1) : (int) 0
<|endoftext|>


<commit_before>// Copyright 2010 the V8 project authors. All rights reserved.
// 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.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// 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 COPYRIGHT
// OWNER 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.

#include "i18n-extension.h"

#include <algorithm>
#include <string>

#include "unicode/locid.h"
#include "unicode/uloc.h"

namespace v8 {
namespace internal {

I18NExtension* I18NExtension::extension_ = NULL;

// TODO(cira): maybe move JS code to a .js file and generata cc files from it?
const char* const I18NExtension::kSource =
  "Locale = function(optLocale) {"
  "  native function NativeJSLocale();"
  "  var properties = NativeJSLocale(optLocale);"
  "  this.locale = properties.locale;"
  "  this.language = properties.language;"
  "  this.script = properties.script;"
  "  this.region = properties.region;"
  "};"
  "Locale.availableLocales = function() {"
  "  native function NativeJSAvailableLocales();"
  "  return NativeJSAvailableLocales();"
  "};"
  "Locale.prototype.maximizedLocale = function() {"
  "  native function NativeJSMaximizedLocale();"
  "  return new Locale(NativeJSMaximizedLocale(this.locale));"
  "};"
  "Locale.prototype.minimizedLocale = function() {"
  "  native function NativeJSMinimizedLocale();"
  "  return new Locale(NativeJSMinimizedLocale(this.locale));"
  "};"
  "Locale.prototype.displayLocale_ = function(displayLocale) {"
  "  var result = this.locale;"
  "  if (displayLocale !== undefined) {"
  "    result = displayLocale.locale;"
  "  }"
  "  return result;"
  "};"
  "Locale.prototype.displayLanguage = function(optDisplayLocale) {"
  "  var displayLocale = this.displayLocale_(optDisplayLocale);"
  "  native function NativeJSDisplayLanguage();"
  "  return NativeJSDisplayLanguage(this.locale, displayLocale);"
  "};"
  "Locale.prototype.displayScript = function(optDisplayLocale) {"
  "  var displayLocale = this.displayLocale_(optDisplayLocale);"
  "  native function NativeJSDisplayScript();"
  "  return NativeJSDisplayScript(this.locale, displayLocale);"
  "};"
  "Locale.prototype.displayRegion = function(optDisplayLocale) {"
  "  var displayLocale = this.displayLocale_(optDisplayLocale);"
  "  native function NativeJSDisplayRegion();"
  "  return NativeJSDisplayRegion(this.locale, displayLocale);"
  "};"
  "Locale.prototype.displayName = function(optDisplayLocale) {"
  "  var displayLocale = this.displayLocale_(optDisplayLocale);"
  "  native function NativeJSDisplayName();"
  "  return NativeJSDisplayName(this.locale, displayLocale);"
  "};";

v8::Handle<v8::FunctionTemplate> I18NExtension::GetNativeFunction(
    v8::Handle<v8::String> name) {
  if (name->Equals(v8::String::New("NativeJSLocale"))) {
    return v8::FunctionTemplate::New(JSLocale);
  } else if (name->Equals(v8::String::New("NativeJSAvailableLocales"))) {
    return v8::FunctionTemplate::New(JSAvailableLocales);
  } else if (name->Equals(v8::String::New("NativeJSMaximizedLocale"))) {
    return v8::FunctionTemplate::New(JSMaximizedLocale);
  } else if (name->Equals(v8::String::New("NativeJSMinimizedLocale"))) {
    return v8::FunctionTemplate::New(JSMinimizedLocale);
  } else if (name->Equals(v8::String::New("NativeJSDisplayLanguage"))) {
    return v8::FunctionTemplate::New(JSDisplayLanguage);
  } else if (name->Equals(v8::String::New("NativeJSDisplayScript"))) {
    return v8::FunctionTemplate::New(JSDisplayScript);
  } else if (name->Equals(v8::String::New("NativeJSDisplayRegion"))) {
    return v8::FunctionTemplate::New(JSDisplayRegion);
  } else if (name->Equals(v8::String::New("NativeJSDisplayName"))) {
    return v8::FunctionTemplate::New(JSDisplayName);
  }

  return v8::Handle<v8::FunctionTemplate>();
}

v8::Handle<v8::Value> I18NExtension::JSLocale(const v8::Arguments& args) {
  // TODO(cira): Fetch browser locale. Accept en-US as good default for now.
  // We could possibly pass browser locale as a parameter in the constructor.
  std::string locale_name("en-US");
  if (args.Length() == 1 && args[0]->IsString()) {
    locale_name = *v8::String::Utf8Value(args[0]->ToString());
  }

  v8::Local<v8::Object> locale = v8::Object::New();
  locale->Set(v8::String::New("locale"), v8::String::New(locale_name.c_str()));

  icu::Locale icu_locale(locale_name.c_str());

  const char* language = icu_locale.getLanguage();
  locale->Set(v8::String::New("language"), v8::String::New(language));

  const char* script = icu_locale.getScript();
  if (strlen(script)) {
    locale->Set(v8::String::New("script"), v8::String::New(script));
  }

  const char* region = icu_locale.getCountry();
  if (strlen(region)) {
    locale->Set(v8::String::New("region"), v8::String::New(region));
  }

  return locale;
}

// TODO(cira): Filter out locales that Chrome doesn't support.
v8::Handle<v8::Value> I18NExtension::JSAvailableLocales(
    const v8::Arguments& args) {
  v8::Local<v8::Array> all_locales = v8::Array::New();

  int count = 0;
  const Locale* icu_locales = icu::Locale::getAvailableLocales(count);
  for (int i = 0; i < count; ++i) {
    all_locales->Set(i, v8::String::New(icu_locales[i].getName()));
  }

  return all_locales;
}

// Use - as tag separator, not _ that ICU uses.
static std::string NormalizeLocale(const std::string& locale) {
  std::string result(locale);
  // TODO(cira): remove STL dependency.
  std::replace(result.begin(), result.end(), '_', '-');
  return result;
}

v8::Handle<v8::Value> I18NExtension::JSMaximizedLocale(
    const v8::Arguments& args) {
  if (!args.Length() || !args[0]->IsString()) {
    return v8::Undefined();
  }

  UErrorCode status = U_ZERO_ERROR;
  std::string locale_name = *v8::String::Utf8Value(args[0]->ToString());
  char max_locale[ULOC_FULLNAME_CAPACITY];
  uloc_addLikelySubtags(locale_name.c_str(), max_locale,
                        sizeof(max_locale), &status);
  if (U_FAILURE(status)) {
    return v8::Undefined();
  }

  return v8::String::New(NormalizeLocale(max_locale).c_str());
}

v8::Handle<v8::Value> I18NExtension::JSMinimizedLocale(
    const v8::Arguments& args) {
  if (!args.Length() || !args[0]->IsString()) {
    return v8::Undefined();
  }

  UErrorCode status = U_ZERO_ERROR;
  std::string locale_name = *v8::String::Utf8Value(args[0]->ToString());
  char min_locale[ULOC_FULLNAME_CAPACITY];
  uloc_minimizeSubtags(locale_name.c_str(), min_locale,
                       sizeof(min_locale), &status);
  if (U_FAILURE(status)) {
    return v8::Undefined();
  }

  return v8::String::New(NormalizeLocale(min_locale).c_str());
}

// Common code for JSDisplayXXX methods.
static v8::Handle<v8::Value> GetDisplayItem(const v8::Arguments& args,
                                            const std::string& item) {
  if (args.Length() != 2 || !args[0]->IsString() || !args[1]->IsString()) {
    return v8::Undefined();
  }

  std::string base_locale = *v8::String::Utf8Value(args[0]->ToString());
  icu::Locale icu_locale(base_locale.c_str());
  icu::Locale display_locale =
      icu::Locale(*v8::String::Utf8Value(args[1]->ToString()));
  UnicodeString result;
  if (item == "language") {
    icu_locale.getDisplayLanguage(display_locale, result);
  } else if (item == "script") {
    icu_locale.getDisplayScript(display_locale, result);
  } else if (item == "region") {
    icu_locale.getDisplayCountry(display_locale, result);
  } else if (item == "name") {
    icu_locale.getDisplayName(display_locale, result);
  } else {
    return v8::Undefined();
  }

  if (result.length()) {
    return v8::String::New(
        reinterpret_cast<const uint16_t*>(result.getBuffer()), result.length());
  }

  return v8::Undefined();
}

v8::Handle<v8::Value> I18NExtension::JSDisplayLanguage(
    const v8::Arguments& args) {
  return GetDisplayItem(args, "language");
}

v8::Handle<v8::Value> I18NExtension::JSDisplayScript(
    const v8::Arguments& args) {
  return GetDisplayItem(args, "script");
}

v8::Handle<v8::Value> I18NExtension::JSDisplayRegion(
    const v8::Arguments& args) {
  return GetDisplayItem(args, "region");
}

v8::Handle<v8::Value> I18NExtension::JSDisplayName(const v8::Arguments& args) {
  return GetDisplayItem(args, "name");
}

I18NExtension* I18NExtension::get() {
  if (!extension_) {
    extension_ = new I18NExtension();
  }
  return extension_;
}

void I18NExtension::Register() {
  static v8::DeclareExtension i18n_extension_declaration(I18NExtension::get());
}

} }  // namespace v8::internal
<commit_msg>Adding vendor prefix to Locale class (becoming v8Locale) to minimize risk of future changes.<commit_after>// Copyright 2010 the V8 project authors. All rights reserved.
// 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.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// 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 COPYRIGHT
// OWNER 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.

#include "i18n-extension.h"

#include <algorithm>
#include <string>

#include "unicode/locid.h"
#include "unicode/uloc.h"

namespace v8 {
namespace internal {

I18NExtension* I18NExtension::extension_ = NULL;

// TODO(cira): maybe move JS code to a .js file and generata cc files from it?
// TODO(cira): Remove v8 prefix from v8Locale once we have stable API.
const char* const I18NExtension::kSource =
  "v8Locale = function(optLocale) {"
  "  native function NativeJSLocale();"
  "  var properties = NativeJSLocale(optLocale);"
  "  this.locale = properties.locale;"
  "  this.language = properties.language;"
  "  this.script = properties.script;"
  "  this.region = properties.region;"
  "};"
  "v8Locale.availableLocales = function() {"
  "  native function NativeJSAvailableLocales();"
  "  return NativeJSAvailableLocales();"
  "};"
  "v8Locale.prototype.maximizedLocale = function() {"
  "  native function NativeJSMaximizedLocale();"
  "  return new v8Locale(NativeJSMaximizedLocale(this.locale));"
  "};"
  "v8Locale.prototype.minimizedLocale = function() {"
  "  native function NativeJSMinimizedLocale();"
  "  return new v8Locale(NativeJSMinimizedLocale(this.locale));"
  "};"
  "v8Locale.prototype.displayLocale_ = function(displayLocale) {"
  "  var result = this.locale;"
  "  if (displayLocale !== undefined) {"
  "    result = displayLocale.locale;"
  "  }"
  "  return result;"
  "};"
  "v8Locale.prototype.displayLanguage = function(optDisplayLocale) {"
  "  var displayLocale = this.displayLocale_(optDisplayLocale);"
  "  native function NativeJSDisplayLanguage();"
  "  return NativeJSDisplayLanguage(this.locale, displayLocale);"
  "};"
  "v8Locale.prototype.displayScript = function(optDisplayLocale) {"
  "  var displayLocale = this.displayLocale_(optDisplayLocale);"
  "  native function NativeJSDisplayScript();"
  "  return NativeJSDisplayScript(this.locale, displayLocale);"
  "};"
  "v8Locale.prototype.displayRegion = function(optDisplayLocale) {"
  "  var displayLocale = this.displayLocale_(optDisplayLocale);"
  "  native function NativeJSDisplayRegion();"
  "  return NativeJSDisplayRegion(this.locale, displayLocale);"
  "};"
  "v8Locale.prototype.displayName = function(optDisplayLocale) {"
  "  var displayLocale = this.displayLocale_(optDisplayLocale);"
  "  native function NativeJSDisplayName();"
  "  return NativeJSDisplayName(this.locale, displayLocale);"
  "};";

v8::Handle<v8::FunctionTemplate> I18NExtension::GetNativeFunction(
    v8::Handle<v8::String> name) {
  if (name->Equals(v8::String::New("NativeJSLocale"))) {
    return v8::FunctionTemplate::New(JSLocale);
  } else if (name->Equals(v8::String::New("NativeJSAvailableLocales"))) {
    return v8::FunctionTemplate::New(JSAvailableLocales);
  } else if (name->Equals(v8::String::New("NativeJSMaximizedLocale"))) {
    return v8::FunctionTemplate::New(JSMaximizedLocale);
  } else if (name->Equals(v8::String::New("NativeJSMinimizedLocale"))) {
    return v8::FunctionTemplate::New(JSMinimizedLocale);
  } else if (name->Equals(v8::String::New("NativeJSDisplayLanguage"))) {
    return v8::FunctionTemplate::New(JSDisplayLanguage);
  } else if (name->Equals(v8::String::New("NativeJSDisplayScript"))) {
    return v8::FunctionTemplate::New(JSDisplayScript);
  } else if (name->Equals(v8::String::New("NativeJSDisplayRegion"))) {
    return v8::FunctionTemplate::New(JSDisplayRegion);
  } else if (name->Equals(v8::String::New("NativeJSDisplayName"))) {
    return v8::FunctionTemplate::New(JSDisplayName);
  }

  return v8::Handle<v8::FunctionTemplate>();
}

v8::Handle<v8::Value> I18NExtension::JSLocale(const v8::Arguments& args) {
  // TODO(cira): Fetch browser locale. Accept en-US as good default for now.
  // We could possibly pass browser locale as a parameter in the constructor.
  std::string locale_name("en-US");
  if (args.Length() == 1 && args[0]->IsString()) {
    locale_name = *v8::String::Utf8Value(args[0]->ToString());
  }

  v8::Local<v8::Object> locale = v8::Object::New();
  locale->Set(v8::String::New("locale"), v8::String::New(locale_name.c_str()));

  icu::Locale icu_locale(locale_name.c_str());

  const char* language = icu_locale.getLanguage();
  locale->Set(v8::String::New("language"), v8::String::New(language));

  const char* script = icu_locale.getScript();
  if (strlen(script)) {
    locale->Set(v8::String::New("script"), v8::String::New(script));
  }

  const char* region = icu_locale.getCountry();
  if (strlen(region)) {
    locale->Set(v8::String::New("region"), v8::String::New(region));
  }

  return locale;
}

// TODO(cira): Filter out locales that Chrome doesn't support.
v8::Handle<v8::Value> I18NExtension::JSAvailableLocales(
    const v8::Arguments& args) {
  v8::Local<v8::Array> all_locales = v8::Array::New();

  int count = 0;
  const Locale* icu_locales = icu::Locale::getAvailableLocales(count);
  for (int i = 0; i < count; ++i) {
    all_locales->Set(i, v8::String::New(icu_locales[i].getName()));
  }

  return all_locales;
}

// Use - as tag separator, not _ that ICU uses.
static std::string NormalizeLocale(const std::string& locale) {
  std::string result(locale);
  // TODO(cira): remove STL dependency.
  std::replace(result.begin(), result.end(), '_', '-');
  return result;
}

v8::Handle<v8::Value> I18NExtension::JSMaximizedLocale(
    const v8::Arguments& args) {
  if (!args.Length() || !args[0]->IsString()) {
    return v8::Undefined();
  }

  UErrorCode status = U_ZERO_ERROR;
  std::string locale_name = *v8::String::Utf8Value(args[0]->ToString());
  char max_locale[ULOC_FULLNAME_CAPACITY];
  uloc_addLikelySubtags(locale_name.c_str(), max_locale,
                        sizeof(max_locale), &status);
  if (U_FAILURE(status)) {
    return v8::Undefined();
  }

  return v8::String::New(NormalizeLocale(max_locale).c_str());
}

v8::Handle<v8::Value> I18NExtension::JSMinimizedLocale(
    const v8::Arguments& args) {
  if (!args.Length() || !args[0]->IsString()) {
    return v8::Undefined();
  }

  UErrorCode status = U_ZERO_ERROR;
  std::string locale_name = *v8::String::Utf8Value(args[0]->ToString());
  char min_locale[ULOC_FULLNAME_CAPACITY];
  uloc_minimizeSubtags(locale_name.c_str(), min_locale,
                       sizeof(min_locale), &status);
  if (U_FAILURE(status)) {
    return v8::Undefined();
  }

  return v8::String::New(NormalizeLocale(min_locale).c_str());
}

// Common code for JSDisplayXXX methods.
static v8::Handle<v8::Value> GetDisplayItem(const v8::Arguments& args,
                                            const std::string& item) {
  if (args.Length() != 2 || !args[0]->IsString() || !args[1]->IsString()) {
    return v8::Undefined();
  }

  std::string base_locale = *v8::String::Utf8Value(args[0]->ToString());
  icu::Locale icu_locale(base_locale.c_str());
  icu::Locale display_locale =
      icu::Locale(*v8::String::Utf8Value(args[1]->ToString()));
  UnicodeString result;
  if (item == "language") {
    icu_locale.getDisplayLanguage(display_locale, result);
  } else if (item == "script") {
    icu_locale.getDisplayScript(display_locale, result);
  } else if (item == "region") {
    icu_locale.getDisplayCountry(display_locale, result);
  } else if (item == "name") {
    icu_locale.getDisplayName(display_locale, result);
  } else {
    return v8::Undefined();
  }

  if (result.length()) {
    return v8::String::New(
        reinterpret_cast<const uint16_t*>(result.getBuffer()), result.length());
  }

  return v8::Undefined();
}

v8::Handle<v8::Value> I18NExtension::JSDisplayLanguage(
    const v8::Arguments& args) {
  return GetDisplayItem(args, "language");
}

v8::Handle<v8::Value> I18NExtension::JSDisplayScript(
    const v8::Arguments& args) {
  return GetDisplayItem(args, "script");
}

v8::Handle<v8::Value> I18NExtension::JSDisplayRegion(
    const v8::Arguments& args) {
  return GetDisplayItem(args, "region");
}

v8::Handle<v8::Value> I18NExtension::JSDisplayName(const v8::Arguments& args) {
  return GetDisplayItem(args, "name");
}

I18NExtension* I18NExtension::get() {
  if (!extension_) {
    extension_ = new I18NExtension();
  }
  return extension_;
}

void I18NExtension::Register() {
  static v8::DeclareExtension i18n_extension_declaration(I18NExtension::get());
}

} }  // namespace v8::internal
<|endoftext|>


<commit_before>// Copyright (c) 2013 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 <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <atomic>
#include <thread>
#include <sstream>

#include "ppapi/c/ppb_image_data.h"
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/input_event.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/point.h"
#include "ppapi/utility/completion_callback_factory.h"

#include "core/synced_image.h"
#include "core/scene.h"
#include "core/camera.h"

#ifdef WIN32
#undef PostMessage
// Allow 'this' in initializer list
#pragma warning(disable : 4355)
#endif

namespace {

const std::string kSceneDescription = R"(
  {
    "lights" : {
      "sunLight" : {
        "type" : "area",
        "color" : "10 10 10"
      },
      "skyLight" : {
        "type" : "area",
        "color" : "0.3 0.4 0.5"
      }
    },
    "materials" : {
      "ground" : {
        "type" : "lambert",
        "albedo" : "0.4 0.3 0.2"
      },
      "sky" : {
        "type" : "lambert",
        "albedo" : "0.4 0.5 0.6"
      },
      "dielectric" : {
        "type" : "dielectric",
        "ior" : 1.5,
        "color" : "1 1 1"
      }
    },
    "geometry" : {
      "worldSphere" : {
        "type" : "sphere",
        "mat" : "sky",
        "light" : "skyLight",
        "origin" : "0 0 0",
        "radius" : 2000.0,
        "inverted" : true
      },
      "bottom" : {
        "type" : "disc",
        "mat" : "ground",
        "light" : "",
        "origin" : "0 -20 -0",
        "normal" : "0 1 0",
        "radiusOuter" : 2001.0,
        "radiusInner" : 0.0
      },
      "lightSource" : {
        "type" : "sphere",
        "mat" : "",
        "light" : "sunLight",
        "origin" : "0 2500 0",
        "radius" : 1000.0,
        "inverted" : false
      },
      "sphere1" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "16 -12 -22",
        "radius" : 8.0,
        "inverted" : false
      },
      "sphere2" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "2 -12 -40",
        "radius" : 8.0,
        "inverted" : false
      },
      "sphere3" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "-12 -12 -58",
        "radius" : 8.0,
        "inverted" : false
      },
      "sphere4" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "-26 -12 -76",
        "radius" : 8.0,
        "inverted" : false
      },
      "sphere5" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "-40 -12 -94",
        "radius" : 8.0,
        "inverted" : false
      },
      "sphere6" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "-54 -12 -112",
        "radius" : 8.0,
        "inverted" : false
      },
      "sphere7" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "-68 -12 -130",
        "radius" : 8.0,
        "inverted" : false
      },
      "sphere8" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "-82 -12 -148",
        "radius" : 8.0,
        "inverted" : false
      },
      "sphere9" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "-96 -12 -166",
        "radius" : 8.0,
        "inverted" : false
      },
      "sphere10" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "-110 -12 -184",
        "radius" : 8.0,
        "inverted" : false
      }
    },
    "cameras" : {
      "default" : {
        "type" : "persp",
        "translate" : "-2 8 30",
        "rotateAngle" :  -0.26180,
        "rotateAxis" : "1 0 0",
        "objects" : [
          "worldSphere", "bottom", "lightSource", "sphere1", "sphere2",
          "sphere3", "sphere4", "sphere5", "sphere6", "sphere7", "sphere8",
          "sphere9", "sphere10"
        ],
        "width" : 512,
        "height" : 384,
        "fov" : 0.78540,
        "focalLength" : 88.0,
        "fStop" : 16.0
      }
    }
  }
)";

}  // namespace

class Graphics2DInstance : public pp::Instance {
 public:
  explicit Graphics2DInstance(PP_Instance instance)
      : pp::Instance(instance),
        callback_factory_(this),
        scene_(NULL),
        image_(NULL),
        device_scale_(1.0f) {}

  ~Graphics2DInstance() {
    delete scene_;
    delete image_;
  }

  virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) {
    std::stringstream ss;
    ss << kSceneDescription;

    scene_ = new Scene(ss);
    image_ = new SyncedImage(
      this,
      pp::Size(scene_->defaultCamera()->GetSize()),
      pp::Size(1, 1)
    );

    pthread_t t;
    pthread_create(
      &t,
      NULL,
      &Graphics2DInstance::InitBackgroundThread,
      this
    );

    return true;
  }

  static void* InitBackgroundThread(void* data) {
    Graphics2DInstance* g2d = reinterpret_cast<Graphics2DInstance*>(data);
    g2d->GetScene()->defaultCamera()->renderMultiple(g2d->GetImage(), -1);
    return NULL;
  }

  virtual void DidChangeView(const pp::View& view) {
    device_scale_ = view.GetDeviceScale();
    pp::Size new_size = pp::Size(view.GetRect().width() * device_scale_,
                                 view.GetRect().height() * device_scale_);

    if (!CreateContext(new_size))
      return;

    // When flush_context_ is null, it means there is no Flush callback in
    // flight. This may have happened if the context was not created
    // successfully, or if this is the first call to DidChangeView (when the
    // module first starts). In either case, start the main loop.
    if (flush_context_.is_null())
      MainLoop(0);
  }

 private:
  bool CreateContext(const pp::Size& new_size) {
    const bool kIsAlwaysOpaque = true;
    context_ = pp::Graphics2D(this, new_size, kIsAlwaysOpaque);
    // Call SetScale before BindGraphics so the image is scaled correctly on
    // HiDPI displays.
    context_.SetScale(1.0f / device_scale_);
    if (!BindGraphics(context_)) {
      fprintf(stderr, "Unable to bind 2d context!\n");
      context_ = pp::Graphics2D();
      return false;
    }

    // Update screen image buffer.
    if (image_) {
      image_->SetScreenSize(new_size);
    }

    return true;
  }

  void MainLoop(int32_t) {
    if (context_.is_null()) {
      // The current Graphics2D context is null, so updating and rendering is
      // pointless. Set flush_context_ to null as well, so if we get another
      // DidChangeView call, the main loop is started again.
      flush_context_ = context_;
      return;
    }

    if (image_) {
      int counter;
      context_.ReplaceContents(image_->GetScreenData(&counter));
      PostMessage(pp::Var(counter));
    } else {
      std::cerr << "no update" << std::endl;
    }

    // Store a reference to the context that is being flushed; this ensures
    // the callback is called, even if context_ changes before the flush
    // completes.
    flush_context_ = context_;
    context_.Flush(
        callback_factory_.NewCallback(&Graphics2DInstance::MainLoop));
  }

  SyncedImage* GetImage() {
    return image_;
  }

  const Scene* GetScene() {
    return scene_;
  }

  pp::CompletionCallbackFactory<Graphics2DInstance> callback_factory_;
  pp::Graphics2D context_;
  pp::Graphics2D flush_context_;
  pp::Size size_;
  Scene* scene_;
  SyncedImage* image_;
  float device_scale_;
};

class Graphics2DModule : public pp::Module {
 public:
  Graphics2DModule() : pp::Module() {}
  virtual ~Graphics2DModule() {}

  virtual pp::Instance* CreateInstance(PP_Instance instance) {
    return new Graphics2DInstance(instance);
  }
};

namespace pp {
Module* CreateModule() { return new Graphics2DModule(); }
}  // namespace pp
<commit_msg>cool marble colors<commit_after>// Copyright (c) 2013 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 <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <atomic>
#include <thread>
#include <sstream>

#include "ppapi/c/ppb_image_data.h"
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/input_event.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/point.h"
#include "ppapi/utility/completion_callback_factory.h"

#include "core/synced_image.h"
#include "core/scene.h"
#include "core/camera.h"

#ifdef WIN32
#undef PostMessage
// Allow 'this' in initializer list
#pragma warning(disable : 4355)
#endif

namespace {

const std::string kSceneDescription = R"(
  {
    "lights" : {
      "sunLight" : {
        "type" : "area",
        "color" : "10 10 10"
      },
      "skyLight" : {
        "type" : "area",
        "color" : "0.3 0.4 0.5"
      }
    },
    "materials" : {
      "ground" : {
        "type" : "lambert",
        "albedo" : "0.4 0.3 0.2"
      },
      "sky" : {
        "type" : "lambert",
        "albedo" : "0.4 0.5 0.6"
      },
      "dielectric" : {
        "type" : "dielectric",
        "ior" : 1.5,
        "color" : "1 1 1"
      },
      "dielectric-g" : {
        "type" : "dielectric",
        "ior" : 1.5,
        "color" : "0.8 1 0.9"
      },
      "dielectric-b" : {
        "type" : "dielectric",
        "ior" : 1.5,
        "color" : "0.8 0.9 1"
      },
      "dielectric-r" : {
        "type" : "dielectric",
        "ior" : 1.5,
        "color" : "1 0.8 0.9"
      }
    },
    "geometry" : {
      "worldSphere" : {
        "type" : "sphere",
        "mat" : "sky",
        "light" : "skyLight",
        "origin" : "0 0 0",
        "radius" : 2000.0,
        "inverted" : true
      },
      "bottom" : {
        "type" : "disc",
        "mat" : "ground",
        "light" : "",
        "origin" : "0 -20 -0",
        "normal" : "0 1 0",
        "radiusOuter" : 2001.0,
        "radiusInner" : 0.0
      },
      "lightSource" : {
        "type" : "sphere",
        "mat" : "",
        "light" : "sunLight",
        "origin" : "0 2500 0",
        "radius" : 1000.0,
        "inverted" : false
      },
      "sphere1" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "16 -10 -22",
        "radius" : 10.0,
        "inverted" : false
      },
      "sphere2" : {
        "type" : "sphere",
        "mat" : "dielectric-r",
        "light" : "",
        "origin" : "2 -10 -40",
        "radius" : 10.0,
        "inverted" : false
      },
      "sphere3" : {
        "type" : "sphere",
        "mat" : "dielectric-g",
        "light" : "",
        "origin" : "-12 -10 -58",
        "radius" : 10.0,
        "inverted" : false
      },
      "sphere4" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "-26 -10 -76",
        "radius" : 10.0,
        "inverted" : false
      },
      "sphere5" : {
        "type" : "sphere",
        "mat" : "dielectric-g",
        "light" : "",
        "origin" : "-40 -10 -94",
        "radius" : 10.0,
        "inverted" : false
      },
      "sphere6" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "-54 -10 -112",
        "radius" : 10.0,
        "inverted" : false
      },
      "sphere7" : {
        "type" : "sphere",
        "mat" : "dielectric-b",
        "light" : "",
        "origin" : "-68 -10 -130",
        "radius" : 10.0,
        "inverted" : false
      },
      "sphere8" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "-82 -10 -148",
        "radius" : 10.0,
        "inverted" : false
      },
      "sphere9" : {
        "type" : "sphere",
        "mat" : "dielectric-b",
        "light" : "",
        "origin" : "-96 -10 -166",
        "radius" : 10.0,
        "inverted" : false
      },
      "sphere10" : {
        "type" : "sphere",
        "mat" : "dielectric",
        "light" : "",
        "origin" : "-110 -10 -184",
        "radius" : 10.0,
        "inverted" : false
      }
    },
    "cameras" : {
      "default" : {
        "type" : "persp",
        "translate" : "-2 8 30",
        "rotateAngle" :  -0.26180,
        "rotateAxis" : "1 0 0",
        "objects" : [
          "worldSphere", "bottom", "lightSource", "sphere1", "sphere2",
          "sphere3", "sphere4", "sphere5", "sphere6", "sphere7", "sphere8",
          "sphere9", "sphere10"
        ],
        "width" : 512,
        "height" : 384,
        "fov" : 0.78540,
        "focalLength" : 88.0,
        "fStop" : 16.0
      }
    }
  }
)";

}  // namespace

class Graphics2DInstance : public pp::Instance {
 public:
  explicit Graphics2DInstance(PP_Instance instance)
      : pp::Instance(instance),
        callback_factory_(this),
        scene_(NULL),
        image_(NULL),
        device_scale_(1.0f) {}

  ~Graphics2DInstance() {
    delete scene_;
    delete image_;
  }

  virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) {
    std::stringstream ss;
    ss << kSceneDescription;

    scene_ = new Scene(ss);
    image_ = new SyncedImage(
      this,
      pp::Size(scene_->defaultCamera()->GetSize()),
      pp::Size(1, 1)
    );

    pthread_t t;
    pthread_create(
      &t,
      NULL,
      &Graphics2DInstance::InitBackgroundThread,
      this
    );

    return true;
  }

  static void* InitBackgroundThread(void* data) {
    Graphics2DInstance* g2d = reinterpret_cast<Graphics2DInstance*>(data);
    g2d->GetScene()->defaultCamera()->renderMultiple(g2d->GetImage(), -1);
    return NULL;
  }

  virtual void DidChangeView(const pp::View& view) {
    device_scale_ = view.GetDeviceScale();
    pp::Size new_size = pp::Size(view.GetRect().width() * device_scale_,
                                 view.GetRect().height() * device_scale_);

    if (!CreateContext(new_size))
      return;

    // When flush_context_ is null, it means there is no Flush callback in
    // flight. This may have happened if the context was not created
    // successfully, or if this is the first call to DidChangeView (when the
    // module first starts). In either case, start the main loop.
    if (flush_context_.is_null())
      MainLoop(0);
  }

 private:
  bool CreateContext(const pp::Size& new_size) {
    const bool kIsAlwaysOpaque = true;
    context_ = pp::Graphics2D(this, new_size, kIsAlwaysOpaque);
    // Call SetScale before BindGraphics so the image is scaled correctly on
    // HiDPI displays.
    context_.SetScale(1.0f / device_scale_);
    if (!BindGraphics(context_)) {
      fprintf(stderr, "Unable to bind 2d context!\n");
      context_ = pp::Graphics2D();
      return false;
    }

    // Update screen image buffer.
    if (image_) {
      image_->SetScreenSize(new_size);
    }

    return true;
  }

  void MainLoop(int32_t) {
    if (context_.is_null()) {
      // The current Graphics2D context is null, so updating and rendering is
      // pointless. Set flush_context_ to null as well, so if we get another
      // DidChangeView call, the main loop is started again.
      flush_context_ = context_;
      return;
    }

    if (image_) {
      int counter;
      context_.ReplaceContents(image_->GetScreenData(&counter));
      PostMessage(pp::Var(counter));
    } else {
      std::cerr << "no update" << std::endl;
    }

    // Store a reference to the context that is being flushed; this ensures
    // the callback is called, even if context_ changes before the flush
    // completes.
    flush_context_ = context_;
    context_.Flush(
        callback_factory_.NewCallback(&Graphics2DInstance::MainLoop));
  }

  SyncedImage* GetImage() {
    return image_;
  }

  const Scene* GetScene() {
    return scene_;
  }

  pp::CompletionCallbackFactory<Graphics2DInstance> callback_factory_;
  pp::Graphics2D context_;
  pp::Graphics2D flush_context_;
  pp::Size size_;
  Scene* scene_;
  SyncedImage* image_;
  float device_scale_;
};

class Graphics2DModule : public pp::Module {
 public:
  Graphics2DModule() : pp::Module() {}
  virtual ~Graphics2DModule() {}

  virtual pp::Instance* CreateInstance(PP_Instance instance) {
    return new Graphics2DInstance(instance);
  }
};

namespace pp {
Module* CreateModule() { return new Graphics2DModule(); }
}  // namespace pp
<|endoftext|>


<commit_before>// Copyright 2010-2013 UT-Battelle, LLC.  See LICENSE.txt for more information.
#include "eavl2DGraphLayoutMutator.h"
#include "eavlCellSetExplicit.h"

eavl2DGraphLayoutMutator::eavl2DGraphLayoutMutator()
{
    niter = 30;
    startdist = 0.3;
    finaldist = 0.01;
}

void
eavl2DGraphLayoutMutator::Execute()
{
    eavlCellSet *cs = dataset->GetCellSet(cellsetname);
    eavlCellSetExplicit *cse = dynamic_cast<eavlCellSetExplicit*>(cs);
    if (!cse)
        THROW(eavlException, "Expected explicit cell set.");

    int npts = dataset->GetNumPoints();

    // add coordinates
    eavlCoordinatesCartesian *coords =
        new eavlCoordinatesCartesian(NULL,
                                     eavlCoordinatesCartesian::X,
                                     eavlCoordinatesCartesian::Y);
    coords->SetAxis(0, new eavlCoordinateAxisField("newx",0));
    coords->SetAxis(1, new eavlCoordinateAxisField("newy",0));
    if (dataset->GetNumCoordinateSystems() == 0)
        dataset->AddCoordinateSystem(coords);
    else
        dataset->SetCoordinateSystem(0, coords);

    eavlFloatArray *x = new eavlFloatArray("newx", 1, npts);
    eavlFloatArray *y = new eavlFloatArray("newy", 1, npts);
    dataset->AddField(new eavlField(1, x, eavlField::ASSOC_POINTS));
    dataset->AddField(new eavlField(1, y, eavlField::ASSOC_POINTS));

    //srand(npts+15);
    //srand(time(NULL));
    // set coordinates to something
#if 0 // first option: arrange them in a circle; that's alas correct too easily
    for (int i=0; i<npts; ++i)
    {
        float a = float(i)/float(npts);
        x->SetValue(i, cos(a * 2 * M_PI));
        y->SetValue(i, sin(a * 2 * M_PI));
    }
#elif 0 // second option: in a grid; less often correct for simple graphs
    int sq = sqrt(npts);
    for (int i=0; i<npts; ++i)
    {
        int xx = i % sq;
        int yy = i / sq;
        x->SetValue(i, float(xx)/float(sq));
        y->SetValue(i, float(yy)/float(sq));
    }
#else // third option: random
    for (int i=0; i<npts; ++i)
    {
        float xx = double(random()) / double(RAND_MAX);
        float yy = double(random()) / double(RAND_MAX);
        x->SetValue(i, 2.*xx-1.);
        y->SetValue(i, 2.*yy-1.);
    }
#endif

    float area = 1;
    float k = sqrt(area / npts);
    float k2 = k*k;
    vector<float> vx(npts, 0);
    vector<float> vy(npts, 0);
    double distchange = finaldist / startdist;
    double distdelta  = niter==1 ? 1 : pow(distchange, 1. / double(niter-1));
    for (int iter = 0 ; iter < niter ; ++iter)
    {
        float maxdist = startdist * pow(distdelta, iter);

        // init vels to 0
        for (int i=0; i<npts; ++i)
        {
            vx[i] = 0;
            vy[i] = 0;
        }

#if 1
        // repulsive force
        for (int i=0; i<npts; ++i)
        {
            float ix = x->GetValue(i);
            float iy = y->GetValue(i);
            for (int j=i+1; j<npts; ++j)
            {
                float dx = ix - x->GetValue(j);
                float dy = iy - y->GetValue(j);
                ///\todo: if dx==dy==0, assume some small random displacement

                /*
                float len = sqrt(dx*dx + dy*dy);
                float udx = dx/len;
                float udy = dy/len;

                float frx = udx * (k*k / len);
                float fry = udy * (k*k / len);
                */
                // same equation, just more efficient via simplification
                float len2 = dx*dx + dy*dy;
                float frx = dx * k2 / len2;
                float fry = dy * k2 / len2;

                vx[i] += frx;
                vy[i] += fry;

                vx[j] -= frx;
                vy[j] -= fry;
            }
        }
#endif

        // attractive force
        for (int c=0; c<cs->GetNumCells(); ++c)
        {
            eavlCell cell = cs->GetCellNodes(c);
            if (cell.numIndices != 2)
                continue;
            int i = cell.indices[0];
            int j = cell.indices[1];

            float dx = x->GetValue(i) - x->GetValue(j);
            float dy = y->GetValue(i) - y->GetValue(j);
            ///\todo: if dx==dy==0, assume some small random displacement
            float len = sqrt(dx*dx + dy*dy);
            float udx = dx/len;
            float udy = dy/len;

            float fax = udx * (len*len / k);
            float fay = udy * (len*len / k);
            vx[i] -= fax;
            vy[i] -= fay;

            vx[j] += fax;
            vy[j] += fay;

        }

#if 0
        // attract to center to keep trees from escaping forest
        for (int i=0; i<npts; ++i)
        {
            float dx = x->GetValue(i);
            float dy = y->GetValue(i);
            if (dx == 0 && dy == 0)
                continue;

            float len = sqrt(dx*dx + dy*dy);
            float udx = dx/len;
            float udy = dy/len;

            float scale = 0.3;
            float fcx = scale * udx * len / k;
            float fcy = scale * udy * len / k;
            vx[i] -= fcx;
            vy[i] -= fcy;
        }
#endif

        // clamp to maxdist
        for (int i=0; i<npts; ++i)
        {
            float len = sqrt(vx[i]*vx[i] + vy[i]*vy[i]);
            if (len > maxdist)
            {
                vx[i] = maxdist * vx[i] / len;
                vy[i] = maxdist * vy[i] / len;
            }
        }

        // update point locations
        for (int i=0; i<npts; ++i)
        {
            x->SetValue(i, x->GetValue(i) + vx[i]);
            y->SetValue(i, y->GetValue(i) + vy[i]);
        }
    }
}
<commit_msg>#include fix and use std::random features<commit_after>// Copyright 2010-2013 UT-Battelle, LLC.  See LICENSE.txt for more information.
#include "eavl2DGraphLayoutForceMutator.h"
#include "eavlCellSetExplicit.h"
// stl
#include <random>

eavl2DGraphLayoutMutator::eavl2DGraphLayoutMutator()
{
    niter = 30;
    startdist = 0.3;
    finaldist = 0.01;
}

void
eavl2DGraphLayoutMutator::Execute()
{
    eavlCellSet *cs = dataset->GetCellSet(cellsetname);
    eavlCellSetExplicit *cse = dynamic_cast<eavlCellSetExplicit*>(cs);
    if (!cse)
        THROW(eavlException, "Expected explicit cell set.");

    int npts = dataset->GetNumPoints();

    // add coordinates
    eavlCoordinatesCartesian *coords =
        new eavlCoordinatesCartesian(NULL,
                                     eavlCoordinatesCartesian::X,
                                     eavlCoordinatesCartesian::Y);
    coords->SetAxis(0, new eavlCoordinateAxisField("newx",0));
    coords->SetAxis(1, new eavlCoordinateAxisField("newy",0));
    if (dataset->GetNumCoordinateSystems() == 0)
        dataset->AddCoordinateSystem(coords);
    else
        dataset->SetCoordinateSystem(0, coords);

    eavlFloatArray *x = new eavlFloatArray("newx", 1, npts);
    eavlFloatArray *y = new eavlFloatArray("newy", 1, npts);
    dataset->AddField(new eavlField(1, x, eavlField::ASSOC_POINTS));
    dataset->AddField(new eavlField(1, y, eavlField::ASSOC_POINTS));

    //srand(npts+15);
    //srand(time(NULL));
    // set coordinates to something
#if 0 // first option: arrange them in a circle; that's alas correct too easily
    for (int i=0; i<npts; ++i)
    {
        float a = float(i)/float(npts);
        x->SetValue(i, cos(a * 2 * M_PI));
        y->SetValue(i, sin(a * 2 * M_PI));
    }
#elif 0 // second option: in a grid; less often correct for simple graphs
    int sq = sqrt(npts);
    for (int i=0; i<npts; ++i)
    {
        int xx = i % sq;
        int yy = i / sq;
        x->SetValue(i, float(xx)/float(sq));
        y->SetValue(i, float(yy)/float(sq));
    }
#else // third option: random
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<float> dis(0.0, 1.0);
    for (int i=0; i<npts; ++i)
    {
        x->SetValue(i, 2*dis(gen)-1);
        y->SetValue(i, 2*dis(gen)-1);
    }
#endif

    float area = 1;
    float k = sqrt(area / npts);
    float k2 = k*k;
    vector<float> vx(npts, 0);
    vector<float> vy(npts, 0);
    double distchange = finaldist / startdist;
    double distdelta  = niter==1 ? 1 : pow(distchange, 1. / double(niter-1));
    for (int iter = 0 ; iter < niter ; ++iter)
    {
        float maxdist = startdist * pow(distdelta, iter);

        // init vels to 0
        for (int i=0; i<npts; ++i)
        {
            vx[i] = 0;
            vy[i] = 0;
        }

#if 1
        // repulsive force
        for (int i=0; i<npts; ++i)
        {
            float ix = x->GetValue(i);
            float iy = y->GetValue(i);
            for (int j=i+1; j<npts; ++j)
            {
                float dx = ix - x->GetValue(j);
                float dy = iy - y->GetValue(j);
                ///\todo: if dx==dy==0, assume some small random displacement

                /*
                float len = sqrt(dx*dx + dy*dy);
                float udx = dx/len;
                float udy = dy/len;

                float frx = udx * (k*k / len);
                float fry = udy * (k*k / len);
                */
                // same equation, just more efficient via simplification
                float len2 = dx*dx + dy*dy;
                float frx = dx * k2 / len2;
                float fry = dy * k2 / len2;

                vx[i] += frx;
                vy[i] += fry;

                vx[j] -= frx;
                vy[j] -= fry;
            }
        }
#endif

        // attractive force
        for (int c=0; c<cs->GetNumCells(); ++c)
        {
            eavlCell cell = cs->GetCellNodes(c);
            if (cell.numIndices != 2)
                continue;
            int i = cell.indices[0];
            int j = cell.indices[1];

            float dx = x->GetValue(i) - x->GetValue(j);
            float dy = y->GetValue(i) - y->GetValue(j);
            ///\todo: if dx==dy==0, assume some small random displacement
            float len = sqrt(dx*dx + dy*dy);
            float udx = dx/len;
            float udy = dy/len;

            float fax = udx * (len*len / k);
            float fay = udy * (len*len / k);
            vx[i] -= fax;
            vy[i] -= fay;

            vx[j] += fax;
            vy[j] += fay;

        }

#if 0
        // attract to center to keep trees from escaping forest
        for (int i=0; i<npts; ++i)
        {
            float dx = x->GetValue(i);
            float dy = y->GetValue(i);
            if (dx == 0 && dy == 0)
                continue;

            float len = sqrt(dx*dx + dy*dy);
            float udx = dx/len;
            float udy = dy/len;

            float scale = 0.3;
            float fcx = scale * udx * len / k;
            float fcy = scale * udy * len / k;
            vx[i] -= fcx;
            vy[i] -= fcy;
        }
#endif

        // clamp to maxdist
        for (int i=0; i<npts; ++i)
        {
            float len = sqrt(vx[i]*vx[i] + vy[i]*vy[i]);
            if (len > maxdist)
            {
                vx[i] = maxdist * vx[i] / len;
                vy[i] = maxdist * vy[i] / len;
            }
        }

        // update point locations
        for (int i=0; i<npts; ++i)
        {
            x->SetValue(i, x->GetValue(i) + vx[i]);
            y->SetValue(i, y->GetValue(i) + vy[i]);
        }
    }
}
<|endoftext|>


<commit_before>#include "Image.hpp"

#include "StringEx.hpp"
#include "TargaImage.hpp"
#include "PNGImage.hpp"

using namespace std;
using namespace MPACK::Core;

namespace MPACK
{
	namespace Graphics
	{
		Image::Image()
			: m_width(0), m_height(0), m_GLFormatType(0), m_bytesPerPixel(0),
			  m_imageBuffer(NULL), m_internalFormatType(Image::InternalFormatType::NONE)
		{
		}

		Image::~Image()
		{
			Unload();
		}

		void Image::Init(const int &width, const int &height)
		{
			Unload();

			if (width < 0)
			{
				LOGW("PNGImage::Init() invalid width!");
				m_width = 1;
			}
			else
			{
				m_width = width;
			}

			if (height < 0)
			{
				LOGW("PNGImage::Init() invalid height!");
				m_height = 1;
			}
			else
			{
				m_height = height;
			}

			m_bytesPerPixel = 4;
			m_GLFormatType = GL_RGBA;

			m_imageBuffer = new BYTE[m_width * m_height * m_bytesPerPixel];
		}

		ReturnValue Image::Load(const std::string& path, bool flipForOpenGL, FileFormatType fileFormatType)
		{
			Unload();

			if (fileFormatType == FileFormatType::AUTO)
			{
				string ext;
				Core::StringEx::GetExtension(path.c_str(), ext);
				Core::StringEx::Upper(ext);
				if(ext == "TGA")
				{
					fileFormatType = FileFormatType::TGA;
				}
				else if(ext == "PNG")
				{
					fileFormatType = FileFormatType::PNG;
				}
				else if(ext == "PPM")
				{
					fileFormatType = FileFormatType::PPM;
				}
				else
				{
					LOGE("Image::Load() format auto-detect fail: invalid extension: %s", path.c_str());
					return RETURN_VALUE_KO;
				}
			}

			switch(fileFormatType)
			{
				case FileFormatType::TGA:
					if (LoadTGA(this, path, flipForOpenGL) == RETURN_VALUE_KO)
					{
						LOGE("Image::Load() fail to load TGA image: %s", path.c_str());
						return RETURN_VALUE_KO;
					}
				break;
				case FileFormatType::PNG:
					if (LoadPNG(this, path, flipForOpenGL) == RETURN_VALUE_KO)
					{
						LOGE("Image::Load() fail to load PNG image: %s", path.c_str());
						return RETURN_VALUE_KO;
					}
				break;
				case FileFormatType::PPM:
					if (LoadPPM(this, path, flipForOpenGL) == RETURN_VALUE_KO)
					{
						LOGE("Image::Load() fail to load PPM image: %s", path.c_str());
						return RETURN_VALUE_KO;
					}
				break;
			}

			return RETURN_VALUE_OK;
		}

		ReturnValue Image::Save(const std::string& path, FileFormatType fileFormatType)
		{
			if (fileFormatType == FileFormatType::AUTO)
			{
				fileFormatType = FileFormatType::PNG;
			}

			switch(fileFormatType)
			{
				case FileFormatType::TGA:
					if (SaveTGA(this, path) == RETURN_VALUE_KO)
					{
						LOGE("Image::Save() fail to save image as TGA");
						return RETURN_VALUE_KO;
					}
				break;
				case FileFormatType::PNG:
					if (SavePNG(this, path) == RETURN_VALUE_KO)
					{
						LOGE("Image::Save() fail to save image as PNG");
						return RETURN_VALUE_KO;
					}
				break;
				case FileFormatType::PPM:
					if (SavePPM(this, path) == RETURN_VALUE_KO)
					{
						LOGE("Image::Save() fail to save image as PPM");
						return RETURN_VALUE_KO;
					}
				break;
			}
			return RETURN_VALUE_OK;
		}

		void Image::Unload()
		{
			if (m_imageBuffer)
			{
				m_width = 0;
				m_height = 0;
				m_internalFormatType = InternalFormatType::NONE;
				m_GLFormatType = 0;
				m_bytesPerPixel = 0;
				delete[] m_imageBuffer;
				m_imageBuffer = 0;
			}
		}

		void Image::InitColor(const int &width, const int &height, const Color &c)
		{
			Init(width, height);
			FillColor(Rect(0, 0, m_width, m_height), c);
		}

		void Image::FillColor(const Rect &rect, const Color &c)
		{
			for(int i = 0; i < m_width; ++i)
			{
				for(int j = 0; j < m_height; ++j)
				{
					SetPixel(rect.x + i, rect.y + j, c);
				}
			}
		}

		void Image::Blit(Image *image, const GLushort &x, const GLushort &y)
		{
			BlitSafe(image, Point(x,y), Rect(0,0,image->GetWidth(),image->GetHeight()));
		}

		void Image::Blit(Image *image, const Point &point)
		{
			BlitSafe(image, point, Rect(0,0,image->GetWidth(),image->GetHeight()));
		}

		void Image::Blit(Image *image, const Point &point, const Rect &rect)
		{
			BlitSafe(image, point, rect);
		}

		void Image::FlipVertical()
		{
			for(int i = 0; i < m_width; ++i)
			{
				for(int j = 0; j < (m_height >> 1); ++j)
				{
					int offset1 = j * m_width + i;
					offset1 *= m_bytesPerPixel;

					int vi = i;
					int vj = m_height - j - 1;

					int offset2 = vj * m_width + vi;
					offset2 *= m_bytesPerPixel;

					StringEx::MemSwap((char*)(m_imageBuffer + offset1),(char*)(m_imageBuffer + offset2),m_bytesPerPixel);
				}
			}
		}

		void Image::FlipHorizontal()
		{
			for(int i = 0; i < (m_width >> 1); ++i)
			{
				for(int j = 0; j < m_height; ++j)
				{
					int offset1 = j * m_width + i;
					offset1 *= m_bytesPerPixel;

					int vi = m_width - i - 1;
					int vj = j;

					int offset2 = vj * m_width + vi;
					offset2 *= m_bytesPerPixel;

					StringEx::MemSwap((char*)(m_imageBuffer + offset1),(char*)(m_imageBuffer + offset2),m_bytesPerPixel);
				}
			}
		}

		GLushort Image::GetWidth() const
		{
			return m_width;
		}

		GLushort Image::GetHeight() const
		{
			return m_height;
		}

		GLushort Image::GetBytesPerPixel() const
		{
			return m_bytesPerPixel;
		}

		GLint Image::GetGLFormat() const
		{
			return m_GLFormatType;
		}

		Image::InternalFormatType Image::GetFormat() const
		{
			return m_internalFormatType;
		}

		bool Image::HaveAlphaChannel() const
		{
			return m_internalFormatType == Image::InternalFormatType::GRAY_ALPHA ||
				   m_internalFormatType == Image::InternalFormatType::RGBA;
		}

		const BYTE* Image::GetImageData() const
		{
			return m_imageBuffer;
		}

		const BYTE* Image::GetPixelPointer(const GLushort &x, const GLushort &y) const
		{
			int index = y * m_width + x;
			index *= m_bytesPerPixel;
			return m_imageBuffer + index;
		}

		Color Image::GetPixel(const GLushort &x, const GLushort &y) const
		{
			int index =  y * m_width + x;
			index *= m_bytesPerPixel;
			if (m_bytesPerPixel == 4)
			{
				return Color(m_imageBuffer[index], m_imageBuffer[index+1],
							 m_imageBuffer[index+2], m_imageBuffer[index+3]);
			}
			else if(m_bytesPerPixel == 3)
			{
				return Color(m_imageBuffer[index], m_imageBuffer[index+1],
							 m_imageBuffer[index+2], 255);
			}
			else if(m_bytesPerPixel == 2)
			{
				return Color(m_imageBuffer[index], m_imageBuffer[index],
							 m_imageBuffer[index], m_imageBuffer[index+1]);
			}
			else
			{
				return Color(m_imageBuffer[index], m_imageBuffer[index],
							 m_imageBuffer[index], 255);
			}
		}

		void Image::SetPixel(const GLushort &x, const GLushort &y, const Color &c)
		{
			int index = y * m_width + x;
			index *= m_bytesPerPixel;
			if (m_bytesPerPixel == 4)
			{
				m_imageBuffer[index] = c.r;
				m_imageBuffer[index+1] = c.g;
				m_imageBuffer[index+2] = c.b;
				m_imageBuffer[index+3] = c.a;
			}
			else if(m_bytesPerPixel == 3)
			{
				m_imageBuffer[index] = c.r;
				m_imageBuffer[index+1] = c.g;
				m_imageBuffer[index+2] = c.b;
			}
			else if(m_bytesPerPixel == 2)
			{
				unsigned char gray = (c.r + c.g + c.b) / 3;
				m_imageBuffer[index] = gray;
				m_imageBuffer[index+1] = c.a;
			}
			else
			{
				unsigned char gray = (c.r + c.g + c.b) / 3;
				m_imageBuffer[index] = gray;
			}
		}

		void Image::BlitSafe(Image *image, Point point, Rect rect)
		{
			GLushort width = image->GetWidth();
			GLushort height = image->GetHeight();

			if (point.x >= m_width || point.y >= m_height)
			{
				return;
			}

			if (rect.width <= 0 || rect.height <= 0)
			{
				return;
			}

			if (rect.x >= width || rect.y >= height)
			{
				return;
			}

			if (point.x < 0)
			{
				point.x = 0;
			}

			if (point.y < 0)
			{
				point.y = 0;
			}

			GLushort maxWidth = m_width - point.x;
			if (rect.width > maxWidth)
			{
				rect.width = maxWidth;
			}

			GLushort maxHeight = m_height - point.y;
			if (rect.height > maxHeight)
			{
				rect.height = maxHeight - point.y;
			}

			for (int i = 0; i < rect.width; ++i)
			{
				for (int j = 0; j < rect.height; ++j)
				{
					SetPixel(point.x + i,point.y + j, image->GetPixel(rect.x + i, rect.y + j));
				}
			}
		}

		GLushort GetBPP(GLint format)
		{
			switch(format)
			{
				case GL_RGB:
					return 3;
				break;
				case GL_RGBA:
					return 4;
				break;
				case GL_LUMINANCE:
					return 1;
				break;
				case GL_LUMINANCE_ALPHA:
					return 2;
				break;
			}
			return 0;
		}
	}
}
<commit_msg>Image: fix warnings<commit_after>#include "Image.hpp"

#include "StringEx.hpp"
#include "TargaImage.hpp"
#include "PNGImage.hpp"

using namespace std;
using namespace MPACK::Core;

namespace MPACK
{
	namespace Graphics
	{
		Image::Image()
			: m_width(0), m_height(0), m_GLFormatType(0), m_bytesPerPixel(0),
			  m_imageBuffer(NULL), m_internalFormatType(Image::InternalFormatType::NONE)
		{
		}

		Image::~Image()
		{
			Unload();
		}

		void Image::Init(const int &width, const int &height)
		{
			Unload();

			if (width < 0)
			{
				LOGW("PNGImage::Init() invalid width!");
				m_width = 1;
			}
			else
			{
				m_width = width;
			}

			if (height < 0)
			{
				LOGW("PNGImage::Init() invalid height!");
				m_height = 1;
			}
			else
			{
				m_height = height;
			}

			m_bytesPerPixel = 4;
			m_GLFormatType = GL_RGBA;

			m_imageBuffer = new BYTE[m_width * m_height * m_bytesPerPixel];
		}

		ReturnValue Image::Load(const std::string& path, bool flipForOpenGL, FileFormatType fileFormatType)
		{
			Unload();

			if (fileFormatType == FileFormatType::AUTO)
			{
				string ext;
				Core::StringEx::GetExtension(path.c_str(), ext);
				Core::StringEx::Upper(ext);
				if(ext == "TGA")
				{
					fileFormatType = FileFormatType::TGA;
				}
				else if(ext == "PNG")
				{
					fileFormatType = FileFormatType::PNG;
				}
				else if(ext == "PPM")
				{
					fileFormatType = FileFormatType::PPM;
				}
				else
				{
					LOGE("Image::Load() format auto-detect fail: invalid extension: %s", path.c_str());
					return RETURN_VALUE_KO;
				}
			}

			switch(fileFormatType)
			{
				case FileFormatType::TGA:
					if (LoadTGA(this, path, flipForOpenGL) == RETURN_VALUE_KO)
					{
						LOGE("Image::Load() fail to load TGA image: %s", path.c_str());
						return RETURN_VALUE_KO;
					}
				break;
				case FileFormatType::PNG:
					if (LoadPNG(this, path, flipForOpenGL) == RETURN_VALUE_KO)
					{
						LOGE("Image::Load() fail to load PNG image: %s", path.c_str());
						return RETURN_VALUE_KO;
					}
				break;
				case FileFormatType::PPM:
					if (LoadPPM(this, path, flipForOpenGL) == RETURN_VALUE_KO)
					{
						LOGE("Image::Load() fail to load PPM image: %s", path.c_str());
						return RETURN_VALUE_KO;
					}
				break;
				default:
				break;
			}

			return RETURN_VALUE_OK;
		}

		ReturnValue Image::Save(const std::string& path, FileFormatType fileFormatType)
		{
			if (fileFormatType == FileFormatType::AUTO)
			{
				fileFormatType = FileFormatType::PNG;
			}

			switch(fileFormatType)
			{
				case FileFormatType::TGA:
					if (SaveTGA(this, path) == RETURN_VALUE_KO)
					{
						LOGE("Image::Save() fail to save image as TGA");
						return RETURN_VALUE_KO;
					}
				break;
				case FileFormatType::PNG:
					if (SavePNG(this, path) == RETURN_VALUE_KO)
					{
						LOGE("Image::Save() fail to save image as PNG");
						return RETURN_VALUE_KO;
					}
				break;
				case FileFormatType::PPM:
					if (SavePPM(this, path) == RETURN_VALUE_KO)
					{
						LOGE("Image::Save() fail to save image as PPM");
						return RETURN_VALUE_KO;
					}
				break;
				default:
				break;
			}
			return RETURN_VALUE_OK;
		}

		void Image::Unload()
		{
			if (m_imageBuffer)
			{
				m_width = 0;
				m_height = 0;
				m_internalFormatType = InternalFormatType::NONE;
				m_GLFormatType = 0;
				m_bytesPerPixel = 0;
				delete[] m_imageBuffer;
				m_imageBuffer = 0;
			}
		}

		void Image::InitColor(const int &width, const int &height, const Color &c)
		{
			Init(width, height);
			FillColor(Rect(0, 0, m_width, m_height), c);
		}

		void Image::FillColor(const Rect &rect, const Color &c)
		{
			for(int i = 0; i < m_width; ++i)
			{
				for(int j = 0; j < m_height; ++j)
				{
					SetPixel(rect.x + i, rect.y + j, c);
				}
			}
		}

		void Image::Blit(Image *image, const GLushort &x, const GLushort &y)
		{
			BlitSafe(image, Point(x,y), Rect(0,0,image->GetWidth(),image->GetHeight()));
		}

		void Image::Blit(Image *image, const Point &point)
		{
			BlitSafe(image, point, Rect(0,0,image->GetWidth(),image->GetHeight()));
		}

		void Image::Blit(Image *image, const Point &point, const Rect &rect)
		{
			BlitSafe(image, point, rect);
		}

		void Image::FlipVertical()
		{
			for(int i = 0; i < m_width; ++i)
			{
				for(int j = 0; j < (m_height >> 1); ++j)
				{
					int offset1 = j * m_width + i;
					offset1 *= m_bytesPerPixel;

					int vi = i;
					int vj = m_height - j - 1;

					int offset2 = vj * m_width + vi;
					offset2 *= m_bytesPerPixel;

					StringEx::MemSwap((char*)(m_imageBuffer + offset1),(char*)(m_imageBuffer + offset2),m_bytesPerPixel);
				}
			}
		}

		void Image::FlipHorizontal()
		{
			for(int i = 0; i < (m_width >> 1); ++i)
			{
				for(int j = 0; j < m_height; ++j)
				{
					int offset1 = j * m_width + i;
					offset1 *= m_bytesPerPixel;

					int vi = m_width - i - 1;
					int vj = j;

					int offset2 = vj * m_width + vi;
					offset2 *= m_bytesPerPixel;

					StringEx::MemSwap((char*)(m_imageBuffer + offset1),(char*)(m_imageBuffer + offset2),m_bytesPerPixel);
				}
			}
		}

		GLushort Image::GetWidth() const
		{
			return m_width;
		}

		GLushort Image::GetHeight() const
		{
			return m_height;
		}

		GLushort Image::GetBytesPerPixel() const
		{
			return m_bytesPerPixel;
		}

		GLint Image::GetGLFormat() const
		{
			return m_GLFormatType;
		}

		Image::InternalFormatType Image::GetFormat() const
		{
			return m_internalFormatType;
		}

		bool Image::HaveAlphaChannel() const
		{
			return m_internalFormatType == Image::InternalFormatType::GRAY_ALPHA ||
				   m_internalFormatType == Image::InternalFormatType::RGBA;
		}

		const BYTE* Image::GetImageData() const
		{
			return m_imageBuffer;
		}

		const BYTE* Image::GetPixelPointer(const GLushort &x, const GLushort &y) const
		{
			int index = y * m_width + x;
			index *= m_bytesPerPixel;
			return m_imageBuffer + index;
		}

		Color Image::GetPixel(const GLushort &x, const GLushort &y) const
		{
			int index =  y * m_width + x;
			index *= m_bytesPerPixel;
			if (m_bytesPerPixel == 4)
			{
				return Color(m_imageBuffer[index], m_imageBuffer[index+1],
							 m_imageBuffer[index+2], m_imageBuffer[index+3]);
			}
			else if(m_bytesPerPixel == 3)
			{
				return Color(m_imageBuffer[index], m_imageBuffer[index+1],
							 m_imageBuffer[index+2], 255);
			}
			else if(m_bytesPerPixel == 2)
			{
				return Color(m_imageBuffer[index], m_imageBuffer[index],
							 m_imageBuffer[index], m_imageBuffer[index+1]);
			}
			else
			{
				return Color(m_imageBuffer[index], m_imageBuffer[index],
							 m_imageBuffer[index], 255);
			}
		}

		void Image::SetPixel(const GLushort &x, const GLushort &y, const Color &c)
		{
			int index = y * m_width + x;
			index *= m_bytesPerPixel;
			if (m_bytesPerPixel == 4)
			{
				m_imageBuffer[index] = c.r;
				m_imageBuffer[index+1] = c.g;
				m_imageBuffer[index+2] = c.b;
				m_imageBuffer[index+3] = c.a;
			}
			else if(m_bytesPerPixel == 3)
			{
				m_imageBuffer[index] = c.r;
				m_imageBuffer[index+1] = c.g;
				m_imageBuffer[index+2] = c.b;
			}
			else if(m_bytesPerPixel == 2)
			{
				unsigned char gray = (c.r + c.g + c.b) / 3;
				m_imageBuffer[index] = gray;
				m_imageBuffer[index+1] = c.a;
			}
			else
			{
				unsigned char gray = (c.r + c.g + c.b) / 3;
				m_imageBuffer[index] = gray;
			}
		}

		void Image::BlitSafe(Image *image, Point point, Rect rect)
		{
			GLushort width = image->GetWidth();
			GLushort height = image->GetHeight();

			if (point.x >= m_width || point.y >= m_height)
			{
				return;
			}

			if (rect.width <= 0 || rect.height <= 0)
			{
				return;
			}

			if (rect.x >= width || rect.y >= height)
			{
				return;
			}

			if (point.x < 0)
			{
				point.x = 0;
			}

			if (point.y < 0)
			{
				point.y = 0;
			}

			GLushort maxWidth = m_width - point.x;
			if (rect.width > maxWidth)
			{
				rect.width = maxWidth;
			}

			GLushort maxHeight = m_height - point.y;
			if (rect.height > maxHeight)
			{
				rect.height = maxHeight - point.y;
			}

			for (int i = 0; i < rect.width; ++i)
			{
				for (int j = 0; j < rect.height; ++j)
				{
					SetPixel(point.x + i,point.y + j, image->GetPixel(rect.x + i, rect.y + j));
				}
			}
		}

		GLushort GetBPP(GLint format)
		{
			switch(format)
			{
				case GL_RGB:
					return 3;
				break;
				case GL_RGBA:
					return 4;
				break;
				case GL_LUMINANCE:
					return 1;
				break;
				case GL_LUMINANCE_ALPHA:
					return 2;
				break;
			}
			return 0;
		}
	}
}
<|endoftext|>