<commit_before>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/

#include "otbOpticalCalibration.h"

#include <iostream>

#include "otbVectorImage.h"
#include "otbImageFileReader.h"

#include "otbImageToLuminanceImageFilter.h"
#include "otbLuminanceToReflectanceImageFilter.h"
#include "otbReflectanceToSurfaceReflectanceImageFilter.h"

#include "otbStreamingImageFileWriter.h"
#include "otbStandardWriterWatcher.h"
#include "otbMultiplyByScalarImageFilter.h"

namespace otb
{

int OpticalCalibration::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("OpticalCalibration");
  descriptor->SetDescription("Perform optical calibration TOA/TOC(Top Of Atmosphere/Top Of Canopy). Output image is in milli-reflectance.");
  descriptor->AddInputImage();
  descriptor->AddOutputImage();
  descriptor->AddOptionNParams("Level",
                               "Level of calibration TOA(Top Of Atmosphere) or TOC(Top Of Canopy) (default is TOA)",
                               "level", false, otb::ApplicationDescriptor::String);
  descriptor->AddOption("RelativeSpectralResponseFile","Sensor relative spectral response file(by default the application gets these informations in the metadata)","rsr", 1, false, otb::ApplicationDescriptor::FileName);
  descriptor->AddOption("AerosolModel","AerosolModel: NO_AEROSOL(0), CONTINENTAL(1), MARITIME(2), URBAN(3), DESERTIC(5); default 0","aerosol", 1, false, otb::ApplicationDescriptor::Integer);
  descriptor->AddOption("OzoneAmount","Amount of Ozone ","oz", 1, false, otb::ApplicationDescriptor::Real);
  descriptor->AddOption("WaterVaporAmount","WaterVaporAmount ","wa", 1, false, otb::ApplicationDescriptor::Real);
  descriptor->AddOption("AtmosphericPressure","Atmospheric pressure ","atmo", 1, false, otb::ApplicationDescriptor::Real);
  descriptor->AddOption("AerosolOptical","AerosolOptical ","opt", 1, false, otb::ApplicationDescriptor::Real);
  descriptor->AddOption("AeronetFile","Aeronet file to get atmospheric parameters","aeronet", 1, false, otb::ApplicationDescriptor::FileName);
  descriptor->AddOption("AvailableMemory","Set the maximum of available memory for the pipeline execution in mega bytes (optional, 256 by default)","ram", 1, false, otb::ApplicationDescriptor::Integer);
  return EXIT_SUCCESS;
}

int OpticalCalibration::Execute(otb::ApplicationOptionsResult* parseResult)
{
  typedef otb::VectorImage<unsigned short int, 2>       ImageType;
  typedef otb::VectorImage<float, 2>                     FloatImageType;
  typedef otb::ImageFileReader<ImageType>               ReaderType;
  typedef otb::StreamingImageFileWriter<ImageType>      WriterType;

  typedef ImageToLuminanceImageFilter<ImageType, FloatImageType> ImageToLuminanceImageFilterType;
  typedef LuminanceToReflectanceImageFilter<FloatImageType,
      FloatImageType>                      LuminanceToReflectanceImageFilterType;
  typedef otb::MultiplyByScalarImageFilter<FloatImageType, ImageType> ScaleFilterType;
  typedef ReflectanceToSurfaceReflectanceImageFilter<FloatImageType,
      FloatImageType>             ReflectanceToSurfaceReflectanceImageFilterType;
  typedef ReflectanceToSurfaceReflectanceImageFilterType::FilterFunctionValuesType  FilterFunctionValuesType;
  typedef FilterFunctionValuesType::ValuesVectorType                                ValuesVectorType;
  typedef AtmosphericCorrectionParameters AtmosphericCorrectionParametersType;
  typedef AtmosphericCorrectionParametersType::AerosolModelType AerosolModelType;

  // Read input image information
  ReaderType::Pointer reader=ReaderType::New();
  reader->SetFileName(parseResult->GetInputImage().c_str());
  reader->GenerateOutputInformation();

  //Check if valid metadata informations are available to compute ImageToLuminance and LuminanceToReflectance
  itk::MetaDataDictionary             dict = reader->GetOutput()->GetMetaDataDictionary();
  OpticalImageMetadataInterface::Pointer lImageMetadataInterface = OpticalImageMetadataInterfaceFactory::CreateIMI(dict);
  // Test if needed data are available.
  try
  {
    // ImageToLuminance
    lImageMetadataInterface->GetPhysicalGain();
    lImageMetadataInterface->GetPhysicalBias();

    // LuminanceToReflectance
    lImageMetadataInterface->GetDay();
    lImageMetadataInterface->GetMonth();

    lImageMetadataInterface->GetSolarIrradiance();
    lImageMetadataInterface->GetSunElevation();

  }
  catch (itk::ExceptionObject& err)
  {
    std::cout << "Invalid input image medadata. The parsing returns the following error:\n" << std::endl;
    return EXIT_FAILURE;
  }

  ImageToLuminanceImageFilterType ::Pointer imageToLuminanceFilter                = ImageToLuminanceImageFilterType::New();
  LuminanceToReflectanceImageFilterType::Pointer luminanceToReflectanceFilter          = LuminanceToReflectanceImageFilterType::New();
  ReflectanceToSurfaceReflectanceImageFilterType::Pointer reflectanceToSurfaceReflectanceFilter = ReflectanceToSurfaceReflectanceImageFilterType::New();

  imageToLuminanceFilter->SetInput(reader->GetOutput());
  luminanceToReflectanceFilter->SetInput(imageToLuminanceFilter->GetOutput());
  reflectanceToSurfaceReflectanceFilter->SetInput(luminanceToReflectanceFilter->GetOutput());

  ScaleFilterType::Pointer scaleFilter = ScaleFilterType::New();
  scaleFilter->SetCoef(1000.);

  if(parseResult->GetParameterString("Level") == "toc")
    {
    AtmosphericCorrectionParametersType::Pointer atmosphericParam = reflectanceToSurfaceReflectanceFilter->GetCorrectionParameters();

    AerosolModelType aeroMod = AtmosphericCorrectionParametersType::NO_AEROSOL;

    if(parseResult->IsOptionPresent("AerosolModel"))
      {
      aeroMod = static_cast<AerosolModelType>(parseResult->GetParameterUInt("AerosolModel"));
      }
    atmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(aeroMod));

    double ozoneAmount = 0.;
    double waterVaporAmount = 2.5;
    double atmosphericPressure = 1030.;
    double aerosolOptical = 0.2;

    if (parseResult->IsOptionPresent("OzoneAmount"))
      {
      ozoneAmount = parseResult->GetParameterFloat("OzoneAmount");
      }
    atmosphericParam->SetOzoneAmount(ozoneAmount);

    if (parseResult->IsOptionPresent("WaterVaporAmount"))
      {
      waterVaporAmount = parseResult->GetParameterFloat("WaterVaporAmount");
      }
    atmosphericParam->SetWaterVaporAmount(waterVaporAmount);

    if (parseResult->IsOptionPresent("AtmosphericPressure"))
      {
      atmosphericPressure = parseResult->GetParameterFloat("AtmosphericPressure");
      }
    atmosphericParam->SetAtmosphericPressure(atmosphericPressure);

    if (parseResult->IsOptionPresent("AerosolOptical"))
      {
      aerosolOptical = parseResult->GetParameterFloat("AerosolOptical");
      }
    atmosphericParam->SetAerosolOptical(aerosolOptical);

    if (parseResult->IsOptionPresent("RelativeSpectralResponseFile"))
      {
      reflectanceToSurfaceReflectanceFilter->SetFilterFunctionValuesFileName(parseResult->GetParameterString("RelativeSpectralResponseFile", 0));
      }
    else
      {
      atmosphericParam->SetWavelengthSpectralBand(lImageMetadataInterface->GetSpectralSensitivity());
      }

    if (parseResult->IsOptionPresent("AeronetFile"))
      {
      reflectanceToSurfaceReflectanceFilter->SetAeronetFileName(parseResult->GetParameterString("AeronetFile", 0));
      }

    AtmosphericRadiativeTerms::Pointer radTerms = AtmosphericRadiativeTerms::New();
    radTerms->ValuesInitialization(reader->GetOutput()->GetNumberOfComponentsPerPixel());
    reflectanceToSurfaceReflectanceFilter->SetAtmosphericRadiativeTerms(radTerms);

    reflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(true);
    reflectanceToSurfaceReflectanceFilter->GenerateAtmosphericRadiativeTerms();
    reflectanceToSurfaceReflectanceFilter->GenerateParameters();
    reflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false);

    //rescale the surface reflectance in milli-reflectance
    scaleFilter->SetInput(reflectanceToSurfaceReflectanceFilter->GetOutput());
    }
  else
    {
    //Rescale luminanceToReflectance filter output (TOA level)
    scaleFilter->SetInput(luminanceToReflectanceFilter->GetOutput());
    }

  //Instantiate the writer
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(parseResult->GetOutputImage());
  writer->SetInput(scaleFilter->GetOutput());
  writer->SetWriteGeomFile(true);

  unsigned int ram = 256;
  if (parseResult->IsOptionPresent("AvailableMemory"))
    {
    ram = parseResult->GetParameterUInt("AvailableMemory");
    }
  writer->SetAutomaticTiledStreaming(ram);

  otb::StandardWriterWatcher watcher(writer,"OpticalCalibration");
  writer->Update();

  return EXIT_SUCCESS;
}
}
<commit_msg>WRG: unused variable<commit_after>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/

#include "otbOpticalCalibration.h"

#include <iostream>

#include "otbVectorImage.h"
#include "otbImageFileReader.h"

#include "otbImageToLuminanceImageFilter.h"
#include "otbLuminanceToReflectanceImageFilter.h"
#include "otbReflectanceToSurfaceReflectanceImageFilter.h"

#include "otbStreamingImageFileWriter.h"
#include "otbStandardWriterWatcher.h"
#include "otbMultiplyByScalarImageFilter.h"

namespace otb
{

int OpticalCalibration::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("OpticalCalibration");
  descriptor->SetDescription("Perform optical calibration TOA/TOC(Top Of Atmosphere/Top Of Canopy). Output image is in milli-reflectance.");
  descriptor->AddInputImage();
  descriptor->AddOutputImage();
  descriptor->AddOptionNParams("Level",
                               "Level of calibration TOA(Top Of Atmosphere) or TOC(Top Of Canopy) (default is TOA)",
                               "level", false, otb::ApplicationDescriptor::String);
  descriptor->AddOption("RelativeSpectralResponseFile","Sensor relative spectral response file(by default the application gets these informations in the metadata)","rsr", 1, false, otb::ApplicationDescriptor::FileName);
  descriptor->AddOption("AerosolModel","AerosolModel: NO_AEROSOL(0), CONTINENTAL(1), MARITIME(2), URBAN(3), DESERTIC(5); default 0","aerosol", 1, false, otb::ApplicationDescriptor::Integer);
  descriptor->AddOption("OzoneAmount","Amount of Ozone ","oz", 1, false, otb::ApplicationDescriptor::Real);
  descriptor->AddOption("WaterVaporAmount","WaterVaporAmount ","wa", 1, false, otb::ApplicationDescriptor::Real);
  descriptor->AddOption("AtmosphericPressure","Atmospheric pressure ","atmo", 1, false, otb::ApplicationDescriptor::Real);
  descriptor->AddOption("AerosolOptical","AerosolOptical ","opt", 1, false, otb::ApplicationDescriptor::Real);
  descriptor->AddOption("AeronetFile","Aeronet file to get atmospheric parameters","aeronet", 1, false, otb::ApplicationDescriptor::FileName);
  descriptor->AddOption("AvailableMemory","Set the maximum of available memory for the pipeline execution in mega bytes (optional, 256 by default)","ram", 1, false, otb::ApplicationDescriptor::Integer);
  return EXIT_SUCCESS;
}

int OpticalCalibration::Execute(otb::ApplicationOptionsResult* parseResult)
{
  typedef otb::VectorImage<unsigned short int, 2>       ImageType;
  typedef otb::VectorImage<float, 2>                     FloatImageType;
  typedef otb::ImageFileReader<ImageType>               ReaderType;
  typedef otb::StreamingImageFileWriter<ImageType>      WriterType;

  typedef ImageToLuminanceImageFilter<ImageType, FloatImageType> ImageToLuminanceImageFilterType;
  typedef LuminanceToReflectanceImageFilter<FloatImageType,
      FloatImageType>                      LuminanceToReflectanceImageFilterType;
  typedef otb::MultiplyByScalarImageFilter<FloatImageType, ImageType> ScaleFilterType;
  typedef ReflectanceToSurfaceReflectanceImageFilter<FloatImageType,
      FloatImageType>             ReflectanceToSurfaceReflectanceImageFilterType;
  typedef ReflectanceToSurfaceReflectanceImageFilterType::FilterFunctionValuesType  FilterFunctionValuesType;
  typedef FilterFunctionValuesType::ValuesVectorType                                ValuesVectorType;
  typedef AtmosphericCorrectionParameters AtmosphericCorrectionParametersType;
  typedef AtmosphericCorrectionParametersType::AerosolModelType AerosolModelType;

  // Read input image information
  ReaderType::Pointer reader=ReaderType::New();
  reader->SetFileName(parseResult->GetInputImage().c_str());
  reader->GenerateOutputInformation();

  //Check if valid metadata informations are available to compute ImageToLuminance and LuminanceToReflectance
  itk::MetaDataDictionary             dict = reader->GetOutput()->GetMetaDataDictionary();
  OpticalImageMetadataInterface::Pointer lImageMetadataInterface = OpticalImageMetadataInterfaceFactory::CreateIMI(dict);
  // Test if needed data are available.
  try
  {
    // ImageToLuminance
    lImageMetadataInterface->GetPhysicalGain();
    lImageMetadataInterface->GetPhysicalBias();

    // LuminanceToReflectance
    lImageMetadataInterface->GetDay();
    lImageMetadataInterface->GetMonth();

    lImageMetadataInterface->GetSolarIrradiance();
    lImageMetadataInterface->GetSunElevation();

  }
  catch (itk::ExceptionObject& err)
  {
    std::cout << "Invalid input image medadata. The parsing returns the following error:\n" << err << std::endl;
    return EXIT_FAILURE;
  }

  ImageToLuminanceImageFilterType ::Pointer imageToLuminanceFilter                = ImageToLuminanceImageFilterType::New();
  LuminanceToReflectanceImageFilterType::Pointer luminanceToReflectanceFilter          = LuminanceToReflectanceImageFilterType::New();
  ReflectanceToSurfaceReflectanceImageFilterType::Pointer reflectanceToSurfaceReflectanceFilter = ReflectanceToSurfaceReflectanceImageFilterType::New();

  imageToLuminanceFilter->SetInput(reader->GetOutput());
  luminanceToReflectanceFilter->SetInput(imageToLuminanceFilter->GetOutput());
  reflectanceToSurfaceReflectanceFilter->SetInput(luminanceToReflectanceFilter->GetOutput());

  ScaleFilterType::Pointer scaleFilter = ScaleFilterType::New();
  scaleFilter->SetCoef(1000.);

  if(parseResult->GetParameterString("Level") == "toc")
    {
    AtmosphericCorrectionParametersType::Pointer atmosphericParam = reflectanceToSurfaceReflectanceFilter->GetCorrectionParameters();

    AerosolModelType aeroMod = AtmosphericCorrectionParametersType::NO_AEROSOL;

    if(parseResult->IsOptionPresent("AerosolModel"))
      {
      aeroMod = static_cast<AerosolModelType>(parseResult->GetParameterUInt("AerosolModel"));
      }
    atmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(aeroMod));

    double ozoneAmount = 0.;
    double waterVaporAmount = 2.5;
    double atmosphericPressure = 1030.;
    double aerosolOptical = 0.2;

    if (parseResult->IsOptionPresent("OzoneAmount"))
      {
      ozoneAmount = parseResult->GetParameterFloat("OzoneAmount");
      }
    atmosphericParam->SetOzoneAmount(ozoneAmount);

    if (parseResult->IsOptionPresent("WaterVaporAmount"))
      {
      waterVaporAmount = parseResult->GetParameterFloat("WaterVaporAmount");
      }
    atmosphericParam->SetWaterVaporAmount(waterVaporAmount);

    if (parseResult->IsOptionPresent("AtmosphericPressure"))
      {
      atmosphericPressure = parseResult->GetParameterFloat("AtmosphericPressure");
      }
    atmosphericParam->SetAtmosphericPressure(atmosphericPressure);

    if (parseResult->IsOptionPresent("AerosolOptical"))
      {
      aerosolOptical = parseResult->GetParameterFloat("AerosolOptical");
      }
    atmosphericParam->SetAerosolOptical(aerosolOptical);

    if (parseResult->IsOptionPresent("RelativeSpectralResponseFile"))
      {
      reflectanceToSurfaceReflectanceFilter->SetFilterFunctionValuesFileName(parseResult->GetParameterString("RelativeSpectralResponseFile", 0));
      }
    else
      {
      atmosphericParam->SetWavelengthSpectralBand(lImageMetadataInterface->GetSpectralSensitivity());
      }

    if (parseResult->IsOptionPresent("AeronetFile"))
      {
      reflectanceToSurfaceReflectanceFilter->SetAeronetFileName(parseResult->GetParameterString("AeronetFile", 0));
      }

    AtmosphericRadiativeTerms::Pointer radTerms = AtmosphericRadiativeTerms::New();
    radTerms->ValuesInitialization(reader->GetOutput()->GetNumberOfComponentsPerPixel());
    reflectanceToSurfaceReflectanceFilter->SetAtmosphericRadiativeTerms(radTerms);

    reflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(true);
    reflectanceToSurfaceReflectanceFilter->GenerateAtmosphericRadiativeTerms();
    reflectanceToSurfaceReflectanceFilter->GenerateParameters();
    reflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false);

    //rescale the surface reflectance in milli-reflectance
    scaleFilter->SetInput(reflectanceToSurfaceReflectanceFilter->GetOutput());
    }
  else
    {
    //Rescale luminanceToReflectance filter output (TOA level)
    scaleFilter->SetInput(luminanceToReflectanceFilter->GetOutput());
    }

  //Instantiate the writer
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(parseResult->GetOutputImage());
  writer->SetInput(scaleFilter->GetOutput());
  writer->SetWriteGeomFile(true);

  unsigned int ram = 256;
  if (parseResult->IsOptionPresent("AvailableMemory"))
    {
    ram = parseResult->GetParameterUInt("AvailableMemory");
    }
  writer->SetAutomaticTiledStreaming(ram);

  otb::StandardWriterWatcher watcher(writer,"OpticalCalibration");
  writer->Update();

  return EXIT_SUCCESS;
}
}
<|endoftext|>


<commit_before>#include "MS5837.h"
#include <Wire.h>

#define MS5837_ADDR               0x76
#define MS5837_RESET              0x1E
#define MS5837_ADC_READ           0x00
#define MS5837_PROM_READ          0xA0
#define MS5837_CONVERT_D1_8192    0x4A
#define MS5837_CONVERT_D2_8192    0x5A

MS5837::MS5837() {
	fluidDensity = 1029;
}

void MS5837::init() {
	// Reset the MS5837, per datasheet
	Wire.beginTransmission(MS5837_ADDR);
	Wire.write(MS5837_RESET);
	Wire.endTransmission();

	// Wait for reset to complete
	delay(10);

	// Read calibration values and CRC
	for ( uint8_t i = 0 ; i < 8 ; i++ ) {
		Wire.beginTransmission(MS5837_ADDR);
		Wire.write(MS5837_PROM_READ+i*2);
		Wire.endTransmission();

		Wire.requestFrom(MS5837_ADDR,2);
		C[i] = (Wire.read() << 8) | Wire.read();
	}

	// Verify that data is correct with CRC
	uint8_t crcRead = C[0] >> 12;
	uint8_t crcCalculated = crc4(C);

	if ( crcCalculated == crcRead ) {
		// Success
	} else {
		// Failure - try again?
	}
}

void MS5837::setFluidDensity(float density) {
	fluidDensity = density;
}

void MS5837::read() {
	// Request D1 conversion
	Wire.beginTransmission(MS5837_ADDR);
	Wire.write(MS5837_CONVERT_D1_8192);
	Wire.endTransmission();

	delay(20); // Max conversion time per datasheet

	Wire.beginTransmission(MS5837_ADDR);
	Wire.write(MS5837_ADC_READ);
	Wire.endTransmission();

 	Wire.requestFrom(MS5837_ADDR,3);
	D1 = 0;
	D1 = Wire.read();
	D1 = (D1 << 8) | Wire.read();
	D1 = (D1 << 8) | Wire.read();

	// Request D2 conversion
	Wire.beginTransmission(MS5837_ADDR);
	Wire.write(MS5837_CONVERT_D2_8192);
	Wire.endTransmission();

	delay(20); // Max conversion time per datasheet

	Wire.beginTransmission(MS5837_ADDR);
	Wire.write(MS5837_ADC_READ);
	Wire.endTransmission();

	Wire.requestFrom(MS5837_ADDR,3);
	D2 = 0;
	D2 = Wire.read();
	D2 = (D2 << 8) | Wire.read();
	D2 = (D2 << 8) | Wire.read();

	Serial.println("----");

	calculate();
}

void MS5837::readTestCase() {
	C[0] = 0;
	C[1] = 34982;
	C[2] = 36352;
	C[3] = 20328;
	C[4] = 22354;
	C[5] = 26646;
	C[6] = 26146;
	C[7] = 0;

	D1 = 4958179;
	D2 = 6815414;

	calculate();
}

void MS5837::calculate() {
	// Given C1-C6 and D1, D2, calculated TEMP and P
	// Do conversion first and then second order temp compensation

	int32_t dT;
	int64_t SENS;
	int64_t OFF;
	int32_t SENSi;
	int32_t OFFi;
	int32_t Ti;
	int64_t OFF2;
	int64_t SENS2;

	// Terms called
	dT = D2-uint32_t(C[5])*256l;
	SENS = int64_t(C[1])*32768l+(int64_t(C[3])*dT)/256l;
	OFF = int64_t(C[2])*65536l+(int64_t(C[4])*dT)/128l;

	//Temp and P conversion
	TEMP = 2000l+int64_t(dT)*C[6]/8388608LL;
	P = (D1*SENS/(2097152l)-OFF)/(8192l);

	//Second order compensation
	if((TEMP/100)<20){         //Low temp
		Ti = (3*int64_t(dT)*int64_t(dT))/8589934592l;
		OFFi = (3*(TEMP-2000)*(TEMP-2000))/2;
		SENSi = (5*(TEMP-2000)*(TEMP-2000))/8;
		if((TEMP/100)<-15){    //Very low temp
			OFFi = OFFi+7*(TEMP+1500l)*(TEMP+1500l);
			SENSi = SENSi+4*(TEMP+1500l)*(TEMP+1500l);
		}
	}
	else if((TEMP/100)>=20){    //High temp
		Ti = 2*(int64_t(dT)*int64_t(dT))/(137438953472l);
		OFFi = 1*((TEMP-2000)*(TEMP-2000))/16;
		SENSi = 0;
	}

	OFF2 = OFF-OFFi;           //Calculate pressure and temp second order
	SENS2 = SENS-SENSi;

	TEMP = (TEMP-Ti);
	P = (((D1*SENS2)/2097152l-OFF2)/8192l);
}

float MS5837::pressure(float conversion) {
	return P/10.0f*conversion;
}

float MS5837::temperature() {
	return TEMP/100.0f;
}

float MS5837::depth() {
	return (pressure(MS5837::Pa)-101300)/(fluidDensity*9.80665);
}

float MS5837::altitude() {
	return 0.0f;
}

uint8_t MS5837::crc4(uint16_t n_prom[]) {
	uint16_t n_rem = 0;

	n_prom[0] = ((n_prom[0]) & 0x0FFF);
	n_prom[7] = 0;

	for ( uint8_t i = 0 ; i < 16; i++ ) {
		if ( i%2 == 1 ) {
			n_rem ^= (uint16_t)((n_prom[i>>1]) & 0x00FF0);
		} else {
			n_rem ^= (uint16_t)(n_prom[i>>1] >> 8);
		}
		for ( uint8_t n_bit = 8 ; n_bit > 0 ; n_bit-- ) {
			if ( n_rem & 0x8000 ) {
				n_rem = (n_rem << 1) ^ 0x3000;
			} else {
				n_rem = (n_rem << 1);
			}
		}
	}

	n_rem = ((n_rem >> 12) & 0x000F);

	return n_rem ^ 0x00;
}<commit_msg>Now functions, may need to edit second order compensation functions.<commit_after>#include "MS5837.h"
#include <Wire.h>

#define MS5837_ADDR               0x76
#define MS5837_RESET              0x1E
#define MS5837_ADC_READ           0x00
#define MS5837_PROM_READ          0xA0
#define MS5837_CONVERT_D1_8192    0x4A
#define MS5837_CONVERT_D2_8192    0x5A

MS5837::MS5837() {
	fluidDensity = 1029;
}

void MS5837::init() {
	// Reset the MS5837, per datasheet
	Wire.beginTransmission(MS5837_ADDR);
	Wire.write(MS5837_RESET);
	Wire.endTransmission();

	// Wait for reset to complete
	delay(10);

	// Read calibration values and CRC
	for ( uint8_t i = 0 ; i < 8 ; i++ ) {
		Wire.beginTransmission(MS5837_ADDR);
		Wire.write(MS5837_PROM_READ+i*2);
		Wire.endTransmission();

		Wire.requestFrom(MS5837_ADDR,2);
		C[i] = (Wire.read() << 8) | Wire.read();
	}

	// Verify that data is correct with CRC
	uint8_t crcRead = C[0] >> 12;
	uint8_t crcCalculated = crc4(C);

	if ( crcCalculated == crcRead ) {
		// Success
	} else {
		// Failure - try again?
	}
}

void MS5837::setFluidDensity(float density) {
	fluidDensity = density;
}

void MS5837::read() {
	// Request D1 conversion
	Wire.beginTransmission(MS5837_ADDR);
	Wire.write(MS5837_CONVERT_D1_8192);
	Wire.endTransmission();

	delay(20); // Max conversion time per datasheet

	Wire.beginTransmission(MS5837_ADDR);
	Wire.write(MS5837_ADC_READ);
	Wire.endTransmission();

 	Wire.requestFrom(MS5837_ADDR,3);
	D1 = 0;
	D1 = Wire.read();
	D1 = (D1 << 8) | Wire.read();
	D1 = (D1 << 8) | Wire.read();

	// Request D2 conversion
	Wire.beginTransmission(MS5837_ADDR);
	Wire.write(MS5837_CONVERT_D2_8192);
	Wire.endTransmission();

	delay(20); // Max conversion time per datasheet

	Wire.beginTransmission(MS5837_ADDR);
	Wire.write(MS5837_ADC_READ);
	Wire.endTransmission();

	Wire.requestFrom(MS5837_ADDR,3);
	D2 = 0;
	D2 = Wire.read();
	D2 = (D2 << 8) | Wire.read();
	D2 = (D2 << 8) | Wire.read();

	Serial.println("----");

	calculate();
}

void MS5837::readTestCase() {
	C[0] = 0;
	C[1] = 34982;
	C[2] = 36352;
	C[3] = 20328;
	C[4] = 22354;
	C[5] = 26646;
	C[6] = 26146;
	C[7] = 0;

	D1 = 4958179;
	D2 = 6815414;

	calculate();
}

void MS5837::calculate() {
	// Given C1-C6 and D1, D2, calculated TEMP and P
	// Do conversion first and then second order temp compensation

	int32_t dT;
	int64_t SENS;
	int64_t OFF;
	int32_t SENSi;
	int32_t OFFi;
	int32_t Ti;
	int64_t OFF2;
	int64_t SENS2;

	// Terms called
	dT = D2-uint32_t(C[5])*256l;
	SENS = int64_t(C[1])*32768l+(int64_t(C[3])*dT)/256l;
	OFF = int64_t(C[2])*65536l+(int64_t(C[4])*dT)/128l;

	//Temp and P conversion
	TEMP = 2000l+int64_t(dT)*C[6]/8388608LL;
	P = (D1*SENS/(2097152l)-OFF)/(8192l);

	//Second order compensation
	if((TEMP/100)<20){         //Low temp
		Ti = (3*int64_t(dT)*int64_t(dT))/(8589934592LL);
		OFFi = (3*(TEMP-2000)*(TEMP-2000))/2;
		SENSi = (5*(TEMP-2000)*(TEMP-2000))/8;
		if((TEMP/100)<-15){    //Very low temp
			OFFi = OFFi+7*(TEMP+1500l)*(TEMP+1500l);
			SENSi = SENSi+4*(TEMP+1500l)*(TEMP+1500l);
		}
	}
	else if((TEMP/100)>=20){    //High temp
		Ti = 2*(dT*dT)/(137438953472LL);
		OFFi = (1*(TEMP-2000)*(TEMP-2000))/16;
		SENSi = 0;
	}

	OFF2 = OFF-OFFi;           //Calculate pressure and temp second order
	SENS2 = SENS-SENSi;

	TEMP = (TEMP-Ti);
	P = (((D1*SENS2)/2097152l-OFF2)/8192l);
}

float MS5837::pressure(float conversion) {
	return P/10.0f*conversion;
}

float MS5837::temperature() {
	return TEMP/100.0f;
}

float MS5837::depth() {
	return (pressure(MS5837::Pa)-101300)/(fluidDensity*9.80665);
}

float MS5837::altitude() {
	return 0.0f;
}

uint8_t MS5837::crc4(uint16_t n_prom[]) {
	uint16_t n_rem = 0;

	n_prom[0] = ((n_prom[0]) & 0x0FFF);
	n_prom[7] = 0;

	for ( uint8_t i = 0 ; i < 16; i++ ) {
		if ( i%2 == 1 ) {
			n_rem ^= (uint16_t)((n_prom[i>>1]) & 0x00FF0);
		} else {
			n_rem ^= (uint16_t)(n_prom[i>>1] >> 8);
		}
		for ( uint8_t n_bit = 8 ; n_bit > 0 ; n_bit-- ) {
			if ( n_rem & 0x8000 ) {
				n_rem = (n_rem << 1) ^ 0x3000;
			} else {
				n_rem = (n_rem << 1);
			}
		}
	}

	n_rem = ((n_rem >> 12) & 0x000F);

	return n_rem ^ 0x00;
}<|endoftext|>


<commit_before>// STL
#include <sstream>
#include <fstream>
#include <string>
// CPPUNIT
#include <extracppunit/CppUnitCore.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
// Dsim
#include <dsim/DSIM_Types.hpp>
#include <dsim/DSIM_Service.hpp>
// Dsim Test Suite
#include <test/dsim/SimulationTestSuite.hpp>

// //////////////////////////////////////////////////////////////////////
// Test is based on ...
// //////////////////////////////////////////////////////////////////////

// //////////////////////////////////////////////////////////////////////
void SimulationTestSuite::simpleSimulationHelper() {

  try {

    // Schedule input file name
    const std::string lScheduleInputFilename ("../samples/schedule01.csv");

    // Demand input file name
    const stdair::Filename_T lDemandInputFilename ("../samples/demand01.csv");

    // Output log File
    const std::string lLogFilename ("SimulationTestSuite.log");

    // Set the log parameters
    std::ofstream logOutputFile;
    // Open and clean the log outputfile
    logOutputFile.open (lLogFilename.c_str());
    logOutputFile.clear();

    // Initialise the simulation context
    const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
    const stdair::BasDBParams lDBParams ("dsim", "dsim",
                                         "localhost", "3306",
                                         "sim_dsim");
    DSIM::DSIM_Service dsimService (lLogParams, lDBParams,
                                    lScheduleInputFilename,
                                    lDemandInputFilename);

    // Perform a simulation
    dsimService.simulate();

  } catch (const DSIM::RootException& otexp) {
    std::cerr << "Standard exception: " << otexp.what() << std::endl;
    return;

  } catch (const std::exception& stde) {
    std::cerr << "Standard exception: " << stde.what() << std::endl;
    return;

  } catch (...) {
    return;
  }

}

// //////////////////////////////////////////////////////////////////////
void SimulationTestSuite::simpleSimulation () {
  // TODO: Check that the simulation goes as expected
  CPPUNIT_ASSERT_NO_THROW ( simpleSimulationHelper(););
}

// //////////////////////////////////////////////////////////////////////
// void SimulationTestSuite::errorCase () {
//  CPPUNIT_ASSERT (false);
// }

// //////////////////////////////////////////////////////////////////////
SimulationTestSuite::SimulationTestSuite () {
  _describeKey << "Running test on simulation";
}

// /////////////// M A I N /////////////////
CPPUNIT_MAIN()

<commit_msg>[test] Adapted the test suite to the new interface.<commit_after>// STL
#include <sstream>
#include <fstream>
#include <string>
// CPPUNIT
#include <extracppunit/CppUnitCore.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
// Dsim
#include <dsim/DSIM_Types.hpp>
#include <dsim/DSIM_Service.hpp>
// Dsim Test Suite
#include <test/dsim/SimulationTestSuite.hpp>

// //////////////////////////////////////////////////////////////////////
// Test is based on ...
// //////////////////////////////////////////////////////////////////////

// //////////////////////////////////////////////////////////////////////
void SimulationTestSuite::simpleSimulationHelper() {

  try {

    // Schedule input file name
    const std::string lScheduleInputFilename ("../samples/schedule01.csv");

    // O&D input file name
    const std::string lODInputFilename ("../samples/ond01.csv");

    // Demand input file name
    const stdair::Filename_T lDemandInputFilename ("../samples/demand01.csv");

    // Fare input file name
    const stdair::Filename_T lFareInputFilename ("../samples/fare01.csv");

    // Output log File
    const std::string lLogFilename ("SimulationTestSuite.log");

    // Set the log parameters
    std::ofstream logOutputFile;
    // Open and clean the log outputfile
    logOutputFile.open (lLogFilename.c_str());
    logOutputFile.clear();

    // Initialise the simulation context
    const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
    const stdair::BasDBParams lDBParams ("dsim", "dsim",
                                         "localhost", "3306",
                                         "sim_dsim");
    DSIM::DSIM_Service dsimService (lLogParams, lDBParams,
                                    lScheduleInputFilename, lODInputFilename,
                                    lDemandInputFilename, lFareInputFilename);

    // Perform a simulation
    dsimService.simulate();

  } catch (const DSIM::RootException& otexp) {
    std::cerr << "Standard exception: " << otexp.what() << std::endl;
    return;

  } catch (const std::exception& stde) {
    std::cerr << "Standard exception: " << stde.what() << std::endl;
    return;

  } catch (...) {
    return;
  }

}

// //////////////////////////////////////////////////////////////////////
void SimulationTestSuite::simpleSimulation () {
  // TODO: Check that the simulation goes as expected
  CPPUNIT_ASSERT_NO_THROW ( simpleSimulationHelper(););
}

// //////////////////////////////////////////////////////////////////////
// void SimulationTestSuite::errorCase () {
//  CPPUNIT_ASSERT (false);
// }

// //////////////////////////////////////////////////////////////////////
SimulationTestSuite::SimulationTestSuite () {
  _describeKey << "Running test on simulation";
}

// /////////////// M A I N /////////////////
CPPUNIT_MAIN()

<|endoftext|>


<commit_before><commit_msg>Fixed VulkanTexture::copyBufferToImage for 2D texture arrays<commit_after><|endoftext|>


<commit_before>/* prefetch-2lev-IP.cpp: IP-based (PC) prefetcher [http://download.intel.com/technology/architecture/sma.pdf] */
/*
 * __COPYRIGHT__ GT
 */
#define COMPONENT_NAME "2lev-IP"
/*
  This has been modified from the original IP prefetcher to better handle the case
  when we have an access pattern similar to:

  Strides:
  X, 0, 0, 0, 0, X, 0, 0, 0 ...

  With our changes, the prefetcher does not update on the strides of 0, since
  strides of 0 are not interesting.

  Instead, it correctly prefetches a stride of X whenever it is seen, assuming
  X does not change.

  It is currently not really a two level prefetcher, but may be someday.
 */

#ifdef PREFETCH_PARSE_ARGS
if(!strcasecmp(COMPONENT_NAME,type))
{
  int num_entries;
  int last_addr_bits;
  int last_stride_bits;
  int last_prefetch_bits;
  if(sscanf(opt_string,"%*[^:]:%d:%d:%d:%d",&num_entries,&last_addr_bits,&last_stride_bits,&last_prefetch_bits) != 4)
    fatal("bad %s prefetcher options string %s (should be \"2lev-IP:num_entries:addr-bits:stride-bits:last-PF-bits\")",cp->name,opt_string);
  return new prefetch_2lev_IP_t(cp,num_entries,last_addr_bits,last_stride_bits,last_prefetch_bits);
}
#else

class prefetch_2lev_IP_t:public prefetch_t
{
  protected:
  int num_entries;
  int mask;

  int last_addr_bits;
  int last_stride_bits;
  int last_prefetch_bits;

  int last_addr_mask;
  int last_stride_mask;
  int last_prefetch_mask;

  struct prefetch_IP_table_t {
    md_paddr_t last_paddr;
    int last_stride;
    my2bc_t conf;
    md_paddr_t last_prefetch;
  } * table;

  public:
  /* CREATE */
  prefetch_2lev_IP_t(struct cache_t * arg_cp,
                int arg_num_entries,
                int arg_last_addr_bits,
                int arg_last_stride_bits,
                int arg_last_prefetch_bits)
  {
    init();

    char name[256]; /* just used for error checking macros */

    type = strdup("2lev-IP");
    if(!type)
      fatal("couldn't calloc IP-prefetch type (strdup)");

    cp = arg_cp;
    sprintf(name,"%s.%s",cp->name,type);

    CHECK_PPOW2(arg_num_entries);
    num_entries = arg_num_entries;
    mask = num_entries - 1;

    last_addr_bits = arg_last_addr_bits;
    last_stride_bits = arg_last_stride_bits;
    last_prefetch_bits = arg_last_prefetch_bits;

    last_addr_mask = (1<<last_addr_bits)-1;
    last_stride_mask = (1<<last_stride_bits)-1;
    last_prefetch_mask = (1<<last_prefetch_bits)-1;

    table = (struct prefetch_2lev_IP_t::prefetch_IP_table_t*) calloc(num_entries,sizeof(*table));
    if(!table)
      fatal("couldn't calloc IP-prefetch table");

    bits = num_entries * (last_addr_bits + last_stride_bits + last_prefetch_bits + 2);
    assert(arg_cp);
  }

  /* DESTROY */
  ~prefetch_2lev_IP_t()
  {
    free(table);
    table = NULL;
  }

  /* LOOKUP */
  PREFETCH_LOOKUP_HEADER
  {
    lookups++;

    int index = PC & mask;
    md_paddr_t pf_paddr = 0;

    /* train entry first */
    md_paddr_t last_paddr = (paddr&~last_addr_mask) | table[index].last_paddr;
    int this_stride = (paddr - last_paddr) & last_stride_mask;

    /* zero stride is just unuseful prefetches, don't update tables */
    if(this_stride == 0)
      return 0;

    if(this_stride == table[index].last_stride)
      MY2BC_UPDATE(table[index].conf,true);
    else
      table[index].conf = MY2BC_STRONG_NT;

    table[index].last_paddr = paddr&last_addr_mask;
    table[index].last_stride = this_stride;

    /* only make a prefetch if confident */
    if(table[index].conf == MY2BC_STRONG_TAKEN)
    {
      pf_paddr = paddr + this_stride;
      if((pf_paddr & last_prefetch_mask) == table[index].last_prefetch)
        pf_paddr = 0; /* don't keep prefetching the same thing */
      table[index].last_prefetch = pf_paddr & last_prefetch_mask;
    }

    return pf_paddr;
  }

  virtual md_paddr_t latest_lookup (const md_addr_t PC, const md_paddr_t paddr)
  {
    (void) paddr;

    int index = PC & mask;
    return table[index].last_stride + paddr;
  }
};

#endif /* PREFETCH_PARSE_ARGS */
#undef COMPONENT_NAME
<commit_msg>Implemented a different state machine for the prefetcher, which makes it more suitable for longer strides that cross page boundaries.  Comment in source points to the paper the prefetcher originated from.<commit_after>/* prefetch-2lev-IP.cpp: IP-based (PC) prefetcher [http://download.intel.com/technology/architecture/sma.pdf] */
/*
 * __COPYRIGHT__ GT
 */

#define COMPONENT_NAME "2lev-IP"
/*
  This has been modified from the original IP prefetcher to better handle the case
  when we have an access pattern similar to:

  Strides:
  X, 0, 0, 0, 0, X, 0, 0, 0 ...

  With our changes, the prefetcher does not update on the strides of 0, since
  strides of 0 are not interesting.

  Instead, it correctly prefetches a stride of X whenever it is seen, assuming
  X does not change.

  Also, we do not prefetch if we're going to cross a page boundary.

  It implements the state machine detailed in:
  Jean-Loup Baer and Tien-Fu Chen. 1995. Effective Hardware-Based Data Prefetching for High-Performance
  Processors. IEEE Trans. Comput. 44, 5 (May 1995), 609-623.

  It is currently not really a two level prefetcher, but may be someday.
 */

#ifdef PREFETCH_PARSE_ARGS
if(!strcasecmp(COMPONENT_NAME,type))
{
  int num_entries;
  int last_addr_bits;
  int last_stride_bits;
  if(sscanf(opt_string,"%*[^:]:%d:%d:%d:%d",&num_entries,&last_addr_bits,&last_stride_bits) != 3)
    fatal("bad %s prefetcher options string %s (should be \"2lev-IP:num_entries:addr-bits:stride-bits\")",cp->name,opt_string);
  return new prefetch_2lev_IP_t(cp,num_entries,last_addr_bits,last_stride_bits,last_prefetch_bits);
}
#else

class prefetch_2lev_IP_t:public prefetch_t
{
  protected:
  int num_entries;
  int mask;

  int last_addr_bits;
  int last_stride_bits;

  int last_addr_mask;
  int last_stride_mask;

  struct prefetch_IP_table_t {
    //    md_addr_t PC;
    md_paddr_t last_paddr;
    int last_stride;
    my2bc_t conf;
  } * table;

  public:
  /* CREATE */
  prefetch_2lev_IP_t(struct cache_t * arg_cp,
                int arg_num_entries,
                int arg_last_addr_bits,
                int arg_last_stride_bits,
                int arg_last_prefetch_bits)
  {
    init();

    char name[256]; /* just used for error checking macros */

    type = strdup("2lev-IP");
    if(!type)
      fatal("couldn't calloc IP-prefetch type (strdup)");

    cp = arg_cp;
    sprintf(name,"%s.%s",cp->name,type);

    CHECK_PPOW2(arg_num_entries);
    num_entries = arg_num_entries;
    mask = num_entries - 1;

    last_addr_bits = arg_last_addr_bits;
    last_stride_bits = arg_last_stride_bits;

    last_addr_mask = (1<<last_addr_bits)-1;
    last_stride_mask = (1<<last_stride_bits)-1;

    table = (struct prefetch_2lev_IP_t::prefetch_IP_table_t*) calloc(num_entries,sizeof(*table));
    if(!table)
      fatal("couldn't calloc IP-prefetch table");

    bits = num_entries * (last_addr_bits + last_stride_bits + 2);
    assert(arg_cp);
  }

  /* DESTROY */
  ~prefetch_2lev_IP_t()
  {
    free(table);
    table = NULL;
  }

  /* LOOKUP */
  PREFETCH_LOOKUP_HEADER
{
    lookups++;

    int index = PC & mask;
    md_paddr_t pf_paddr = 0;

    // If want to use tags for table
    /*    if(table[index].PC != PC) {
      table[index].last_paddr = paddr&last_addr_mask;
      table[index].last_stride = 0;
      table[index].conf = MY2BC_WEAKLY_TAKEN;
      table[index].PC = PC;
      return 0;
      }*/

    /* train entry first */
    md_paddr_t last_paddr = (paddr&~last_addr_mask) | table[index].last_paddr;
    int this_stride = (paddr - last_paddr) & last_stride_mask;

    /* zero stride is just unuseful prefetches, don't update tables */
    if(this_stride == 0) {
      return 0;
    }

    table[index].last_paddr = paddr&last_addr_mask;
    if(table[index].conf != MY2BC_STRONG_TAKEN) {
      table[index].last_stride = this_stride;
    }

    bool is_correct = (this_stride == table[index].last_stride);

    if(table[index].conf == MY2BC_WEAKLY_NT && is_correct) {
      table[index].conf = MY2BC_STRONG_TAKEN;
    }
    else {
      MY2BC_UPDATE(table[index].conf, is_correct);
    }

    if((table[index].conf != MY2BC_STRONG_NT)) {
      pf_paddr = paddr + table[index].last_stride;

      // If going to cross page boundary, don't prefetch
      int page_mask = ~((1 << PAGE_SHIFT) - 1);
      if((pf_paddr & page_mask) != (paddr & page_mask)) {
	return 0;
      }
    }
    return pf_paddr;
  }

  virtual md_paddr_t latest_lookup (const md_addr_t PC, const md_paddr_t paddr)
  {
    (void) paddr;

    int index = PC & mask;
    return table[index].last_stride + paddr;
  }
};

#endif /* PREFETCH_PARSE_ARGS */
#undef COMPONENT_NAME
<|endoftext|>


<commit_before>/* Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html */
#include "coffer.hh"
#include "containerimpl.hh"
#include "factory.hh"
#include "../rcore/rsvg/svg.hh"

namespace Rapicorn {

class CofferImpl : public virtual Coffer, public virtual SingleContainerImpl {
  String        m_element;
  Svg::Element  m_sel;
  bool          m_overlap_child;
protected:
  virtual void          size_request    (Requisition &requisition);
  virtual void          size_allocate   (Allocation area);
  virtual void          do_invalidate   ();
public:
  explicit              CofferImpl      ();
  virtual              ~CofferImpl      ();
  virtual String        element         () const                { return m_element; }
  virtual void          element         (const String &id)      { m_element = id; invalidate(); }
  virtual bool          overlap_child   () const                { return m_overlap_child; }
  virtual void          overlap_child   (bool overlap)          { m_overlap_child = overlap; invalidate(); }
};

const PropertyList&
Coffer::list_properties()
{
  static Property *properties[] = {
    MakeProperty (Coffer, element,        _("Element"),         _("The SVG element ID to be rendered."), "rw"),
    MakeProperty (Coffer, overlap_child,  _("Overlap Child"),   _("Draw child on top of container area."), "rw"),
  };
  static const PropertyList property_list (properties, Container::list_properties());
  return property_list;
}

CofferImpl::CofferImpl() :
  m_overlap_child (false)
{}

CofferImpl::~CofferImpl()
{}

void
CofferImpl::size_request (Requisition &requisition)
{
  SingleContainerImpl::size_request (requisition);
  int thickness = 2; // FIXME: use real border marks
  if (!m_overlap_child)
    {
      requisition.width += 2 * thickness;
      requisition.height += 2 * thickness;
    }
}

void
CofferImpl::size_allocate (Allocation area)
{
  Allocation carea = area;
  if (has_allocatable_child() && !m_overlap_child)
    {
      int thickness = 2; // FIXME: use real border marks
      carea.x += thickness;
      carea.y += thickness;
      carea.width -= 2 * thickness;
      carea.height -= 2 * thickness;
    }
  SingleContainerImpl::size_allocate (carea);
  allocation (area);
}

void
CofferImpl::do_invalidate()
{
  if (m_element.empty())
    {
      m_sel = m_sel.none();
      return;
    }
  Svg::Element e = Svg::Library::lookup_element (m_element);
  if (e.is_null())
    return;
  m_sel = e;
}

static const ItemFactory<CofferImpl> coffer_factory ("Rapicorn::Factory::Coffer");

} // Rapicorn
<commit_msg>UI: made Coffer render SVG element using pixel scaling<commit_after>/* Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html */
#include "coffer.hh"
#include "containerimpl.hh"
#include "factory.hh"
#include "../rcore/rsvg/svg.hh"
#include <string.h>

#define CHECK_CAIRO_STATUS(status)      do {    \
  cairo_status_t ___s = (status);               \
  if (___s != CAIRO_STATUS_SUCCESS)             \
    RAPICORN_LOG (DIAG, "%s: %s", #status, cairo_status_to_string (___s)); \
  } while (0)

namespace Rapicorn {

class CofferImpl : public virtual Coffer, public virtual SingleContainerImpl {
  String        m_element;
  Svg::Element  m_sel;
  bool          m_overlap_child;
protected:
  virtual void          size_request    (Requisition &requisition);
  virtual void          size_allocate   (Allocation area);
  virtual void          do_invalidate   ();
  virtual void          render          (Display &display);
public:
  explicit              CofferImpl      ();
  virtual              ~CofferImpl      ();
  virtual String        element         () const                { return m_element; }
  virtual void          element         (const String &id)      { m_element = id; invalidate(); }
  virtual bool          overlap_child   () const                { return m_overlap_child; }
  virtual void          overlap_child   (bool overlap)          { m_overlap_child = overlap; invalidate(); }
};

const PropertyList&
Coffer::list_properties()
{
  static Property *properties[] = {
    MakeProperty (Coffer, element,        _("Element"),         _("The SVG element ID to be rendered."), "rw"),
    MakeProperty (Coffer, overlap_child,  _("Overlap Child"),   _("Draw child on top of container area."), "rw"),
  };
  static const PropertyList property_list (properties, Container::list_properties());
  return property_list;
}

CofferImpl::CofferImpl() :
  m_overlap_child (false)
{}

CofferImpl::~CofferImpl()
{}

void
CofferImpl::do_invalidate()
{
  if (m_element.empty())
    {
      m_sel = m_sel.none();
      return;
    }
  Svg::Element e = Svg::Library::lookup_element (m_element);
  if (e.is_null())
    return;
  m_sel = e;
}

void
CofferImpl::size_request (Requisition &requisition)
{
  SingleContainerImpl::size_request (requisition);
  if (m_sel)
    {
      requisition.width = m_sel.allocation().width;
      requisition.height = m_sel.allocation().height;
      int thickness = 2; // FIXME: use real border marks
      if (!m_overlap_child)
        {
          requisition.width += 2 * thickness;
          requisition.height += 2 * thickness;
        }
    }
}

void
CofferImpl::size_allocate (Allocation area)
{
  Allocation carea = area;
  if (has_allocatable_child() && !m_overlap_child)
    {
      int thickness = 2; // FIXME: use real border marks
      carea.x += thickness;
      carea.y += thickness;
      carea.width -= 2 * thickness;
      carea.height -= 2 * thickness;
    }
  SingleContainerImpl::size_allocate (carea);
  allocation (area);
}

void
CofferImpl::render (Display &display)
{
  Allocation area = allocation();
  if (m_sel)
    {
      Svg::Allocation a = m_sel.allocation();
      uint8 *pixels = new uint8[int (a.width * a.height * 4)];
      memset (pixels, 0, a.width * a.height * 4);
      cairo_surface_t *surface = cairo_image_surface_create_for_data (pixels, CAIRO_FORMAT_ARGB32, a.width, a.height, 4 * a.width);
      CHECK_CAIRO_STATUS (cairo_surface_status (surface));
      bool rendered = m_sel.render (surface, Svg::Allocation (0, 0, a.width, a.height));
      if (rendered)
        {
          cairo_t *cr = display.create_cairo ();
          cairo_set_source_surface (cr, surface, 0, 0); // (x,y) are set in the matrix below
          cairo_matrix_t matrix;
          cairo_matrix_init_identity (&matrix);
          double sx = a.width / area.width;
          double sy = a.height / area.height;
          cairo_matrix_translate (&matrix, -area.x * sx, (area.y + area.height) * sy); // -x, y + height
          cairo_matrix_scale (&matrix, sx, -sy);
          cairo_pattern_set_matrix (cairo_get_source (cr), &matrix);
          cairo_paint (cr);
        }
      else
        warning ("Failed to render SVG element: %s", m_element.c_str());
      cairo_surface_destroy (surface);
      delete[] pixels;
    }
  SingleContainerImpl::render (display);
}

static const ItemFactory<CofferImpl> coffer_factory ("Rapicorn::Factory::Coffer");

} // Rapicorn
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
**************************************************************************/

#include "cppquickopenfilter.h"
#include "cppmodelmanager.h"

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>

using namespace CppTools::Internal;

CppQuickOpenFilter::CppQuickOpenFilter(CppModelManager *manager, Core::EditorManager *editorManager)
    : m_manager(manager),
    m_editorManager(editorManager),
    m_forceNewSearchList(true)
{
    setShortcutString(":");
    setIncludedByDefault(false);

    connect(manager, SIGNAL(documentUpdated(CPlusPlus::Document::Ptr)),
            this, SLOT(onDocumentUpdated(CPlusPlus::Document::Ptr)));

    connect(manager, SIGNAL(aboutToRemoveFiles(QStringList)),
            this, SLOT(onAboutToRemoveFiles(QStringList)));
}

CppQuickOpenFilter::~CppQuickOpenFilter()
{ }

void CppQuickOpenFilter::onDocumentUpdated(CPlusPlus::Document::Ptr doc)
{
    m_searchList[doc->fileName()] = Info(doc);
}

void CppQuickOpenFilter::onAboutToRemoveFiles(const QStringList &files)
{
    foreach (const QString &file, files)
        m_searchList.remove(file);
}

void CppQuickOpenFilter::refresh(QFutureInterface<void> &future)
{
    Q_UNUSED(future);
}

static bool compareLexigraphically(const QuickOpen::FilterEntry &a,
                                   const QuickOpen::FilterEntry &b)
{
    return a.displayName < b.displayName;
}

QList<QuickOpen::FilterEntry> CppQuickOpenFilter::matchesFor(const QString &origEntry)
{
    QString entry = trimWildcards(origEntry);
    QList<QuickOpen::FilterEntry> goodEntries;
    QList<QuickOpen::FilterEntry> betterEntries;
    QStringMatcher matcher(entry, Qt::CaseInsensitive);
    const QRegExp regexp("*"+entry+"*", Qt::CaseInsensitive, QRegExp::Wildcard);
    if (!regexp.isValid())
        return goodEntries;
    bool hasWildcard = (entry.contains('*') || entry.contains('?'));

    QMutableMapIterator<QString, Info> it(m_searchList);
    while (it.hasNext()) {
        it.next();

        Info info = it.value();
        if (info.dirty) {
            info.dirty = false;
            info.items = search(info.doc);
            it.setValue(info);
        }

        QList<ModelItemInfo> items = info.items;

        foreach (ModelItemInfo info, items) {
            if ((hasWildcard && regexp.exactMatch(info.symbolName))
                    || (!hasWildcard && matcher.indexIn(info.symbolName) != -1)) {
                QVariant id = qVariantFromValue(info);
                QuickOpen::FilterEntry filterEntry(this, info.symbolName, id, info.icon);
                filterEntry.extraInfo = info.symbolType;
                if (info.symbolName.startsWith(entry))
                    betterEntries.append(filterEntry);
                else
                    goodEntries.append(filterEntry);
            }
        }
    }

    if (goodEntries.size() < 1000)
        qSort(goodEntries.begin(), goodEntries.end(), compareLexigraphically);
    if (betterEntries.size() < 1000)
        qSort(betterEntries.begin(), betterEntries.end(), compareLexigraphically);

    betterEntries += goodEntries;
    return betterEntries;
}

void CppQuickOpenFilter::accept(QuickOpen::FilterEntry selection) const
{
    ModelItemInfo info = qvariant_cast<CppTools::Internal::ModelItemInfo>(selection.internalData);
    TextEditor::BaseTextEditor::openEditorAt(info.fileName, info.line);
}
<commit_msg>Show the filename of a symbol if it doesn't have additional type info<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
**************************************************************************/

#include "cppquickopenfilter.h"
#include "cppmodelmanager.h"

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>

using namespace CppTools::Internal;

CppQuickOpenFilter::CppQuickOpenFilter(CppModelManager *manager, Core::EditorManager *editorManager)
    : m_manager(manager),
    m_editorManager(editorManager),
    m_forceNewSearchList(true)
{
    setShortcutString(":");
    setIncludedByDefault(false);

    connect(manager, SIGNAL(documentUpdated(CPlusPlus::Document::Ptr)),
            this, SLOT(onDocumentUpdated(CPlusPlus::Document::Ptr)));

    connect(manager, SIGNAL(aboutToRemoveFiles(QStringList)),
            this, SLOT(onAboutToRemoveFiles(QStringList)));
}

CppQuickOpenFilter::~CppQuickOpenFilter()
{ }

void CppQuickOpenFilter::onDocumentUpdated(CPlusPlus::Document::Ptr doc)
{
    m_searchList[doc->fileName()] = Info(doc);
}

void CppQuickOpenFilter::onAboutToRemoveFiles(const QStringList &files)
{
    foreach (const QString &file, files)
        m_searchList.remove(file);
}

void CppQuickOpenFilter::refresh(QFutureInterface<void> &future)
{
    Q_UNUSED(future);
}

static bool compareLexigraphically(const QuickOpen::FilterEntry &a,
                                   const QuickOpen::FilterEntry &b)
{
    return a.displayName < b.displayName;
}

QList<QuickOpen::FilterEntry> CppQuickOpenFilter::matchesFor(const QString &origEntry)
{
    QString entry = trimWildcards(origEntry);
    QList<QuickOpen::FilterEntry> goodEntries;
    QList<QuickOpen::FilterEntry> betterEntries;
    QStringMatcher matcher(entry, Qt::CaseInsensitive);
    const QRegExp regexp("*"+entry+"*", Qt::CaseInsensitive, QRegExp::Wildcard);
    if (!regexp.isValid())
        return goodEntries;
    bool hasWildcard = (entry.contains('*') || entry.contains('?'));

    QMutableMapIterator<QString, Info> it(m_searchList);
    while (it.hasNext()) {
        it.next();

        Info info = it.value();
        if (info.dirty) {
            info.dirty = false;
            info.items = search(info.doc);
            it.setValue(info);
        }

        QList<ModelItemInfo> items = info.items;

        foreach (ModelItemInfo info, items) {
            if ((hasWildcard && regexp.exactMatch(info.symbolName))
                    || (!hasWildcard && matcher.indexIn(info.symbolName) != -1)) {

                QVariant id = qVariantFromValue(info);
                QuickOpen::FilterEntry filterEntry(this, info.symbolName, id, info.icon);
                if (! info.symbolType.isEmpty())
                    filterEntry.extraInfo = info.symbolType;
                else
                    filterEntry.extraInfo = info.fileName;

                if (info.symbolName.startsWith(entry))
                    betterEntries.append(filterEntry);
                else
                    goodEntries.append(filterEntry);
            }
        }
    }

    if (goodEntries.size() < 1000)
        qSort(goodEntries.begin(), goodEntries.end(), compareLexigraphically);
    if (betterEntries.size() < 1000)
        qSort(betterEntries.begin(), betterEntries.end(), compareLexigraphically);

    betterEntries += goodEntries;
    return betterEntries;
}

void CppQuickOpenFilter::accept(QuickOpen::FilterEntry selection) const
{
    ModelItemInfo info = qvariant_cast<CppTools::Internal::ModelItemInfo>(selection.internalData);
    TextEditor::BaseTextEditor::openEditorAt(info.fileName, info.line);
}
<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_ANALYTICAL_HH
#define DUNE_STUFF_ANALYTICAL_HH

#ifdef HAVE_CMAKE_CONFIG
 #include "cmake_config.h"
#else
 #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

#ifdef HAVE_DUNE_FEM

#include "timefunction.hh"

namespace Dune {
namespace Stuff {
namespace Fem {

template< class FunctionSpaceImp >
class ConstantFunction
  : public Dune::Fem::Function< FunctionSpaceImp, ConstantFunction< FunctionSpaceImp > >
{
public:
  typedef ConstantFunction< FunctionSpaceImp >
    ThisType;
  typedef Dune::Fem::Function< FunctionSpaceImp, ThisType >
    BaseType;
  typedef typename BaseType::DomainType
    DomainType;
  typedef typename BaseType::RangeType
    RangeType;

  ConstantFunction(const FunctionSpaceImp& /*space*/,
                   const double constant = 0.0)
    : constant_(RangeType(constant))
  {}
  explicit ConstantFunction(const double constant = 0.0)
    : constant_(RangeType(constant))
  {}
  explicit ConstantFunction(const RangeType& constant)
    : constant_(constant)
  {}

  ~ConstantFunction()
  {}

  inline void evaluate(const double /*time*/, const DomainType& /*arg*/, RangeType& ret) const {
    ret = constant_;
  }

  inline void evaluate(const DomainType& /*arg*/, RangeType& ret) const { ret = RangeType(constant_); }

  template< class IntersectionIteratorType >
  inline void evaluate(const double /*time*/, const DomainType& /*arg*/,
                       RangeType& ret, const IntersectionIteratorType /*it*/) const
  { ret = constant_; }

  //! this signature might be used by GRAPE
  inline void evaluate(const DomainType& /*arg*/,const typename RangeType::value_type /*time*/,  RangeType& ret) const {
    ret = constant_;
  }

  inline void evaluateJacobian(const DomainType& /*arg*/, typename BaseType::JacobianRangeType& jacobian) const {
    jacobian = typename BaseType::JacobianRangeType(0);
  }

private:
  const RangeType constant_;
};

template< class FunctionSpaceImp, class TimeProviderImp >
class ConstantFunctionTP
  : public TimeFunction< FunctionSpaceImp,
                               ConstantFunctionTP< FunctionSpaceImp, TimeProviderImp >, TimeProviderImp >
{
public:
  typedef ConstantFunctionTP< FunctionSpaceImp, TimeProviderImp >
    ThisType;
  typedef TimeFunction< FunctionSpaceImp, ThisType, TimeProviderImp >
    BaseType;
  typedef typename BaseType::DomainType
    DomainType;
  typedef typename BaseType::RangeType
    RangeType;

  ConstantFunctionTP(const TimeProviderImp& timeprovider,
                     const FunctionSpaceImp& space,
                     const double constant = 0.0)
    : BaseType(timeprovider, space)
      , constant_(constant)
  {}

  ~ConstantFunctionTP()
  {}

  void evaluateTime(const double /*time*/, const DomainType& /*arg*/, RangeType& ret) const { ret = RangeType(constant_); }

private:
  const double constant_;
};

template< class FunctionSpaceImp, class TimeProviderImp >
class ConstantIntersectionTimeFunction
  : public IntersectionTimeFunction< FunctionSpaceImp,
                                           ConstantIntersectionTimeFunction< FunctionSpaceImp,
                                                                             TimeProviderImp >, TimeProviderImp >
{
public:
  typedef ConstantIntersectionTimeFunction< FunctionSpaceImp, TimeProviderImp >
    ThisType;
  typedef IntersectionTimeFunction< FunctionSpaceImp, ThisType, TimeProviderImp >
    BaseType;
  typedef typename BaseType::DomainType
    DomainType;
  typedef typename BaseType::RangeType
    RangeType;

  /**
     *  \brief  constructor
     *  \param  viscosity,alpha   dummies
     **/
  ConstantIntersectionTimeFunction(const TimeProviderImp& timeprovider,
                                   const FunctionSpaceImp& space,
                                   const double constant = 0.0)
    : BaseType(timeprovider, space)
      , constant_(constant)
  {}

  /**
     *  \brief  destructor
     *
     *  doing nothing
     **/
  ~ConstantIntersectionTimeFunction()
  {}

  template< class IntersectionType >
  void evaluateTime(const double /*time*/, const DomainType& /*arg*/, RangeType& ret,
                    const IntersectionType& /*intersection */) const {
    ret = RangeType(constant_);
  }

  void evaluateTime(const double /*time*/, const DomainType& /*arg*/, RangeType& ret) const {
    ret = RangeType(constant_);
  }

private:
  const double constant_;
};

} // end namespace Fem
} // end namespace Stuff
} // end namespace Dune

#define NULLFUNCTION_TP(classname) \
  template< class T, class P > \
  struct classname \
    : public Dune::Stuff::Fem::ConstantFunctionTP< T, P > \
  { classname(const P &p, const T &t, double = 0.0, double = 0.0) \
      : Dune::Stuff::Fem::ConstantFunctionTP< T, P >(p, t) {} };

#define NULLFUNCTION_TP_BOUNDARY(classname) \
  template< class T, class P > \
  struct classname \
    : public Dune::Stuff::Fem::ConstantIntersectionTimeFunction< T, P > \
  { classname(const P &p, const T &t, double = 0.0, double = 0.0) \
      : Dune::Stuff::Fem::ConstantIntersectionTimeFunction< T, P >(p, t) {} };

#define NULLFUNCTION(classname) \
  template< class T > \
  struct classname \
    : public Dune::Stuff::Fem::ConstantFunction< T > \
  { classname(const double /*d*/, const T &t, double = 0.0, double = 0.0) \
      : Dune::Stuff::Fem::ConstantFunction< T >(t) {} \
    classname() \
      : Dune::Stuff::Fem::ConstantFunction< T >() {} \
    classname(const T &t) \
      : Dune::Stuff::Fem::ConstantFunction< T >(t) {} };

#define CONSTANTFUNCTION(classname, constant) \
  template< class T > \
  struct classname \
    : public Dune::Stuff::Fem::ConstantFunction< T > \
  { classname() \
      : Dune::Stuff::Fem::ConstantFunction< T >(typename T::RangeType(constant)) {} };

#endif // HAVE_DUNE_FEM

#endif // DUNE_STUFF_ANALYTICAL_HH

/** Copyright (c) 2012, Rene Milk
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the documentation
   *    and/or other materials provided with the distribution.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE 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.
   *
   * The views and conclusions contained in the software and documentation are those
   * of the authors and should not be interpreted as representing official policies,
   * either expressed or implied, of the FreeBSD Project.
   **/
<commit_msg>[fem] implements a more generic ConstantFunction<commit_after>#ifndef DUNE_STUFF_ANALYTICAL_HH
#define DUNE_STUFF_ANALYTICAL_HH

#ifdef HAVE_CMAKE_CONFIG
 #include "cmake_config.h"
#else
 #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

#ifdef HAVE_DUNE_FEM

#include "timefunction.hh"

namespace Dune {
namespace Stuff {
namespace Fem {

template< class FunctionSpaceImp >
class ConstantFunction
  : public Dune::Fem::Function< FunctionSpaceImp, ConstantFunction< FunctionSpaceImp > >
{
public:
  typedef ConstantFunction< FunctionSpaceImp >
    ThisType;
  typedef Dune::Fem::Function< FunctionSpaceImp, ThisType >
    BaseType;
  typedef typename BaseType::DomainType
    DomainType;
  typedef typename BaseType::RangeType
    RangeType;

  ConstantFunction(const FunctionSpaceImp& /*space*/,
                   const double constant = 0.0)
    : constant_(RangeType(constant))
  {}
  explicit ConstantFunction(const double constant = 0.0)
    : constant_(RangeType(constant))
  {}
  explicit ConstantFunction(const RangeType& constant)
    : constant_(constant)
  {}

  ~ConstantFunction()
  {}

  inline void evaluate(RangeType& ret) const {
    ret = constant_;
  }

  //! recursively consume args until only the output arg RangeType is left and the above function is called
  template <class FirstType, class... Args>
  void evaluate(FirstType&&, Args&&... args) const { evaluate(args...); }

  template< class IntersectionIteratorType >
  inline void evaluate(const double /*time*/, const DomainType& /*arg*/,
                       RangeType& ret, const IntersectionIteratorType /*it*/) const
  { ret = constant_; }

  inline void jacobian(typename BaseType::JacobianRangeType& jac) const {
    jac = typename BaseType::JacobianRangeType(0);
  }

  template <class FirstType, class... Args>
  void jacobian(FirstType&&, Args&&... args) const { jacobian(args...); }

  //! alias for evaluate
  template <class... Args>
  void position_derivative(Args&&... args) const { evaluate(std::forward<Args>(args)...); }

  //! alias for jacobian
  template <class... Args>
  void direction_derivative(Args&&... args) const { jacobian(std::forward<Args>(args)...); }

  //! deprecated alias for jacobian
  template <class... Args>
  void evaluateJacobian(Args&&... args) const { jacobian(std::forward<Args>(args)...); }

private:
  const RangeType constant_;
};

template< class FunctionSpaceImp, class TimeProviderImp >
class ConstantFunctionTP
  : public TimeFunction< FunctionSpaceImp,
                               ConstantFunctionTP< FunctionSpaceImp, TimeProviderImp >, TimeProviderImp >
{
public:
  typedef ConstantFunctionTP< FunctionSpaceImp, TimeProviderImp >
    ThisType;
  typedef TimeFunction< FunctionSpaceImp, ThisType, TimeProviderImp >
    BaseType;
  typedef typename BaseType::DomainType
    DomainType;
  typedef typename BaseType::RangeType
    RangeType;

  ConstantFunctionTP(const TimeProviderImp& timeprovider,
                     const FunctionSpaceImp& space,
                     const double constant = 0.0)
    : BaseType(timeprovider, space)
      , constant_(constant)
  {}

  ~ConstantFunctionTP()
  {}

  void evaluateTime(const double /*time*/, const DomainType& /*arg*/, RangeType& ret) const { ret = RangeType(constant_); }

private:
  const double constant_;
};

template< class FunctionSpaceImp, class TimeProviderImp >
class ConstantIntersectionTimeFunction
  : public IntersectionTimeFunction< FunctionSpaceImp,
                                           ConstantIntersectionTimeFunction< FunctionSpaceImp,
                                                                             TimeProviderImp >, TimeProviderImp >
{
public:
  typedef ConstantIntersectionTimeFunction< FunctionSpaceImp, TimeProviderImp >
    ThisType;
  typedef IntersectionTimeFunction< FunctionSpaceImp, ThisType, TimeProviderImp >
    BaseType;
  typedef typename BaseType::DomainType
    DomainType;
  typedef typename BaseType::RangeType
    RangeType;

  /**
     *  \brief  constructor
     *  \param  viscosity,alpha   dummies
     **/
  ConstantIntersectionTimeFunction(const TimeProviderImp& timeprovider,
                                   const FunctionSpaceImp& space,
                                   const double constant = 0.0)
    : BaseType(timeprovider, space)
      , constant_(constant)
  {}

  /**
     *  \brief  destructor
     *
     *  doing nothing
     **/
  ~ConstantIntersectionTimeFunction()
  {}

  template< class IntersectionType >
  void evaluateTime(const double /*time*/, const DomainType& /*arg*/, RangeType& ret,
                    const IntersectionType& /*intersection */) const {
    ret = RangeType(constant_);
  }

  void evaluateTime(const double /*time*/, const DomainType& /*arg*/, RangeType& ret) const {
    ret = RangeType(constant_);
  }

private:
  const double constant_;
};

} // end namespace Fem
} // end namespace Stuff
} // end namespace Dune

#define NULLFUNCTION_TP(classname) \
  template< class T, class P > \
  struct classname \
    : public Dune::Stuff::Fem::ConstantFunctionTP< T, P > \
  { classname(const P &p, const T &t, double = 0.0, double = 0.0) \
      : Dune::Stuff::Fem::ConstantFunctionTP< T, P >(p, t) {} };

#define NULLFUNCTION_TP_BOUNDARY(classname) \
  template< class T, class P > \
  struct classname \
    : public Dune::Stuff::Fem::ConstantIntersectionTimeFunction< T, P > \
  { classname(const P &p, const T &t, double = 0.0, double = 0.0) \
      : Dune::Stuff::Fem::ConstantIntersectionTimeFunction< T, P >(p, t) {} };

#define NULLFUNCTION(classname) \
  template< class T > \
  struct classname \
    : public Dune::Stuff::Fem::ConstantFunction< T > \
  { classname(const double /*d*/, const T &t, double = 0.0, double = 0.0) \
      : Dune::Stuff::Fem::ConstantFunction< T >(t) {} \
    classname() \
      : Dune::Stuff::Fem::ConstantFunction< T >() {} \
    classname(const T &t) \
      : Dune::Stuff::Fem::ConstantFunction< T >(t) {} };

#define CONSTANTFUNCTION(classname, constant) \
  template< class T > \
  struct classname \
    : public Dune::Stuff::Fem::ConstantFunction< T > \
  { classname() \
      : Dune::Stuff::Fem::ConstantFunction< T >(typename T::RangeType(constant)) {} };

#endif // HAVE_DUNE_FEM

#endif // DUNE_STUFF_ANALYTICAL_HH

/** Copyright (c) 2012, Rene Milk
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the documentation
   *    and/or other materials provided with the distribution.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE 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.
   *
   * The views and conclusions contained in the software and documentation are those
   * of the authors and should not be interpreted as representing official policies,
   * either expressed or implied, of the FreeBSD Project.
   **/
<|endoftext|>


<commit_before><commit_msg>Minor VulkanTexture simplification.<commit_after><|endoftext|>


<commit_before>#include "TestSprite.h"

#include <easyejoy2d.h>
#include <dtex_facade.h>

namespace tdtex
{

TestSprite::TestSprite()
{
	const char* cfg =
		"{ \n"
		"	\"open_c1\" : false, \n"
		"	\"open_c2\" : false, \n"
		"	\"open_c3\" : true \n"
		"} \n"
		;
	dtexf_create(cfg);
}

TestSprite::~TestSprite()
{
	dtexf_release();
}

void TestSprite::Load()
{
	{
		ej_package* pkg = dtexf_c3_load_pkg("2002jumin", "test-dtex/2002jumin.epd", 1);
		m_spr = new eejoy2d::EJSprite(pkg, "2002jumin1_run_1");
		dtexf_c3_load_pkg("2002jumin", "test-dtex/2002jumin.epp", 1);
	}
	dtexf_c3_load_pkg_finish();

	m_spr2 = new eejoy2d::EJSprite(dtexf_create_sprite("test-dtex/360.png"));
	m_spr2->Translate(300, 0);
}

void TestSprite::Update()
{
}

void TestSprite::Draw() const
{
	eejoy2d::EJScreen* scr = eejoy2d::EJScreen::Instance();
	assert(scr);
	scr->Bind();
	scr->Clear();

	m_spr->Draw(100, 100);
	m_spr2->Draw(200, 200);

	scr->UnBind();
}

}<commit_msg>[FIXED] test sprite<commit_after>#include "TestSprite.h"

#include <easyejoy2d.h>
#include <dtex_facade.h>

namespace tdtex
{

TestSprite::TestSprite()
{
	const char* cfg =
		"{ \n"
		"	\"open_c1\" : false, \n"
		"	\"open_c2\" : false, \n"
		"	\"open_c3\" : true \n"
		"} \n"
		;
	dtexf_create(cfg);
}

TestSprite::~TestSprite()
{
	dtexf_release();
}

void TestSprite::Load()
{
	{
		ej_package* pkg = dtexf_c3_load_pkg("2005mojin", "2005mojin.epd", 1);
		m_spr = new eejoy2d::EJSprite(pkg, "2005mojin1_attack1_1");
		dtexf_c3_load_pkg("2005mojin", "2005mojin.epp", 1);
	}
	dtexf_c3_load_pkg_finish();

	m_spr2 = new eejoy2d::EJSprite(dtexf_create_sprite("360.png"));
	m_spr2->Translate(300, 0);
}

void TestSprite::Update()
{
	m_spr->Update();
}

void TestSprite::Draw() const
{
	eejoy2d::EJScreen* scr = eejoy2d::EJScreen::Instance();
	assert(scr);
	scr->Bind();
	scr->Clear();

	m_spr->Draw(100, 100);
	m_spr2->Draw(200, 200);

	scr->UnBind();
}

}<|endoftext|>


<commit_before>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB

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

   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 GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/* create and drop of databases */

#include "mysql_priv.h"
#include "sql_acl.h"
#include <my_dir.h>
#include <m_ctype.h>
#ifdef __WIN__
#include <direct.h>
#endif

static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *path,
				 uint level);

/* db-name is already validated when we come here */

void mysql_create_db(THD *thd, char *db, uint create_options)
{
  char	 path[FN_REFLEN+16];
  MY_DIR *dirp;
  long result=1;
  DBUG_ENTER("mysql_create_db");

  VOID(pthread_mutex_lock(&LOCK_mysql_create_db));
  VOID(pthread_mutex_lock(&LOCK_open));

  // do not create database if another thread is holding read lock
  if (global_read_lock)
  {
    if (thd->global_read_lock)
    {
      net_printf(&thd->net, ER_CREATE_DB_WITH_READ_LOCK);
      VOID(pthread_mutex_unlock(&LOCK_open));
      goto exit;
    }
    while (global_read_lock && ! thd->killed)
    {
      (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
    }

    if (thd->killed)
    {
      net_printf(&thd->net, ER_SERVER_SHUTDOWN);
      VOID(pthread_mutex_unlock(&LOCK_open));
      goto exit;
    }

  }

  VOID(pthread_mutex_unlock(&LOCK_open));

  /* Check directory */
  (void)sprintf(path,"%s/%s", mysql_data_home, db);
  unpack_dirname(path,path);			// Convert if not unix
  if ((dirp = my_dir(path,MYF(MY_DONT_SORT))))
  {
    my_dirend(dirp);
    if (!(create_options & HA_LEX_CREATE_IF_NOT_EXISTS))
    {
      net_printf(&thd->net,ER_DB_CREATE_EXISTS,db);
      goto exit;
    }
    result = 0;
  }
  else
  {
    strend(path)[-1]=0;				// Remove last '/' from path
    if (my_mkdir(path,0777,MYF(0)) < 0)
    {
      net_printf(&thd->net,ER_CANT_CREATE_DB,db,my_errno);
      goto exit;
    }
  }
  if (!thd->query)
  {
    thd->query = path;
    thd->query_length = (uint) (strxmov(path,"create database ", db, NullS)-
				path);
  }
  {
    mysql_update_log.write(thd,thd->query, thd->query_length);
    if (mysql_bin_log.is_open())
    {
      Query_log_event qinfo(thd, thd->query);
      mysql_bin_log.write(&qinfo);
    }
  }
  if (thd->query == path)
  {
    thd->query = 0; // just in case
    thd->query_length = 0;
  }
  send_ok(&thd->net, result);

exit:
  VOID(pthread_mutex_unlock(&LOCK_mysql_create_db));
  DBUG_VOID_RETURN;
}

const char *del_exts[]=
{".frm",".ISM",".ISD",".ISM",".HSH",".DAT",".MRG",".MYI",".MYD", ".db", ".BAK", NullS};
static TYPELIB deletable_extentions=
{array_elements(del_exts)-1,"del_exts", del_exts};

/* db-name is already validated when we come here */

void mysql_rm_db(THD *thd,char *db,bool if_exists)
{
  long deleted=0;
  char	path[FN_REFLEN+16];
  MY_DIR *dirp;
  DBUG_ENTER("mysql_rm_db");

  VOID(pthread_mutex_lock(&LOCK_mysql_create_db));
  VOID(pthread_mutex_lock(&LOCK_open));

  // do not drop database if another thread is holding read lock
  if (global_read_lock)
  {
    if (thd->global_read_lock)
    {
      net_printf(&thd->net, ER_DROP_DB_WITH_READ_LOCK);
      goto exit;
    }
    while (global_read_lock && ! thd->killed)
    {
      (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
    }

    if (thd->killed)
    {
      net_printf(&thd->net, ER_SERVER_SHUTDOWN);
      goto exit;
    }
  }

  (void) sprintf(path,"%s/%s",mysql_data_home,db);
  unpack_dirname(path,path);			// Convert if not unix
  /* See if the directory exists */
  if (!(dirp = my_dir(path,MYF(MY_WME | MY_DONT_SORT))))
  {
    if (!if_exists)
      net_printf(&thd->net,ER_DB_DROP_EXISTS,db);
    else
      send_ok(&thd->net,0);
    goto exit;
  }
  remove_db_from_cache(db);

  if ((deleted=mysql_rm_known_files(thd, dirp, path,0)) >= 0)
  {
    if (!thd->query)
    {
      thd->query = path;
      thd->query_length = (uint) (strxmov(path,"drop database ", db, NullS)-
				  path);
    }
    mysql_update_log.write(thd, thd->query, thd->query_length);
    if (mysql_bin_log.is_open())
    {
      Query_log_event qinfo(thd, thd->query);
      mysql_bin_log.write(&qinfo);
    }
    if (thd->query == path)
    {
      thd->query = 0; // just in case
      thd->query_length = 0;
    }
    send_ok(&thd->net,(ulong) deleted);
  }

exit:
  VOID(pthread_mutex_unlock(&LOCK_open));
  VOID(pthread_mutex_unlock(&LOCK_mysql_create_db));

  /* If there are running queries on the tables, MySQL needs to get
     access to LOCK_open to end them. InnoDB on the other hand waits
     for the queries to end before dropping the database. That is why we
     must do the dropping outside of the mutexes above, otherwise the server
     always hangs if there are running queries. We only drop inside InnoDB
     if deleted got value >= 0 which means that it was successful. */

  if (deleted >= 0)
    ha_drop_database(path);

  DBUG_VOID_RETURN;
}

/*
  Removes files with known extensions plus all found subdirectories that
  are 2 digits (raid directories).
*/

static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *org_path,
				 uint level)
{
  long deleted=0;
  ulong found_other_files=0;
  char filePath[FN_REFLEN];
  DBUG_ENTER("mysql_rm_known_files");
  DBUG_PRINT("enter",("path: %s", org_path));
  /* remove all files with known extensions */

  for (uint idx=2 ;
       idx < (uint) dirp->number_off_files && !thd->killed ;
       idx++)
  {
    FILEINFO *file=dirp->dir_entry+idx;
    DBUG_PRINT("info",("Examining: %s", file->name));

    /* Check if file is a raid directory */
    if (isdigit(file->name[0]) && isdigit(file->name[1]) &&
	!file->name[2] && !level)
    {
      char newpath[FN_REFLEN];
      MY_DIR *new_dirp;
      strxmov(newpath,org_path,"/",file->name,NullS);
      unpack_filename(newpath,newpath);
      if ((new_dirp = my_dir(newpath,MYF(MY_DONT_SORT))))
      {
	DBUG_PRINT("my",("New subdir found: %s", newpath));
	if ((mysql_rm_known_files(thd,new_dirp,newpath,1)) < 0)
	{
	  my_dirend(dirp);
	  DBUG_RETURN(-1);
	}
      }
      continue;
    }
    if (find_type(fn_ext(file->name),&deletable_extentions,1+2) <= 0)
    {
      found_other_files++;
      continue;
    }
    strxmov(filePath,org_path,"/",file->name,NullS);
    unpack_filename(filePath,filePath);
    if (my_delete(filePath,MYF(MY_WME)))
    {
      net_printf(&thd->net,ER_DB_DROP_DELETE,filePath,my_error);
      my_dirend(dirp);
      DBUG_RETURN(-1);
    }
    deleted++;
  }

  my_dirend(dirp);

  if (thd->killed)
  {
    send_error(&thd->net,ER_SERVER_SHUTDOWN);
    DBUG_RETURN(-1);
  }

  /*
    If the directory is a symbolic link, remove the link first, then
    remove the directory the symbolic link pointed at
  */
  if (!found_other_files)
  {
    char tmp_path[FN_REFLEN], *pos;
    char *path=unpack_filename(tmp_path,org_path);
#ifdef HAVE_READLINK
    int error;

    /* Remove end FN_LIBCHAR as this causes problem on Linux in readlink */
    pos=strend(path);
    if (pos > path && pos[-1] == FN_LIBCHAR)
      *--pos=0;

    if ((error=my_readlink(filePath, path, MYF(MY_WME))) < 0)
      DBUG_RETURN(-1);
    if (!error)
    {
      if (my_delete(path,MYF(!level ? MY_WME : 0)))
      {
	/* Don't give errors if we can't delete 'RAID' directory */
	if (level)
	  DBUG_RETURN(deleted);
	send_error(&thd->net);
	DBUG_RETURN(-1);
      }
      /* Delete directory symbolic link pointed at */
      path= filePath;
    }
#endif
    /* Remove last FN_LIBCHAR to not cause a probelm on OS/2 */
    pos=strend(path);
    if (pos > path && pos[-1] == FN_LIBCHAR)
      *--pos=0;
    /* Don't give errors if we can't delete 'RAID' directory */
    if (rmdir(path) < 0 && !level)
    {
      net_printf(&thd->net,ER_DB_DROP_RMDIR, path,errno);
      DBUG_RETURN(-1);
    }
  }
  DBUG_RETURN(deleted);
}

bool mysql_change_db(THD *thd,const char *name)
{
  int length;
  char *dbname=my_strdup((char*) name,MYF(MY_WME));
  char	path[FN_REFLEN];
  uint db_access;
  DBUG_ENTER("mysql_change_db");

  if (!dbname || !(length=strip_sp(dbname)))
  {
    x_free(dbname);				/* purecov: inspected */
    send_error(&thd->net,ER_NO_DB_ERROR);	/* purecov: inspected */
    DBUG_RETURN(1);				/* purecov: inspected */
  }
  if ((length > NAME_LEN) || check_db_name(dbname))
  {
    net_printf(&thd->net,ER_WRONG_DB_NAME, dbname);
    x_free(dbname);
    DBUG_RETURN(1);
  }
  DBUG_PRINT("general",("Use database: %s", dbname));
  if (test_all_bits(thd->master_access,DB_ACLS))
    db_access=DB_ACLS;
  else
    db_access= (acl_get(thd->host,thd->ip,(char*) &thd->remote.sin_addr,
			thd->priv_user,dbname) |
		thd->master_access);
  if (!(db_access & DB_ACLS) && (!grant_option || check_grant_db(thd,dbname)))
  {
    net_printf(&thd->net,ER_DBACCESS_DENIED_ERROR,
	       thd->priv_user,
	       thd->host ? thd->host : thd->ip ? thd->ip : "unknown",
	       dbname);
    mysql_log.write(thd,COM_INIT_DB,ER(ER_DBACCESS_DENIED_ERROR),
		    thd->priv_user,
		    thd->host ? thd->host : thd->ip ? thd->ip : "unknown",
		    dbname);
    my_free(dbname,MYF(0));
    DBUG_RETURN(1);
  }

  (void) sprintf(path,"%s/%s",mysql_data_home,dbname);
  length=unpack_dirname(path,path);		// Convert if not unix
  if (length && path[length-1] == FN_LIBCHAR)
    path[length-1]=0;				// remove ending '\'
  if (access(path,F_OK))
  {
    net_printf(&thd->net,ER_BAD_DB_ERROR,dbname);
    my_free(dbname,MYF(0));
    DBUG_RETURN(1);
  }
  send_ok(&thd->net);
  x_free(thd->db);
  thd->db=dbname;
  thd->db_access=db_access;
  DBUG_RETURN(0);
}
<commit_msg>sql_db.cc:   On Monty's suggestion move ha_drop_database back inside LOCK_mysql_create_db, but we release LOCK_open during it to let possible running queries complete. I tested this and it seemed to work also in complex concurrent DELETE, SELECT, DROP DATABASE, and CREATE DATABASE situations<commit_after>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB

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

   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 GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/* create and drop of databases */

#include "mysql_priv.h"
#include "sql_acl.h"
#include <my_dir.h>
#include <m_ctype.h>
#ifdef __WIN__
#include <direct.h>
#endif

static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *path,
				 uint level);

/* db-name is already validated when we come here */

void mysql_create_db(THD *thd, char *db, uint create_options)
{
  char	 path[FN_REFLEN+16];
  MY_DIR *dirp;
  long result=1;
  DBUG_ENTER("mysql_create_db");

  VOID(pthread_mutex_lock(&LOCK_mysql_create_db));
  VOID(pthread_mutex_lock(&LOCK_open));

  // do not create database if another thread is holding read lock
  if (global_read_lock)
  {
    if (thd->global_read_lock)
    {
      net_printf(&thd->net, ER_CREATE_DB_WITH_READ_LOCK);
      VOID(pthread_mutex_unlock(&LOCK_open));
      goto exit;
    }
    while (global_read_lock && ! thd->killed)
    {
      (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
    }

    if (thd->killed)
    {
      net_printf(&thd->net, ER_SERVER_SHUTDOWN);
      VOID(pthread_mutex_unlock(&LOCK_open));
      goto exit;
    }

  }

  VOID(pthread_mutex_unlock(&LOCK_open));

  /* Check directory */
  (void)sprintf(path,"%s/%s", mysql_data_home, db);
  unpack_dirname(path,path);			// Convert if not unix
  if ((dirp = my_dir(path,MYF(MY_DONT_SORT))))
  {
    my_dirend(dirp);
    if (!(create_options & HA_LEX_CREATE_IF_NOT_EXISTS))
    {
      net_printf(&thd->net,ER_DB_CREATE_EXISTS,db);
      goto exit;
    }
    result = 0;
  }
  else
  {
    strend(path)[-1]=0;				// Remove last '/' from path
    if (my_mkdir(path,0777,MYF(0)) < 0)
    {
      net_printf(&thd->net,ER_CANT_CREATE_DB,db,my_errno);
      goto exit;
    }
  }
  if (!thd->query)
  {
    thd->query = path;
    thd->query_length = (uint) (strxmov(path,"create database ", db, NullS)-
				path);
  }
  {
    mysql_update_log.write(thd,thd->query, thd->query_length);
    if (mysql_bin_log.is_open())
    {
      Query_log_event qinfo(thd, thd->query);
      mysql_bin_log.write(&qinfo);
    }
  }
  if (thd->query == path)
  {
    thd->query = 0; // just in case
    thd->query_length = 0;
  }
  send_ok(&thd->net, result);

exit:
  VOID(pthread_mutex_unlock(&LOCK_mysql_create_db));
  DBUG_VOID_RETURN;
}

const char *del_exts[]=
{".frm",".ISM",".ISD",".ISM",".HSH",".DAT",".MRG",".MYI",".MYD", ".db", ".BAK", NullS};
static TYPELIB deletable_extentions=
{array_elements(del_exts)-1,"del_exts", del_exts};

/* db-name is already validated when we come here */

void mysql_rm_db(THD *thd,char *db,bool if_exists)
{
  long deleted=0;
  char	path[FN_REFLEN+16];
  MY_DIR *dirp;
  DBUG_ENTER("mysql_rm_db");

  VOID(pthread_mutex_lock(&LOCK_mysql_create_db));
  VOID(pthread_mutex_lock(&LOCK_open));

  // do not drop database if another thread is holding read lock
  if (global_read_lock)
  {
    if (thd->global_read_lock)
    {
      net_printf(&thd->net, ER_DROP_DB_WITH_READ_LOCK);
      goto exit;
    }
    while (global_read_lock && ! thd->killed)
    {
      (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
    }

    if (thd->killed)
    {
      net_printf(&thd->net, ER_SERVER_SHUTDOWN);
      goto exit;
    }
  }

  (void) sprintf(path,"%s/%s",mysql_data_home,db);
  unpack_dirname(path,path);			// Convert if not unix
  /* See if the directory exists */
  if (!(dirp = my_dir(path,MYF(MY_WME | MY_DONT_SORT))))
  {
    if (!if_exists)
      net_printf(&thd->net,ER_DB_DROP_EXISTS,db);
    else
      send_ok(&thd->net,0);
    goto exit;
  }
  remove_db_from_cache(db);

  if ((deleted=mysql_rm_known_files(thd, dirp, path,0)) >= 0)
  {
    /* If there are running queries on the tables, MySQL needs to get
       access to LOCK_open to end them. InnoDB on the other hand waits
       for the queries to end before dropping the database. That is why we
       must do the dropping with LOCK_open released. */

    VOID(pthread_mutex_unlock(&LOCK_open));
    ha_drop_database(path);
    VOID(pthread_mutex_lock(&LOCK_open));

    if (!thd->query)
    {
      thd->query = path;
      thd->query_length = (uint) (strxmov(path,"drop database ", db, NullS)-
				  path);
    }
    mysql_update_log.write(thd, thd->query, thd->query_length);
    if (mysql_bin_log.is_open())
    {
      Query_log_event qinfo(thd, thd->query);
      mysql_bin_log.write(&qinfo);
    }
    if (thd->query == path)
    {
      thd->query = 0; // just in case
      thd->query_length = 0;
    }
    send_ok(&thd->net,(ulong) deleted);
  }

exit:
  VOID(pthread_mutex_unlock(&LOCK_open));
  VOID(pthread_mutex_unlock(&LOCK_mysql_create_db));

  DBUG_VOID_RETURN;
}

/*
  Removes files with known extensions plus all found subdirectories that
  are 2 digits (raid directories).
*/

static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *org_path,
				 uint level)
{
  long deleted=0;
  ulong found_other_files=0;
  char filePath[FN_REFLEN];
  DBUG_ENTER("mysql_rm_known_files");
  DBUG_PRINT("enter",("path: %s", org_path));
  /* remove all files with known extensions */

  for (uint idx=2 ;
       idx < (uint) dirp->number_off_files && !thd->killed ;
       idx++)
  {
    FILEINFO *file=dirp->dir_entry+idx;
    DBUG_PRINT("info",("Examining: %s", file->name));

    /* Check if file is a raid directory */
    if (isdigit(file->name[0]) && isdigit(file->name[1]) &&
	!file->name[2] && !level)
    {
      char newpath[FN_REFLEN];
      MY_DIR *new_dirp;
      strxmov(newpath,org_path,"/",file->name,NullS);
      unpack_filename(newpath,newpath);
      if ((new_dirp = my_dir(newpath,MYF(MY_DONT_SORT))))
      {
	DBUG_PRINT("my",("New subdir found: %s", newpath));
	if ((mysql_rm_known_files(thd,new_dirp,newpath,1)) < 0)
	{
	  my_dirend(dirp);
	  DBUG_RETURN(-1);
	}
      }
      continue;
    }
    if (find_type(fn_ext(file->name),&deletable_extentions,1+2) <= 0)
    {
      found_other_files++;
      continue;
    }
    strxmov(filePath,org_path,"/",file->name,NullS);
    unpack_filename(filePath,filePath);
    if (my_delete(filePath,MYF(MY_WME)))
    {
      net_printf(&thd->net,ER_DB_DROP_DELETE,filePath,my_error);
      my_dirend(dirp);
      DBUG_RETURN(-1);
    }
    deleted++;
  }

  my_dirend(dirp);

  if (thd->killed)
  {
    send_error(&thd->net,ER_SERVER_SHUTDOWN);
    DBUG_RETURN(-1);
  }

  /*
    If the directory is a symbolic link, remove the link first, then
    remove the directory the symbolic link pointed at
  */
  if (!found_other_files)
  {
    char tmp_path[FN_REFLEN], *pos;
    char *path=unpack_filename(tmp_path,org_path);
#ifdef HAVE_READLINK
    int error;

    /* Remove end FN_LIBCHAR as this causes problem on Linux in readlink */
    pos=strend(path);
    if (pos > path && pos[-1] == FN_LIBCHAR)
      *--pos=0;

    if ((error=my_readlink(filePath, path, MYF(MY_WME))) < 0)
      DBUG_RETURN(-1);
    if (!error)
    {
      if (my_delete(path,MYF(!level ? MY_WME : 0)))
      {
	/* Don't give errors if we can't delete 'RAID' directory */
	if (level)
	  DBUG_RETURN(deleted);
	send_error(&thd->net);
	DBUG_RETURN(-1);
      }
      /* Delete directory symbolic link pointed at */
      path= filePath;
    }
#endif
    /* Remove last FN_LIBCHAR to not cause a probelm on OS/2 */
    pos=strend(path);
    if (pos > path && pos[-1] == FN_LIBCHAR)
      *--pos=0;
    /* Don't give errors if we can't delete 'RAID' directory */
    if (rmdir(path) < 0 && !level)
    {
      net_printf(&thd->net,ER_DB_DROP_RMDIR, path,errno);
      DBUG_RETURN(-1);
    }
  }
  DBUG_RETURN(deleted);
}

bool mysql_change_db(THD *thd,const char *name)
{
  int length;
  char *dbname=my_strdup((char*) name,MYF(MY_WME));
  char	path[FN_REFLEN];
  uint db_access;
  DBUG_ENTER("mysql_change_db");

  if (!dbname || !(length=strip_sp(dbname)))
  {
    x_free(dbname);				/* purecov: inspected */
    send_error(&thd->net,ER_NO_DB_ERROR);	/* purecov: inspected */
    DBUG_RETURN(1);				/* purecov: inspected */
  }
  if ((length > NAME_LEN) || check_db_name(dbname))
  {
    net_printf(&thd->net,ER_WRONG_DB_NAME, dbname);
    x_free(dbname);
    DBUG_RETURN(1);
  }
  DBUG_PRINT("general",("Use database: %s", dbname));
  if (test_all_bits(thd->master_access,DB_ACLS))
    db_access=DB_ACLS;
  else
    db_access= (acl_get(thd->host,thd->ip,(char*) &thd->remote.sin_addr,
			thd->priv_user,dbname) |
		thd->master_access);
  if (!(db_access & DB_ACLS) && (!grant_option || check_grant_db(thd,dbname)))
  {
    net_printf(&thd->net,ER_DBACCESS_DENIED_ERROR,
	       thd->priv_user,
	       thd->host ? thd->host : thd->ip ? thd->ip : "unknown",
	       dbname);
    mysql_log.write(thd,COM_INIT_DB,ER(ER_DBACCESS_DENIED_ERROR),
		    thd->priv_user,
		    thd->host ? thd->host : thd->ip ? thd->ip : "unknown",
		    dbname);
    my_free(dbname,MYF(0));
    DBUG_RETURN(1);
  }

  (void) sprintf(path,"%s/%s",mysql_data_home,dbname);
  length=unpack_dirname(path,path);		// Convert if not unix
  if (length && path[length-1] == FN_LIBCHAR)
    path[length-1]=0;				// remove ending '\'
  if (access(path,F_OK))
  {
    net_printf(&thd->net,ER_BAD_DB_ERROR,dbname);
    my_free(dbname,MYF(0));
    DBUG_RETURN(1);
  }
  send_ok(&thd->net);
  x_free(thd->db);
  thd->db=dbname;
  thd->db_access=db_access;
  DBUG_RETURN(0);
}
<|endoftext|>


<commit_before>#include "includes.h"

namespace fancy {

  ostream& warn(string message)
  {
    cout << "[WARNING] " << message;
    return cout;
  }

  ostream& warnln(string message)
  {
    cout << "[WARNING] " << message << endl;
    return cout;
  }

  ostream& error(string message)
  {
    cerr << "[ERROR] " << message;
    return cout;
  }

  ostream& errorln(string message)
  {
    cerr << "[ERROR] " << message << endl;
    return cout;
  }

}
<commit_msg>src/utils: fixed error() and errorln() to return cerr and not cout.<commit_after>#include "includes.h"

namespace fancy {

  ostream& warn(string message)
  {
    cout << "[WARNING] " << message;
    return cout;
  }

  ostream& warnln(string message)
  {
    cout << "[WARNING] " << message << endl;
    return cout;
  }

  ostream& error(string message)
  {
    cerr << "[ERROR] " << message;
    return cerr;
  }

  ostream& errorln(string message)
  {
    cerr << "[ERROR] " << message << endl;
    return cerr;
  }

}
<|endoftext|>