<commit_before>#include <core/mat4.h>
#include "core/draw.h"
#include "core/random.h"
#include "core/shufflebag.h"
#include "core/filesystem.h"
#include "core/mat4.h"
#include "core/axisangle.h"
#include "core/aabb.h"
#include "core/texturetypes.h"
#include "core/filesystemimagegenerator.h"
#include "core/path.h"

#include <render/init.h>
#include <render/debuggl.h>
#include <render/materialshader.h>
#include <render/compiledmesh.h>
#include <render/texturecache.h>
#include "render/shaderattribute3d.h"
#include "render/texture.h"
#include "render/world.h"
#include "render/viewport.h"
#include "render/camera.h"
#include "render/materialshadercache.h"
#include "render/defaultfiles.h"

#include "window/imguilibrary.h"
#include "window/timer.h"
#include "window/imgui.h"
#include "window/fpscontroller.h"
#include "window/sdllibrary.h"
#include "window/sdlwindow.h"
#include "window/sdlglcontext.h"

#include "imgui/imgui.h"
#include <SDL2/SDL.h>
#include <iostream>
#include <memory>

struct CubeAnimation
{
  CubeAnimation()
      : timer(0)
      , from(quatf::Identity())
      , to(quatf::Identity())
      , rotation_speed(1.0f)
      , move_speed(1.0f)
  {
  }

  std::shared_ptr<Actor> actor;
  float                  timer;
  quatf                  from;
  quatf                  to;
  float                  rotation_speed;
  float                  move_speed;
};

int
main(int argc, char** argv)
{
  SdlLibrary sdl;
  if(sdl.ok == false)
  {
    return -1;
  }

  int width  = 1280;
  int height = 720;

  SdlWindow window{"Euphoria Demo", 1280, 720};
  if(window.window == nullptr)
  {
    return -1;
  }

  SdlGlContext context{&window};

  if(context.context == nullptr)
  {
    return -1;
  }

  Init init;
  if(init.ok == false)
  {
    return -4;
  }

  SetupOpenglDebug();

  ImguiLibrary imgui{window.window};

  Viewport viewport{Recti::FromTopLeftWidthHeight(0, 0, width, height)};
  viewport.Activate();

  FileSystem file_system;
  auto       catalog = FileSystemRootCatalog::AddRoot(&file_system);
  FileSystemRootFolder::AddRoot(&file_system);
  FileSystemImageGenerator::AddRoot(&file_system, "img-plain");

  SetupDefaultFiles(catalog);

  MaterialShaderCache material_shader_cache{&file_system};

  // SET_ENUM_VALUES(TextureType, SetupTextureNames);
  SET_ENUM_FROM_FILE(&file_system, "texture_types.json", TextureType);

  Image image;
  image.Setup(256, 256, false);
  Draw       drawer{&image};
  const auto wi = drawer.WholeImage();
  drawer.Clear(Rgb::From(Color::Red));
  Random random{42};

  for(int i = 0; i < 20; i += 1)
  {
    const auto color = Rgb::From(random.NextDawnbringerPalette());
    const auto pos   = random.NextPoint(wi);
    const auto outer = random.NextRange(55.0f, 100.0f);
    const auto inner = random.NextRange(50.0f);
    drawer.Circle(color, pos, outer, 10, inner);
  }
  drawer
      .LineAntialiased(Rgb::From(Color::Black), wi.TopLeft(), wi.BottomRight())
      .LineAntialiased(Rgb::From(Color::Black), wi.BottomLeft(), wi.TopRight())
      .Text(wi.GetAbsoluteCenterPos(), "Hello world", Rgb::From(Color::Black),
            2);
  catalog->RegisterFileData("image", image.Write(ImageWriteFormat::PNG));

  TextureCache texture_cache{&file_system};

  bool running = true;

  SdlTimer timer;

  World world;

  auto box_mesh1 = meshes::CreateCube(0.5f);
  box_mesh1.materials[0].SetTexture("Diffuse", "container2.png");
  box_mesh1.materials[0].SetTexture("Specular", "container2_specular.png");
  box_mesh1.materials[0].ambient =
      Rgb::From(Color::White);  // fix ambient color on material
  box_mesh1.materials[0].specular  = Rgb::From(Color::White);
  box_mesh1.materials[0].shininess = 120.0f;
  auto box1 = CompileMesh(box_mesh1, &material_shader_cache, &texture_cache,
                          Path::FromRoot());

  auto box_mesh2 = meshes::CreateSphere(0.5f, "image");
  box_mesh2.materials[0].SetTexture("Specular", "img-plain/white");
  box_mesh2.materials[0].ambient =
      Rgb::From(Color::White);  // fix ambient color on material
  box_mesh2.materials[0].specular  = Rgb::From(Color::White);
  box_mesh2.materials[0].shininess = 10.0f;
  auto box2 = CompileMesh(box_mesh2, &material_shader_cache, &texture_cache,
                          Path::FromRoot());

  auto loaded_dude = meshes::LoadMesh(&file_system, "nanosuit/nanosuit.obj");
  if(!loaded_dude.error.empty())
  {
    std::cerr << "Failed to load dude: " << loaded_dude.error << "\n";
    return -5;
  }
  auto dude_mesh = CompileMesh(loaded_dude.mesh, &material_shader_cache,
                               &texture_cache, Path::FromDirectory("nanosuit"));

  auto light_mesh                = meshes::CreateCube(0.2f);
  light_mesh.materials[0].shader = "basic_shader";
  auto light = CompileMesh(light_mesh, &material_shader_cache, &texture_cache,
                           Path::FromRoot());
  float light_position = 0.0f;

  const float box_extent_value = 4;
  Aabb        box_extents{
      vec3f{-box_extent_value, -box_extent_value, -box_extent_value},
      vec3f{box_extent_value, box_extent_value, box_extent_value}};

  std::vector<CubeAnimation> animation_handler;

  bool capturing_mouse_movement = false;

  // 0=do nothing, 1=use light actor, 2=follow camera
  int light_update = 1;

  for(int i = 0; i < 20; ++i)
  {
    std::shared_ptr<Actor> actor =
        std::make_shared<Actor>(random.NextBool() ? box1 : box2);
    world.AddActor(actor);

    CubeAnimation anim;
    anim.actor          = actor;
    anim.from           = random.NextQuatf();
    anim.to             = random.NextQuatf();
    anim.rotation_speed = random.NextRange(0.5f, 1.0f);
    anim.move_speed     = random.NextRange(0.5f, 1.0f);
    anim.timer          = random.NextFloat01();

    // generate a position not too close to the center
    vec3f position = vec3f::Origo();
    do
    {
      position = random.NextVec3(box_extents);
    } while(position.GetLength() < 1.4f);

    actor->SetPosition(position);
    actor->SetRotation(anim.from);

    animation_handler.push_back(anim);
  }

  auto light_actor = std::make_shared<Actor>(light);
  world.AddActor(light_actor);
  light_actor->BeginMaterialOverride(0);
  auto* light_material = light_actor->GetOverriddenMaterial(0);

  auto dude_actor = std::make_shared<Actor>(dude_mesh);
  world.AddActor(dude_actor);

  Camera camera;
  camera.SetPosition(vec3f(0, 0, 0));

  FpsController fps;
  fps.SetPosition(vec3f(0, 0, 3));

  bool paused = true;

  bool show_test_window = true;

  while(running)
  {
    const bool  show_imgui = !capturing_mouse_movement;
    const float delta      = timer.Update();

    if(show_imgui)
    {
      imgui.Begin();

      // 3. Show the ImGui test window. Most of the sample code is in
      // ImGui::ShowTestWindow()
      if(show_test_window)
      {
        ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);

        ImGui::SetNextWindowSize(ImVec2(200, 100), ImGuiSetCond_FirstUseEver);
        ImGui::Begin("Light");
        ImGui::Combo("Type", reinterpret_cast<int*>(world.light.GetTypeMod()),
                     "Directional\0Point\0Spot\0\0");
        ImGui::ColorEdit3("Ambient", world.light.ModifyAmbient()->GetData());
        ImGui::ColorEdit3("Diffuse", world.light.ModifyDiffuse()->GetData());
        ImGui::ColorEdit3("Specular", world.light.ModifySpecular()->GetData());
        ImGui::Combo("Update", &light_update,
                     "Do nothing\0Follow actor\0Follow camera\0\0");

        ImguiAngleSlider("Cutoff Angle Inner",
                         world.light.GetCutoffAngleInnerMod(), 0, 45);
        ImguiAngleSlider("Cutoff Angle Outer",
                         world.light.GetCutoffAngleOuterMod(), 0, 90);

        ImGui::End();

        light_material->SetColors(world.light.GetAmbient(),
                                  world.light.GetDiffuse(),
                                  world.light.GetSpecular(), 10);
      }
    }

    light_position = Wrap(0, light_position + delta * 0.1f, 1);
    const auto light_pos =
        PolarCoord{light_position, light_position * 2}.ToCartesian() * 2.0f;
    light_actor->SetPosition(light_pos);

    switch(light_update)
    {
      case 1:
        world.light.SetPosition(light_pos);
        break;
      case 2:
        world.light.SetPosition(fps.GetPosition());
        world.light.SetDirection(fps.GetRotation().In().GetNormalized());
    }

    for(auto& anim : animation_handler)
    {
      if(paused == false)
      {
        anim.timer += delta * anim.rotation_speed;
        int count = 0;
        while(anim.timer > 1.0f)
        {
          count += 1;
          anim.timer -= 1.0f;
          anim.from           = anim.to;
          anim.to             = random.NextQuatf();
          anim.rotation_speed = random.NextRange(0.3f, 1.0f);
          anim.move_speed     = random.NextRange(0.2f, 3.0f);
        }
        ASSERT(count < 2);
        quatf q = quatf::SlerpShortway(anim.from, anim.timer, anim.to);
        anim.actor->SetRotation(q);
        const vec3f movement = q.In() * anim.move_speed * delta;
        const vec3f new_pos =
            box_extents.Wrap(anim.actor->GetPosition() + movement);
        anim.actor->SetPosition(
            new_pos);  // hard to see movement when everything is moving
      }
    }

    SDL_Event e;
    while(SDL_PollEvent(&e) != 0)
    {
      if(show_imgui)
      {
        imgui.ProcessEvents(&e);
      }
      switch(e.type)
      {
        case SDL_QUIT:
          running = false;
          break;
        case SDL_MOUSEMOTION:
          if(capturing_mouse_movement)
          {
            fps.Look(e.motion.xrel, e.motion.yrel);
          }
          break;
        case SDL_KEYDOWN:
        case SDL_KEYUP:
        {
          const bool down = e.type == SDL_KEYDOWN;

          fps.HandleSdlKey(e.key.keysym.sym, down);

          switch(e.key.keysym.sym)
          {
            case SDLK_ESCAPE:
              if(down)
              {
                running = false;
              }
              break;
            case SDLK_p:
              if(!down)
              {
                paused = !paused;
              }
              break;
            case SDLK_TAB:
              if(!down)
              {
                capturing_mouse_movement = !capturing_mouse_movement;
                window.KeepWithin(capturing_mouse_movement);
              }
              break;
            default:
              // ignore other keys
              break;
          }
        }
        break;
        default:
          // ignore other events
          break;
      }
    }

    fps.Update(delta);
    camera.SetPosition(fps.GetPosition());
    camera.SetRotation(fps.GetRotation());

    init.ClearScreen(Rgb::From(Color::DarkslateGray));
    world.Render(viewport, camera);

    if(show_imgui)
    {
      imgui.Render();
    }

    SDL_GL_SwapWindow(window.window);
  }

  return 0;
}

#if 0
class View {
Camera[] cameras;
};

class CameraView {
Camera;
ViewPort area; // glViewport
};

class Camera {
Mode mode;
World world;
culling info from world, created when camera is added to world
viewMatrix; // position + rotation
projectionMatrix; // ortho/perspective

// 4 planes from the projection matrix
getFrustum();

toViewSpace(); // camera space, eye space
toWorldSpace();
};

// normal, thermo optics/powerup
class Mode {
Pass[] passes;
};

class Pass {
tag/list
Shader shader;
};

class Shader {
texture list: list of texture names mapped to shader variables
};

class World {
Actor[] objects;
};

class Actor {
Mesh mesh;
position;
rotation;
modelMatrix;
ToLocalSpace();
ToWorldSpace();
};

class Mesh {
MeshPart[] meshParts;
};

class MeshPart {
Material material;
};

class MaterialList {
maps id, material name, shader variable
};

class Material {
Texture[] textures;
};
#endif
<commit_msg>use variable instead of magic constant when creating window<commit_after>#include <core/mat4.h>
#include "core/draw.h"
#include "core/random.h"
#include "core/shufflebag.h"
#include "core/filesystem.h"
#include "core/mat4.h"
#include "core/axisangle.h"
#include "core/aabb.h"
#include "core/texturetypes.h"
#include "core/filesystemimagegenerator.h"
#include "core/path.h"

#include <render/init.h>
#include <render/debuggl.h>
#include <render/materialshader.h>
#include <render/compiledmesh.h>
#include <render/texturecache.h>
#include "render/shaderattribute3d.h"
#include "render/texture.h"
#include "render/world.h"
#include "render/viewport.h"
#include "render/camera.h"
#include "render/materialshadercache.h"
#include "render/defaultfiles.h"

#include "window/imguilibrary.h"
#include "window/timer.h"
#include "window/imgui.h"
#include "window/fpscontroller.h"
#include "window/sdllibrary.h"
#include "window/sdlwindow.h"
#include "window/sdlglcontext.h"

#include "imgui/imgui.h"
#include <SDL2/SDL.h>
#include <iostream>
#include <memory>

struct CubeAnimation
{
  CubeAnimation()
      : timer(0)
      , from(quatf::Identity())
      , to(quatf::Identity())
      , rotation_speed(1.0f)
      , move_speed(1.0f)
  {
  }

  std::shared_ptr<Actor> actor;
  float                  timer;
  quatf                  from;
  quatf                  to;
  float                  rotation_speed;
  float                  move_speed;
};

int
main(int argc, char** argv)
{
  SdlLibrary sdl;
  if(sdl.ok == false)
  {
    return -1;
  }

  int width  = 1280;
  int height = 720;

  SdlWindow window{"Euphoria Demo", width, height};
  if(window.window == nullptr)
  {
    return -1;
  }

  SdlGlContext context{&window};

  if(context.context == nullptr)
  {
    return -1;
  }

  Init init;
  if(init.ok == false)
  {
    return -4;
  }

  SetupOpenglDebug();

  ImguiLibrary imgui{window.window};

  Viewport viewport{Recti::FromTopLeftWidthHeight(0, 0, width, height)};
  viewport.Activate();

  FileSystem file_system;
  auto       catalog = FileSystemRootCatalog::AddRoot(&file_system);
  FileSystemRootFolder::AddRoot(&file_system);
  FileSystemImageGenerator::AddRoot(&file_system, "img-plain");

  SetupDefaultFiles(catalog);

  MaterialShaderCache material_shader_cache{&file_system};

  // SET_ENUM_VALUES(TextureType, SetupTextureNames);
  SET_ENUM_FROM_FILE(&file_system, "texture_types.json", TextureType);

  Image image;
  image.Setup(256, 256, false);
  Draw       drawer{&image};
  const auto wi = drawer.WholeImage();
  drawer.Clear(Rgb::From(Color::Red));
  Random random{42};

  for(int i = 0; i < 20; i += 1)
  {
    const auto color = Rgb::From(random.NextDawnbringerPalette());
    const auto pos   = random.NextPoint(wi);
    const auto outer = random.NextRange(55.0f, 100.0f);
    const auto inner = random.NextRange(50.0f);
    drawer.Circle(color, pos, outer, 10, inner);
  }
  drawer
      .LineAntialiased(Rgb::From(Color::Black), wi.TopLeft(), wi.BottomRight())
      .LineAntialiased(Rgb::From(Color::Black), wi.BottomLeft(), wi.TopRight())
      .Text(wi.GetAbsoluteCenterPos(), "Hello world", Rgb::From(Color::Black),
            2);
  catalog->RegisterFileData("image", image.Write(ImageWriteFormat::PNG));

  TextureCache texture_cache{&file_system};

  bool running = true;

  SdlTimer timer;

  World world;

  auto box_mesh1 = meshes::CreateCube(0.5f);
  box_mesh1.materials[0].SetTexture("Diffuse", "container2.png");
  box_mesh1.materials[0].SetTexture("Specular", "container2_specular.png");
  box_mesh1.materials[0].ambient =
      Rgb::From(Color::White);  // fix ambient color on material
  box_mesh1.materials[0].specular  = Rgb::From(Color::White);
  box_mesh1.materials[0].shininess = 120.0f;
  auto box1 = CompileMesh(box_mesh1, &material_shader_cache, &texture_cache,
                          Path::FromRoot());

  auto box_mesh2 = meshes::CreateSphere(0.5f, "image");
  box_mesh2.materials[0].SetTexture("Specular", "img-plain/white");
  box_mesh2.materials[0].ambient =
      Rgb::From(Color::White);  // fix ambient color on material
  box_mesh2.materials[0].specular  = Rgb::From(Color::White);
  box_mesh2.materials[0].shininess = 10.0f;
  auto box2 = CompileMesh(box_mesh2, &material_shader_cache, &texture_cache,
                          Path::FromRoot());

  auto loaded_dude = meshes::LoadMesh(&file_system, "nanosuit/nanosuit.obj");
  if(!loaded_dude.error.empty())
  {
    std::cerr << "Failed to load dude: " << loaded_dude.error << "\n";
    return -5;
  }
  auto dude_mesh = CompileMesh(loaded_dude.mesh, &material_shader_cache,
                               &texture_cache, Path::FromDirectory("nanosuit"));

  auto light_mesh                = meshes::CreateCube(0.2f);
  light_mesh.materials[0].shader = "basic_shader";
  auto light = CompileMesh(light_mesh, &material_shader_cache, &texture_cache,
                           Path::FromRoot());
  float light_position = 0.0f;

  const float box_extent_value = 4;
  Aabb        box_extents{
      vec3f{-box_extent_value, -box_extent_value, -box_extent_value},
      vec3f{box_extent_value, box_extent_value, box_extent_value}};

  std::vector<CubeAnimation> animation_handler;

  bool capturing_mouse_movement = false;

  // 0=do nothing, 1=use light actor, 2=follow camera
  int light_update = 1;

  for(int i = 0; i < 20; ++i)
  {
    std::shared_ptr<Actor> actor =
        std::make_shared<Actor>(random.NextBool() ? box1 : box2);
    world.AddActor(actor);

    CubeAnimation anim;
    anim.actor          = actor;
    anim.from           = random.NextQuatf();
    anim.to             = random.NextQuatf();
    anim.rotation_speed = random.NextRange(0.5f, 1.0f);
    anim.move_speed     = random.NextRange(0.5f, 1.0f);
    anim.timer          = random.NextFloat01();

    // generate a position not too close to the center
    vec3f position = vec3f::Origo();
    do
    {
      position = random.NextVec3(box_extents);
    } while(position.GetLength() < 1.4f);

    actor->SetPosition(position);
    actor->SetRotation(anim.from);

    animation_handler.push_back(anim);
  }

  auto light_actor = std::make_shared<Actor>(light);
  world.AddActor(light_actor);
  light_actor->BeginMaterialOverride(0);
  auto* light_material = light_actor->GetOverriddenMaterial(0);

  auto dude_actor = std::make_shared<Actor>(dude_mesh);
  world.AddActor(dude_actor);

  Camera camera;
  camera.SetPosition(vec3f(0, 0, 0));

  FpsController fps;
  fps.SetPosition(vec3f(0, 0, 3));

  bool paused = true;

  bool show_test_window = true;

  while(running)
  {
    const bool  show_imgui = !capturing_mouse_movement;
    const float delta      = timer.Update();

    if(show_imgui)
    {
      imgui.Begin();

      // 3. Show the ImGui test window. Most of the sample code is in
      // ImGui::ShowTestWindow()
      if(show_test_window)
      {
        ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);

        ImGui::SetNextWindowSize(ImVec2(200, 100), ImGuiSetCond_FirstUseEver);
        ImGui::Begin("Light");
        ImGui::Combo("Type", reinterpret_cast<int*>(world.light.GetTypeMod()),
                     "Directional\0Point\0Spot\0\0");
        ImGui::ColorEdit3("Ambient", world.light.ModifyAmbient()->GetData());
        ImGui::ColorEdit3("Diffuse", world.light.ModifyDiffuse()->GetData());
        ImGui::ColorEdit3("Specular", world.light.ModifySpecular()->GetData());
        ImGui::Combo("Update", &light_update,
                     "Do nothing\0Follow actor\0Follow camera\0\0");

        ImguiAngleSlider("Cutoff Angle Inner",
                         world.light.GetCutoffAngleInnerMod(), 0, 45);
        ImguiAngleSlider("Cutoff Angle Outer",
                         world.light.GetCutoffAngleOuterMod(), 0, 90);

        ImGui::End();

        light_material->SetColors(world.light.GetAmbient(),
                                  world.light.GetDiffuse(),
                                  world.light.GetSpecular(), 10);
      }
    }

    light_position = Wrap(0, light_position + delta * 0.1f, 1);
    const auto light_pos =
        PolarCoord{light_position, light_position * 2}.ToCartesian() * 2.0f;
    light_actor->SetPosition(light_pos);

    switch(light_update)
    {
      case 1:
        world.light.SetPosition(light_pos);
        break;
      case 2:
        world.light.SetPosition(fps.GetPosition());
        world.light.SetDirection(fps.GetRotation().In().GetNormalized());
    }

    for(auto& anim : animation_handler)
    {
      if(paused == false)
      {
        anim.timer += delta * anim.rotation_speed;
        int count = 0;
        while(anim.timer > 1.0f)
        {
          count += 1;
          anim.timer -= 1.0f;
          anim.from           = anim.to;
          anim.to             = random.NextQuatf();
          anim.rotation_speed = random.NextRange(0.3f, 1.0f);
          anim.move_speed     = random.NextRange(0.2f, 3.0f);
        }
        ASSERT(count < 2);
        quatf q = quatf::SlerpShortway(anim.from, anim.timer, anim.to);
        anim.actor->SetRotation(q);
        const vec3f movement = q.In() * anim.move_speed * delta;
        const vec3f new_pos =
            box_extents.Wrap(anim.actor->GetPosition() + movement);
        anim.actor->SetPosition(
            new_pos);  // hard to see movement when everything is moving
      }
    }

    SDL_Event e;
    while(SDL_PollEvent(&e) != 0)
    {
      if(show_imgui)
      {
        imgui.ProcessEvents(&e);
      }
      switch(e.type)
      {
        case SDL_QUIT:
          running = false;
          break;
        case SDL_MOUSEMOTION:
          if(capturing_mouse_movement)
          {
            fps.Look(e.motion.xrel, e.motion.yrel);
          }
          break;
        case SDL_KEYDOWN:
        case SDL_KEYUP:
        {
          const bool down = e.type == SDL_KEYDOWN;

          fps.HandleSdlKey(e.key.keysym.sym, down);

          switch(e.key.keysym.sym)
          {
            case SDLK_ESCAPE:
              if(down)
              {
                running = false;
              }
              break;
            case SDLK_p:
              if(!down)
              {
                paused = !paused;
              }
              break;
            case SDLK_TAB:
              if(!down)
              {
                capturing_mouse_movement = !capturing_mouse_movement;
                window.KeepWithin(capturing_mouse_movement);
              }
              break;
            default:
              // ignore other keys
              break;
          }
        }
        break;
        default:
          // ignore other events
          break;
      }
    }

    fps.Update(delta);
    camera.SetPosition(fps.GetPosition());
    camera.SetRotation(fps.GetRotation());

    init.ClearScreen(Rgb::From(Color::DarkslateGray));
    world.Render(viewport, camera);

    if(show_imgui)
    {
      imgui.Render();
    }

    SDL_GL_SwapWindow(window.window);
  }

  return 0;
}

#if 0
class View {
Camera[] cameras;
};

class CameraView {
Camera;
ViewPort area; // glViewport
};

class Camera {
Mode mode;
World world;
culling info from world, created when camera is added to world
viewMatrix; // position + rotation
projectionMatrix; // ortho/perspective

// 4 planes from the projection matrix
getFrustum();

toViewSpace(); // camera space, eye space
toWorldSpace();
};

// normal, thermo optics/powerup
class Mode {
Pass[] passes;
};

class Pass {
tag/list
Shader shader;
};

class Shader {
texture list: list of texture names mapped to shader variables
};

class World {
Actor[] objects;
};

class Actor {
Mesh mesh;
position;
rotation;
modelMatrix;
ToLocalSpace();
ToWorldSpace();
};

class Mesh {
MeshPart[] meshParts;
};

class MeshPart {
Material material;
};

class MaterialList {
maps id, material name, shader variable
};

class Material {
Texture[] textures;
};
#endif
<|endoftext|>


<commit_before>#include <fstream>
#include <string>
#include <cmath>
#include <random>
#include <unordered_map>
#include <vector>
#include <stdexcept>

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
using boost::numeric::ublas::matrix;

void read_dict(std::unordered_map<int, std::string>& map, std::string filename)
{
  int key;
  std::string word;
  std::fstream fs{filename, std::fstream::in};

  while (!fs.eof()) {
    fs >> key;
    std::getline(fs, word);
    word.erase(0, word.find_first_not_of("\t "));
    map[key] = word;
  }
}

void roll_dice_sets(matrix<int>& mat)
{
  std::random_device rd;  // non-deterministic entropy.
  std::mt19937 mt{rd()};
  std::uniform_int_distribution<int> dist(1, 5);
  for (int i = 0; i < mat.size1(); ++i)
    for (int j = 0; j < mat.size2(); ++j)
      mat(i, j) = dist(mt);
}

std::vector<int> bit_matrix_to_nums(matrix<int>& mat)
{
  std::vector<int> temp(mat.size1(), 0);
  for (int i = 0; i < mat.size1(); ++i)
    for (int j = 0; j < mat.size2(); ++j)
      temp[i] += mat(i, j) * pow(10, j); // not all that portable, but I can trust ints to have 5 bits.

  return temp;
}

int main(int argc, char* argv[])
try
{
  if (argc != 2)
    throw std::invalid_argument{"Usage: "
        "./diceware <no_of_words>"};

  std::unordered_map<int, std::string> dice_map;
  read_dict(dice_map, "diceware_dict.txt");

  const     int no_of_words = std::stoi(argv[1]);
  constexpr int digits_per_word = 5;  // compile time #define, way better than #define
  matrix<int> m{no_of_words, digits_per_word};
  roll_dice_sets(m);

  std::vector<int> word_codes = bit_matrix_to_nums(m);

  std::cout << "Here is your diceware word list\n";
  for (int code : word_codes)
    std::cout << dice_map[code] << " ";
  std::cout << "\n";
}
catch (std::invalid_argument e)
{
  e.what();
  return -3;
}
catch (...)
{
  std::cout << "Something strange happened...";
  return -10;
}
<commit_msg>Refactored out boost and simplifying the code<commit_after>#include <fstream>
#include <iostream>
#include <string>
#include <random>
#include <unordered_map>
#include <vector>
#include <stdexcept>

struct FileNotFound : public std::runtime_error
{
  explicit FileNotFound(const char* message)
    : std::runtime_error{message} { };
  explicit FileNotFound(const std::string& message)
    : std::runtime_error{message.c_str()} { };
};

void read_dict(const std::string& filename,
               std::unordered_map<int, std::string>& map)
{
  int key;
  std::string word;

  std::fstream fs{filename, std::fstream::in};
  if (fs.fail())
    throw FileNotFound{filename + " is not in the current directory"};

  while (!fs.eof()) {
    fs >> key;
    std::getline(fs, word);
    word.erase(0, word.find_first_not_of("\t "));
    map[key] = word;
  }
}

// Fills the rows with digits
std::vector<int> get_word_codes(int no_of_words, int digits_per_word)
{
  std::vector<int> temp(no_of_words, 0);

  std::random_device rd;
  std::mt19937 mt{rd()};
  std::uniform_int_distribution<int> dist(1, 5);
  for (int i = 0; i < no_of_words; ++i) {
    for (int j = digits_per_word-1; j >= 0; --j)
      temp[i] += dist(mt) * pow(10, j);
  }

  return std::move(temp);
}

int main(int argc, char* argv[])
try
{
  if (argc != 2) {
    std::cout << "Usage: ./diceware <no_of_words>\n";
    return -3;
  }

  std::unordered_map<int, std::string> dice_map;
  read_dict("diceware_dict.txt", dice_map);

  // Creates a matrix of
  // words in pass x digits_per_word
  const     int no_of_words = std::stoi(argv[1]);
  constexpr int digits_per_word = 5;
  const std::vector<int> word_codes = get_word_codes(no_of_words, digits_per_word);

  std::cout << "Here is your diceware word list\n";
  std::cout << "-------------------------------\n";
  for (int code : word_codes)
    std::cout << dice_map[code] << " ";
  std::cout << "\n";
}
catch (const FileNotFound& e) {
  std::cout << e.what();
  return -4;
}
catch (...)
{
  std::cout << "Something strange happened...";
  return -77;
}
<|endoftext|>


<commit_before>#include "vtkVRMLExporter.h"
#include "vtkPLOT3DReader.h"
#include "vtkContourFilter.h"
#include "vtkPolyDataNormals.h"
#include "vtkStructuredGridOutlineFilter.h"
#include "vtkPolyDataMapper.h"

int main ()
{
  char arg1[80];
  float isoval;
  char isoType[20];
  char *env;

  // first get the form data
  env = getenv("CONTENT_LENGTH");
  if (!env) return -1;
  int inputLength = atoi(env);
  // a quick sanity check on the input
  if ((inputLength > 40)||(inputLength < 17)) return -1;
  cin >> arg1;
  //  printf("Content-type: text/plain\n\n");

  if (strncmp(arg1,"isoval=",7) == 0)
    {
    isoval = atof(arg1 + 7);
    strcpy(isoType,arg1 + 11);
    //    printf("Status: 200 %s %f %s\n",arg1,isoval,isoType);
    //    return 0;
    }
  else
    {
    isoval = atof(arg1 + inputLength - 4);
    strncpy(isoType,arg1 + 4,inputLength - 16);
    isoType[inputLength - 16] = '\0';
    //    printf("Status: 200 %i %s %f %s\n",inputLength,arg1,isoval,isoType);
    //    return 0;
    }

  vtkRenderer *ren1 = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->AddRenderer(ren1);

  // read data
  vtkPLOT3DReader *reader = vtkPLOT3DReader::New();
  reader->SetXYZFileName("/home/martink2/vtkdata/combxyz.bin");
  reader->SetQFileName("/home/martink2/vtkdata/combq.bin");
  reader->SetFileFormat(VTK_WHOLE_SINGLE_GRID_NO_IBLANKING);
  reader->SetScalarFunctionNumber(100);
  reader->SetVectorFunctionNumber(202);
  reader->Update(); //force a read to occur

  vtkContourFilter *iso = vtkContourFilter::New();
  iso->SetInput( reader->GetOutput() );
  iso->SetValue(0, isoval );

  vtkPolyDataNormals *normals = vtkPolyDataNormals::New();
  normals->SetInput( iso->GetOutput() );
  normals->SetFeatureAngle( 45 );
  normals->FlipNormalsOn();

  vtkPolyDataMapper *isoMapper = vtkPolyDataMapper::New();
  isoMapper->SetInput(normals->GetOutput());
  isoMapper->ScalarVisibilityOff();

  vtkActor *isoActor = vtkActor::New();
  isoActor->GetProperty()->SetColor(0.5,0.5,1.0);
  isoActor->SetMapper( isoMapper );

  // create outline
  vtkStructuredGridOutlineFilter *outlineF =
    vtkStructuredGridOutlineFilter::New();
  outlineF->SetInput(reader->GetOutput());
  vtkPolyDataMapper *outlineMapper = vtkPolyDataMapper::New();
  outlineMapper->SetInput(outlineF->GetOutput());
  vtkActor *outline = vtkActor::New();
  outline->SetMapper(outlineMapper);
  outline->GetProperty()->SetAmbient(1);
  outline->GetProperty()->SetDiffuse(0);
  outline->GetProperty()->SetColor(0.5,1,0.5);

  // should we do the iso-surface
  if (strcmp(isoType,"Off"))
    {
    ren1->AddActor( isoActor );
    }
  if (strcmp(isoType,"Transparent") == 0)
    {
    isoActor->GetProperty()->SetOpacity( 0.5 );
    }

  ren1->AddActor( outline );

  // Send out vrml header stuff
  fprintf(stdout,"Content-type: x-world/x-vrml\n");
  fprintf(stdout,"Pragma: no-cache\n\n");

  // write out VRRML 2.0 file
  vtkVRMLExporter *writer = vtkVRMLExporter::New();
  writer->SetInput( renWin );
  writer->SetFilePointer( stdout );
  writer->Write();

  return 0;
}

<commit_msg>updated for rpi<commit_after>#include "vtkVRMLExporter.h"
#include "vtkPLOT3DReader.h"
#include "vtkContourFilter.h"
#include "vtkPolyDataNormals.h"
#include "vtkStructuredGridOutlineFilter.h"
#include "vtkStructuredGridGeometryFilter.h"
#include "vtkPolyDataMapper.h"

char *getCGIValue(char *key, char *input)
{
  int idx, found, end;
  int len = strlen(input);
  int klen = strlen(key);
  char *result;

  // first find the key
  found = -1;
  for (idx = 0; idx < len; idx++)
    {
    if (strncmp(key,input+idx,klen) == 0)
      {
      found = idx;
      break;
      }
    }

  if (found == -1) return NULL;

  // find end of return value
  end = -1;
  found = found + strlen(key);
  for (idx = found; idx < len; idx++)
    {
    if (input[idx] == '&')
      {
      end = idx;
      break;
      }
    }

  if (end == -1) end = len;

  result = new char [end - found + 1];
  for (idx = found; idx < end; idx++)
    {
    result[idx - found] = input[idx];
    }
  result[end-found] = '\0';

  return result;
}

int main ()
{
  char arg1[1024];
  float isoval;
  char *isoType;
  char *env;
  char *probeOn;
  char *probeCont;
  float probeLoc;

  // first get the form data
  env = getenv("CONTENT_LENGTH");
  if (!env) return -1;
  int inputLength = atoi(env);
  cin >> arg1;

  isoval = atof(getCGIValue("isoval=",arg1));
  isoType = getCGIValue("iso=",arg1);
  probeLoc = atof(getCGIValue("probeloc=",arg1));
  probeCont = getCGIValue("probecont=",arg1);
  probeOn = getCGIValue("probe=",arg1);

  vtkRenderer *ren1 = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->AddRenderer(ren1);

  // read data
  vtkPLOT3DReader *reader = vtkPLOT3DReader::New();
  reader->SetXYZFileName("/home/martink/vtkdata/combxyz.bin");
  reader->SetQFileName("/home/martink/vtkdata/combq.bin");
  reader->SetFileFormat(VTK_WHOLE_SINGLE_GRID_NO_IBLANKING);
  reader->SetScalarFunctionNumber(100);
  reader->SetVectorFunctionNumber(202);
  reader->Update(); //force a read to occur

  vtkContourFilter *iso = vtkContourFilter::New();
  iso->SetInput( reader->GetOutput() );
  iso->SetValue(0, isoval );

  vtkPolyDataNormals *normals = vtkPolyDataNormals::New();
  normals->SetInput( iso->GetOutput() );
  normals->SetFeatureAngle( 45 );
  normals->FlipNormalsOn();

  vtkPolyDataMapper *isoMapper = vtkPolyDataMapper::New();
  isoMapper->SetInput(normals->GetOutput());
  isoMapper->ScalarVisibilityOff();

  vtkActor *isoActor = vtkActor::New();
  isoActor->GetProperty()->SetColor(0.5,0.5,1.0);
  isoActor->SetMapper( isoMapper );

  // create outline
  vtkStructuredGridOutlineFilter *outlineF =
    vtkStructuredGridOutlineFilter::New();
  outlineF->SetInput(reader->GetOutput());
  vtkPolyDataMapper *outlineMapper = vtkPolyDataMapper::New();
  outlineMapper->SetInput(outlineF->GetOutput());
  vtkActor *outline = vtkActor::New();
  outline->SetMapper(outlineMapper);
  outline->GetProperty()->SetAmbient(1);
  outline->GetProperty()->SetDiffuse(1);
  outline->GetProperty()->SetColor(0.5,1,0.5);

  vtkStructuredGridGeometryFilter *plane =
    vtkStructuredGridGeometryFilter::New();
  plane->SetInput(reader->GetOutput());
  plane->SetExtent(1,100,1,100,probeLoc,probeLoc);

  vtkPolyDataMapper *contourMapper = vtkPolyDataMapper::New();
  contourMapper->SetScalarRange(reader->GetOutput()->GetScalarRange());
  if (!strcmp(probeCont,"On"))
    {
    vtkContourFilter *contour = vtkContourFilter::New();
    contour->SetInput(plane->GetOutput());
    contour->GenerateValues(50,reader->GetOutput()->GetScalarRange());
    contourMapper->SetInput(contour->GetOutput());
    }
  else
    {
    contourMapper->SetInput(plane->GetOutput());
    }

  vtkActor *planeActor = vtkActor::New();
  planeActor->SetMapper(contourMapper);

  // should we do the iso-surface
  if (strcmp(probeOn,"Off"))
    {
    ren1->AddActor( planeActor );
    }
  if (strcmp(isoType,"Off"))
    {
    ren1->AddActor( isoActor );
    }
  if (strcmp(isoType,"Transparent") == 0)
    {
    isoActor->GetProperty()->SetOpacity( 0.5 );
    }

  ren1->AddActor( outline );

  // Send out vrml header stuff
  fprintf(stdout,"Content-type: x-world/x-vrml\n");
  fprintf(stdout,"Pragma: no-cache\n\n");

  // write out VRRML 2.0 file
  vtkVRMLExporter *writer = vtkVRMLExporter::New();
  writer->SetInput( renWin );
  writer->SetFilePointer( stdout );
  writer->Write();

  return 0;
}

<|endoftext|>


<commit_before>#include "xchainer/python/backprop_mode.h"

#include <memory>
#include <string>
#include <utility>
#include <vector>

#include <nonstd/optional.hpp>

#include "xchainer/backprop_mode.h"
#include "xchainer/context.h"
#include "xchainer/graph.h"

#include "xchainer/python/common.h"
#include "xchainer/python/context.h"

namespace xchainer {
namespace python {
namespace internal {
namespace {

namespace py = pybind11;  // standard convention

template <class BackpropModeScope>
class PyBackpropModeScope {
public:
    PyBackpropModeScope() {}
    explicit PyBackpropModeScope(std::vector<GraphId> graph_ids) : graph_ids_{std::move(graph_ids)} {}
    void Enter() {
        scope_ = graph_ids_.has_value() ? std::make_unique<BackpropModeScope>(*graph_ids_) : std::make_unique<BackpropModeScope>();
    }
    void Exit(py::args args) {
        (void)args;  // unused
        scope_.reset();
    }

private:
    // optional requires having copy ctor, so use unique_ptr instead
    std::unique_ptr<BackpropModeScope> scope_;
    nonstd::optional<std::vector<GraphId>> graph_ids_{};
};

using PyNoBackpropModeScope = PyBackpropModeScope<NoBackpropModeScope>;
using PyForceBackpropModeScope = PyBackpropModeScope<ForceBackpropModeScope>;

template <class PyBackpropModeScope>
void InitXchainerBackpropModeScope(pybind11::module& m, const char* class_name, const char* function_name) {
    py::class_<PyBackpropModeScope> c{m, class_name};
    c.def("__enter__", &PyBackpropModeScope::Enter);
    c.def("__exit__", &PyBackpropModeScope::Exit);

    m.def(function_name, []() { return PyBackpropModeScope{}; });
    m.def(function_name, [](GraphId graph_id) { return PyBackpropModeScope{{std::move(graph_id)}}; });
    m.def(function_name, [](const std::vector<GraphId>& graph_ids) { return PyBackpropModeScope{graph_ids}; });
}

}  // namespace

void InitXchainerBackpropMode(pybind11::module& m) {
    InitXchainerBackpropModeScope<PyNoBackpropModeScope>(m, "NoBackpropMode", "no_backprop_mode");
    InitXchainerBackpropModeScope<PyForceBackpropModeScope>(m, "ForceBackpropMode", "force_backprop_mode");

    m.def("is_backprop_required",
          [](const GraphId& graph_id, py::handle context) { return IsBackpropRequired(graph_id, GetContext(context)); },
          py::arg("graph_id") = kDefaultGraphId,
          py::arg("context") = py::none());
}

}  // namespace internal
}  // namespace python
}  // namespace xchainer
<commit_msg>remove PyNoBackpropModeScope, and PyForceBackpropModeScope<commit_after>#include "xchainer/python/backprop_mode.h"

#include <memory>
#include <string>
#include <utility>
#include <vector>

#include <nonstd/optional.hpp>

#include "xchainer/backprop_mode.h"
#include "xchainer/context.h"
#include "xchainer/graph.h"

#include "xchainer/python/common.h"
#include "xchainer/python/context.h"

namespace xchainer {
namespace python {
namespace internal {
namespace {

namespace py = pybind11;  // standard convention

template <class BackpropModeScope>
class PyBackpropModeScope {
public:
    PyBackpropModeScope() {}
    explicit PyBackpropModeScope(std::vector<GraphId> graph_ids) : graph_ids_{std::move(graph_ids)} {}
    void Enter() {
        scope_ = graph_ids_.has_value() ? std::make_unique<BackpropModeScope>(*graph_ids_) : std::make_unique<BackpropModeScope>();
    }
    void Exit(py::args args) {
        (void)args;  // unused
        scope_.reset();
    }

private:
    // optional requires having copy ctor, so use unique_ptr instead
    std::unique_ptr<BackpropModeScope> scope_;
    nonstd::optional<std::vector<GraphId>> graph_ids_{};
};

template <class BackpropModeScope>
void InitXchainerBackpropModeScope(pybind11::module& m, const char* class_name, const char* function_name) {
    py::class_<PyBackpropModeScope<BackpropModeScope>> c{m, class_name};
    c.def("__enter__", &PyBackpropModeScope<BackpropModeScope>::Enter);
    c.def("__exit__", &PyBackpropModeScope<BackpropModeScope>::Exit);

    m.def(function_name, []() { return PyBackpropModeScope<BackpropModeScope>{}; });
    m.def(function_name, [](GraphId graph_id) { return PyBackpropModeScope<BackpropModeScope>{{std::move(graph_id)}}; });
    m.def(function_name, [](const std::vector<GraphId>& graph_ids) { return PyBackpropModeScope<BackpropModeScope>{graph_ids}; });
}

}  // namespace

void InitXchainerBackpropMode(pybind11::module& m) {
    InitXchainerBackpropModeScope<NoBackpropModeScope>(m, "NoBackpropMode", "no_backprop_mode");
    InitXchainerBackpropModeScope<ForceBackpropModeScope>(m, "ForceBackpropMode", "force_backprop_mode");

    m.def("is_backprop_required",
          [](const GraphId& graph_id, py::handle context) { return IsBackpropRequired(graph_id, GetContext(context)); },
          py::arg("graph_id") = kDefaultGraphId,
          py::arg("context") = py::none());
}

}  // namespace internal
}  // namespace python
}  // namespace xchainer
<|endoftext|>


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

#ifndef _XMLOFF_PROPERTYHANDLER_CHARHEIGHTTYPES_HXX
#include <chrhghdl.hxx>
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _XMLOFF_XMLEHELP_HXX
#include "xmlehelp.hxx"
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

#ifndef _XMLOFF_XMLEMENT_HXX
#include "xmlelement.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;

// this is a copy of defines in svx/inc/escpitem.hxx
#define DFLT_ESC_PROP    58
#define DFLT_ESC_AUTO_SUPER 101
#define DFLT_ESC_AUTO_SUB  -101

///////////////////////////////////////////////////////////////////////////////
//
// class XMLEscapementPropHdl
//

XMLCharHeightHdl::~XMLCharHeightHdl()
{
    // nothing to do
}

sal_Bool XMLCharHeightHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    double fSize;

    if( rStrImpValue.indexOf( sal_Unicode('%') ) == -1 )
    {
        MapUnit eSrcUnit = SvXMLExportHelper::GetUnitFromString( rStrImpValue, MAP_POINT );
        if( SvXMLUnitConverter::convertDouble( fSize, rStrImpValue, eSrcUnit, MAP_POINT ))
        {
            rValue <<= (float)fSize;
            return sal_True;
        }
    }

    return sal_False;
}

sal_Bool XMLCharHeightHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    OUStringBuffer aOut;

    float fSize = 0;
    if( rValue >>= fSize )
    {
        SvXMLUnitConverter::convertDouble( aOut, (double)fSize, TRUE, MAP_POINT, MAP_POINT );
        aOut.append( sal_Unicode('p'));
        aOut.append( sal_Unicode('t'));
    }

    rStrExpValue = aOut.makeStringAndClear();
    return rStrExpValue.getLength() != 0;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLEscapementHeightPropHdl
//

XMLCharHeightPropHdl::~XMLCharHeightPropHdl()
{
    // nothing to do
}

sal_Bool XMLCharHeightPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Int32 nPrc = 100;

    if( rStrImpValue.indexOf( sal_Unicode('%') ) != -1 )
    {
        if( rUnitConverter.convertPercent( nPrc, rStrImpValue ) )
        {
            rValue <<= (sal_Int16)nPrc;
            return sal_True;
        }
    }

    return sal_False;
}

sal_Bool XMLCharHeightPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    OUStringBuffer aOut( rStrExpValue );

    sal_Int16 nValue;
    if( rValue >>= nValue )
    {
        rUnitConverter.convertPercent( aOut, nValue );
    }

    rStrExpValue = aOut.makeStringAndClear();
    return rStrExpValue.getLength() != 0;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLEscapementPropHdl
//

XMLCharHeightDiffHdl::~XMLCharHeightDiffHdl()
{
    // nothing to do
}

sal_Bool XMLCharHeightDiffHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Int32 nRel = 0;

    if( SvXMLUnitConverter::convertMeasure( nRel, rStrImpValue, MAP_POINT ) )
    {
        rValue <<= (float)nRel;
        return sal_True;
    }

    return sal_False;
}

sal_Bool XMLCharHeightDiffHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    OUStringBuffer aOut;

    float nRel = 0;
    if( (rValue >>= nRel) && (nRel != 0) )
    {
        SvXMLUnitConverter::convertMeasure( aOut, nRel, MAP_POINT, MAP_POINT );
        rStrExpValue = aOut.makeStringAndClear();
    }

    return rStrExpValue.getLength() != 0;
}

<commit_msg>INTEGRATION: CWS warnings01 (1.5.34); FILE MERGED 2005/11/16 22:47:23 pl 1.5.34.2: #i55991# removed warnings 2005/11/03 17:47:04 cl 1.5.34.1: warning free code changes for unxlngi6<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: chrhghdl.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 18:31:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XMLOFF_PROPERTYHANDLER_CHARHEIGHTTYPES_HXX
#include <chrhghdl.hxx>
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _XMLOFF_XMLEHELP_HXX
#include "xmlehelp.hxx"
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

#ifndef _XMLOFF_XMLEMENT_HXX
#include "xmlelement.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;

// this is a copy of defines in svx/inc/escpitem.hxx
#define DFLT_ESC_PROP    58
#define DFLT_ESC_AUTO_SUPER 101
#define DFLT_ESC_AUTO_SUB  -101

///////////////////////////////////////////////////////////////////////////////
//
// class XMLEscapementPropHdl
//

XMLCharHeightHdl::~XMLCharHeightHdl()
{
    // nothing to do
}

sal_Bool XMLCharHeightHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& ) const
{
    double fSize;

    if( rStrImpValue.indexOf( sal_Unicode('%') ) == -1 )
    {
        MapUnit eSrcUnit = SvXMLExportHelper::GetUnitFromString( rStrImpValue, MAP_POINT );
        if( SvXMLUnitConverter::convertDouble( fSize, rStrImpValue, eSrcUnit, MAP_POINT ))
        {
            rValue <<= (float)fSize;
            return sal_True;
        }
    }

    return sal_False;
}

sal_Bool XMLCharHeightHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& ) const
{
    OUStringBuffer aOut;

    float fSize = 0;
    if( rValue >>= fSize )
    {
        SvXMLUnitConverter::convertDouble( aOut, (double)fSize, TRUE, MAP_POINT, MAP_POINT );
        aOut.append( sal_Unicode('p'));
        aOut.append( sal_Unicode('t'));
    }

    rStrExpValue = aOut.makeStringAndClear();
    return rStrExpValue.getLength() != 0;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLEscapementHeightPropHdl
//

XMLCharHeightPropHdl::~XMLCharHeightPropHdl()
{
    // nothing to do
}

sal_Bool XMLCharHeightPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Int32 nPrc = 100;

    if( rStrImpValue.indexOf( sal_Unicode('%') ) != -1 )
    {
        if( rUnitConverter.convertPercent( nPrc, rStrImpValue ) )
        {
            rValue <<= (sal_Int16)nPrc;
            return sal_True;
        }
    }

    return sal_False;
}

sal_Bool XMLCharHeightPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    OUStringBuffer aOut( rStrExpValue );

    sal_Int16 nValue;
    if( rValue >>= nValue )
    {
        rUnitConverter.convertPercent( aOut, nValue );
    }

    rStrExpValue = aOut.makeStringAndClear();
    return rStrExpValue.getLength() != 0;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLEscapementPropHdl
//

XMLCharHeightDiffHdl::~XMLCharHeightDiffHdl()
{
    // nothing to do
}

sal_Bool XMLCharHeightDiffHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& ) const
{
    sal_Int32 nRel = 0;

    if( SvXMLUnitConverter::convertMeasure( nRel, rStrImpValue, MAP_POINT ) )
    {
        rValue <<= (float)nRel;
        return sal_True;
    }

    return sal_False;
}

sal_Bool XMLCharHeightDiffHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& ) const
{
    OUStringBuffer aOut;

    float nRel = 0;
    if( (rValue >>= nRel) && (nRel != 0) )
    {
        SvXMLUnitConverter::convertMeasure( aOut, (sal_Int32)nRel, MAP_POINT, MAP_POINT );
        rStrExpValue = aOut.makeStringAndClear();
    }

    return rStrExpValue.getLength() != 0;
}

<|endoftext|>


<commit_before>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrSoftwarePathRenderer.h"
#include "GrPaint.h"
#include "SkPaint.h"
#include "GrRenderTarget.h"
#include "GrContext.h"
#include "SkDraw.h"
#include "SkRasterClip.h"

////////////////////////////////////////////////////////////////////////////////
bool GrSoftwarePathRenderer::canDrawPath(const SkPath& path,
                                         GrPathFill fill,
                                         const GrDrawTarget* target,
                                         bool antiAlias) const {
    if (!antiAlias || NULL == fContext) {
        // TODO: We could allow the SW path to also handle non-AA paths but
        // this would mean that GrDefaultPathRenderer would never be called
        // (since it appears after the SW renderer in the path renderer
        // chain). Some testing would need to be done r.e. performance
        // and consistency of the resulting images before removing
        // the "!antiAlias" clause from the above test
        return false;
    }

    return true;
}

namespace {

////////////////////////////////////////////////////////////////////////////////
SkPath::FillType gr_fill_to_sk_fill(GrPathFill fill) {
    switch (fill) {
        case kWinding_PathFill:
            return SkPath::kWinding_FillType;
        case kEvenOdd_PathFill:
            return SkPath::kEvenOdd_FillType;
        case kInverseWinding_PathFill:
            return SkPath::kInverseWinding_FillType;
        case kInverseEvenOdd_PathFill:
            return SkPath::kInverseEvenOdd_FillType;
        default:
            GrCrash("Unexpected fill.");
            return SkPath::kWinding_FillType;
    }
}

////////////////////////////////////////////////////////////////////////////////
// gets device coord bounds of path (not considering the fill) and clip. The
// path bounds will be a subset of the clip bounds. returns false if
// path bounds would be empty.
bool get_path_and_clip_bounds(const GrDrawTarget* target,
                              const SkPath& path,
                              const GrVec* translate,
                              GrIRect* pathBounds,
                              GrIRect* clipBounds) {
    // compute bounds as intersection of rt size, clip, and path
    const GrRenderTarget* rt = target->getDrawState().getRenderTarget();
    if (NULL == rt) {
        return false;
    }
    *pathBounds = GrIRect::MakeWH(rt->width(), rt->height());
    const GrClip& clip = target->getClip();
    if (clip.hasConservativeBounds()) {
        clip.getConservativeBounds().roundOut(clipBounds);
        if (!pathBounds->intersect(*clipBounds)) {
            return false;
        }
    } else {
        // pathBounds is currently the rt extent, set clip bounds to that rect.
        *clipBounds = *pathBounds;
    }
    GrRect pathSBounds = path.getBounds();
    if (!pathSBounds.isEmpty()) {
        if (NULL != translate) {
            pathSBounds.offset(*translate);
        }
        target->getDrawState().getViewMatrix().mapRect(&pathSBounds,
                                                        pathSBounds);
        GrIRect pathIBounds;
        pathSBounds.roundOut(&pathIBounds);
        if (!pathBounds->intersect(pathIBounds)) {
            return false;
        }
    } else {
        return false;
    }
    return true;
}

////////////////////////////////////////////////////////////////////////////////
/**
 * sw rasterizes path to A8 mask using the context's matrix and uploads to a
 * scratch texture.
 */

bool sw_draw_path_to_mask_texture(const SkPath& clientPath,
                                  const GrIRect& pathDevBounds,
                                  GrPathFill fill,
                                  GrContext* context,
                                  const GrPoint* translate,
                                  GrAutoScratchTexture* tex,
                                  bool antiAlias) {
    SkPaint paint;
    SkPath tmpPath;
    const SkPath* pathToDraw = &clientPath;
    if (kHairLine_PathFill == fill) {
        paint.setStyle(SkPaint::kStroke_Style);
        paint.setStrokeWidth(SK_Scalar1);
    } else {
        paint.setStyle(SkPaint::kFill_Style);
        SkPath::FillType skfill = gr_fill_to_sk_fill(fill);
        if (skfill != pathToDraw->getFillType()) {
            tmpPath = *pathToDraw;
            tmpPath.setFillType(skfill);
            pathToDraw = &tmpPath;
        }
    }
    paint.setAntiAlias(antiAlias);
    paint.setColor(SK_ColorWHITE);

    GrMatrix matrix = context->getMatrix();
    if (NULL != translate) {
        matrix.postTranslate(translate->fX, translate->fY);
    }

    matrix.postTranslate(-pathDevBounds.fLeft * SK_Scalar1,
                         -pathDevBounds.fTop * SK_Scalar1);
    GrIRect bounds = GrIRect::MakeWH(pathDevBounds.width(),
                                     pathDevBounds.height());

    SkBitmap bm;
    bm.setConfig(SkBitmap::kA8_Config, bounds.fRight, bounds.fBottom);
    if (!bm.allocPixels()) {
        return false;
    }
    sk_bzero(bm.getPixels(), bm.getSafeSize());

    SkDraw  draw;
    sk_bzero(&draw, sizeof(draw));
    SkRasterClip rc(bounds);
    draw.fRC    = &rc;
    draw.fClip  = &rc.bwRgn();
    draw.fMatrix = &matrix;
    draw.fBitmap = &bm;
    draw.drawPath(*pathToDraw, paint);

    const GrTextureDesc desc = {
        kNone_GrTextureFlags,
        bounds.fRight,
        bounds.fBottom,
        kAlpha_8_GrPixelConfig,
        0 // samples
    };

    tex->set(context, desc);
    GrTexture* texture = tex->texture();

    if (NULL == texture) {
        return false;
    }
    SkAutoLockPixels alp(bm);
    texture->writePixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig,
                         bm.getPixels(), bm.rowBytes());
    return true;
}

////////////////////////////////////////////////////////////////////////////////
void draw_around_inv_path(GrDrawTarget* target,
                          GrDrawState::StageMask stageMask,
                          const GrIRect& clipBounds,
                          const GrIRect& pathBounds) {
    GrDrawTarget::AutoDeviceCoordDraw adcd(target, stageMask);
    GrRect rect;
    if (clipBounds.fTop < pathBounds.fTop) {
        rect.iset(clipBounds.fLeft, clipBounds.fTop,
                    clipBounds.fRight, pathBounds.fTop);
        target->drawSimpleRect(rect, NULL, stageMask);
    }
    if (clipBounds.fLeft < pathBounds.fLeft) {
        rect.iset(clipBounds.fLeft, pathBounds.fTop,
                    pathBounds.fLeft, pathBounds.fBottom);
        target->drawSimpleRect(rect, NULL, stageMask);
    }
    if (clipBounds.fRight > pathBounds.fRight) {
        rect.iset(pathBounds.fRight, pathBounds.fTop,
                    clipBounds.fRight, pathBounds.fBottom);
        target->drawSimpleRect(rect, NULL, stageMask);
    }
    if (clipBounds.fBottom > pathBounds.fBottom) {
        rect.iset(clipBounds.fLeft, pathBounds.fBottom,
                    clipBounds.fRight, clipBounds.fBottom);
        target->drawSimpleRect(rect, NULL, stageMask);
    }
}

}

////////////////////////////////////////////////////////////////////////////////
// return true on success; false on failure
bool GrSoftwarePathRenderer::onDrawPath(const SkPath& path,
                                        GrPathFill fill,
                                        const GrVec* translate,
                                        GrDrawTarget* target,
                                        GrDrawState::StageMask stageMask,
                                        bool antiAlias) {

    if (NULL == fContext) {
        return false;
    }

    GrAutoScratchTexture ast;
    GrIRect pathBounds, clipBounds;
    if (!get_path_and_clip_bounds(target, path, translate,
                                  &pathBounds, &clipBounds)) {
        return true;    // path is empty so there is nothing to do
    }
    if (sw_draw_path_to_mask_texture(path, pathBounds,
                                     fill, fContext,
                                     translate, &ast, antiAlias)) {
        GrTexture* texture = ast.texture();
        GrAssert(NULL != texture);
        GrDrawTarget::AutoDeviceCoordDraw adcd(target, stageMask);
        enum {
            // the SW path renderer shares this stage with glyph
            // rendering (kGlyphMaskStage in GrBatchedTextContext)
            kPathMaskStage = GrPaint::kTotalStages,
        };
        GrAssert(NULL == target->drawState()->getTexture(kPathMaskStage));
        target->drawState()->setTexture(kPathMaskStage, texture);
        target->drawState()->sampler(kPathMaskStage)->reset();
        GrScalar w = GrIntToScalar(pathBounds.width());
        GrScalar h = GrIntToScalar(pathBounds.height());
        GrRect maskRect = GrRect::MakeWH(w / texture->width(),
                                         h / texture->height());
        const GrRect* srcRects[GrDrawState::kNumStages] = {NULL};
        srcRects[kPathMaskStage] = &maskRect;
        stageMask |= 1 << kPathMaskStage;
        GrRect dstRect = GrRect::MakeLTRB(
                              SK_Scalar1* pathBounds.fLeft,
                              SK_Scalar1* pathBounds.fTop,
                              SK_Scalar1* pathBounds.fRight,
                              SK_Scalar1* pathBounds.fBottom);
        target->drawRect(dstRect, NULL, stageMask, srcRects, NULL);
        target->drawState()->setTexture(kPathMaskStage, NULL);
        if (GrIsFillInverted(fill)) {
            draw_around_inv_path(target, stageMask,
                                 clipBounds, pathBounds);
        }
        return true;
    }

    return false;
}

<commit_msg>Created SW clip mask creation helper class (in GrSoftwarePathRenderer)<commit_after>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrSoftwarePathRenderer.h"
#include "GrPaint.h"
#include "SkPaint.h"
#include "GrRenderTarget.h"
#include "GrContext.h"
#include "SkDraw.h"
#include "SkRasterClip.h"

////////////////////////////////////////////////////////////////////////////////
bool GrSoftwarePathRenderer::canDrawPath(const SkPath& path,
                                         GrPathFill fill,
                                         const GrDrawTarget* target,
                                         bool antiAlias) const {
    if (!antiAlias || NULL == fContext) {
        // TODO: We could allow the SW path to also handle non-AA paths but
        // this would mean that GrDefaultPathRenderer would never be called
        // (since it appears after the SW renderer in the path renderer
        // chain). Some testing would need to be done r.e. performance
        // and consistency of the resulting images before removing
        // the "!antiAlias" clause from the above test
        return false;
    }

    return true;
}

namespace {

////////////////////////////////////////////////////////////////////////////////
SkPath::FillType gr_fill_to_sk_fill(GrPathFill fill) {
    switch (fill) {
        case kWinding_PathFill:
            return SkPath::kWinding_FillType;
        case kEvenOdd_PathFill:
            return SkPath::kEvenOdd_FillType;
        case kInverseWinding_PathFill:
            return SkPath::kInverseWinding_FillType;
        case kInverseEvenOdd_PathFill:
            return SkPath::kInverseEvenOdd_FillType;
        default:
            GrCrash("Unexpected fill.");
            return SkPath::kWinding_FillType;
    }
}

////////////////////////////////////////////////////////////////////////////////
// gets device coord bounds of path (not considering the fill) and clip. The
// path bounds will be a subset of the clip bounds. returns false if
// path bounds would be empty.
bool get_path_and_clip_bounds(const GrDrawTarget* target,
                              const SkPath& path,
                              const GrVec* translate,
                              GrIRect* pathBounds,
                              GrIRect* clipBounds) {
    // compute bounds as intersection of rt size, clip, and path
    const GrRenderTarget* rt = target->getDrawState().getRenderTarget();
    if (NULL == rt) {
        return false;
    }
    *pathBounds = GrIRect::MakeWH(rt->width(), rt->height());
    const GrClip& clip = target->getClip();
    if (clip.hasConservativeBounds()) {
        clip.getConservativeBounds().roundOut(clipBounds);
        if (!pathBounds->intersect(*clipBounds)) {
            return false;
        }
    } else {
        // pathBounds is currently the rt extent, set clip bounds to that rect.
        *clipBounds = *pathBounds;
    }
    GrRect pathSBounds = path.getBounds();
    if (!pathSBounds.isEmpty()) {
        if (NULL != translate) {
            pathSBounds.offset(*translate);
        }
        target->getDrawState().getViewMatrix().mapRect(&pathSBounds,
                                                        pathSBounds);
        GrIRect pathIBounds;
        pathSBounds.roundOut(&pathIBounds);
        if (!pathBounds->intersect(pathIBounds)) {
            return false;
        }
    } else {
        return false;
    }
    return true;
}

/**
 * The GrSWMaskHelper helps generate clip masks using the software rendering
 * path.
 */
class GrSWMaskHelper : public GrNoncopyable {
public:
    GrSWMaskHelper(GrContext* context)
    : fContext(context) {

    }

    /**
     * Draw a single element of the clip stack into the accumulation bitmap
     */
    void draw(const SkPath& clientPath, GrPathFill fill, bool antiAlias) {
        SkPaint paint;
        SkPath tmpPath;
        const SkPath* pathToDraw = &clientPath;
        if (kHairLine_PathFill == fill) {
            paint.setStyle(SkPaint::kStroke_Style);
            paint.setStrokeWidth(SK_Scalar1);
        } else {
            paint.setStyle(SkPaint::kFill_Style);
            SkPath::FillType skfill = gr_fill_to_sk_fill(fill);
            if (skfill != pathToDraw->getFillType()) {
                tmpPath = *pathToDraw;
                tmpPath.setFillType(skfill);
                pathToDraw = &tmpPath;
            }
        }
        paint.setAntiAlias(antiAlias);
        paint.setColor(SK_ColorWHITE);

        fDraw.drawPath(*pathToDraw, paint);
    }

    bool init(const GrIRect& pathDevBounds, const GrPoint* translate) {
        fMatrix = fContext->getMatrix();
        if (NULL != translate) {
            fMatrix.postTranslate(translate->fX, translate->fY);
        }

        fMatrix.postTranslate(-pathDevBounds.fLeft * SK_Scalar1,
                              -pathDevBounds.fTop * SK_Scalar1);
        GrIRect bounds = GrIRect::MakeWH(pathDevBounds.width(),
                                         pathDevBounds.height());

        fBM.setConfig(SkBitmap::kA8_Config, bounds.fRight, bounds.fBottom);
        if (!fBM.allocPixels()) {
            return false;
        }
        sk_bzero(fBM.getPixels(), fBM.getSafeSize());

        sk_bzero(&fDraw, sizeof(fDraw));
        fRasterClip.setRect(bounds);
        fDraw.fRC    = &fRasterClip;
        fDraw.fClip  = &fRasterClip.bwRgn();
        fDraw.fMatrix = &fMatrix;
        fDraw.fBitmap = &fBM;
        return true;
    }

    /**
     * Move the result of the software mask generation back to the gpu
     */
    bool toTexture(GrAutoScratchTexture* tex) {
        const GrTextureDesc desc = {
            kNone_GrTextureFlags,
            fBM.width(),
            fBM.height(),
            kAlpha_8_GrPixelConfig,
            0 // samples
        };

        tex->set(fContext, desc);
        GrTexture* texture = tex->texture();

        if (NULL == texture) {
            return false;
        }
        SkAutoLockPixels alp(fBM);
        texture->writePixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig,
                             fBM.getPixels(), fBM.rowBytes());
        return true;
    }

protected:
private:
    GrContext*      fContext;
    GrMatrix        fMatrix;
    SkBitmap        fBM;
    SkDraw          fDraw;
    SkRasterClip    fRasterClip;

    typedef GrPathRenderer INHERITED;
};

////////////////////////////////////////////////////////////////////////////////
/**
 * sw rasterizes path to A8 mask using the context's matrix and uploads to a
 * scratch texture.
 */
bool sw_draw_path_to_mask_texture(const SkPath& clientPath,
                                  const GrIRect& pathDevBounds,
                                  GrPathFill fill,
                                  GrContext* context,
                                  const GrPoint* translate,
                                  GrAutoScratchTexture* tex,
                                  bool antiAlias) {
    GrSWMaskHelper helper(context);

    if (!helper.init(pathDevBounds, translate)) {
        return false;
    }

    helper.draw(clientPath, fill, antiAlias);

    if (!helper.toTexture(tex)) {
        return false;
    }

    return true;
}

////////////////////////////////////////////////////////////////////////////////
void draw_around_inv_path(GrDrawTarget* target,
                          GrDrawState::StageMask stageMask,
                          const GrIRect& clipBounds,
                          const GrIRect& pathBounds) {
    GrDrawTarget::AutoDeviceCoordDraw adcd(target, stageMask);
    GrRect rect;
    if (clipBounds.fTop < pathBounds.fTop) {
        rect.iset(clipBounds.fLeft, clipBounds.fTop,
                    clipBounds.fRight, pathBounds.fTop);
        target->drawSimpleRect(rect, NULL, stageMask);
    }
    if (clipBounds.fLeft < pathBounds.fLeft) {
        rect.iset(clipBounds.fLeft, pathBounds.fTop,
                    pathBounds.fLeft, pathBounds.fBottom);
        target->drawSimpleRect(rect, NULL, stageMask);
    }
    if (clipBounds.fRight > pathBounds.fRight) {
        rect.iset(pathBounds.fRight, pathBounds.fTop,
                    clipBounds.fRight, pathBounds.fBottom);
        target->drawSimpleRect(rect, NULL, stageMask);
    }
    if (clipBounds.fBottom > pathBounds.fBottom) {
        rect.iset(clipBounds.fLeft, pathBounds.fBottom,
                    clipBounds.fRight, clipBounds.fBottom);
        target->drawSimpleRect(rect, NULL, stageMask);
    }
}

}

////////////////////////////////////////////////////////////////////////////////
// return true on success; false on failure
bool GrSoftwarePathRenderer::onDrawPath(const SkPath& path,
                                        GrPathFill fill,
                                        const GrVec* translate,
                                        GrDrawTarget* target,
                                        GrDrawState::StageMask stageMask,
                                        bool antiAlias) {

    if (NULL == fContext) {
        return false;
    }

    GrAutoScratchTexture ast;
    GrIRect pathBounds, clipBounds;
    if (!get_path_and_clip_bounds(target, path, translate,
                                  &pathBounds, &clipBounds)) {
        return true;    // path is empty so there is nothing to do
    }
    if (sw_draw_path_to_mask_texture(path, pathBounds,
                                     fill, fContext,
                                     translate, &ast, antiAlias)) {
        GrTexture* texture = ast.texture();
        GrAssert(NULL != texture);
        GrDrawTarget::AutoDeviceCoordDraw adcd(target, stageMask);
        enum {
            // the SW path renderer shares this stage with glyph
            // rendering (kGlyphMaskStage in GrBatchedTextContext)
            kPathMaskStage = GrPaint::kTotalStages,
        };
        GrAssert(NULL == target->drawState()->getTexture(kPathMaskStage));
        target->drawState()->setTexture(kPathMaskStage, texture);
        target->drawState()->sampler(kPathMaskStage)->reset();
        GrScalar w = GrIntToScalar(pathBounds.width());
        GrScalar h = GrIntToScalar(pathBounds.height());
        GrRect maskRect = GrRect::MakeWH(w / texture->width(),
                                         h / texture->height());
        const GrRect* srcRects[GrDrawState::kNumStages] = {NULL};
        srcRects[kPathMaskStage] = &maskRect;
        stageMask |= 1 << kPathMaskStage;
        GrRect dstRect = GrRect::MakeLTRB(
                              SK_Scalar1* pathBounds.fLeft,
                              SK_Scalar1* pathBounds.fTop,
                              SK_Scalar1* pathBounds.fRight,
                              SK_Scalar1* pathBounds.fBottom);
        target->drawRect(dstRect, NULL, stageMask, srcRects, NULL);
        target->drawState()->setTexture(kPathMaskStage, NULL);
        if (GrIsFillInverted(fill)) {
            draw_around_inv_path(target, stageMask,
                                 clipBounds, pathBounds);
        }
        return true;
    }

    return false;
}

<|endoftext|>


<commit_before>#include "ZipLib.h"
#include "../../OfficeUtils/src/zlib-1.2.11/contrib/minizip/unzip.h"
#include "../../OfficeUtils/src/zlib-1.2.11/contrib/minizip/ioapibuf.h"
#include "../../OfficeUtils/src/ZipUtilsCP.h"

#include <algorithm> // для std::min в get_file_in_archive

unzFile unzOpenHelp(BUFFER_IO* buffer)
{
    zlib_filefunc_def ffunc;
    fill_buffer_filefunc(&ffunc, buffer);
    return unzOpen2(NULL, &ffunc);
}
zipFile zipOpenHelp(BUFFER_IO* buffer)
{
    zlib_filefunc_def ffunc;
    fill_buffer_filefunc(&ffunc, buffer);
    return zipOpen2(NULL, APPEND_STATUS_CREATE, NULL, &ffunc);
}
unsigned int GetLength(BYTE* x)
{
    return x[0] | x[1] << 8 | x[2] << 16 | x[3] << 24;
}

// begin from (ZipUtilsCP.cpp)
bool current_file_is_find(unzFile uf, const char* filename)
{
    char filename_inzip[256];
    int err = UNZ_OK;

    unz_file_info file_info;

    err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
    if (err != UNZ_OK)
        return false;

    std::string name(filename_inzip);
    //todooo есть ли необходимость свести все к нижнему ???
    return strcmp(filename, name.c_str()) == 0;
}
bool get_file(unzFile unzip_file_handle, BYTE* arr, uInt array_size)
{
    if (UNZ_OK == unzOpenCurrentFile(unzip_file_handle))
    {
        int data_read_size = unzReadCurrentFile(unzip_file_handle, arr, array_size);

        unzCloseCurrentFile(unzip_file_handle);
        return data_read_size == array_size;
    }
    return false;
}
static const std::string get_filename_from_unzfile(unzFile unzip_file_handle)
{
    char filename_inzip[256];

    if (UNZ_OK == unzGetCurrentFileInfo(unzip_file_handle, NULL, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0))
        return std::string(filename_inzip);

    return "";
}
bool get_file_in_archive(unzFile unzip_file_handle, const char* filePathInZip, BYTE** fileInBytes, ULONG& nFileSize)
{
    if (NULL == fileInBytes)
        return false;
    (*fileInBytes) = NULL;
    do
    {
        if (current_file_is_find(unzip_file_handle, filePathInZip) == true)
        {
          unz_file_info file_info;
          unzGetCurrentFileInfo(unzip_file_handle, &file_info, NULL, 0, NULL, 0, NULL, 0);

          if (nFileSize > 0)
              nFileSize = (std::min)(nFileSize, file_info.uncompressed_size);
          else
              nFileSize = file_info.uncompressed_size;

          (*fileInBytes) = new BYTE[nFileSize];
          get_file(unzip_file_handle, (*fileInBytes), nFileSize);
          return true;
        }
        // else just skip the erroneous file
    } while (UNZ_OK == unzGoToNextFile(unzip_file_handle));

    return false;
}
// end from (ZipUtilsCP.cpp)

void CZLib::create()
{
    m_zipFile = NULL;
    m_sizeZip = 0;
}
void CZLib::open(BYTE* buffer, DWORD size)
{
    RELEASEARRAYOBJECTS(m_zipFile);
    m_zipFile = buffer;
    m_sizeZip = size;

    // Получаем пути в архиве
    BUFFER_IO* buf = new BUFFER_IO;
    buf->buffer = buffer;
    buf->nSize  = size;
    unzFile uf  = unzOpenHelp(buf);

    do
    {
        unz_file_info file_info;
        unzGetCurrentFileInfo(uf, &file_info, NULL, 0, NULL, 0, NULL, 0);
        if (file_info.uncompressed_size != 0)
            m_arrFiles.push_back(CFile(get_filename_from_unzfile(uf), NULL, 0));
    } while (UNZ_OK == unzGoToNextFile(uf));
}
void CZLib::close()
{
    RELEASEARRAYOBJECTS(m_zipFile);
    m_arrFiles.clear();
}

std::vector<std::string> CZLib::getPaths()
{
    std::vector<std::string> oRes;
    for (CFile& oFile : m_arrFiles)
        oRes.push_back(oFile.m_sPath);
    return oRes;
}
std::pair<DWORD, BYTE*> CZLib::save()
{
    BUFFER_IO* buf = new BUFFER_IO;
    buf->bGrow = 1;
    buf->nCurrentPos = 0;
    zipFile zip_file_handle = zipOpenHelp(buf);

    for (CFile& oFile : m_arrFiles)
    {
        if (ZIP_OK != zipOpenNewFileInZip( zip_file_handle, oFile.m_sPath.c_str(), NULL, NULL, 0, NULL, 0, NULL, Z_DEFLATED, -1 ) ||
            ZIP_OK != zipWriteInFileInZip(zip_file_handle, oFile.m_pData, oFile.m_nLength) ||
            ZIP_OK != zipCloseFileInZip(zip_file_handle))
        {
            zipClose(zip_file_handle, NULL);
            return make_pair(m_sizeZip, m_zipFile);
        }
    }
    zipClose(zip_file_handle, NULL);

    m_zipFile = buf->buffer;
    m_sizeZip = buf->nSize;
    return make_pair(m_sizeZip, m_zipFile);
}
std::pair<DWORD, BYTE*> CZLib::getFile(const std::string& sPath)
{
    BUFFER_IO* buf = new BUFFER_IO;
    buf->buffer = m_zipFile;
    buf->nSize  = m_sizeZip;
    unzFile uf  = unzOpenHelp(buf);

    BYTE* file = new BYTE;
    DWORD nFileSize = 0;
    get_file_in_archive(uf, sPath.c_str(), &file, nFileSize);
    unzClose(uf);
    return make_pair(nFileSize, file);
}
void CZLib::addFile   (const std::string& sPath, BYTE* data, DWORD length)
{
    bool bExists = false;
    for (CFile& oFile : m_arrFiles)
    {
        if (oFile.m_sPath == sPath)
        {
            RELEASEARRAYOBJECTS(oFile.m_pData);
            oFile.m_pData = data;
            oFile.m_nLength = length;
            bExists = true;
            break;
        }
    }
    if (!bExists)
        m_arrFiles.push_back(CFile(sPath, data, length));
}
bool CZLib::removeFile(const std::string& sPath)
{
    for (std::vector<CFile>::iterator i = m_arrFiles.begin(); i != m_arrFiles.end(); i++)
    {
        if (i->m_sPath == sPath)
        {
            m_arrFiles.erase(i);
            return true;
        }
    }
    return false;
}
<commit_msg>fix constructor CZLib<commit_after>#include "ZipLib.h"
#include "../../OfficeUtils/src/zlib-1.2.11/contrib/minizip/unzip.h"
#include "../../OfficeUtils/src/zlib-1.2.11/contrib/minizip/ioapibuf.h"
#include "../../OfficeUtils/src/ZipUtilsCP.h"

#include <algorithm> // для std::min в get_file_in_archive

unzFile unzOpenHelp(BUFFER_IO* buffer)
{
    zlib_filefunc_def ffunc;
    fill_buffer_filefunc(&ffunc, buffer);
    return unzOpen2(NULL, &ffunc);
}
zipFile zipOpenHelp(BUFFER_IO* buffer)
{
    zlib_filefunc_def ffunc;
    fill_buffer_filefunc(&ffunc, buffer);
    return zipOpen2(NULL, APPEND_STATUS_CREATE, NULL, &ffunc);
}
unsigned int GetLength(BYTE* x)
{
    return x[0] | x[1] << 8 | x[2] << 16 | x[3] << 24;
}

// begin from (ZipUtilsCP.cpp)
bool current_file_is_find(unzFile uf, const char* filename)
{
    char filename_inzip[256];
    int err = UNZ_OK;

    unz_file_info file_info;

    err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
    if (err != UNZ_OK)
        return false;

    std::string name(filename_inzip);
    //todooo есть ли необходимость свести все к нижнему ???
    return strcmp(filename, name.c_str()) == 0;
}
bool get_file(unzFile unzip_file_handle, BYTE* arr, uInt array_size)
{
    if (UNZ_OK == unzOpenCurrentFile(unzip_file_handle))
    {
        int data_read_size = unzReadCurrentFile(unzip_file_handle, arr, array_size);

        unzCloseCurrentFile(unzip_file_handle);
        return data_read_size == array_size;
    }
    return false;
}
static const std::string get_filename_from_unzfile(unzFile unzip_file_handle)
{
    char filename_inzip[256];

    if (UNZ_OK == unzGetCurrentFileInfo(unzip_file_handle, NULL, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0))
        return std::string(filename_inzip);

    return "";
}
bool get_file_in_archive(unzFile unzip_file_handle, const char* filePathInZip, BYTE** fileInBytes, ULONG& nFileSize)
{
    if (NULL == fileInBytes)
        return false;
    (*fileInBytes) = NULL;
    do
    {
        if (current_file_is_find(unzip_file_handle, filePathInZip) == true)
        {
          unz_file_info file_info;
          unzGetCurrentFileInfo(unzip_file_handle, &file_info, NULL, 0, NULL, 0, NULL, 0);

          if (nFileSize > 0)
              nFileSize = (std::min)(nFileSize, file_info.uncompressed_size);
          else
              nFileSize = file_info.uncompressed_size;

          (*fileInBytes) = new BYTE[nFileSize];
          get_file(unzip_file_handle, (*fileInBytes), nFileSize);
          return true;
        }
        // else just skip the erroneous file
    } while (UNZ_OK == unzGoToNextFile(unzip_file_handle));

    return false;
}
// end from (ZipUtilsCP.cpp)

void CZLib::create()
{
    m_zipFile = NULL;
    m_sizeZip = 0;
}
void CZLib::open(BYTE* buffer, DWORD size)
{
    m_zipFile = buffer;
    m_sizeZip = size;

    // Получаем пути в архиве
    BUFFER_IO* buf = new BUFFER_IO;
    buf->buffer = buffer;
    buf->nSize  = size;
    unzFile uf  = unzOpenHelp(buf);

    do
    {
        unz_file_info file_info;
        unzGetCurrentFileInfo(uf, &file_info, NULL, 0, NULL, 0, NULL, 0);
        if (file_info.uncompressed_size != 0)
            m_arrFiles.push_back(CFile(get_filename_from_unzfile(uf), NULL, 0));
    } while (UNZ_OK == unzGoToNextFile(uf));
}
void CZLib::close()
{
    RELEASEARRAYOBJECTS(m_zipFile);
    m_arrFiles.clear();
}

std::vector<std::string> CZLib::getPaths()
{
    std::vector<std::string> oRes;
    for (CFile& oFile : m_arrFiles)
        oRes.push_back(oFile.m_sPath);
    return oRes;
}
std::pair<DWORD, BYTE*> CZLib::save()
{
    BUFFER_IO* buf = new BUFFER_IO;
    buf->bGrow = 1;
    buf->nCurrentPos = 0;
    zipFile zip_file_handle = zipOpenHelp(buf);

    for (CFile& oFile : m_arrFiles)
    {
        if (ZIP_OK != zipOpenNewFileInZip( zip_file_handle, oFile.m_sPath.c_str(), NULL, NULL, 0, NULL, 0, NULL, Z_DEFLATED, -1 ) ||
            ZIP_OK != zipWriteInFileInZip(zip_file_handle, oFile.m_pData, oFile.m_nLength) ||
            ZIP_OK != zipCloseFileInZip(zip_file_handle))
        {
            zipClose(zip_file_handle, NULL);
            return make_pair(m_sizeZip, m_zipFile);
        }
    }
    zipClose(zip_file_handle, NULL);

    m_zipFile = buf->buffer;
    m_sizeZip = buf->nSize;
    return make_pair(m_sizeZip, m_zipFile);
}
std::pair<DWORD, BYTE*> CZLib::getFile(const std::string& sPath)
{
    BUFFER_IO* buf = new BUFFER_IO;
    buf->buffer = m_zipFile;
    buf->nSize  = m_sizeZip;
    unzFile uf  = unzOpenHelp(buf);

    BYTE* file = new BYTE;
    DWORD nFileSize = 0;
    get_file_in_archive(uf, sPath.c_str(), &file, nFileSize);
    unzClose(uf);
    return make_pair(nFileSize, file);
}
void CZLib::addFile   (const std::string& sPath, BYTE* data, DWORD length)
{
    bool bExists = false;
    for (CFile& oFile : m_arrFiles)
    {
        if (oFile.m_sPath == sPath)
        {
            RELEASEARRAYOBJECTS(oFile.m_pData);
            oFile.m_pData = data;
            oFile.m_nLength = length;
            bExists = true;
            break;
        }
    }
    if (!bExists)
        m_arrFiles.push_back(CFile(sPath, data, length));
}
bool CZLib::removeFile(const std::string& sPath)
{
    for (std::vector<CFile>::iterator i = m_arrFiles.begin(); i != m_arrFiles.end(); i++)
    {
        if (i->m_sPath == sPath)
        {
            m_arrFiles.erase(i);
            return true;
        }
    }
    return false;
}
<|endoftext|>


<commit_before><commit_msg>Added comments with function names to linker assembly output<commit_after><|endoftext|>