<commit_before>#include "Runtime/GuiSys/CHudMissileInterface.hpp"

#include "Runtime/CStateManager.hpp"
#include "Runtime/GameGlobalObjects.hpp"
#include "Runtime/GuiSys/CAuiEnergyBarT01.hpp"
#include "Runtime/GuiSys/CGuiFrame.hpp"
#include "Runtime/GuiSys/CGuiModel.hpp"
#include "Runtime/GuiSys/CGuiTextPane.hpp"
#include "Runtime/GuiSys/CStringTable.hpp"

namespace urde {

static const CAuiEnergyBarT01::FCoordFunc CoordFuncs[] = {CHudMissileInterface::CombatMissileBarCoordFunc, nullptr,
                                                          CHudMissileInterface::XRayMissileBarCoordFunc,
                                                          CHudMissileInterface::ThermalMissileBarCoordFunc, nullptr};

static const float IconTranslateRanges[] = {6.05f, 0.f, 0.f, 8.4f, 0.f};

CHudMissileInterface::CHudMissileInterface(CGuiFrame& selHud, int missileCapacity, int numMissiles, float chargeFactor,
                                           bool missilesActive, EHudType hudType, const CStateManager& mgr)
: x0_hudType(hudType)
, x4_missileCapacity(missileCapacity)
, x8_numMissles(numMissiles)
, x4c_chargeBeamFactor(chargeFactor) {
  x58_24_missilesActive = missilesActive;
  x58_25_visibleDebug = true;
  x58_26_visibleGame = true;

  x5c_basewidget_missileicon = selHud.FindWidget("basewidget_missileicon");
  x60_textpane_missiledigits = static_cast<CGuiTextPane*>(selHud.FindWidget("textpane_missiledigits"));
  x64_energybart01_missilebar = static_cast<CAuiEnergyBarT01*>(selHud.FindWidget("energybart01_missilebar"));
  x68_textpane_missilewarning = static_cast<CGuiTextPane*>(selHud.FindWidget("textpane_missilewarning"));
  x6c_model_missilearrowup = static_cast<CGuiModel*>(selHud.FindWidget("model_missilearrowup"));
  x70_model_missilearrowdown = static_cast<CGuiModel*>(selHud.FindWidget("model_missilearrowdown"));
  x74_basewidget_missileicon = selHud.FindWidget("basewidget_missileicon");

  x58_27_hasArrows = x6c_model_missilearrowup && x70_model_missilearrowdown;
  x58_28_notXRay = hudType != EHudType::XRay;

  x10_missleIconXf = x74_basewidget_missileicon->GetLocalTransform();

  x60_textpane_missiledigits->TextSupport().SetFontColor(g_tweakGuiColors->GetMissileDigitsFont());
  x60_textpane_missiledigits->TextSupport().SetOutlineColor(g_tweakGuiColors->GetMissileDigitsOutline());
  x74_basewidget_missileicon->SetColor(g_tweakGuiColors->GetMissileIconColorInactive());
  x64_energybart01_missilebar->SetEmptyColor(g_tweakGuiColors->GetMissileBarEmpty());
  x64_energybart01_missilebar->SetFilledColor(g_tweakGuiColors->GetMissileBarFilled());
  x64_energybart01_missilebar->SetShadowColor(g_tweakGuiColors->GetMissileBarShadow());
  x64_energybart01_missilebar->SetCoordFunc(CoordFuncs[int(hudType)]);
  x64_energybart01_missilebar->SetTesselation(hudType == EHudType::Combat ? 1.f : 0.1f);
  x64_energybart01_missilebar->SetMaxEnergy(5.f);
  x64_energybart01_missilebar->SetFilledDrainSpeed(g_tweakGui->GetEnergyBarFilledSpeed());
  x64_energybart01_missilebar->SetShadowDrainSpeed(g_tweakGui->GetEnergyBarShadowSpeed());
  x64_energybart01_missilebar->SetShadowDrainDelay(g_tweakGui->GetEnergyBarDrainDelay());
  x64_energybart01_missilebar->SetIsAlwaysResetTimer(true);

  if (x68_textpane_missilewarning) {
    x68_textpane_missilewarning->TextSupport().SetFontColor(g_tweakGuiColors->GetMissileWarningFont());
    x68_textpane_missilewarning->TextSupport().SetOutlineColor(g_tweakGuiColors->GetMissileWarningOutline());
  }

  SetNumMissiles(x8_numMissles, mgr);
  x44_latestStatus = GetMissileInventoryStatus();
}

void CHudMissileInterface::UpdateVisibility(const CStateManager& mgr) {
  bool vis = x58_25_visibleDebug && x58_26_visibleGame;
  x5c_basewidget_missileicon->SetVisibility(vis, ETraversalMode::Children);
  x64_energybart01_missilebar->SetVisibility(vis, ETraversalMode::Children);
  if (vis)
    Update(0.f, mgr);
}

void CHudMissileInterface::Update(float dt, const CStateManager& mgr) {
  if (x4_missileCapacity < 1)
    x5c_basewidget_missileicon->SetIsVisible(false);
  else
    x5c_basewidget_missileicon->SetIsVisible(true);

  if (x54_missileIconIncrement < 0.f) {
    x54_missileIconIncrement -= 3.f * dt;
    if (x54_missileIconIncrement <= -1.f)
      x54_missileIconIncrement = 1.f;
  } else if (x54_missileIconIncrement > 0.f) {
    x54_missileIconIncrement = std::max(0.f, x54_missileIconIncrement - dt);
  }

  zeus::CColor addColor = g_tweakGuiColors->GetMissileIconColorActive() * x54_missileIconIncrement;

  if (x50_missileIconAltDeplete > 0.f) {
    x74_basewidget_missileicon->SetColor(zeus::CColor::lerp(g_tweakGuiColors->GetMissileIconColorInactive(),
                                                            g_tweakGuiColors->GetMissileIconColorDepleteAlt(),
                                                            x50_missileIconAltDeplete) +
                                         addColor);
  } else {
    if (x4c_chargeBeamFactor > 0.f) {
      float factor = std::min(x4c_chargeBeamFactor / CPlayerState::GetMissileComboChargeFactor(), 1.f);
      if (x8_numMissles > mgr.GetPlayerState()->GetMissileCostForAltAttack()) {
        x74_basewidget_missileicon->SetColor(zeus::CColor::lerp(g_tweakGuiColors->GetMissileIconColorInactive(),
                                                                g_tweakGuiColors->GetMissileIconColorChargedCanAlt(),
                                                                factor) +
                                             addColor);
      } else {
        x74_basewidget_missileicon->SetColor(zeus::CColor::lerp(g_tweakGuiColors->GetMissileIconColorInactive(),
                                                                g_tweakGuiColors->GetMissileIconColorChargedNoAlt(),
                                                                factor) +
                                             addColor);
      }
    } else {
      if (x58_24_missilesActive)
        x74_basewidget_missileicon->SetColor(g_tweakGuiColors->GetMissileIconColorActive() + addColor);
      else
        x74_basewidget_missileicon->SetColor(g_tweakGuiColors->GetMissileIconColorInactive() + addColor);
    }
  }

  x50_missileIconAltDeplete = std::max(0.f, x50_missileIconAltDeplete - dt);

  x64_energybart01_missilebar->SetMaxEnergy(x4_missileCapacity);
  x64_energybart01_missilebar->SetCurrEnergy(x8_numMissles, CAuiEnergyBarT01::ESetMode::Normal);

  if (x58_28_notXRay) {
    x74_basewidget_missileicon->SetLocalTransform(
        x10_missleIconXf *
        zeus::CTransform::Translate(0.f, 0.f,
                                    x8_numMissles * IconTranslateRanges[int(x0_hudType)] / float(x4_missileCapacity)));
  }

  if (x58_27_hasArrows) {
    if (xc_arrowTimer > 0.f) {
      xc_arrowTimer = std::max(0.f, xc_arrowTimer - dt);
      zeus::CColor color = g_tweakGuiColors->GetMissileIconColorActive();
      color.a() *= xc_arrowTimer / g_tweakGui->GetMissileArrowVisTime();
      x6c_model_missilearrowup->SetColor(color);
      x70_model_missilearrowdown->SetIsVisible(false);
    } else if (xc_arrowTimer < 0.f) {
      xc_arrowTimer = std::min(0.f, xc_arrowTimer + dt);
      zeus::CColor color = g_tweakGuiColors->GetMissileIconColorActive();
      color.a() *= -xc_arrowTimer / g_tweakGui->GetMissileArrowVisTime();
      x70_model_missilearrowdown->SetColor(color);
      x6c_model_missilearrowup->SetIsVisible(false);
    } else {
      x6c_model_missilearrowup->SetIsVisible(false);
      x70_model_missilearrowdown->SetIsVisible(false);
    }
  }

  if (x68_textpane_missilewarning) {
    EInventoryStatus curStatus = GetMissileInventoryStatus();
    if (curStatus != x44_latestStatus) {
      std::u16string string;
      switch (curStatus) {
      case EInventoryStatus::Warning:
        string = g_MainStringTable->GetString(12); // Missiles Low
        break;
      case EInventoryStatus::Depleted:
        string = g_MainStringTable->GetString(13); // Depleted
        break;
      default:
        break;
      }
      x68_textpane_missilewarning->TextSupport().SetText(string);

      if (x44_latestStatus == EInventoryStatus::Normal && curStatus == EInventoryStatus::Warning) {
        CSfxManager::SfxStart(SFXui_missile_warning, 1.f, 0.f, false, 0x7f, false, kInvalidAreaId);
        x48_missileWarningPulse = g_tweakGui->GetMissileWarningPulseTime();
      } else if (curStatus == EInventoryStatus::Depleted) {
        CSfxManager::SfxStart(SFXui_missile_warning, 1.f, 0.f, false, 0x7f, false, kInvalidAreaId);
        x48_missileWarningPulse = g_tweakGui->GetMissileWarningPulseTime();
      }

      x44_latestStatus = curStatus;
    }

    x48_missileWarningPulse = std::max(0.f, x48_missileWarningPulse - dt);
    float warnPulse = std::min(x48_missileWarningPulse, 1.f);

    if (x44_latestStatus != EInventoryStatus::Normal)
      x40_missileWarningAlpha = std::min(x40_missileWarningAlpha + 2.f * dt, 1.f);
    else
      x40_missileWarningAlpha = std::max(0.f, x40_missileWarningAlpha - 2.f * dt);

    float tmp = std::fabs(std::fmod(CGraphics::GetSecondsMod900(), 0.5f));
    if (tmp < 0.25f)
      tmp = tmp / 0.25f;
    else
      tmp = (0.5f - tmp) / 0.25f;

    zeus::CColor color = zeus::skWhite;
    color.a() = x40_missileWarningAlpha * tmp * warnPulse;
    x68_textpane_missilewarning->SetColor(color);
    if (x68_textpane_missilewarning->GetGeometryColor().a())
      x68_textpane_missilewarning->SetIsVisible(true);
    else
      x68_textpane_missilewarning->SetIsVisible(false);
  }
}

void CHudMissileInterface::SetIsVisibleGame(bool v, const CStateManager& mgr) {
  x58_26_visibleGame = v;
  UpdateVisibility(mgr);
}

void CHudMissileInterface::SetIsVisibleDebug(bool v, const CStateManager& mgr) {
  x58_25_visibleDebug = v;
  UpdateVisibility(mgr);
}

void CHudMissileInterface::SetIsMissilesActive(bool active) { x58_24_missilesActive = active; }

void CHudMissileInterface::SetChargeBeamFactor(float t) { x4c_chargeBeamFactor = t; }

void CHudMissileInterface::SetNumMissiles(int numMissiles, const CStateManager& mgr) {
  numMissiles = zeus::clamp(0, numMissiles, 999);

  x60_textpane_missiledigits->TextSupport().SetText(fmt::format(fmt("{:3d}"), numMissiles));

  if (x8_numMissles < numMissiles) {
    xc_arrowTimer = g_tweakGui->GetMissileArrowVisTime();
    x54_missileIconIncrement = -FLT_EPSILON;
  } else if (x8_numMissles > numMissiles) {
    xc_arrowTimer = -g_tweakGui->GetMissileArrowVisTime();
  }

  if (mgr.GetPlayerState()->GetMissileCostForAltAttack() + numMissiles <= x8_numMissles)
    x50_missileIconAltDeplete = 1.f;

  x8_numMissles = numMissiles;
}

void CHudMissileInterface::SetMissileCapacity(int missileCapacity) { x4_missileCapacity = missileCapacity; }

CHudMissileInterface::EInventoryStatus CHudMissileInterface::GetMissileInventoryStatus() const {
  if (x64_energybart01_missilebar->GetSetEnergy() == 0.f)
    return EInventoryStatus::Depleted;
  return EInventoryStatus(x64_energybart01_missilebar->GetActualFraction() < g_tweakGui->GetMissileWarningFraction());
}

std::pair<zeus::CVector3f, zeus::CVector3f> CHudMissileInterface::CombatMissileBarCoordFunc(float t) {
  float z = t * IconTranslateRanges[int(EHudType::Combat)];
  return {zeus::CVector3f(0.f, 0.f, z), zeus::CVector3f(0.3f, 0.f, z)};
}

std::pair<zeus::CVector3f, zeus::CVector3f> CHudMissileInterface::XRayMissileBarCoordFunc(float t) {
  float theta = 0.8f * (t - 0.5f);
  float x = 9.55f * std::cos(theta);
  float z = 9.55f * std::sin(theta);
  return {zeus::CVector3f(x - 0.4f, 0.f, z), zeus::CVector3f(x, 0.f, z)};
}

std::pair<zeus::CVector3f, zeus::CVector3f> CHudMissileInterface::ThermalMissileBarCoordFunc(float t) {
  float transRange = IconTranslateRanges[int(EHudType::Thermal)];
  float a = 0.08f * transRange;
  float b = t * transRange;
  float c;
  if (b < a)
    c = b / a;
  else if (b < transRange - a)
    c = 1.f;
  else
    c = 1.f - (b - (transRange - a)) / a;

  return {zeus::CVector3f(-0.5f * c - 0.1f, 0.f, b), zeus::CVector3f(-0.1f, 0.f, b)};
}

} // namespace urde
<commit_msg>CHudMissileInterface: Make use of std::array where applicable<commit_after>#include "Runtime/GuiSys/CHudMissileInterface.hpp"

#include <array>

#include "Runtime/CStateManager.hpp"
#include "Runtime/GameGlobalObjects.hpp"
#include "Runtime/GuiSys/CAuiEnergyBarT01.hpp"
#include "Runtime/GuiSys/CGuiFrame.hpp"
#include "Runtime/GuiSys/CGuiModel.hpp"
#include "Runtime/GuiSys/CGuiTextPane.hpp"
#include "Runtime/GuiSys/CStringTable.hpp"

namespace urde {

constexpr std::array<CAuiEnergyBarT01::FCoordFunc, 5> CoordFuncs{
    CHudMissileInterface::CombatMissileBarCoordFunc,  nullptr, CHudMissileInterface::XRayMissileBarCoordFunc,
    CHudMissileInterface::ThermalMissileBarCoordFunc, nullptr,
};

constexpr std::array IconTranslateRanges{
    6.05f, 0.f, 0.f, 8.4f, 0.f,
};

CHudMissileInterface::CHudMissileInterface(CGuiFrame& selHud, int missileCapacity, int numMissiles, float chargeFactor,
                                           bool missilesActive, EHudType hudType, const CStateManager& mgr)
: x0_hudType(hudType)
, x4_missileCapacity(missileCapacity)
, x8_numMissles(numMissiles)
, x4c_chargeBeamFactor(chargeFactor) {
  x58_24_missilesActive = missilesActive;
  x58_25_visibleDebug = true;
  x58_26_visibleGame = true;

  x5c_basewidget_missileicon = selHud.FindWidget("basewidget_missileicon");
  x60_textpane_missiledigits = static_cast<CGuiTextPane*>(selHud.FindWidget("textpane_missiledigits"));
  x64_energybart01_missilebar = static_cast<CAuiEnergyBarT01*>(selHud.FindWidget("energybart01_missilebar"));
  x68_textpane_missilewarning = static_cast<CGuiTextPane*>(selHud.FindWidget("textpane_missilewarning"));
  x6c_model_missilearrowup = static_cast<CGuiModel*>(selHud.FindWidget("model_missilearrowup"));
  x70_model_missilearrowdown = static_cast<CGuiModel*>(selHud.FindWidget("model_missilearrowdown"));
  x74_basewidget_missileicon = selHud.FindWidget("basewidget_missileicon");

  x58_27_hasArrows = x6c_model_missilearrowup && x70_model_missilearrowdown;
  x58_28_notXRay = hudType != EHudType::XRay;

  x10_missleIconXf = x74_basewidget_missileicon->GetLocalTransform();

  x60_textpane_missiledigits->TextSupport().SetFontColor(g_tweakGuiColors->GetMissileDigitsFont());
  x60_textpane_missiledigits->TextSupport().SetOutlineColor(g_tweakGuiColors->GetMissileDigitsOutline());
  x74_basewidget_missileicon->SetColor(g_tweakGuiColors->GetMissileIconColorInactive());
  x64_energybart01_missilebar->SetEmptyColor(g_tweakGuiColors->GetMissileBarEmpty());
  x64_energybart01_missilebar->SetFilledColor(g_tweakGuiColors->GetMissileBarFilled());
  x64_energybart01_missilebar->SetShadowColor(g_tweakGuiColors->GetMissileBarShadow());
  x64_energybart01_missilebar->SetCoordFunc(CoordFuncs[size_t(hudType)]);
  x64_energybart01_missilebar->SetTesselation(hudType == EHudType::Combat ? 1.f : 0.1f);
  x64_energybart01_missilebar->SetMaxEnergy(5.f);
  x64_energybart01_missilebar->SetFilledDrainSpeed(g_tweakGui->GetEnergyBarFilledSpeed());
  x64_energybart01_missilebar->SetShadowDrainSpeed(g_tweakGui->GetEnergyBarShadowSpeed());
  x64_energybart01_missilebar->SetShadowDrainDelay(g_tweakGui->GetEnergyBarDrainDelay());
  x64_energybart01_missilebar->SetIsAlwaysResetTimer(true);

  if (x68_textpane_missilewarning) {
    x68_textpane_missilewarning->TextSupport().SetFontColor(g_tweakGuiColors->GetMissileWarningFont());
    x68_textpane_missilewarning->TextSupport().SetOutlineColor(g_tweakGuiColors->GetMissileWarningOutline());
  }

  SetNumMissiles(x8_numMissles, mgr);
  x44_latestStatus = GetMissileInventoryStatus();
}

void CHudMissileInterface::UpdateVisibility(const CStateManager& mgr) {
  bool vis = x58_25_visibleDebug && x58_26_visibleGame;
  x5c_basewidget_missileicon->SetVisibility(vis, ETraversalMode::Children);
  x64_energybart01_missilebar->SetVisibility(vis, ETraversalMode::Children);
  if (vis)
    Update(0.f, mgr);
}

void CHudMissileInterface::Update(float dt, const CStateManager& mgr) {
  if (x4_missileCapacity < 1)
    x5c_basewidget_missileicon->SetIsVisible(false);
  else
    x5c_basewidget_missileicon->SetIsVisible(true);

  if (x54_missileIconIncrement < 0.f) {
    x54_missileIconIncrement -= 3.f * dt;
    if (x54_missileIconIncrement <= -1.f)
      x54_missileIconIncrement = 1.f;
  } else if (x54_missileIconIncrement > 0.f) {
    x54_missileIconIncrement = std::max(0.f, x54_missileIconIncrement - dt);
  }

  zeus::CColor addColor = g_tweakGuiColors->GetMissileIconColorActive() * x54_missileIconIncrement;

  if (x50_missileIconAltDeplete > 0.f) {
    x74_basewidget_missileicon->SetColor(zeus::CColor::lerp(g_tweakGuiColors->GetMissileIconColorInactive(),
                                                            g_tweakGuiColors->GetMissileIconColorDepleteAlt(),
                                                            x50_missileIconAltDeplete) +
                                         addColor);
  } else {
    if (x4c_chargeBeamFactor > 0.f) {
      float factor = std::min(x4c_chargeBeamFactor / CPlayerState::GetMissileComboChargeFactor(), 1.f);
      if (x8_numMissles > mgr.GetPlayerState()->GetMissileCostForAltAttack()) {
        x74_basewidget_missileicon->SetColor(zeus::CColor::lerp(g_tweakGuiColors->GetMissileIconColorInactive(),
                                                                g_tweakGuiColors->GetMissileIconColorChargedCanAlt(),
                                                                factor) +
                                             addColor);
      } else {
        x74_basewidget_missileicon->SetColor(zeus::CColor::lerp(g_tweakGuiColors->GetMissileIconColorInactive(),
                                                                g_tweakGuiColors->GetMissileIconColorChargedNoAlt(),
                                                                factor) +
                                             addColor);
      }
    } else {
      if (x58_24_missilesActive)
        x74_basewidget_missileicon->SetColor(g_tweakGuiColors->GetMissileIconColorActive() + addColor);
      else
        x74_basewidget_missileicon->SetColor(g_tweakGuiColors->GetMissileIconColorInactive() + addColor);
    }
  }

  x50_missileIconAltDeplete = std::max(0.f, x50_missileIconAltDeplete - dt);

  x64_energybart01_missilebar->SetMaxEnergy(x4_missileCapacity);
  x64_energybart01_missilebar->SetCurrEnergy(x8_numMissles, CAuiEnergyBarT01::ESetMode::Normal);

  if (x58_28_notXRay) {
    x74_basewidget_missileicon->SetLocalTransform(
        x10_missleIconXf *
        zeus::CTransform::Translate(
            0.f, 0.f, x8_numMissles * IconTranslateRanges[size_t(x0_hudType)] / float(x4_missileCapacity)));
  }

  if (x58_27_hasArrows) {
    if (xc_arrowTimer > 0.f) {
      xc_arrowTimer = std::max(0.f, xc_arrowTimer - dt);
      zeus::CColor color = g_tweakGuiColors->GetMissileIconColorActive();
      color.a() *= xc_arrowTimer / g_tweakGui->GetMissileArrowVisTime();
      x6c_model_missilearrowup->SetColor(color);
      x70_model_missilearrowdown->SetIsVisible(false);
    } else if (xc_arrowTimer < 0.f) {
      xc_arrowTimer = std::min(0.f, xc_arrowTimer + dt);
      zeus::CColor color = g_tweakGuiColors->GetMissileIconColorActive();
      color.a() *= -xc_arrowTimer / g_tweakGui->GetMissileArrowVisTime();
      x70_model_missilearrowdown->SetColor(color);
      x6c_model_missilearrowup->SetIsVisible(false);
    } else {
      x6c_model_missilearrowup->SetIsVisible(false);
      x70_model_missilearrowdown->SetIsVisible(false);
    }
  }

  if (x68_textpane_missilewarning) {
    EInventoryStatus curStatus = GetMissileInventoryStatus();
    if (curStatus != x44_latestStatus) {
      std::u16string string;
      switch (curStatus) {
      case EInventoryStatus::Warning:
        string = g_MainStringTable->GetString(12); // Missiles Low
        break;
      case EInventoryStatus::Depleted:
        string = g_MainStringTable->GetString(13); // Depleted
        break;
      default:
        break;
      }
      x68_textpane_missilewarning->TextSupport().SetText(string);

      if (x44_latestStatus == EInventoryStatus::Normal && curStatus == EInventoryStatus::Warning) {
        CSfxManager::SfxStart(SFXui_missile_warning, 1.f, 0.f, false, 0x7f, false, kInvalidAreaId);
        x48_missileWarningPulse = g_tweakGui->GetMissileWarningPulseTime();
      } else if (curStatus == EInventoryStatus::Depleted) {
        CSfxManager::SfxStart(SFXui_missile_warning, 1.f, 0.f, false, 0x7f, false, kInvalidAreaId);
        x48_missileWarningPulse = g_tweakGui->GetMissileWarningPulseTime();
      }

      x44_latestStatus = curStatus;
    }

    x48_missileWarningPulse = std::max(0.f, x48_missileWarningPulse - dt);
    float warnPulse = std::min(x48_missileWarningPulse, 1.f);

    if (x44_latestStatus != EInventoryStatus::Normal)
      x40_missileWarningAlpha = std::min(x40_missileWarningAlpha + 2.f * dt, 1.f);
    else
      x40_missileWarningAlpha = std::max(0.f, x40_missileWarningAlpha - 2.f * dt);

    float tmp = std::fabs(std::fmod(CGraphics::GetSecondsMod900(), 0.5f));
    if (tmp < 0.25f)
      tmp = tmp / 0.25f;
    else
      tmp = (0.5f - tmp) / 0.25f;

    zeus::CColor color = zeus::skWhite;
    color.a() = x40_missileWarningAlpha * tmp * warnPulse;
    x68_textpane_missilewarning->SetColor(color);
    if (x68_textpane_missilewarning->GetGeometryColor().a())
      x68_textpane_missilewarning->SetIsVisible(true);
    else
      x68_textpane_missilewarning->SetIsVisible(false);
  }
}

void CHudMissileInterface::SetIsVisibleGame(bool v, const CStateManager& mgr) {
  x58_26_visibleGame = v;
  UpdateVisibility(mgr);
}

void CHudMissileInterface::SetIsVisibleDebug(bool v, const CStateManager& mgr) {
  x58_25_visibleDebug = v;
  UpdateVisibility(mgr);
}

void CHudMissileInterface::SetIsMissilesActive(bool active) { x58_24_missilesActive = active; }

void CHudMissileInterface::SetChargeBeamFactor(float t) { x4c_chargeBeamFactor = t; }

void CHudMissileInterface::SetNumMissiles(int numMissiles, const CStateManager& mgr) {
  numMissiles = zeus::clamp(0, numMissiles, 999);

  x60_textpane_missiledigits->TextSupport().SetText(fmt::format(fmt("{:3d}"), numMissiles));

  if (x8_numMissles < numMissiles) {
    xc_arrowTimer = g_tweakGui->GetMissileArrowVisTime();
    x54_missileIconIncrement = -FLT_EPSILON;
  } else if (x8_numMissles > numMissiles) {
    xc_arrowTimer = -g_tweakGui->GetMissileArrowVisTime();
  }

  if (mgr.GetPlayerState()->GetMissileCostForAltAttack() + numMissiles <= x8_numMissles)
    x50_missileIconAltDeplete = 1.f;

  x8_numMissles = numMissiles;
}

void CHudMissileInterface::SetMissileCapacity(int missileCapacity) { x4_missileCapacity = missileCapacity; }

CHudMissileInterface::EInventoryStatus CHudMissileInterface::GetMissileInventoryStatus() const {
  if (x64_energybart01_missilebar->GetSetEnergy() == 0.f)
    return EInventoryStatus::Depleted;
  return EInventoryStatus(x64_energybart01_missilebar->GetActualFraction() < g_tweakGui->GetMissileWarningFraction());
}

std::pair<zeus::CVector3f, zeus::CVector3f> CHudMissileInterface::CombatMissileBarCoordFunc(float t) {
  const float z = t * IconTranslateRanges[size_t(EHudType::Combat)];
  return {zeus::CVector3f(0.f, 0.f, z), zeus::CVector3f(0.3f, 0.f, z)};
}

std::pair<zeus::CVector3f, zeus::CVector3f> CHudMissileInterface::XRayMissileBarCoordFunc(float t) {
  const float theta = 0.8f * (t - 0.5f);
  const float x = 9.55f * std::cos(theta);
  const float z = 9.55f * std::sin(theta);
  return {zeus::CVector3f(x - 0.4f, 0.f, z), zeus::CVector3f(x, 0.f, z)};
}

std::pair<zeus::CVector3f, zeus::CVector3f> CHudMissileInterface::ThermalMissileBarCoordFunc(float t) {
  const float transRange = IconTranslateRanges[size_t(EHudType::Thermal)];
  const float a = 0.08f * transRange;
  const float b = t * transRange;

  float c;
  if (b < a) {
    c = b / a;
  } else if (b < transRange - a) {
    c = 1.f;
  } else {
    c = 1.f - (b - (transRange - a)) / a;
  }

  return {zeus::CVector3f(-0.5f * c - 0.1f, 0.f, b), zeus::CVector3f(-0.1f, 0.f, b)};
}

} // namespace urde
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          configdlg.cpp
* Purpose:       Implementation of wxExtension config dialog class
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <functional>
#include <algorithm>
#include <wx/filepicker.h>
#include <wx/notebook.h>
#include <wx/persist/treebook.h>
#include <wx/spinctrl.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/frame.h>

#if wxUSE_GUI

wxExConfigDialog* wxExConfigComboBoxDialog(wxWindow* parent,
  const wxString& title,
  const wxString& item,
  int max_items,
  long flags,
  wxWindowID id,
  long style)
{
  std::vector<wxExConfigItem> v;

  v.push_back(wxExConfigItem(
    item,
    CONFIG_COMBOBOX,
    wxEmptyString,
    true, // is required
    wxID_ANY,
    max_items,
    false,// add name
    -1));

  return new wxExConfigDialog(
    parent,
    v,
    title,
    0,
    1,
    flags,
    id,
    style);
}

BEGIN_EVENT_TABLE(wxExConfigDialog, wxExDialog)
  EVT_BUTTON(wxID_APPLY, wxExConfigDialog::OnCommand)
  EVT_BUTTON(wxID_CANCEL, wxExConfigDialog::OnCommand)
  EVT_BUTTON(wxID_CLOSE, wxExConfigDialog::OnCommand)
  EVT_BUTTON(wxID_OK, wxExConfigDialog::OnCommand)
  EVT_UPDATE_UI(wxID_APPLY, wxExConfigDialog::OnUpdateUI)
  EVT_UPDATE_UI(wxID_OK, wxExConfigDialog::OnUpdateUI)
END_EVENT_TABLE()

// wxPropertySheetDialog has been tried as well,
// then you always have a notebook, and apply button is not supported.
wxExConfigDialog::wxExConfigDialog(wxWindow* parent,
  const std::vector<wxExConfigItem>& v,
  const wxString& title,
  int rows,
  int cols,
  long flags,
  wxWindowID id,
  long style)
  : wxExDialog(
      parent,
      title,
      flags,
      id,
      wxDefaultPosition,
      wxDefaultSize,
      style)
  , m_ForceCheckBoxChecked(false)
  , m_Page(wxEmptyString)
  , m_ConfigItems(v)
{
  wxASSERT(!m_ConfigItems.empty());

  Layout(rows, cols);
}

std::vector< wxExConfigItem >::const_iterator
wxExConfigDialog::FindConfigItem(int id) const
{
  for (
    auto it = m_ConfigItems.begin();
    it != m_ConfigItems.end();
    ++it)
  {
    if (it->GetControl()->GetId() == id)
    {
      return it;
    }
  }

  return m_ConfigItems.end();
}

void wxExConfigDialog::Click(int id) const
{
  wxASSERT(wxTheApp != NULL);
  wxWindow* window = wxTheApp->GetTopWindow();
  wxASSERT(window != NULL);
  wxExFrame* frame = wxDynamicCast(window, wxExFrame);
  wxASSERT(frame != NULL);

  frame->OnCommandConfigDialog(GetId(), id);
}

void wxExConfigDialog::ForceCheckBoxChecked(
  const wxString& contains,
  const wxString& page)
{
  m_ForceCheckBoxChecked = true;
  m_Contains = contains;
  m_Page = page;
}

void wxExConfigDialog::Layout(int rows, int cols)
{
  bool first_time = true;
  wxFlexGridSizer* sizer = NULL;
  wxFlexGridSizer* previous_item_sizer = NULL;
  int previous_item_type = -1;
  wxNotebook* notebook =
    (m_ConfigItems.begin()->GetPage().empty() ?
       NULL:
       new wxNotebook(this, wxID_ANY));
  wxString previous_page = "XXXXXX";

  for (
    auto it = m_ConfigItems.begin();
    it != m_ConfigItems.end();
    ++it)
  {
    if (first_time ||
        (it->GetPage() != previous_page && !it->GetPage().empty()))
    {
      first_time = false;

      if (notebook != NULL)
      {
        // Finish the current page.
        if (notebook->GetCurrentPage() != NULL)
        {
          notebook->GetCurrentPage()->SetSizerAndFit(sizer);
        }

        // And make a new one.
        notebook->AddPage(
          new wxWindow(notebook, wxID_ANY), it->GetPage(), true); // select
      }

      previous_page = it->GetPage();

      const int use_cols = (it->GetColumns() != -1 ? it->GetColumns(): cols);

      sizer = (rows != 0 ?
        new wxFlexGridSizer(rows, use_cols, 0, 0):
        new wxFlexGridSizer(use_cols));

      for (auto i = 0; i < use_cols; i++)
      {
        sizer->AddGrowableCol(i);
      }
    }

    wxFlexGridSizer* use_item_sizer = (it->GetType() == previous_item_type ?
      previous_item_sizer: NULL);

    previous_item_sizer = it->Layout(
      (notebook != NULL ? notebook->GetCurrentPage(): this),
      sizer,
      GetButtonFlags() == wxCANCEL,
      use_item_sizer);

    previous_item_type = it->GetType();

    if (
      it->GetType() == CONFIG_BUTTON ||
      it->GetType() == CONFIG_COMBOBOXDIR)
    {
      Bind(
        wxEVT_COMMAND_BUTTON_CLICKED,
        &wxExConfigDialog::OnCommand,
        this,
        it->GetControl()->GetId());
    }

    if ( sizer->GetRows() > 0 &&
        !sizer->IsRowGrowable(sizer->GetRows() - 1))
    {
      sizer->AddGrowableRow(sizer->GetRows() - 1);
    }
  }

  if (notebook != NULL)
  {
    notebook->GetCurrentPage()->SetSizerAndFit(sizer);
    notebook->SetName("book" + GetName());

    if (!wxPersistenceManager::Get().RegisterAndRestore(notebook))
    {
      // nothing was restored, so choose the default page ourselves
      notebook->SetSelection(0);
    }

    AddUserSizer(notebook);
  }
  else
  {
    AddUserSizer(sizer);
  }

  LayoutSizers(notebook == NULL); // add separator line if no notebook
}

void wxExConfigDialog::OnCommand(wxCommandEvent& command)
{
  if (command.GetId() < wxID_LOWEST)
  {
    auto it = FindConfigItem(command.GetId());

    if (it != m_ConfigItems.end())
    {
      if (it->GetType() == CONFIG_COMBOBOXDIR)
      {
        auto browse = (wxComboBox*)it->GetControl();

        wxDirDialog dir_dlg(
          this,
          _(wxDirSelectorPromptStr),
          browse->GetValue(),
          wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);

        if (dir_dlg.ShowModal() == wxID_OK)
        {
          browse->SetValue(dir_dlg.GetPath());
        }
      }
      else if (it->GetType() == CONFIG_BUTTON)
      {
        Click(command.GetId());
      }
      else
      {
        wxFAIL;
      }
    }
  }
  else if (command.GetId() == wxID_CANCEL)
  {
    Reload();
  }
  else
  {
    // Save to config.
    for_each (m_ConfigItems.begin(), m_ConfigItems.end(),
      std::bind2nd(std::mem_fun_ref(&wxExConfigItem::ToConfig), true));
  }

  if ( command.GetId() == wxID_APPLY ||
      ((command.GetId() == wxID_OK ||
        command.GetId() == wxID_CANCEL) && !IsModal()))
  {
    Click(command.GetId());
  }

  command.Skip();
}

void wxExConfigDialog::OnUpdateUI(wxUpdateUIEvent& event)
{
  bool one_checkbox_checked = false;

  for (
    auto it = m_ConfigItems.begin();
    it != m_ConfigItems.end();
    ++it)
  {
    switch (it->GetType())
    {
    case CONFIG_CHECKBOX:
      if (m_ForceCheckBoxChecked)
      {
        wxCheckBox* cb = (wxCheckBox*)it->GetControl();

        if (it->GetName().Lower().Contains(m_Contains.Lower()) &&
            cb->GetValue() &&
            it->GetPage() == m_Page)
        {
          one_checkbox_checked = true;
        }
      }
      break;

    case CONFIG_CHECKLISTBOX_NONAME:
      if (m_ForceCheckBoxChecked)
      {
        wxCheckListBox* clb = (wxCheckListBox*)it->GetControl();

        for (
          size_t i = 0;
          i < clb->GetCount();
          i++)
        {
          if (clb->GetString(i).Lower().Contains(m_Contains.Lower()) &&
              clb->IsChecked(i) &&
              it->GetPage() == m_Page)
          {
            one_checkbox_checked = true;
          }
        }
      }
      break;

    case CONFIG_COMBOBOX:
    case CONFIG_COMBOBOXDIR:
      {
      wxComboBox* cb = (wxComboBox*)it->GetControl();
      if (it->GetIsRequired())
      {
        if (cb->GetValue().empty())
        {
          event.Enable(false);
          return;
        }
      }
      }
      break;

    case CONFIG_INT:
    case CONFIG_STRING:
      {
      wxTextCtrl* tc = (wxTextCtrl*)it->GetControl();
      if (it->GetIsRequired())
      {
        if (tc->GetValue().empty())
        {
          event.Enable(false);
          return;
        }
      }
      }
      break;

    case CONFIG_DIRPICKERCTRL:
      {
      wxDirPickerCtrl* pc = (wxDirPickerCtrl*)it->GetControl();
      if (it->GetIsRequired())
      {
        if (pc->GetPath().empty())
        {
          event.Enable(false);
          return;
        }
      }
      }
      break;

    case CONFIG_FILEPICKERCTRL:
      {
      wxFilePickerCtrl* pc = (wxFilePickerCtrl*)it->GetControl();
      if (it->GetIsRequired())
      {
        if (pc->GetPath().empty())
        {
          event.Enable(false);
          return;
        }
      }
      }
      break;
    }
  }

  if (m_ForceCheckBoxChecked)
  {
    event.Enable(one_checkbox_checked);
  }
  else
  {
    event.Enable(true);
  }
}

void wxExConfigDialog::Reload() const
{
  for_each (m_ConfigItems.begin(), m_ConfigItems.end(),
    std::bind2nd(std::mem_fun_ref(&wxExConfigItem::ToConfig), false));
}
#endif // wxUSE_GUI
<commit_msg>use more auto<commit_after>/******************************************************************************\
* File:          configdlg.cpp
* Purpose:       Implementation of wxExtension config dialog class
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <functional>
#include <algorithm>
#include <wx/filepicker.h>
#include <wx/notebook.h>
#include <wx/persist/treebook.h>
#include <wx/spinctrl.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/frame.h>

#if wxUSE_GUI

wxExConfigDialog* wxExConfigComboBoxDialog(wxWindow* parent,
  const wxString& title,
  const wxString& item,
  int max_items,
  long flags,
  wxWindowID id,
  long style)
{
  std::vector<wxExConfigItem> v;

  v.push_back(wxExConfigItem(
    item,
    CONFIG_COMBOBOX,
    wxEmptyString,
    true, // is required
    wxID_ANY,
    max_items,
    false,// add name
    -1));

  return new wxExConfigDialog(
    parent,
    v,
    title,
    0,
    1,
    flags,
    id,
    style);
}

BEGIN_EVENT_TABLE(wxExConfigDialog, wxExDialog)
  EVT_BUTTON(wxID_APPLY, wxExConfigDialog::OnCommand)
  EVT_BUTTON(wxID_CANCEL, wxExConfigDialog::OnCommand)
  EVT_BUTTON(wxID_CLOSE, wxExConfigDialog::OnCommand)
  EVT_BUTTON(wxID_OK, wxExConfigDialog::OnCommand)
  EVT_UPDATE_UI(wxID_APPLY, wxExConfigDialog::OnUpdateUI)
  EVT_UPDATE_UI(wxID_OK, wxExConfigDialog::OnUpdateUI)
END_EVENT_TABLE()

// wxPropertySheetDialog has been tried as well,
// then you always have a notebook, and apply button is not supported.
wxExConfigDialog::wxExConfigDialog(wxWindow* parent,
  const std::vector<wxExConfigItem>& v,
  const wxString& title,
  int rows,
  int cols,
  long flags,
  wxWindowID id,
  long style)
  : wxExDialog(
      parent,
      title,
      flags,
      id,
      wxDefaultPosition,
      wxDefaultSize,
      style)
  , m_ForceCheckBoxChecked(false)
  , m_Page(wxEmptyString)
  , m_ConfigItems(v)
{
  wxASSERT(!m_ConfigItems.empty());

  Layout(rows, cols);
}

std::vector< wxExConfigItem >::const_iterator
wxExConfigDialog::FindConfigItem(int id) const
{
  for (
    auto it = m_ConfigItems.begin();
    it != m_ConfigItems.end();
    ++it)
  {
    if (it->GetControl()->GetId() == id)
    {
      return it;
    }
  }

  return m_ConfigItems.end();
}

void wxExConfigDialog::Click(int id) const
{
  wxASSERT(wxTheApp != NULL);
  wxWindow* window = wxTheApp->GetTopWindow();
  wxASSERT(window != NULL);
  wxExFrame* frame = wxDynamicCast(window, wxExFrame);
  wxASSERT(frame != NULL);

  frame->OnCommandConfigDialog(GetId(), id);
}

void wxExConfigDialog::ForceCheckBoxChecked(
  const wxString& contains,
  const wxString& page)
{
  m_ForceCheckBoxChecked = true;
  m_Contains = contains;
  m_Page = page;
}

void wxExConfigDialog::Layout(int rows, int cols)
{
  bool first_time = true;
  wxFlexGridSizer* sizer = NULL;
  wxFlexGridSizer* previous_item_sizer = NULL;
  int previous_item_type = -1;
  wxNotebook* notebook =
    (m_ConfigItems.begin()->GetPage().empty() ?
       NULL:
       new wxNotebook(this, wxID_ANY));
  wxString previous_page = "XXXXXX";

  for (
    auto it = m_ConfigItems.begin();
    it != m_ConfigItems.end();
    ++it)
  {
    if (first_time ||
        (it->GetPage() != previous_page && !it->GetPage().empty()))
    {
      first_time = false;

      if (notebook != NULL)
      {
        // Finish the current page.
        if (notebook->GetCurrentPage() != NULL)
        {
          notebook->GetCurrentPage()->SetSizerAndFit(sizer);
        }

        // And make a new one.
        notebook->AddPage(
          new wxWindow(notebook, wxID_ANY), it->GetPage(), true); // select
      }

      previous_page = it->GetPage();

      const auto use_cols = (it->GetColumns() != -1 ? it->GetColumns(): cols);

      sizer = (rows != 0 ?
        new wxFlexGridSizer(rows, use_cols, 0, 0):
        new wxFlexGridSizer(use_cols));

      for (auto i = 0; i < use_cols; i++)
      {
        sizer->AddGrowableCol(i);
      }
    }

    wxFlexGridSizer* use_item_sizer = (it->GetType() == previous_item_type ?
      previous_item_sizer: NULL);

    previous_item_sizer = it->Layout(
      (notebook != NULL ? notebook->GetCurrentPage(): this),
      sizer,
      GetButtonFlags() == wxCANCEL,
      use_item_sizer);

    previous_item_type = it->GetType();

    if (
      it->GetType() == CONFIG_BUTTON ||
      it->GetType() == CONFIG_COMBOBOXDIR)
    {
      Bind(
        wxEVT_COMMAND_BUTTON_CLICKED,
        &wxExConfigDialog::OnCommand,
        this,
        it->GetControl()->GetId());
    }

    if ( sizer->GetRows() > 0 &&
        !sizer->IsRowGrowable(sizer->GetRows() - 1))
    {
      sizer->AddGrowableRow(sizer->GetRows() - 1);
    }
  }

  if (notebook != NULL)
  {
    notebook->GetCurrentPage()->SetSizerAndFit(sizer);
    notebook->SetName("book" + GetName());

    if (!wxPersistenceManager::Get().RegisterAndRestore(notebook))
    {
      // nothing was restored, so choose the default page ourselves
      notebook->SetSelection(0);
    }

    AddUserSizer(notebook);
  }
  else
  {
    AddUserSizer(sizer);
  }

  LayoutSizers(notebook == NULL); // add separator line if no notebook
}

void wxExConfigDialog::OnCommand(wxCommandEvent& command)
{
  if (command.GetId() < wxID_LOWEST)
  {
    auto it = FindConfigItem(command.GetId());

    if (it != m_ConfigItems.end())
    {
      if (it->GetType() == CONFIG_COMBOBOXDIR)
      {
        auto browse = (wxComboBox*)it->GetControl();

        wxDirDialog dir_dlg(
          this,
          _(wxDirSelectorPromptStr),
          browse->GetValue(),
          wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);

        if (dir_dlg.ShowModal() == wxID_OK)
        {
          browse->SetValue(dir_dlg.GetPath());
        }
      }
      else if (it->GetType() == CONFIG_BUTTON)
      {
        Click(command.GetId());
      }
      else
      {
        wxFAIL;
      }
    }
  }
  else if (command.GetId() == wxID_CANCEL)
  {
    Reload();
  }
  else
  {
    // Save to config.
    for_each (m_ConfigItems.begin(), m_ConfigItems.end(),
      std::bind2nd(std::mem_fun_ref(&wxExConfigItem::ToConfig), true));
  }

  if ( command.GetId() == wxID_APPLY ||
      ((command.GetId() == wxID_OK ||
        command.GetId() == wxID_CANCEL) && !IsModal()))
  {
    Click(command.GetId());
  }

  command.Skip();
}

void wxExConfigDialog::OnUpdateUI(wxUpdateUIEvent& event)
{
  bool one_checkbox_checked = false;

  for (
    auto it = m_ConfigItems.begin();
    it != m_ConfigItems.end();
    ++it)
  {
    switch (it->GetType())
    {
    case CONFIG_CHECKBOX:
      if (m_ForceCheckBoxChecked)
      {
        wxCheckBox* cb = (wxCheckBox*)it->GetControl();

        if (it->GetName().Lower().Contains(m_Contains.Lower()) &&
            cb->GetValue() &&
            it->GetPage() == m_Page)
        {
          one_checkbox_checked = true;
        }
      }
      break;

    case CONFIG_CHECKLISTBOX_NONAME:
      if (m_ForceCheckBoxChecked)
      {
        wxCheckListBox* clb = (wxCheckListBox*)it->GetControl();

        for (
          size_t i = 0;
          i < clb->GetCount();
          i++)
        {
          if (clb->GetString(i).Lower().Contains(m_Contains.Lower()) &&
              clb->IsChecked(i) &&
              it->GetPage() == m_Page)
          {
            one_checkbox_checked = true;
          }
        }
      }
      break;

    case CONFIG_COMBOBOX:
    case CONFIG_COMBOBOXDIR:
      {
      wxComboBox* cb = (wxComboBox*)it->GetControl();
      if (it->GetIsRequired())
      {
        if (cb->GetValue().empty())
        {
          event.Enable(false);
          return;
        }
      }
      }
      break;

    case CONFIG_INT:
    case CONFIG_STRING:
      {
      wxTextCtrl* tc = (wxTextCtrl*)it->GetControl();
      if (it->GetIsRequired())
      {
        if (tc->GetValue().empty())
        {
          event.Enable(false);
          return;
        }
      }
      }
      break;

    case CONFIG_DIRPICKERCTRL:
      {
      wxDirPickerCtrl* pc = (wxDirPickerCtrl*)it->GetControl();
      if (it->GetIsRequired())
      {
        if (pc->GetPath().empty())
        {
          event.Enable(false);
          return;
        }
      }
      }
      break;

    case CONFIG_FILEPICKERCTRL:
      {
      wxFilePickerCtrl* pc = (wxFilePickerCtrl*)it->GetControl();
      if (it->GetIsRequired())
      {
        if (pc->GetPath().empty())
        {
          event.Enable(false);
          return;
        }
      }
      }
      break;
    }
  }

  if (m_ForceCheckBoxChecked)
  {
    event.Enable(one_checkbox_checked);
  }
  else
  {
    event.Enable(true);
  }
}

void wxExConfigDialog::Reload() const
{
  for_each (m_ConfigItems.begin(), m_ConfigItems.end(),
    std::bind2nd(std::mem_fun_ref(&wxExConfigItem::ToConfig), false));
}
#endif // wxUSE_GUI
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2013-2014 winlin

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef SRS_APP_AVC_AAC_HPP
#define SRS_APP_AVC_AAC_HPP

/*
#include <srs_app_avc_aac.hpp>
*/

#include <srs_core.hpp>

#include <srs_kernel_codec.hpp>

class SrsStream;

#define SRS_MAX_CODEC_SAMPLE 128
#define _SRS_AAC_SAMPLE_RATE_UNSET 15

/**
* the FLV/RTMP supported audio sample rate.
* Sampling rate. The following values are defined:
* 0 = 5.5 kHz = 5512 Hz
* 1 = 11 kHz = 11025 Hz
* 2 = 22 kHz = 22050 Hz
* 3 = 44 kHz = 44100 Hz
*/
enum SrsCodecAudioSampleRate
{
    // set to the max value to reserved, for array map.
    SrsCodecAudioSampleRateReserved                    = 4,

    SrsCodecAudioSampleRate5512                     = 0,
    SrsCodecAudioSampleRate11025                     = 1,
    SrsCodecAudioSampleRate22050                     = 2,
    SrsCodecAudioSampleRate44100                     = 3,
};

/**
* the FLV/RTMP supported audio sample size.
* Size of each audio sample. This parameter only pertains to
* uncompressed formats. Compressed formats always decode
* to 16 bits internally.
* 0 = 8-bit samples
* 1 = 16-bit samples
*/
enum SrsCodecAudioSampleSize
{
    // set to the max value to reserved, for array map.
    SrsCodecAudioSampleSizeReserved                    = 2,

    SrsCodecAudioSampleSize8bit                     = 0,
    SrsCodecAudioSampleSize16bit                     = 1,
};

/**
* the FLV/RTMP supported audio sound type/channel.
* Mono or stereo sound
* 0 = Mono sound
* 1 = Stereo sound
*/
enum SrsCodecAudioSoundType
{
    // set to the max value to reserved, for array map.
    SrsCodecAudioSoundTypeReserved                    = 2,

    SrsCodecAudioSoundTypeMono                         = 0,
    SrsCodecAudioSoundTypeStereo                     = 1,
};

/**
* the codec sample unit.
* for h.264 video packet, a NALU is a sample unit.
* for aac raw audio packet, a NALU is the entire aac raw data.
* for sequence header, it's not a sample unit.
*/
class SrsCodecSampleUnit
{
public:
    /**
    * the sample bytes is directly ptr to packet bytes,
    * user should never use it when packet destroyed.
    */
    int size;
    char* bytes;
public:
    SrsCodecSampleUnit();
    virtual ~SrsCodecSampleUnit();
};

/**
* the samples in the flv audio/video packet.
* the sample used to analysis a video/audio packet,
* split the h.264 NALUs to buffers, or aac raw data to a buffer,
* and decode the video/audio specified infos.
*
* the sample unit:
*       a video packet codec in h.264 contains many NALUs, each is a sample unit.
*       a audio packet codec in aac is a sample unit.
* @remark, the video/audio sequence header is not sample unit,
*       all sequence header stores as extra data,
*       @see SrsAvcAacCodec.avc_extra_data and SrsAvcAacCodec.aac_extra_data
* @remark, user must clear all samples before decode a new video/audio packet.
*/
class SrsCodecSample
{
public:
    /**
    * each audio/video raw data packet will dumps to one or multiple buffers,
    * the buffers will write to hls and clear to reset.
    * generally, aac audio packet corresponding to one buffer,
    * where avc/h264 video packet may contains multiple buffer.
    */
    int nb_sample_units;
    SrsCodecSampleUnit sample_units[SRS_MAX_CODEC_SAMPLE];
public:
    bool is_video;
    /**
    * CompositionTime, video_file_format_spec_v10_1.pdf, page 78.
    * cts = pts - dts, where dts = flvheader->timestamp.
    */
    int32_t cts;
public:
    // video specified
    SrsCodecVideoAVCFrame frame_type;
    SrsCodecVideoAVCType avc_packet_type;
public:
    // audio specified
    SrsCodecAudioSampleRate sound_rate;
    SrsCodecAudioSampleSize sound_size;
    SrsCodecAudioSoundType sound_type;
    SrsCodecAudioType aac_packet_type;
public:
    SrsCodecSample();
    virtual ~SrsCodecSample();
public:
    /**
    * clear all samples.
    * the sample units never copy the bytes, it directly use the ptr,
    * so when video/audio packet is destroyed, the sample must be clear.
    * in a word, user must clear sample before demux it.
    * @remark demux sample use SrsAvcAacCodec.audio_aac_demux or video_avc_demux.
    */
    void clear();
    /**
    * add the a sample unit, it's a h.264 NALU or aac raw data.
    * the sample unit directly use the ptr of packet bytes,
    * so user must never use sample unit when packet is destroyed.
    * in a word, user must clear sample before demux it.
    */
    int add_sample_unit(char* bytes, int size);
};

/**
* the h264/avc and aac codec, for media stream.
*
* to demux the FLV/RTMP video/audio packet to sample,
* add each NALUs of h.264 as a sample unit to sample,
* while the entire aac raw data as a sample unit.
*
* for sequence header,
* demux it and save it in the avc_extra_data and aac_extra_data,
*
* for the codec info, such as audio sample rate,
* decode from FLV/RTMP header, then use codec info in sequence
* header to override it.
*/
class SrsAvcAacCodec
{
private:
    SrsStream* stream;
public:
    /**
    * video specified
    */
    // @see: SrsCodecVideo
    int            video_codec_id;
    // profile_idc, H.264-AVC-ISO_IEC_14496-10.pdf, page 45.
    u_int8_t    avc_profile;
    // level_idc, H.264-AVC-ISO_IEC_14496-10.pdf, page 45.
    u_int8_t    avc_level;
    int            width;
    int            height;
    int            video_data_rate; // in bps
    int            frame_rate;
    int            duration;
    // lengthSizeMinusOne, H.264-AVC-ISO_IEC_14496-15.pdf, page 16
    int8_t         NAL_unit_length;
    u_int16_t     sequenceParameterSetLength;
    char*         sequenceParameterSetNALUnit;
    u_int16_t     pictureParameterSetLength;
    char*         pictureParameterSetNALUnit;
public:
    /**
    * audio specified
    */
    // @see: SrsCodecAudioType
    int            audio_codec_id;
    int            audio_data_rate; // in bps
    // 1.6.2.1 AudioSpecificConfig, in aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 33.
    // audioObjectType, value defines in 7.1 Profiles, aac-iso-13818-7.pdf, page 40.
    u_int8_t    aac_profile;
    // samplingFrequencyIndex
    u_int8_t    aac_sample_rate;
    // channelConfiguration
    u_int8_t    aac_channels;
public:
    // the avc extra data, the AVC sequence header,
    // without the flv codec header,
    // @see: ffmpeg, AVCodecContext::extradata
    int         avc_extra_size;
    char*        avc_extra_data;
    // the aac extra data, the AAC sequence header,
    // without the flv codec header,
    // @see: ffmpeg, AVCodecContext::extradata
    int         aac_extra_size;
    char*        aac_extra_data;
public:
    SrsAvcAacCodec();
    virtual ~SrsAvcAacCodec();
// the following function used for hls to build the codec info.
public:
    virtual int audio_aac_demux(char* data, int size, SrsCodecSample* sample);
    virtual int video_avc_demux(char* data, int size, SrsCodecSample* sample);
};

#endif
<commit_msg>refine the hls codec, add comments.<commit_after>/*
The MIT License (MIT)

Copyright (c) 2013-2014 winlin

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef SRS_APP_AVC_AAC_HPP
#define SRS_APP_AVC_AAC_HPP

/*
#include <srs_app_avc_aac.hpp>
*/

#include <srs_core.hpp>

#include <srs_kernel_codec.hpp>

class SrsStream;

#define SRS_MAX_CODEC_SAMPLE 128
#define _SRS_AAC_SAMPLE_RATE_UNSET 15

/**
* the FLV/RTMP supported audio sample rate.
* Sampling rate. The following values are defined:
* 0 = 5.5 kHz = 5512 Hz
* 1 = 11 kHz = 11025 Hz
* 2 = 22 kHz = 22050 Hz
* 3 = 44 kHz = 44100 Hz
*/
enum SrsCodecAudioSampleRate
{
    // set to the max value to reserved, for array map.
    SrsCodecAudioSampleRateReserved                 = 4,

    SrsCodecAudioSampleRate5512                     = 0,
    SrsCodecAudioSampleRate11025                    = 1,
    SrsCodecAudioSampleRate22050                    = 2,
    SrsCodecAudioSampleRate44100                    = 3,
};

/**
* the FLV/RTMP supported audio sample size.
* Size of each audio sample. This parameter only pertains to
* uncompressed formats. Compressed formats always decode
* to 16 bits internally.
* 0 = 8-bit samples
* 1 = 16-bit samples
*/
enum SrsCodecAudioSampleSize
{
    // set to the max value to reserved, for array map.
    SrsCodecAudioSampleSizeReserved                 = 2,

    SrsCodecAudioSampleSize8bit                     = 0,
    SrsCodecAudioSampleSize16bit                    = 1,
};

/**
* the FLV/RTMP supported audio sound type/channel.
* Mono or stereo sound
* 0 = Mono sound
* 1 = Stereo sound
*/
enum SrsCodecAudioSoundType
{
    // set to the max value to reserved, for array map.
    SrsCodecAudioSoundTypeReserved                  = 2,

    SrsCodecAudioSoundTypeMono                      = 0,
    SrsCodecAudioSoundTypeStereo                    = 1,
};

/**
* the codec sample unit.
* for h.264 video packet, a NALU is a sample unit.
* for aac raw audio packet, a NALU is the entire aac raw data.
* for sequence header, it's not a sample unit.
*/
class SrsCodecSampleUnit
{
public:
    /**
    * the sample bytes is directly ptr to packet bytes,
    * user should never use it when packet destroyed.
    */
    int size;
    char* bytes;
public:
    SrsCodecSampleUnit();
    virtual ~SrsCodecSampleUnit();
};

/**
* the samples in the flv audio/video packet.
* the sample used to analysis a video/audio packet,
* split the h.264 NALUs to buffers, or aac raw data to a buffer,
* and decode the video/audio specified infos.
*
* the sample unit:
*       a video packet codec in h.264 contains many NALUs, each is a sample unit.
*       a audio packet codec in aac is a sample unit.
* @remark, the video/audio sequence header is not sample unit,
*       all sequence header stores as extra data,
*       @see SrsAvcAacCodec.avc_extra_data and SrsAvcAacCodec.aac_extra_data
* @remark, user must clear all samples before decode a new video/audio packet.
*/
class SrsCodecSample
{
public:
    /**
    * each audio/video raw data packet will dumps to one or multiple buffers,
    * the buffers will write to hls and clear to reset.
    * generally, aac audio packet corresponding to one buffer,
    * where avc/h264 video packet may contains multiple buffer.
    */
    int nb_sample_units;
    SrsCodecSampleUnit sample_units[SRS_MAX_CODEC_SAMPLE];
public:
    /**
    * whether the sample is video sample which demux from video packet.
    */
    bool is_video;
    /**
    * CompositionTime, video_file_format_spec_v10_1.pdf, page 78.
    * cts = pts - dts, where dts = flvheader->timestamp.
    */
    int32_t cts;
public:
    // video specified
    SrsCodecVideoAVCFrame frame_type;
    SrsCodecVideoAVCType avc_packet_type;
public:
    // audio specified
    SrsCodecAudioSampleRate sound_rate;
    SrsCodecAudioSampleSize sound_size;
    SrsCodecAudioSoundType sound_type;
    SrsCodecAudioType aac_packet_type;
public:
    SrsCodecSample();
    virtual ~SrsCodecSample();
public:
    /**
    * clear all samples.
    * the sample units never copy the bytes, it directly use the ptr,
    * so when video/audio packet is destroyed, the sample must be clear.
    * in a word, user must clear sample before demux it.
    * @remark demux sample use SrsAvcAacCodec.audio_aac_demux or video_avc_demux.
    */
    void clear();
    /**
    * add the a sample unit, it's a h.264 NALU or aac raw data.
    * the sample unit directly use the ptr of packet bytes,
    * so user must never use sample unit when packet is destroyed.
    * in a word, user must clear sample before demux it.
    */
    int add_sample_unit(char* bytes, int size);
};

/**
* the h264/avc and aac codec, for media stream.
*
* to demux the FLV/RTMP video/audio packet to sample,
* add each NALUs of h.264 as a sample unit to sample,
* while the entire aac raw data as a sample unit.
*
* for sequence header,
* demux it and save it in the avc_extra_data and aac_extra_data,
*
* for the codec info, such as audio sample rate,
* decode from FLV/RTMP header, then use codec info in sequence
* header to override it.
*/
class SrsAvcAacCodec
{
private:
    SrsStream* stream;
public:
    /**
    * metadata specified
    */
    int             duration;
    int             width;
    int             height;
    int             frame_rate;
    // @see: SrsCodecVideo
    int             video_codec_id;
    int             video_data_rate; // in bps
    // @see: SrsCod ecAudioType
    int             audio_codec_id;
    int             audio_data_rate; // in bps
public:
    /**
    * video specified
    */
    // profile_idc, H.264-AVC-ISO_IEC_14496-10.pdf, page 45.
    u_int8_t        avc_profile;
    // level_idc, H.264-AVC-ISO_IEC_14496-10.pdf, page 45.
    u_int8_t        avc_level;
    // lengthSizeMinusOne, H.264-AVC-ISO_IEC_14496-15.pdf, page 16
    int8_t          NAL_unit_length;
    u_int16_t       sequenceParameterSetLength;
    char*           sequenceParameterSetNALUnit;
    u_int16_t       pictureParameterSetLength;
    char*           pictureParameterSetNALUnit;
public:
    /**
    * audio specified
    */
    // 1.6.2.1 AudioSpecificConfig, in aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 33.
    // audioObjectType, value defines in 7.1 Profiles, aac-iso-13818-7.pdf, page 40.
    u_int8_t        aac_profile;
    // samplingFrequencyIndex
    u_int8_t        aac_sample_rate;
    // channelConfiguration
    u_int8_t        aac_channels;
public:
    // the avc extra data, the AVC sequence header,
    // without the flv codec header,
    // @see: ffmpeg, AVCodecContext::extradata
    int             avc_extra_size;
    char*           avc_extra_data;
    // the aac extra data, the AAC sequence header,
    // without the flv codec header,
    // @see: ffmpeg, AVCodecContext::extradata
    int             aac_extra_size;
    char*           aac_extra_data;
public:
    SrsAvcAacCodec();
    virtual ~SrsAvcAacCodec();
// the following function used for hls to build the codec info.
public:
    virtual int audio_aac_demux(char* data, int size, SrsCodecSample* sample);
    virtual int video_avc_demux(char* data, int size, SrsCodecSample* sample);
};

#endif
<|endoftext|>


<commit_before>//
// Copyright (C) 1997-2000 Shigeru Chiba
// Copyright (C) 2004 Stefan Seefeld
// All rights reserved.
// Licensed to the public under the terms of the GNU LGPL (>= 2),
// see the file COPYING for details.
//
#include "PTree/Atoms.hh"

namespace
{
// little helper for initialization
char *dup_alloc(const char *str1, size_t len1,
		const char *str2, size_t len2)
{
  char *buffer = new (GC) char[len1 + len2];
  memmove(buffer, str1, len1);
  memmove(buffer + len1, str2, len2);
  return buffer;
}

}

using namespace PTree;

DupAtom::DupAtom(const char *str, size_t len)
  : CommentedAtom(static_cast<char *>(memmove(new (GC) char[len], str, len)), len)
{
}

DupAtom::DupAtom(const char *str1, size_t len1,
		 const char *str2, size_t len2)
  : CommentedAtom(dup_alloc(str1, len1, str2, len2), len1 + len2)
{
}

<commit_msg>little fix to reenable gc-free configuration<commit_after>//
// Copyright (C) 1997-2000 Shigeru Chiba
// Copyright (C) 2004 Stefan Seefeld
// All rights reserved.
// Licensed to the public under the terms of the GNU LGPL (>= 2),
// see the file COPYING for details.
//
#include "PTree/Atoms.hh"

using namespace PTree;

namespace
{
// little helper for initialization
char *dup_alloc(const char *str1, size_t len1,
		const char *str2, size_t len2)
{
  char *buffer = new (GC) char[len1 + len2];
  memmove(buffer, str1, len1);
  memmove(buffer + len1, str2, len2);
  return buffer;
}

}

using namespace PTree;

DupAtom::DupAtom(const char *str, size_t len)
  : CommentedAtom(static_cast<char *>(memmove(new (GC) char[len], str, len)), len)
{
}

DupAtom::DupAtom(const char *str1, size_t len1,
		 const char *str2, size_t len2)
  : CommentedAtom(dup_alloc(str1, len1, str2, len2), len1 + len2)
{
}

<|endoftext|>


<commit_before>// This program must be compiled and executed with Aclic as follows
//
// .x unuranFoamTest.C+
//
// it is an extension of tutorials foam_kanwa.C to compare
// generation of a 2D distribution with unuran and Foam
//_____________________________________________________________________________

#if defined(__CINT__) && !defined(__MAKECINT__)
{
   TString macroFileName = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
   gSystem->CompileMacro(macroFileName, "k");
   unuranFoamTest();
}
#else

#include "TH2.h"
#include "TF2.h"
#include "TSystem.h"
#include "TCanvas.h"
#include "TMath.h"
#include "TRandom3.h"
#include "TFoam.h"
#include "TFoamIntegrand.h"
#include "TStopwatch.h"
#include "TROOT.h"

#include "TUnuran.h"
#include "TUnuranMultiContDist.h"

#include <iostream>

//_____________________________________________________________________________
Double_t sqr(Double_t x){return x*x;};
//_____________________________________________________________________________
//_____________________________________________________________________________

Double_t Camel2(Int_t, Double_t *Xarg){
// 2-dimensional distribution for Foam, normalized to one (within 1e-5)
  Double_t x=Xarg[0];
  Double_t y=Xarg[1];
  Double_t GamSq= sqr(0.100e0);
  Double_t Dist= 0;
  Dist +=exp(-(sqr(x-1./3) +sqr(y-1./3))/GamSq)/GamSq/TMath::Pi();
  Dist +=exp(-(sqr(x-2./3) +sqr(y-2./3))/GamSq)/GamSq/TMath::Pi();
  return 0.5*Dist;
}// Camel2

class FoamFunction : public TFoamIntegrand {
   public:
   virtual ~FoamFunction() {}
   double Density(int nDim, double * x) {
      return Camel2(nDim,x);
   }
   ClassDef(FoamFunction,1);

};

TH2 * hFoam;
TH2 * hUnr;

Int_t run_foam(int nev){
  cout<<"--- kanwa started ---"<<endl;
  gSystem->Load("libFoam.so");
  TH2D  *hst_xy = new TH2D("foam_hst_xy" ,  "FOAM x-y plot", 50,0,1.0, 50,0,1.0);
  hFoam = hst_xy;

  Double_t *MCvect =new Double_t[2]; // 2-dim vector generated in the MC run
  //
  TRandom     *PseRan   = new TRandom3();  // Create random number generator
  PseRan->SetSeed(4357);
  TFoam   *FoamX    = new TFoam("FoamX");   // Create Simulator
  FoamX->SetkDim(2);         // No. of dimensions, obligatory!
  FoamX->SetnCells(500);     // Optionally No. of cells, default=2000
  FoamX->SetRho(new FoamFunction() );  // Set 2-dim distribution, included below
  FoamX->SetPseRan(PseRan);  // Set random number generator
  //
  // From now on FoamX is ready to generate events

   // test first the time
   TStopwatch w;

  w.Start();
  FoamX->Initialize();       // Initialize simulator, may take time...

  //int nshow=5000;
  int nshow=nev;

  for(long loop=0; loop<nev; loop++){
    FoamX->MakeEvent();            // generate MC event
    FoamX->GetMCvect( MCvect);     // get generated vector (x,y)
    Double_t x=MCvect[0];
    Double_t y=MCvect[1];
    //if(loop<10) cout<<"(x,y) =  ( "<< x <<", "<< y <<" )"<<endl;
    hst_xy->Fill(x,y);
    // live plot
    if(loop == nshow){
      nshow += 5000;
      hst_xy->Draw("lego2");
      //cKanwa->Update();
    }
  }// loop
  w.Stop();

  double time = w.CpuTime()*1.E9/nev;
  cout << "Time using FOAM \t\t " << "   \t=\t " << time << "\tns/call" << endl;

  //
  hst_xy->Draw("lego2");  // final plot
  //
  Double_t MCresult, MCerror;
  FoamX->GetIntegMC( MCresult, MCerror);  // get MC integral, should be one
  cout << " MCresult= " << MCresult << " +- " << MCerror <<endl;
  cout<<"--- kanwa ended ---"<<endl;

  return 0;
}//kanwa

double UCamel2(double * x, double *) {
   return Camel2(2,x);
}

int run_unuran(int nev, std::string method = "hitro") {
   // use unuran

   std::cout << "run unuran " << std::endl;

   gSystem->Load("libUnuran.so");

   TH2D  *h1 = new TH2D("unr_hst_xy" ,  "UNURAN x-y plot", 50,0,1.0, 50,0,1.0);
   hUnr= h1;

   TF2 * f = new TF2("f",UCamel2,0,1,0,1,0);

   TUnuranMultiContDist dist(f);

   TRandom3 r;

   TUnuran unr(&r,2);  // 2 is debug level

   // test first the time
   TStopwatch w;

   w.Start();

   // init unuran
   bool ret =   unr.Init(dist,method);
   if (!ret) {
      std::cerr << "Error initializing unuran with method " << unr.MethodName() << endl;
      return -1;
   }

   double x[2];
   for (int i = 0; i < nev; ++i) {
      unr.SampleMulti(x);
      h1->Fill(x[0],x[1]);
//       if (method == "gibbs" && i < 100)
//          std::cout << x[0] << " , " << x[1] << std::endl;
   }

   w.Stop();
   double time = w.CpuTime()*1.E9/nev;
   cout << "Time using Unuran  " << unr.MethodName() << "   \t=\t " << time << "\tns/call" << endl;
   h1->Draw("lego2");
   return 0;
}

Int_t unuranFoamTest(){

  // visualising generated distribution
  TCanvas *cKanwa = new TCanvas("cKanwa","Canvas for plotting",600,1000);
  cKanwa->Divide(1,2);
  cKanwa->cd(1);
  int n = 100000;

  run_unuran(n,"hitro");
  cKanwa->Update();

  cKanwa->cd(2);

  run_foam(n);
  cKanwa->Update();

  std::cout <<"\nChi2 Test Results (UNURAN-FOAM):\t";
  // test chi2
  hFoam->Chi2Test(hUnr,"UUP");

  return 0;
}

#endif<commit_msg>Force recompilation of tutorial with AClic<commit_after>// This program must be compiled and executed with Aclic as follows
//
// .x unuranFoamTest.C+
//
// it is an extension of tutorials foam_kanwa.C to compare
// generation of a 2D distribution with unuran and Foam
//_____________________________________________________________________________

#if defined(__CINT__) && !defined(__MAKECINT__)
{
   TString macroFileName = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
   gSystem->CompileMacro(macroFileName, "f");  // force re-compilation
   unuranFoamTest();
}
#else

#include "TH2.h"
#include "TF2.h"
#include "TSystem.h"
#include "TCanvas.h"
#include "TMath.h"
#include "TRandom3.h"
#include "TFoam.h"
#include "TFoamIntegrand.h"
#include "TStopwatch.h"
#include "TROOT.h"

#include "TUnuran.h"
#include "TUnuranMultiContDist.h"

#include <iostream>

//_____________________________________________________________________________
Double_t sqr(Double_t x){return x*x;};
//_____________________________________________________________________________
//_____________________________________________________________________________

Double_t Camel2(Int_t, Double_t *Xarg){
// 2-dimensional distribution for Foam, normalized to one (within 1e-5)
  Double_t x=Xarg[0];
  Double_t y=Xarg[1];
  Double_t GamSq= sqr(0.100e0);
  Double_t Dist= 0;
  Dist +=exp(-(sqr(x-1./3) +sqr(y-1./3))/GamSq)/GamSq/TMath::Pi();
  Dist +=exp(-(sqr(x-2./3) +sqr(y-2./3))/GamSq)/GamSq/TMath::Pi();
  return 0.5*Dist;
}// Camel2

class FoamFunction : public TFoamIntegrand {
   public:
   virtual ~FoamFunction() {}
   double Density(int nDim, double * x) {
      return Camel2(nDim,x);
   }
   ClassDef(FoamFunction,1);

};

TH2 * hFoam;
TH2 * hUnr;

Int_t run_foam(int nev){
  cout<<"--- kanwa started ---"<<endl;
  gSystem->Load("libFoam.so");
  TH2D  *hst_xy = new TH2D("foam_hst_xy" ,  "FOAM x-y plot", 50,0,1.0, 50,0,1.0);
  hFoam = hst_xy;

  Double_t *MCvect =new Double_t[2]; // 2-dim vector generated in the MC run
  //
  TRandom     *PseRan   = new TRandom3();  // Create random number generator
  PseRan->SetSeed(4357);
  TFoam   *FoamX    = new TFoam("FoamX");   // Create Simulator
  FoamX->SetkDim(2);         // No. of dimensions, obligatory!
  FoamX->SetnCells(500);     // Optionally No. of cells, default=2000
  FoamX->SetRho(new FoamFunction() );  // Set 2-dim distribution, included below
  FoamX->SetPseRan(PseRan);  // Set random number generator
  //
  // From now on FoamX is ready to generate events

   // test first the time
   TStopwatch w;

  w.Start();
  FoamX->Initialize();       // Initialize simulator, may take time...

  //int nshow=5000;
  int nshow=nev;

  for(long loop=0; loop<nev; loop++){
    FoamX->MakeEvent();            // generate MC event
    FoamX->GetMCvect( MCvect);     // get generated vector (x,y)
    Double_t x=MCvect[0];
    Double_t y=MCvect[1];
    //if(loop<10) cout<<"(x,y) =  ( "<< x <<", "<< y <<" )"<<endl;
    hst_xy->Fill(x,y);
    // live plot
    if(loop == nshow){
      nshow += 5000;
      hst_xy->Draw("lego2");
      //cKanwa->Update();
    }
  }// loop
  w.Stop();

  double time = w.CpuTime()*1.E9/nev;
  cout << "Time using FOAM \t\t " << "   \t=\t " << time << "\tns/call" << endl;

  //
  hst_xy->Draw("lego2");  // final plot
  //
  Double_t MCresult, MCerror;
  FoamX->GetIntegMC( MCresult, MCerror);  // get MC integral, should be one
  cout << " MCresult= " << MCresult << " +- " << MCerror <<endl;
  cout<<"--- kanwa ended ---"<<endl;

  return 0;
}//kanwa

double UCamel2(double * x, double *) {
   return Camel2(2,x);
}

int run_unuran(int nev, std::string method = "hitro") {
   // use unuran

   std::cout << "run unuran " << std::endl;

   gSystem->Load("libUnuran.so");

   TH2D  *h1 = new TH2D("unr_hst_xy" ,  "UNURAN x-y plot", 50,0,1.0, 50,0,1.0);
   hUnr= h1;

   TF2 * f = new TF2("f",UCamel2,0,1,0,1,0);

   TUnuranMultiContDist dist(f);

   TRandom3 r;

   TUnuran unr(&r,2);  // 2 is debug level

   // test first the time
   TStopwatch w;

   w.Start();

   // init unuran
   bool ret =   unr.Init(dist,method);
   if (!ret) {
      std::cerr << "Error initializing unuran with method " << unr.MethodName() << endl;
      return -1;
   }

   double x[2];
   for (int i = 0; i < nev; ++i) {
      unr.SampleMulti(x);
      h1->Fill(x[0],x[1]);
//       if (method == "gibbs" && i < 100)
//          std::cout << x[0] << " , " << x[1] << std::endl;
   }

   w.Stop();
   double time = w.CpuTime()*1.E9/nev;
   cout << "Time using Unuran  " << unr.MethodName() << "   \t=\t " << time << "\tns/call" << endl;
   h1->Draw("lego2");
   return 0;
}

Int_t unuranFoamTest(){

  // visualising generated distribution
  TCanvas *cKanwa = new TCanvas("cKanwa","Canvas for plotting",600,1000);
  cKanwa->Divide(1,2);
  cKanwa->cd(1);
  int n = 100000;

  run_unuran(n,"hitro");
  cKanwa->Update();

  cKanwa->cd(2);

  run_foam(n);
  cKanwa->Update();

  std::cout <<"\nChi2 Test Results (UNURAN-FOAM):\t";
  // test chi2
  hFoam->Chi2Test(hUnr,"UUP");

  return 0;
}

#endif
<|endoftext|>


<commit_before>//========- unittests/Support/ThreadPools.cpp - ThreadPools.h tests --========//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/ThreadPool.h"

#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetSelect.h"

#include "gtest/gtest.h"

using namespace llvm;
using namespace std::chrono;

/// Try best to make this thread not progress faster than the main thread
static void yield() {
#ifdef LLVM_ENABLE_THREADS
  std::this_thread::yield();
#endif
  std::this_thread::sleep_for(milliseconds(200));
#ifdef LLVM_ENABLE_THREADS
  std::this_thread::yield();
#endif
}

// Fixture for the unittests, allowing to *temporarily* disable the unittests
// on a particular platform
class ThreadPoolTest : public testing::Test {
  Triple Host;
  SmallVector<Triple::ArchType, 4> UnsupportedArchs;
  SmallVector<Triple::OSType, 4> UnsupportedOSs;
  SmallVector<Triple::EnvironmentType, 1> UnsupportedEnvironments;
protected:
  // This is intended for platform as a temporary "XFAIL"
  bool isUnsupportedOSOrEnvironment() {
    Triple Host(Triple::normalize(sys::getProcessTriple()));

    if (std::find(UnsupportedEnvironments.begin(), UnsupportedEnvironments.end(),
                  Host.getEnvironment()) != UnsupportedEnvironments.end())
      return true;

    if (std::find(UnsupportedOSs.begin(), UnsupportedOSs.end(), Host.getOS())
        != UnsupportedOSs.end())
      return true;

    if (std::find(UnsupportedArchs.begin(), UnsupportedArchs.end(), Host.getArch())
        != UnsupportedArchs.end())
      return true;

    return false;
  }

  ThreadPoolTest() {
    // Add unsupported configuration here, example:
    //   UnsupportedArchs.push_back(Triple::x86_64);
  }
};

#define CHECK_UNSUPPORTED() \
  do { \
    if (isUnsupportedOSOrEnvironment()) \
      return; \
  } while (0); \

TEST_F(ThreadPoolTest, AsyncBarrier) {
  CHECK_UNSUPPORTED();
  // test that async & barrier work together properly.

  std::atomic_int checked_in{0};

  ThreadPool Pool;
  for (size_t i = 0; i < 5; ++i) {
    Pool.async([&checked_in, i] {
      yield();
      ++checked_in;
    });
  }
  ASSERT_EQ(0, checked_in);
  Pool.wait();
  ASSERT_EQ(5, checked_in);
}

static void TestFunc(std::atomic_int &checked_in, int i) { checked_in += i; }

TEST_F(ThreadPoolTest, AsyncBarrierArgs) {
  CHECK_UNSUPPORTED();
  // Test that async works with a function requiring multiple parameters.
  std::atomic_int checked_in{0};

  ThreadPool Pool;
  for (size_t i = 0; i < 5; ++i) {
    Pool.async(TestFunc, std::ref(checked_in), i);
  }
  Pool.wait();
  ASSERT_EQ(10, checked_in);
}

TEST_F(ThreadPoolTest, Async) {
  CHECK_UNSUPPORTED();
  ThreadPool Pool;
  std::atomic_int i{0};
  // sleep here just to ensure that the not-equal is correct.
  Pool.async([&i] {
    yield();
    ++i;
  });
  Pool.async([&i] { ++i; });
  ASSERT_NE(2, i.load());
  Pool.wait();
  ASSERT_EQ(2, i.load());
}

TEST_F(ThreadPoolTest, GetFuture) {
  CHECK_UNSUPPORTED();
  ThreadPool Pool;
  std::atomic_int i{0};
  // sleep here just to ensure that the not-equal is correct.
  Pool.async([&i] {
    yield();
    ++i;
  });
  // Force the future using get()
  Pool.async([&i] { ++i; }).get();
  ASSERT_NE(2, i.load());
  Pool.wait();
  ASSERT_EQ(2, i.load());
}

TEST_F(ThreadPoolTest, PoolDestruction) {
  CHECK_UNSUPPORTED();
  // Test that we are waiting on destruction
  std::atomic_int checked_in{0};

  {
    ThreadPool Pool;
    for (size_t i = 0; i < 5; ++i) {
      Pool.async([&checked_in, i] {
        yield();
        ++checked_in;
      });
    }
    ASSERT_EQ(0, checked_in);
  }
  ASSERT_EQ(5, checked_in);
}
<commit_msg>Mark ThreadPool unittests as unsupported on PowerPC64<commit_after>//========- unittests/Support/ThreadPools.cpp - ThreadPools.h tests --========//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/ThreadPool.h"

#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetSelect.h"

#include "gtest/gtest.h"

using namespace llvm;
using namespace std::chrono;

/// Try best to make this thread not progress faster than the main thread
static void yield() {
#ifdef LLVM_ENABLE_THREADS
  std::this_thread::yield();
#endif
  std::this_thread::sleep_for(milliseconds(200));
#ifdef LLVM_ENABLE_THREADS
  std::this_thread::yield();
#endif
}

// Fixture for the unittests, allowing to *temporarily* disable the unittests
// on a particular platform
class ThreadPoolTest : public testing::Test {
  Triple Host;
  SmallVector<Triple::ArchType, 4> UnsupportedArchs;
  SmallVector<Triple::OSType, 4> UnsupportedOSs;
  SmallVector<Triple::EnvironmentType, 1> UnsupportedEnvironments;
protected:
  // This is intended for platform as a temporary "XFAIL"
  bool isUnsupportedOSOrEnvironment() {
    Triple Host(Triple::normalize(sys::getProcessTriple()));

    if (std::find(UnsupportedEnvironments.begin(), UnsupportedEnvironments.end(),
                  Host.getEnvironment()) != UnsupportedEnvironments.end())
      return true;

    if (std::find(UnsupportedOSs.begin(), UnsupportedOSs.end(), Host.getOS())
        != UnsupportedOSs.end())
      return true;

    if (std::find(UnsupportedArchs.begin(), UnsupportedArchs.end(), Host.getArch())
        != UnsupportedArchs.end())
      return true;

    return false;
  }

  ThreadPoolTest() {
    // Add unsupported configuration here, example:
    //   UnsupportedArchs.push_back(Triple::x86_64);

    // See https://llvm.org/bugs/show_bug.cgi?id=25829
    UnsupportedArchs.push_back(Triple::ppc64le);
    UnsupportedArchs.push_back(Triple::ppc64);
  }
};

#define CHECK_UNSUPPORTED() \
  do { \
    if (isUnsupportedOSOrEnvironment()) \
      return; \
  } while (0); \

TEST_F(ThreadPoolTest, AsyncBarrier) {
  CHECK_UNSUPPORTED();
  // test that async & barrier work together properly.

  std::atomic_int checked_in{0};

  ThreadPool Pool;
  for (size_t i = 0; i < 5; ++i) {
    Pool.async([&checked_in, i] {
      yield();
      ++checked_in;
    });
  }
  ASSERT_EQ(0, checked_in);
  Pool.wait();
  ASSERT_EQ(5, checked_in);
}

static void TestFunc(std::atomic_int &checked_in, int i) { checked_in += i; }

TEST_F(ThreadPoolTest, AsyncBarrierArgs) {
  CHECK_UNSUPPORTED();
  // Test that async works with a function requiring multiple parameters.
  std::atomic_int checked_in{0};

  ThreadPool Pool;
  for (size_t i = 0; i < 5; ++i) {
    Pool.async(TestFunc, std::ref(checked_in), i);
  }
  Pool.wait();
  ASSERT_EQ(10, checked_in);
}

TEST_F(ThreadPoolTest, Async) {
  CHECK_UNSUPPORTED();
  ThreadPool Pool;
  std::atomic_int i{0};
  // sleep here just to ensure that the not-equal is correct.
  Pool.async([&i] {
    yield();
    ++i;
  });
  Pool.async([&i] { ++i; });
  ASSERT_NE(2, i.load());
  Pool.wait();
  ASSERT_EQ(2, i.load());
}

TEST_F(ThreadPoolTest, GetFuture) {
  CHECK_UNSUPPORTED();
  ThreadPool Pool;
  std::atomic_int i{0};
  // sleep here just to ensure that the not-equal is correct.
  Pool.async([&i] {
    yield();
    ++i;
  });
  // Force the future using get()
  Pool.async([&i] { ++i; }).get();
  ASSERT_NE(2, i.load());
  Pool.wait();
  ASSERT_EQ(2, i.load());
}

TEST_F(ThreadPoolTest, PoolDestruction) {
  CHECK_UNSUPPORTED();
  // Test that we are waiting on destruction
  std::atomic_int checked_in{0};

  {
    ThreadPool Pool;
    for (size_t i = 0; i < 5; ++i) {
      Pool.async([&checked_in, i] {
        yield();
        ++checked_in;
      });
    }
    ASSERT_EQ(0, checked_in);
  }
  ASSERT_EQ(5, checked_in);
}
<|endoftext|>


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

#include "xpathapi.hxx"
#include "nodelist.hxx"
#include "xpathobject.hxx"

#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>

namespace XPath
{

    Reference< XInterface > CXPathAPI::_getInstance(const Reference< XMultiServiceFactory >& rSMgr)
    {
        // XXX
        // return static_cast< XXPathAPI* >(new CXPathAPI());
        return Reference< XInterface >(static_cast<XXPathAPI*>(new CXPathAPI(rSMgr)));
    }

    CXPathAPI::CXPathAPI(const Reference< XMultiServiceFactory >& rSMgr)
        : m_aFactory(rSMgr)
    {
    }

    const char* CXPathAPI::aImplementationName = "com.sun.star.comp.xml.xpath.XPathAPI";
    const char* CXPathAPI::aSupportedServiceNames[] = {
        "com.sun.star.xml.xpath.XPathAPI",
        NULL
    };

    OUString CXPathAPI::_getImplementationName()
    {
        return OUString::createFromAscii(aImplementationName);
    }
    Sequence<OUString> CXPathAPI::_getSupportedServiceNames()
    {
        Sequence<OUString> aSequence;
        for (int i=0; aSupportedServiceNames[i]!=NULL; i++) {
            aSequence.realloc(i+1);
            aSequence[i]=(OUString::createFromAscii(aSupportedServiceNames[i]));
        }
        return aSequence;
    }

    Sequence< OUString > SAL_CALL CXPathAPI::getSupportedServiceNames()
        throw (RuntimeException)
    {
        return CXPathAPI::_getSupportedServiceNames();
    }

    OUString SAL_CALL CXPathAPI::getImplementationName()
        throw (RuntimeException)
    {
        return CXPathAPI::_getImplementationName();
    }

    sal_Bool SAL_CALL CXPathAPI::supportsService(const OUString& aServiceName)
        throw (RuntimeException)
    {
        Sequence< OUString > supported = CXPathAPI::_getSupportedServiceNames();
        for (sal_Int32 i=0; i<supported.getLength(); i++)
        {
            if (supported[i] == aServiceName) return sal_True;
        }
        return sal_False;
    }

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

    void SAL_CALL CXPathAPI::registerNS(const OUString& aPrefix, const OUString& aURI)
        throw (RuntimeException)
    {
        m_nsmap.insert(nsmap_t::value_type(aPrefix, aURI));
    }

    void SAL_CALL CXPathAPI::unregisterNS(const OUString& aPrefix, const OUString& aURI)
        throw (RuntimeException)
    {
        if ((m_nsmap.find(aPrefix))->second.equals(aURI))
            m_nsmap.erase(aPrefix);

    }

    static void _registerNamespaces(xmlXPathContextPtr ctx, const nsmap_t& nsmap)
    {
        nsmap_t::const_iterator i = nsmap.begin();
        OString oprefix, ouri;
        xmlChar *p, *u;
        while (i != nsmap.end())
        {
            oprefix = OUStringToOString(i->first,  RTL_TEXTENCODING_UTF8);
            ouri    = OUStringToOString(i->second, RTL_TEXTENCODING_UTF8);
            p = (xmlChar*)oprefix.getStr();
            u = (xmlChar*)ouri.getStr();
            xmlXPathRegisterNs(ctx, p, u);
            i++;
        }
    }

    static void _registerExtensions(xmlXPathContextPtr ctx, const extensions_t& extensions)
    {
        extensions_t::const_iterator i = extensions.begin();
        while (i != extensions.end())
        {
            Libxml2ExtensionHandle aHandle = (*i)->getLibxml2ExtensionHandle();
            if ( aHandle.functionLookupFunction != 0 )
                xmlXPathRegisterFuncLookup(ctx, (xmlXPathFuncLookupFunc) aHandle.functionLookupFunction, (void*)(aHandle.functionData));
            if ( aHandle.variableLookupFunction != 0 )
                xmlXPathRegisterVariableLookup(ctx, (xmlXPathVariableLookupFunc) aHandle.variableLookupFunction, (void*)(aHandle.variableData));
            i++;
        }
    }

    /**
    Use an XPath string to select a nodelist.
    */
    Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeList(
            const Reference< XNode >& contextNode,
            const OUString& str)
        throw (RuntimeException)
    {

        xmlXPathContextPtr xpathCtx;
        xmlXPathObjectPtr xpathObj;

        // get the node and document
        Reference< XUnoTunnel > tunnel(contextNode, UNO_QUERY);
        xmlNodePtr pNode = (xmlNodePtr)tunnel->getSomething(Sequence< sal_Int8 >());
        xmlDocPtr pDoc = pNode->doc;

        /* Create xpath evaluation context */
        xpathCtx = xmlXPathNewContext(pDoc);
        if (xpathCtx == NULL)throw RuntimeException();
        _registerNamespaces(xpathCtx, m_nsmap);

        OString o1 = OUStringToOString(str, RTL_TEXTENCODING_UTF8);
        xmlChar *xStr = (xmlChar*)o1.getStr();

        /* run the query */
        if ((xpathObj = xmlXPathEval(xStr, xpathCtx)) == NULL)
        {
            xmlXPathFreeContext(xpathCtx);
            throw RuntimeException();
        }
        Reference< XNodeList > aList(new CNodeList(xpathObj));
        xmlXPathFreeContext(xpathCtx);
        return aList;
    }

    /**
    Use an XPath string to select a nodelist.
    */
    Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeListNS(
            const Reference< XNode >& contextNode,
            const OUString& str,
            const Reference< XNode >&  namespaceNode)
        throw (RuntimeException)
    {
        return Reference< XNodeList>();
    }

    /**
    Use an XPath string to select a single node.
    */
    Reference< XNode > SAL_CALL CXPathAPI::selectSingleNode(
            const Reference< XNode >& contextNode,
            const OUString& str)
        throw (RuntimeException)
    {
        Reference< XNodeList > aList = selectNodeList(contextNode, str);
        Reference< XNode > aNode = aList->item(0);
        return aNode;
    }

    /**
    Use an XPath string to select a single node.
    */
    Reference< XNode > SAL_CALL CXPathAPI::selectSingleNodeNS(
            const Reference< XNode >& contextNode,
            const OUString& str,
            const Reference< XNode >&  namespaceNode)
        throw (RuntimeException)
    {
        return Reference< XNode >();
    }

    Reference< XXPathObject > SAL_CALL CXPathAPI::eval(const Reference< XNode >& contextNode, const OUString& str)
            throw (RuntimeException)
    {
        xmlXPathContextPtr xpathCtx;
        xmlXPathObjectPtr xpathObj;

        // get the node and document
        Reference< XUnoTunnel > tunnel(contextNode, UNO_QUERY);
        xmlNodePtr pNode = (xmlNodePtr)tunnel->getSomething(Sequence< sal_Int8 >());
        xmlDocPtr pDoc = pNode->doc;

        /* Create xpath evaluation context */
        xpathCtx = xmlXPathNewContext(pDoc);
        if (xpathCtx == NULL)throw RuntimeException();

        // set conext node
        xpathCtx->node = pNode;

        _registerNamespaces(xpathCtx, m_nsmap);
        _registerExtensions(xpathCtx, m_extensions);

        OString o1 = OUStringToOString(str, RTL_TEXTENCODING_UTF8);
        xmlChar *xStr = (xmlChar*)o1.getStr();

        /* run the query */
        if ((xpathObj = xmlXPathEval(xStr, xpathCtx)) == NULL) {
            // OSL_ENSURE(xpathCtx->lastError == NULL, xpathCtx->lastError->message);
            xmlXPathFreeContext(xpathCtx);
            throw RuntimeException();
        }
        xmlXPathFreeContext(xpathCtx);

        Reference< XXPathObject > aObj(new CXPathObject(xpathObj));
        return aObj;
    }

    Reference< XXPathObject > SAL_CALL CXPathAPI::evalNS(const Reference< XNode >& contextNode, const OUString& str, const Reference< XNode >&  namespaceNode)
            throw (RuntimeException)
    {
        return Reference< XXPathObject>();
    }

    void SAL_CALL CXPathAPI::registerExtension(const OUString& aName) throw (RuntimeException)
    {
        // get extension from service manager
        Reference< XXPathExtension > aExtension(m_aFactory->createInstance(aName), UNO_QUERY_THROW);
        m_extensions.push_back( aExtension );
    }

    void SAL_CALL CXPathAPI::registerExtensionInstance(const Reference< XXPathExtension>& aExtension) throw (RuntimeException)
    {
        if (aExtension.is()) {
            m_extensions.push_back( aExtension );
        }
        else
            throw RuntimeException();
    }

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

#include "xpathapi.hxx"
#include "nodelist.hxx"
#include "xpathobject.hxx"
#include "../dom/node.hxx"

#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>

namespace XPath
{

    Reference< XInterface > CXPathAPI::_getInstance(const Reference< XMultiServiceFactory >& rSMgr)
    {
        // XXX
        // return static_cast< XXPathAPI* >(new CXPathAPI());
        return Reference< XInterface >(static_cast<XXPathAPI*>(new CXPathAPI(rSMgr)));
    }

    CXPathAPI::CXPathAPI(const Reference< XMultiServiceFactory >& rSMgr)
        : m_aFactory(rSMgr)
    {
    }

    const char* CXPathAPI::aImplementationName = "com.sun.star.comp.xml.xpath.XPathAPI";
    const char* CXPathAPI::aSupportedServiceNames[] = {
        "com.sun.star.xml.xpath.XPathAPI",
        NULL
    };

    OUString CXPathAPI::_getImplementationName()
    {
        return OUString::createFromAscii(aImplementationName);
    }
    Sequence<OUString> CXPathAPI::_getSupportedServiceNames()
    {
        Sequence<OUString> aSequence;
        for (int i=0; aSupportedServiceNames[i]!=NULL; i++) {
            aSequence.realloc(i+1);
            aSequence[i]=(OUString::createFromAscii(aSupportedServiceNames[i]));
        }
        return aSequence;
    }

    Sequence< OUString > SAL_CALL CXPathAPI::getSupportedServiceNames()
        throw (RuntimeException)
    {
        return CXPathAPI::_getSupportedServiceNames();
    }

    OUString SAL_CALL CXPathAPI::getImplementationName()
        throw (RuntimeException)
    {
        return CXPathAPI::_getImplementationName();
    }

    sal_Bool SAL_CALL CXPathAPI::supportsService(const OUString& aServiceName)
        throw (RuntimeException)
    {
        Sequence< OUString > supported = CXPathAPI::_getSupportedServiceNames();
        for (sal_Int32 i=0; i<supported.getLength(); i++)
        {
            if (supported[i] == aServiceName) return sal_True;
        }
        return sal_False;
    }

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

    void SAL_CALL CXPathAPI::registerNS(const OUString& aPrefix, const OUString& aURI)
        throw (RuntimeException)
    {
        m_nsmap.insert(nsmap_t::value_type(aPrefix, aURI));
    }

    void SAL_CALL CXPathAPI::unregisterNS(const OUString& aPrefix, const OUString& aURI)
        throw (RuntimeException)
    {
        if ((m_nsmap.find(aPrefix))->second.equals(aURI))
            m_nsmap.erase(aPrefix);

    }

    static void _registerNamespaces(xmlXPathContextPtr ctx, const nsmap_t& nsmap)
    {
        nsmap_t::const_iterator i = nsmap.begin();
        OString oprefix, ouri;
        xmlChar *p, *u;
        while (i != nsmap.end())
        {
            oprefix = OUStringToOString(i->first,  RTL_TEXTENCODING_UTF8);
            ouri    = OUStringToOString(i->second, RTL_TEXTENCODING_UTF8);
            p = (xmlChar*)oprefix.getStr();
            u = (xmlChar*)ouri.getStr();
            xmlXPathRegisterNs(ctx, p, u);
            i++;
        }
    }

    static void _registerExtensions(xmlXPathContextPtr ctx, const extensions_t& extensions)
    {
        extensions_t::const_iterator i = extensions.begin();
        while (i != extensions.end())
        {
            Libxml2ExtensionHandle aHandle = (*i)->getLibxml2ExtensionHandle();
            if ( aHandle.functionLookupFunction != 0 )
                xmlXPathRegisterFuncLookup(ctx,
                        reinterpret_cast<xmlXPathFuncLookupFunc>(sal::static_int_cast<sal_IntPtr>(aHandle.functionLookupFunction)),
                        /* (xmlXPathFuncLookupFunc) aHandle.functionLookupFunction, */
                        reinterpret_cast<void*>(sal::static_int_cast<sal_IntPtr>(aHandle.functionData)));
                        /* (void*)(aHandle.functionData));*/
            if ( aHandle.variableLookupFunction != 0 )
                xmlXPathRegisterVariableLookup(ctx,
                        /* (xmlXPathVariableLookupFunc) aHandle.variableLookupFunction, */
                        reinterpret_cast<xmlXPathVariableLookupFunc>(sal::static_int_cast<sal_IntPtr>(aHandle.variableLookupFunction)),
                        /*(void*)(aHandle.variableData));*/
                        reinterpret_cast<void*>(sal::static_int_cast<sal_IntPtr>(aHandle.variableData)));
            i++;
        }
    }

    /**
    Use an XPath string to select a nodelist.
    */
    Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeList(
            const Reference< XNode >& contextNode,
            const OUString& str)
        throw (RuntimeException)
    {

        xmlXPathContextPtr xpathCtx;
        xmlXPathObjectPtr xpathObj;

        // get the node and document
        xmlNodePtr pNode = DOM::CNode::getNodePtr(contextNode);
        xmlDocPtr pDoc = pNode->doc;

        /* Create xpath evaluation context */
        xpathCtx = xmlXPathNewContext(pDoc);
        if (xpathCtx == NULL)throw RuntimeException();
        _registerNamespaces(xpathCtx, m_nsmap);

        OString o1 = OUStringToOString(str, RTL_TEXTENCODING_UTF8);
        xmlChar *xStr = (xmlChar*)o1.getStr();

        /* run the query */
        if ((xpathObj = xmlXPathEval(xStr, xpathCtx)) == NULL)
        {
            xmlXPathFreeContext(xpathCtx);
            throw RuntimeException();
        }
        Reference< XNodeList > aList(new CNodeList(xpathObj));
        xmlXPathFreeContext(xpathCtx);
        return aList;
    }

    /**
    Use an XPath string to select a nodelist.
    */
    Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeListNS(
            const Reference< XNode >& /* contextNode */,
            const OUString& /* str */,
            const Reference< XNode >&  /* namespaceNode */)
        throw (RuntimeException)
    {
        return Reference< XNodeList>();
    }

    /**
    Use an XPath string to select a single node.
    */
    Reference< XNode > SAL_CALL CXPathAPI::selectSingleNode(
            const Reference< XNode >& contextNode,
            const OUString& str)
        throw (RuntimeException)
    {
        Reference< XNodeList > aList = selectNodeList(contextNode, str);
        Reference< XNode > aNode = aList->item(0);
        return aNode;
    }

    /**
    Use an XPath string to select a single node.
    */
    Reference< XNode > SAL_CALL CXPathAPI::selectSingleNodeNS(
            const Reference< XNode >& /* contextNode */,
            const OUString& /* str */,
            const Reference< XNode >&  /* namespaceNode*/ )
        throw (RuntimeException)
    {
        return Reference< XNode >();
    }

    Reference< XXPathObject > SAL_CALL CXPathAPI::eval(const Reference< XNode >& contextNode, const OUString& str)
            throw (RuntimeException)
    {
        xmlXPathContextPtr xpathCtx;
        xmlXPathObjectPtr xpathObj;

        // get the node and document
        xmlNodePtr pNode = DOM::CNode::getNodePtr(contextNode);
        xmlDocPtr pDoc = pNode->doc;

        /* Create xpath evaluation context */
        xpathCtx = xmlXPathNewContext(pDoc);
        if (xpathCtx == NULL)throw RuntimeException();

        // set conext node
        xpathCtx->node = pNode;

        _registerNamespaces(xpathCtx, m_nsmap);
        _registerExtensions(xpathCtx, m_extensions);

        OString o1 = OUStringToOString(str, RTL_TEXTENCODING_UTF8);
        xmlChar *xStr = (xmlChar*)o1.getStr();

        /* run the query */
        if ((xpathObj = xmlXPathEval(xStr, xpathCtx)) == NULL) {
            // OSL_ENSURE(xpathCtx->lastError == NULL, xpathCtx->lastError->message);
            xmlXPathFreeContext(xpathCtx);
            throw RuntimeException();
        }
        xmlXPathFreeContext(xpathCtx);

        Reference< XXPathObject > aObj(new CXPathObject(xpathObj));
        return aObj;
    }

    Reference< XXPathObject > SAL_CALL CXPathAPI::evalNS(const Reference< XNode >& /* contextNode */, const OUString& /* str */, const Reference< XNode >&  /* namespaceNode */)
            throw (RuntimeException)
    {
        return Reference< XXPathObject>();
    }

    void SAL_CALL CXPathAPI::registerExtension(const OUString& aName) throw (RuntimeException)
    {
        // get extension from service manager
        Reference< XXPathExtension > aExtension(m_aFactory->createInstance(aName), UNO_QUERY_THROW);
        m_extensions.push_back( aExtension );
    }

    void SAL_CALL CXPathAPI::registerExtensionInstance(const Reference< XXPathExtension>& aExtension) throw (RuntimeException)
    {
        if (aExtension.is()) {
            m_extensions.push_back( aExtension );
        }
        else
            throw RuntimeException();
    }

}
<|endoftext|>