<commit_before>// Include standard headers
#include <iostream>
#include <string>
#include <string.h>
#include <cstring>
#include <vector>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

GLFWwindow* window;

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif

#include <glm/gtc/matrix_transform.hpp>

#include "common/shader.hpp"
#include "common/texture.hpp"

#include "common/globals.hpp"
#include "common/controls.hpp"
#include "common/model.hpp"
#include "common/vboindexer.hpp"
#include "common/text2D.hpp"

#define WINDOW_WIDTH 1600
#define WINDOW_HEIGHT 900

#define TEXT_SIZE 40
#define FONT_SIZE 16

#define PI 3.14159265359f

// model file format: obj/bmp/...
// std::string g_model_file_format = "bmp";
std::string g_model_file_format = "bmp";

// model filename.
// std::string g_model_filename = "cube.obj";
// std::string g_model_filename = "oma_icosphere.obj";
// std::string g_model_filename = "kirjainkuutio.obj";
// std::string g_model_filename = "noise1024x1024.bmp";
std::string g_model_filename = "noise256x256.bmp";
// std::string g_model_filename = "noise128x128.bmp";

// texture file format: bmp/...
std::string g_texture_file_format = "bmp";

// color channel to use for height data.
// std::string g_height_data_color_channel = "red";
// std::string g_height_data_color_channel = "green";
// std::string g_height_data_color_channel = "blue";
std::string g_height_data_color_channel = "mean"; // "all" is equivalent to "mean".

// texture filename.
// std::string_g_texture_filename = "kuutio-uv-numerot.bmp";
// std::string g_texture_filename = "punamusta.bmp";
std::string g_texture_filename = "GrassGreenTexture0002.bmp";

// font texture file format: bmp/...
std::string g_font_texture_file_format = "bmp";

// font texture filename.
// std::string g_font_texture_filename = "Holstein.DDS";
std::string g_font_texture_filename = "Holstein.bmp";

int main(void)
{
    // Initial position : on +Z
    position = glm::vec3(100, 100, 100);
    // Initial horizontal angle : toward -Z
    horizontalAngle = 0.0f;
    // Initial vertical angle : none
    verticalAngle = PI / 2;
    // Initial Field of View
    initialFoV = 45.0f;

    // Initialise GLFW
    if (!glfwInit())
    {
        std::cerr << "Failed to initialize GLFW.\n";
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);

    // Open a window and create its OpenGL context.
    window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Ylikuutio", NULL, NULL);
    if (window == NULL)
    {
        std::cerr << "Failed to open GLFW window.\n";
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // Initialize GLEW.
    if (glewInit() != GLEW_OK)
    {
        std::cerr << "Failed to initialize GLEW.\n";
        return -1;
    }

    // Ensure we can capture the escape key being pressed below.
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
    glfwSetCursorPos(window, (WINDOW_WIDTH / 2), (WINDOW_HEIGHT / 2));

    // Dark blue background.
    glClearColor(0.0f, 0.0f, 0.4f, 0.0f);

    // Enable depth test.
    glEnable(GL_DEPTH_TEST);
    // Accept fragment if it closer to the camera than the former one.
    glDepthFunc(GL_LESS);

    // Cull triangles which normal is not towards the camera.
    glEnable(GL_CULL_FACE);

    // Create the species, store it in `terrain_species`.
    SpeciesStruct species_struct;
    species_struct.model_file_format = g_model_file_format;
    species_struct.model_filename = g_model_filename;
    species_struct.texture_file_format = g_texture_file_format;
    species_struct.color_channel = g_height_data_color_channel;
    species_struct.texture_filename = g_texture_filename;
    species_struct.vertex_shader = "StandardShading.vertexshader";
    species_struct.fragment_shader = "StandardShading.fragmentshader";
    species_struct.lightPos = glm::vec3(4, 4, 4);
    model::Species terrain_species = model::Species(species_struct);

    // create a species pointer.
    model::Species *species_ptr = &terrain_species;

    // Create terrain1, store it in `terrain1`.
    ObjectStruct object_struct1;
    object_struct1.model_matrix = glm::mat4(1.0);
    object_struct1.translate_vector = glm::vec3(0.0f, 0.0f, 0.0f);
    model::Object terrain1 = model::Object(object_struct1);
    terrain1.species_ptr = species_ptr;

    std::cout << "number of vertices: " << terrain_species.vertices.size() << ".\n";
    std::cout << "number of UVs: " << terrain_species.UVs.size() << ".\n";
    std::cout << "number of normals: " << terrain_species.normals.size() << ".\n";

    std::cout << "number of indexed vertices: " << terrain_species.indexed_vertices.size() << ".\n";
    std::cout << "number of indexed UVs: " << terrain_species.indexed_UVs.size() << ".\n";
    std::cout << "number of indexed normals: " << terrain_species.indexed_normals.size() << ".\n";

    // Initialize our little text library with the Holstein font
    const char *char_g_font_texture_filename = g_font_texture_filename.c_str();
    const char *char_g_font_texture_file_format = g_font_texture_file_format.c_str();
    text2D::initText2D(WINDOW_WIDTH, WINDOW_HEIGHT, char_g_font_texture_filename, char_g_font_texture_file_format);

    // For speed computation
    double lastTime = glfwGetTime();
    int nbFrames = 0;

    bool ms_frame_text_ready = false;

    do
    {
        // Measure speed
        char ms_frame_text[256];
        double currentTime = glfwGetTime();
        nbFrames++;
        if (currentTime - lastTime >= 1.0)
        {
            // If last `printf()` was more than 1 sec ago,
            // `printf` and reset.
            sprintf(ms_frame_text, "%.02f ms/frame; %.02f Hz", 1000.0f / ((double) nbFrames), 1000.0f / (1000.0f / ((double) nbFrames)));
            ms_frame_text_ready = true;
            nbFrames = 0;
            lastTime += 1.0;
        }
        // Clear the screen.
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        terrain_species.render();

        terrain1.render();

        glDisableVertexAttribArray(terrain_species.vertexPosition_modelspaceID);
        glDisableVertexAttribArray(terrain_species.vertexUVID);
        glDisableVertexAttribArray(terrain_species.vertexNormal_modelspaceID);

        PrintingStruct printing_struct;
        printing_struct.screen_width = WINDOW_WIDTH;
        printing_struct.screen_height = WINDOW_HEIGHT;
        printing_struct.text_size = TEXT_SIZE;
        printing_struct.font_size = FONT_SIZE;
        printing_struct.char_font_texture_file_format = "bmp";

        char coordinates_text[256];
        sprintf(coordinates_text, "(%.2f,%.2f,%.2f) (%.2f,%.2f)", position.x, position.y, position.z, horizontalAngle, verticalAngle);

        char time_text[256];
        sprintf(time_text, "%.2f sec", glfwGetTime(), position.x, position.y, position.z);

        printing_struct.x = 0;
        printing_struct.y = 0;
        printing_struct.text = coordinates_text;
        printing_struct.horizontal_alignment = "left";
        printing_struct.vertical_alignment = "bottom";
        text2D::printText2D(printing_struct);

        printing_struct.x = 0;
        printing_struct.y = WINDOW_HEIGHT;
        printing_struct.text = time_text;
        printing_struct.horizontal_alignment = "left";
        printing_struct.vertical_alignment = "top";
        text2D::printText2D(printing_struct);

        if (ms_frame_text_ready)
        {
            printing_struct.x = WINDOW_WIDTH;
            printing_struct.y = WINDOW_HEIGHT;
            printing_struct.text = ms_frame_text;
            printing_struct.horizontal_alignment = "right";
            printing_struct.vertical_alignment = "top";
            text2D::printText2D(printing_struct);
        }

        // Swap buffers.
        glfwSwapBuffers(window);
        glfwPollEvents();
    } // Check if the ESC key was pressed or the window was closed
    while ((glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS)
            && (glfwWindowShouldClose(window) == 0));

    // Cleanup VBO, shader and texture.
    glDeleteBuffers(1, &terrain_species.vertexbuffer);
    glDeleteBuffers(1, &terrain_species.uvbuffer);
    glDeleteBuffers(1, &terrain_species.normalbuffer);
    glDeleteBuffers(1, &terrain_species.elementbuffer);
    glDeleteProgram(terrain_species.programID);
    glDeleteTextures(1, &terrain_species.texture);

    // Delete the text's VBO, the shader and the texture
    text2D::cleanupText2D();

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    return 0;
}
<commit_msg>Lisätty Suzanne-apinanpäitä vuorten huipuille.<commit_after>// Include standard headers
#include <iostream>
#include <string>
#include <string.h>
#include <cstring>
#include <vector>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

GLFWwindow* window;

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif

#include <glm/gtc/matrix_transform.hpp>

#include "common/shader.hpp"
#include "common/texture.hpp"

#include "common/globals.hpp"
#include "common/controls.hpp"
#include "common/model.hpp"
#include "common/vboindexer.hpp"
#include "common/text2D.hpp"

#define WINDOW_WIDTH 1600
#define WINDOW_HEIGHT 900

#define TEXT_SIZE 40
#define FONT_SIZE 16

#define PI 3.14159265359f

// model file format: obj/bmp/...
// std::string g_model_file_format = "bmp";
std::string g_model_file_format = "bmp";

// model filename.
// std::string g_model_filename = "cube.obj";
// std::string g_model_filename = "oma_icosphere.obj";
// std::string g_model_filename = "kirjainkuutio.obj";
// std::string g_model_filename = "noise1024x1024.bmp";
std::string g_model_filename = "noise256x256.bmp";
// std::string g_model_filename = "noise128x128.bmp";

// texture file format: bmp/...
std::string g_texture_file_format = "bmp";

// color channel to use for height data.
// std::string g_height_data_color_channel = "red";
// std::string g_height_data_color_channel = "green";
// std::string g_height_data_color_channel = "blue";
std::string g_height_data_color_channel = "mean"; // "all" is equivalent to "mean".

// texture filename.
// std::string_g_texture_filename = "kuutio-uv-numerot.bmp";
// std::string g_texture_filename = "punamusta.bmp";
std::string g_texture_filename = "GrassGreenTexture0002.bmp";

// font texture file format: bmp/...
std::string g_font_texture_file_format = "bmp";

// font texture filename.
// std::string g_font_texture_filename = "Holstein.DDS";
std::string g_font_texture_filename = "Holstein.bmp";

int main(void)
{
    // Initial position : on +Z
    position = glm::vec3(100, 100, 100);
    // Initial horizontal angle : toward -Z
    horizontalAngle = 0.0f;
    // Initial vertical angle : none
    verticalAngle = PI / 2;
    // Initial Field of View
    initialFoV = 45.0f;

    // Initialise GLFW
    if (!glfwInit())
    {
        std::cerr << "Failed to initialize GLFW.\n";
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);

    // Open a window and create its OpenGL context.
    window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Ylikuutio", NULL, NULL);
    if (window == NULL)
    {
        std::cerr << "Failed to open GLFW window.\n";
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // Initialize GLEW.
    if (glewInit() != GLEW_OK)
    {
        std::cerr << "Failed to initialize GLEW.\n";
        return -1;
    }

    // Ensure we can capture the escape key being pressed below.
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
    glfwSetCursorPos(window, (WINDOW_WIDTH / 2), (WINDOW_HEIGHT / 2));

    // Dark blue background.
    glClearColor(0.0f, 0.0f, 0.4f, 0.0f);

    // Enable depth test.
    glEnable(GL_DEPTH_TEST);
    // Accept fragment if it closer to the camera than the former one.
    glDepthFunc(GL_LESS);

    // Cull triangles which normal is not towards the camera.
    glEnable(GL_CULL_FACE);

    // Create the species, store it in `terrain_species`.
    SpeciesStruct terrain_species_struct;
    terrain_species_struct.model_file_format = g_model_file_format;
    terrain_species_struct.model_filename = g_model_filename;
    terrain_species_struct.texture_file_format = g_texture_file_format;
    terrain_species_struct.color_channel = g_height_data_color_channel;
    terrain_species_struct.texture_filename = g_texture_filename;
    terrain_species_struct.vertex_shader = "StandardShading.vertexshader";
    terrain_species_struct.fragment_shader = "StandardShading.fragmentshader";
    terrain_species_struct.lightPos = glm::vec3(4, 4, 4);
    model::Species terrain_species = model::Species(terrain_species_struct);

    // create a species pointer.
    model::Species *terrain_species_ptr = &terrain_species;

    // Create terrain1, store it in `terrain1`.
    ObjectStruct terrain_object_struct1;
    terrain_object_struct1.model_matrix = glm::mat4(1.0);
    terrain_object_struct1.translate_vector = glm::vec3(0.0f, 0.0f, 0.0f);
    model::Object terrain1 = model::Object(terrain_object_struct1);
    terrain1.species_ptr = terrain_species_ptr;

    SpeciesStruct suzanne_species_struct;
    suzanne_species_struct.model_file_format = "obj";
    suzanne_species_struct.model_filename = "suzanne.obj";
    suzanne_species_struct.texture_file_format = "dds";
    suzanne_species_struct.texture_filename = "uvmap.DDS";
    suzanne_species_struct.vertex_shader = "StandardShading.vertexshader";
    suzanne_species_struct.fragment_shader = "StandardShading.fragmentshader";
    suzanne_species_struct.lightPos = glm::vec3(4, 4, 4);
    model::Species suzanne_species = model::Species(suzanne_species_struct);

    // create a species pointer.
    model::Species *suzanne_species_ptr = &suzanne_species;

    // Create suzanne1, store it in `suzanne1`.
    ObjectStruct suzanne_object_struct1;
    suzanne_object_struct1.model_matrix = glm::translate(glm::mat4(1.0), glm::vec3(82.50f, 119.00f, 95.50f));
    suzanne_object_struct1.translate_vector = glm::vec3(0.0f, 0.0f, 0.0f);
    model::Object suzanne1 = model::Object(suzanne_object_struct1);
    suzanne1.species_ptr = suzanne_species_ptr;

    ObjectStruct suzanne_object_struct2;
    suzanne_object_struct2.model_matrix = glm::translate(glm::mat4(1.0), glm::vec3(112.90f, 113.90f, 75.50f));
    suzanne_object_struct2.translate_vector = glm::vec3(0.0f, 0.0f, 0.0f);
    model::Object suzanne2 = model::Object(suzanne_object_struct2);
    suzanne2.species_ptr = suzanne_species_ptr;

    ObjectStruct suzanne_object_struct3;
    suzanne_object_struct3.model_matrix = glm::translate(glm::mat4(1.0), glm::vec3(126.90f, 162.90f, 103.00f));
    suzanne_object_struct3.translate_vector = glm::vec3(0.0f, 0.0f, 0.0f);
    model::Object suzanne3 = model::Object(suzanne_object_struct3);
    suzanne3.species_ptr = suzanne_species_ptr;

    ObjectStruct suzanne_object_struct4;
    suzanne_object_struct4.model_matrix = glm::translate(glm::mat4(1.0), glm::vec3(96.00f, 130.00f, 109.00f));
    suzanne_object_struct4.translate_vector = glm::vec3(0.0f, 0.0f, 0.0f);
    model::Object suzanne4 = model::Object(suzanne_object_struct4);
    suzanne4.species_ptr = suzanne_species_ptr;

    ObjectStruct suzanne_object_struct5;
    suzanne_object_struct5.model_matrix = glm::translate(glm::mat4(1.0), glm::vec3(103.00f, 105.00f, 109.00f));
    suzanne_object_struct5.translate_vector = glm::vec3(0.0f, 0.0f, 0.0f);
    model::Object suzanne5 = model::Object(suzanne_object_struct5);
    suzanne5.species_ptr = suzanne_species_ptr;

    std::cout << "number of vertices: " << terrain_species.vertices.size() << ".\n";
    std::cout << "number of UVs: " << terrain_species.UVs.size() << ".\n";
    std::cout << "number of normals: " << terrain_species.normals.size() << ".\n";

    std::cout << "number of indexed vertices: " << terrain_species.indexed_vertices.size() << ".\n";
    std::cout << "number of indexed UVs: " << terrain_species.indexed_UVs.size() << ".\n";
    std::cout << "number of indexed normals: " << terrain_species.indexed_normals.size() << ".\n";

    // Initialize our little text library with the Holstein font
    const char *char_g_font_texture_filename = g_font_texture_filename.c_str();
    const char *char_g_font_texture_file_format = g_font_texture_file_format.c_str();
    text2D::initText2D(WINDOW_WIDTH, WINDOW_HEIGHT, char_g_font_texture_filename, char_g_font_texture_file_format);

    // For speed computation
    double lastTime = glfwGetTime();
    int nbFrames = 0;

    bool ms_frame_text_ready = false;

    do
    {
        // Measure speed
        char ms_frame_text[256];
        double currentTime = glfwGetTime();
        nbFrames++;
        if (currentTime - lastTime >= 1.0)
        {
            // If last `printf()` was more than 1 sec ago,
            // `printf` and reset.
            sprintf(ms_frame_text, "%.02f ms/frame; %.02f Hz", 1000.0f / ((double) nbFrames), 1000.0f / (1000.0f / ((double) nbFrames)));
            ms_frame_text_ready = true;
            nbFrames = 0;
            lastTime += 1.0;
        }
        // Clear the screen.
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        terrain_species.render();

        terrain1.render();

        suzanne_species.render();

        suzanne1.render();
        suzanne2.render();
        suzanne3.render();
        suzanne4.render();
        suzanne5.render();

        glDisableVertexAttribArray(terrain_species.vertexPosition_modelspaceID);
        glDisableVertexAttribArray(terrain_species.vertexUVID);
        glDisableVertexAttribArray(terrain_species.vertexNormal_modelspaceID);

        PrintingStruct printing_struct;
        printing_struct.screen_width = WINDOW_WIDTH;
        printing_struct.screen_height = WINDOW_HEIGHT;
        printing_struct.text_size = TEXT_SIZE;
        printing_struct.font_size = FONT_SIZE;
        printing_struct.char_font_texture_file_format = "bmp";

        char coordinates_text[256];
        sprintf(coordinates_text, "(%.2f,%.2f,%.2f) (%.2f,%.2f)", position.x, position.y, position.z, horizontalAngle, verticalAngle);

        char time_text[256];
        sprintf(time_text, "%.2f sec", glfwGetTime(), position.x, position.y, position.z);

        printing_struct.x = 0;
        printing_struct.y = 0;
        printing_struct.text = coordinates_text;
        printing_struct.horizontal_alignment = "left";
        printing_struct.vertical_alignment = "bottom";
        text2D::printText2D(printing_struct);

        printing_struct.x = 0;
        printing_struct.y = WINDOW_HEIGHT;
        printing_struct.text = time_text;
        printing_struct.horizontal_alignment = "left";
        printing_struct.vertical_alignment = "top";
        text2D::printText2D(printing_struct);

        if (ms_frame_text_ready)
        {
            printing_struct.x = WINDOW_WIDTH;
            printing_struct.y = WINDOW_HEIGHT;
            printing_struct.text = ms_frame_text;
            printing_struct.horizontal_alignment = "right";
            printing_struct.vertical_alignment = "top";
            text2D::printText2D(printing_struct);
        }

        // Swap buffers.
        glfwSwapBuffers(window);
        glfwPollEvents();
    } // Check if the ESC key was pressed or the window was closed
    while ((glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS)
            && (glfwWindowShouldClose(window) == 0));

    // Cleanup VBO, shader and texture.
    glDeleteBuffers(1, &terrain_species.vertexbuffer);
    glDeleteBuffers(1, &terrain_species.uvbuffer);
    glDeleteBuffers(1, &terrain_species.normalbuffer);
    glDeleteBuffers(1, &terrain_species.elementbuffer);
    glDeleteProgram(terrain_species.programID);
    glDeleteTextures(1, &terrain_species.texture);

    // Delete the text's VBO, the shader and the texture
    text2D::cleanupText2D();

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    return 0;
}
<|endoftext|>


<commit_before>#ifndef DOMHEADER_GUARD_HPP
#define DOMHEADER_GUARD_HPP

/*
 * Copyright 2001-2002,2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * $Id$
 */

//
//  This is the primary header file for inclusion in application
//  programs using the C++ XML Document Object Model API.
//

#include <xercesc/dom/DOMAttr.hpp>
#include <xercesc/dom/DOMCDATASection.hpp>
#include <xercesc/dom/DOMCharacterData.hpp>
#include <xercesc/dom/DOMComment.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMDocumentFragment.hpp>
#include <xercesc/dom/DOMDocumentType.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/dom/DOMEntity.hpp>
#include <xercesc/dom/DOMEntityReference.hpp>
#include <xercesc/dom/DOMException.hpp>
#include <xercesc/dom/DOMImplementation.hpp>
#include <xercesc/dom/DOMNamedNodeMap.hpp>
#include <xercesc/dom/DOMNode.hpp>
#include <xercesc/dom/DOMNodeList.hpp>
#include <xercesc/dom/DOMNotation.hpp>
#include <xercesc/dom/DOMProcessingInstruction.hpp>
#include <xercesc/dom/DOMText.hpp>

// Introduced in DOM Level 2
#include <xercesc/dom/DOMDocumentRange.hpp>
#include <xercesc/dom/DOMDocumentTraversal.hpp>
#include <xercesc/dom/DOMNodeFilter.hpp>
#include <xercesc/dom/DOMNodeIterator.hpp>
#include <xercesc/dom/DOMRange.hpp>
#include <xercesc/dom/DOMRangeException.hpp>
#include <xercesc/dom/DOMTreeWalker.hpp>

// Introduced in DOM Level 3
#include <xercesc/dom/DOMLSParser.hpp>
#include <xercesc/dom/DOMConfiguration.hpp>
#include <xercesc/dom/DOMLSResourceResolver.hpp>
#include <xercesc/dom/DOMError.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
#include <xercesc/dom/DOMImplementationLS.hpp>
#include <xercesc/dom/DOMImplementationList.hpp>
#include <xercesc/dom/DOMImplementationRegistry.hpp>
#include <xercesc/dom/DOMImplementationSource.hpp>
#include <xercesc/dom/DOMLSInput.hpp>
#include <xercesc/dom/DOMLSOutput.hpp>
#include <xercesc/dom/DOMLocator.hpp>
#include <xercesc/dom/DOMPSVITypeInfo.hpp>
#include <xercesc/dom/DOMStringList.hpp>
#include <xercesc/dom/DOMTypeInfo.hpp>
#include <xercesc/dom/DOMUserDataHandler.hpp>
#include <xercesc/dom/DOMLSSerializer.hpp>
#include <xercesc/dom/DOMLSSerializerFilter.hpp>

#include <xercesc/dom/DOMXPathEvaluator.hpp>
#include <xercesc/dom/DOMXPathNSResolver.hpp>
#include <xercesc/dom/DOMXPathException.hpp>
#include <xercesc/dom/DOMXPathExpression.hpp>
#include <xercesc/dom/DOMXPathResult.hpp>
#include <xercesc/dom/DOMXPathNamespace.hpp>

#endif
<commit_msg>added DOMLSParserFilter.hpp<commit_after>#ifndef DOMHEADER_GUARD_HPP
#define DOMHEADER_GUARD_HPP

/*
 * Copyright 2001-2002,2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * $Id$
 */

//
//  This is the primary header file for inclusion in application
//  programs using the C++ XML Document Object Model API.
//

#include <xercesc/dom/DOMAttr.hpp>
#include <xercesc/dom/DOMCDATASection.hpp>
#include <xercesc/dom/DOMCharacterData.hpp>
#include <xercesc/dom/DOMComment.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMDocumentFragment.hpp>
#include <xercesc/dom/DOMDocumentType.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/dom/DOMEntity.hpp>
#include <xercesc/dom/DOMEntityReference.hpp>
#include <xercesc/dom/DOMException.hpp>
#include <xercesc/dom/DOMImplementation.hpp>
#include <xercesc/dom/DOMNamedNodeMap.hpp>
#include <xercesc/dom/DOMNode.hpp>
#include <xercesc/dom/DOMNodeList.hpp>
#include <xercesc/dom/DOMNotation.hpp>
#include <xercesc/dom/DOMProcessingInstruction.hpp>
#include <xercesc/dom/DOMText.hpp>

// Introduced in DOM Level 2
#include <xercesc/dom/DOMDocumentRange.hpp>
#include <xercesc/dom/DOMDocumentTraversal.hpp>
#include <xercesc/dom/DOMNodeFilter.hpp>
#include <xercesc/dom/DOMNodeIterator.hpp>
#include <xercesc/dom/DOMRange.hpp>
#include <xercesc/dom/DOMRangeException.hpp>
#include <xercesc/dom/DOMTreeWalker.hpp>

// Introduced in DOM Level 3
#include <xercesc/dom/DOMLSParser.hpp>
#include <xercesc/dom/DOMLSParserFilter.hpp>
#include <xercesc/dom/DOMConfiguration.hpp>
#include <xercesc/dom/DOMLSResourceResolver.hpp>
#include <xercesc/dom/DOMError.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
#include <xercesc/dom/DOMImplementationLS.hpp>
#include <xercesc/dom/DOMImplementationList.hpp>
#include <xercesc/dom/DOMImplementationRegistry.hpp>
#include <xercesc/dom/DOMImplementationSource.hpp>
#include <xercesc/dom/DOMLSInput.hpp>
#include <xercesc/dom/DOMLSOutput.hpp>
#include <xercesc/dom/DOMLocator.hpp>
#include <xercesc/dom/DOMPSVITypeInfo.hpp>
#include <xercesc/dom/DOMStringList.hpp>
#include <xercesc/dom/DOMTypeInfo.hpp>
#include <xercesc/dom/DOMUserDataHandler.hpp>
#include <xercesc/dom/DOMLSSerializer.hpp>
#include <xercesc/dom/DOMLSSerializerFilter.hpp>

#include <xercesc/dom/DOMXPathEvaluator.hpp>
#include <xercesc/dom/DOMXPathNSResolver.hpp>
#include <xercesc/dom/DOMXPathException.hpp>
#include <xercesc/dom/DOMXPathExpression.hpp>
#include <xercesc/dom/DOMXPathResult.hpp>
#include <xercesc/dom/DOMXPathNamespace.hpp>

#endif
<|endoftext|>


<commit_before>#include <tests/lib/test.h>

#include <tests/lib/glib-helpers/test-conn-helper.h>

#include <tests/lib/glib/simple-conn.h>

#define TP_QT4_ENABLE_LOWLEVEL_API

#include <TelepathyQt4/Connection>
#include <TelepathyQt4/ConnectionLowlevel>
#include <TelepathyQt4/PendingHandles>
#include <TelepathyQt4/ReferencedHandles>

#include <telepathy-glib/debug.h>

using namespace Tp;

class TestHandles : public Test
{
    Q_OBJECT

public:
    TestHandles(QObject *parent = 0)
        : Test(parent), mConn(0)
    { }

protected Q_SLOTS:
    void expectPendingHandlesFinished(Tp::PendingOperation*);

private Q_SLOTS:
    void initTestCase();
    void init();

    void testRequestAndRelease();

    void cleanup();
    void cleanupTestCase();

private:
    TestConnHelper *mConn;
    ReferencedHandles mHandles;
};

void TestHandles::expectPendingHandlesFinished(PendingOperation *op)
{
    if (!op->isFinished()) {
        qWarning() << "unfinished";
        mLoop->exit(1);
        return;
    }

    if (op->isError()) {
        qWarning().nospace() << op->errorName()
            << ": " << op->errorMessage();
        mLoop->exit(2);
        return;
    }

    if (!op->isValid()) {
        qWarning() << "inconsistent results";
        mLoop->exit(3);
        return;
    }

    qDebug() << "finished";
    PendingHandles *pending = qobject_cast<PendingHandles*>(op);
    mHandles = pending->handles();
    mLoop->exit(0);
}

void TestHandles::initTestCase()
{
    initTestCaseImpl();

    g_type_init();
    g_set_prgname("handles");
    tp_debug_set_flags("all");
    dbus_g_bus_get(DBUS_BUS_STARTER, 0);

    mConn = new TestConnHelper(this,
            TP_TESTS_TYPE_SIMPLE_CONNECTION,
            "account", "me@example.com",
            "protocol", "simple",
            NULL);
    QCOMPARE(mConn->connect(), true);
}

void TestHandles::init()
{
    initImpl();
}

void TestHandles::testRequestAndRelease()
{
    // Test identifiers
    QStringList ids = QStringList() << QLatin1String("alice")
        << QLatin1String("bob") << QLatin1String("chris");

    // Request handles for the identifiers and wait for the request to process
    PendingHandles *pending = mConn->client()->lowlevel()->requestHandles(Tp::HandleTypeContact, ids);
    QVERIFY(connect(pending,
                    SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(expectPendingHandlesFinished(Tp::PendingOperation*))));
    QCOMPARE(mLoop->exec(), 0);
    QVERIFY(disconnect(pending,
                       SIGNAL(finished(Tp::PendingOperation*)),
                       this,
                       SLOT(expectPendingHandlesFinished(Tp::PendingOperation*))));
    ReferencedHandles handles = mHandles;
    mHandles = ReferencedHandles();

    // Verify that the closure indicates correctly which names we requested
    QCOMPARE(pending->namesRequested(), ids);

    // Verify by directly poking the service that the handles correspond to the requested IDs
    TpHandleRepoIface *serviceRepo =
        tp_base_connection_get_handles(TP_BASE_CONNECTION(mConn->service()), TP_HANDLE_TYPE_CONTACT);
    for (int i = 0; i < 3; i++) {
        uint handle = handles[i];
        QCOMPARE(QString::fromUtf8(tp_handle_inspect(serviceRepo, handle)), ids[i]);
    }

    // Save the handles to a non-referenced normal container
    Tp::UIntList saveHandles = handles.toList();

    // Start releasing the handles, RAII style, and complete the asynchronous process doing that
    handles = ReferencedHandles();
    mLoop->processEvents();
    processDBusQueue(mConn->client().data());
}

void TestHandles::cleanup()
{
    cleanupImpl();
}

void TestHandles::cleanupTestCase()
{
    QCOMPARE(mConn->disconnect(), true);
    delete mConn;

    cleanupTestCaseImpl();
}

QTEST_MAIN(TestHandles)
#include "_gen/handles.cpp.moc.hpp"
<commit_msg>handles test: Use TEST_VERIFY_OP<commit_after>#include <tests/lib/test.h>

#include <tests/lib/glib-helpers/test-conn-helper.h>

#include <tests/lib/glib/simple-conn.h>

#define TP_QT4_ENABLE_LOWLEVEL_API

#include <TelepathyQt4/Connection>
#include <TelepathyQt4/ConnectionLowlevel>
#include <TelepathyQt4/PendingHandles>
#include <TelepathyQt4/ReferencedHandles>

#include <telepathy-glib/debug.h>

using namespace Tp;

class TestHandles : public Test
{
    Q_OBJECT

public:
    TestHandles(QObject *parent = 0)
        : Test(parent), mConn(0)
    { }

protected Q_SLOTS:
    void expectPendingHandlesFinished(Tp::PendingOperation*);

private Q_SLOTS:
    void initTestCase();
    void init();

    void testRequestAndRelease();

    void cleanup();
    void cleanupTestCase();

private:
    TestConnHelper *mConn;
    ReferencedHandles mHandles;
};

void TestHandles::expectPendingHandlesFinished(PendingOperation *op)
{
    TEST_VERIFY_OP(op);

    PendingHandles *pending = qobject_cast<PendingHandles*>(op);
    mHandles = pending->handles();
    mLoop->exit(0);
}

void TestHandles::initTestCase()
{
    initTestCaseImpl();

    g_type_init();
    g_set_prgname("handles");
    tp_debug_set_flags("all");
    dbus_g_bus_get(DBUS_BUS_STARTER, 0);

    mConn = new TestConnHelper(this,
            TP_TESTS_TYPE_SIMPLE_CONNECTION,
            "account", "me@example.com",
            "protocol", "simple",
            NULL);
    QCOMPARE(mConn->connect(), true);
}

void TestHandles::init()
{
    initImpl();
}

void TestHandles::testRequestAndRelease()
{
    // Test identifiers
    QStringList ids = QStringList() << QLatin1String("alice")
        << QLatin1String("bob") << QLatin1String("chris");

    // Request handles for the identifiers and wait for the request to process
    PendingHandles *pending = mConn->client()->lowlevel()->requestHandles(Tp::HandleTypeContact, ids);
    QVERIFY(connect(pending,
                    SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(expectPendingHandlesFinished(Tp::PendingOperation*))));
    QCOMPARE(mLoop->exec(), 0);
    QVERIFY(disconnect(pending,
                       SIGNAL(finished(Tp::PendingOperation*)),
                       this,
                       SLOT(expectPendingHandlesFinished(Tp::PendingOperation*))));
    ReferencedHandles handles = mHandles;
    mHandles = ReferencedHandles();

    // Verify that the closure indicates correctly which names we requested
    QCOMPARE(pending->namesRequested(), ids);

    // Verify by directly poking the service that the handles correspond to the requested IDs
    TpHandleRepoIface *serviceRepo =
        tp_base_connection_get_handles(TP_BASE_CONNECTION(mConn->service()), TP_HANDLE_TYPE_CONTACT);
    for (int i = 0; i < 3; i++) {
        uint handle = handles[i];
        QCOMPARE(QString::fromUtf8(tp_handle_inspect(serviceRepo, handle)), ids[i]);
    }

    // Save the handles to a non-referenced normal container
    Tp::UIntList saveHandles = handles.toList();

    // Start releasing the handles, RAII style, and complete the asynchronous process doing that
    handles = ReferencedHandles();
    mLoop->processEvents();
    processDBusQueue(mConn->client().data());
}

void TestHandles::cleanup()
{
    cleanupImpl();
}

void TestHandles::cleanupTestCase()
{
    QCOMPARE(mConn->disconnect(), true);
    delete mConn;

    cleanupTestCaseImpl();
}

QTEST_MAIN(TestHandles)
#include "_gen/handles.cpp.moc.hpp"
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include <EventStorage.h>
#include <ID.h>
#include <algorithm>
#include <iterator>

namespace test {

 using ::testing::Contains;
 using ::testing::Pointee;
 using ::testing::ElementsAre;
 using ::testing::Each;
 using ::testing::SizeIs;
 using ::testing::UnorderedElementsAre;
 using EventTypes = EventStorage::EventTypes;
 using namespace std;

  struct EventStorageTestSuite : public ::testing::Test {
    EventType eT0, eT1, eT2;
    AbstractPolicy policy;
    EventStorageTestSuite() {
      ValueType v(id::type::UInt8::value(), 1, 1, false);
      AttributeType aT0(251, v, Scale<>(), Dimensionless());
      AttributeType aT1(252, v, Scale<>(), Dimensionless());
      AttributeType aT2(253, v, Scale<>(), Dimensionless());
      eT0.add(aT0);
      eT1.add(aT1);
      eT2.add(aT2);
    }

};

TEST_F(EventStorageTestSuite, singularStorage) {
  EventTypes in = {eT0};
  EventStorage s(in, policy);
  MetaEvent e(eT0);
  MetaAttribute* a = e.attribute(251);
  ASSERT_NE(a, nullptr);
  a->value().set(0,0,{1});
  s.addEvent(e);
  vector<vector<const MetaEvent*>> result;
  copy(s.begin(), s.end(), back_inserter(result));
  EXPECT_THAT(result,
    UnorderedElementsAre(
      ElementsAre(Pointee(e))
    )
  );
}

TEST_F(EventStorageTestSuite, homogeneusDualStorage) {
  EventTypes in = {eT0, eT0};
  EventStorage s(in, policy);
  MetaEvent e0(eT0);
  MetaAttribute* a = e0.attribute(251);
  ASSERT_NE(a, nullptr);
  a->value().set(0,0,{1});
  s.addEvent(e0);
  MetaEvent e1(e0);
  a = e1.attribute(251);
  ASSERT_NE(a, nullptr);
  a->value().set(0,0,{2});
  s.addEvent(e1);
  vector<vector<const MetaEvent*>> result;
  copy(s.begin(), s.end(), back_inserter(result));
  EXPECT_THAT(result,
    UnorderedElementsAre(
      ElementsAre(Pointee(e0), Pointee(e0)),
      ElementsAre(Pointee(e0), Pointee(e1)),
      ElementsAre(Pointee(e1), Pointee(e0)),
      ElementsAre(Pointee(e1), Pointee(e1))
    )
  );
}

TEST_F(EventStorageTestSuite, heterogeneusDualStorage) {
  EventTypes in = {eT0, eT1};
  EventStorage s(in, policy);
  MetaEvent e0(eT0);
  MetaAttribute* a = e0.attribute(251);
  ASSERT_NE(a, nullptr);
  a->value().set(0,0,{1});
  s.addEvent(e0);
  MetaEvent e1(eT1);
  a = e1.attribute(252);
  ASSERT_NE(a, nullptr);
  a->value().set(0,0,{2});
  s.addEvent(e1);
  vector<vector<const MetaEvent*>> result;
  copy(s.begin(), s.end(), back_inserter(result));
  EXPECT_THAT(result,
    UnorderedElementsAre(
      ElementsAre(Pointee(e0), Pointee(e1))
    )
  );

}

TEST_F(EventStorageTestSuite, largeStorage) {
  EventTypes in = {eT0, eT1, eT2};
  EventStorage s(in, policy);
  for(const EventType& eT: in)
    for(size_t i=0;i<policy.bufferSize;i++) {
      MetaEvent e(eT);
      ASSERT_GT(eT.size(), 0U);
      MetaAttribute* a = e.attribute(eT.begin()->id());
      ASSERT_NE(a, nullptr);
      a->value().set(0,0,{(double)i});
      s.addEvent(e);
    }
  vector<vector<const MetaEvent*>> result;
  copy(s.begin(), s.end(), back_inserter(result));
  EXPECT_THAT(result, SizeIs(pow(policy.bufferSize, 3U)));
  EXPECT_THAT(result, Each(SizeIs(3)));
}

}
<commit_msg>Unit-Tests: eventStorage adapt to new combination generation<commit_after>#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include <EventStorage.h>
#include <ID.h>
#include <algorithm>
#include <iterator>

namespace test {

 using ::testing::Contains;
 using ::testing::Pointee;
 using ::testing::ElementsAre;
 using ::testing::Each;
 using ::testing::SizeIs;
 using ::testing::UnorderedElementsAre;
 using EventTypes = EventStorage::EventTypes;
 using namespace std;

  struct EventStorageTestSuite : public ::testing::Test {
    EventType eT0, eT1, eT2;
    AbstractPolicy policy;
    EventStorageTestSuite() {
      ValueType v(id::type::UInt8::value(), 1, 1, false);
      AttributeType aT0(251, v, Scale<>(), Dimensionless());
      AttributeType aT1(252, v, Scale<>(), Dimensionless());
      AttributeType aT2(253, v, Scale<>(), Dimensionless());
      eT0.add(aT0);
      eT1.add(aT1);
      eT2.add(aT2);
    }

};

TEST_F(EventStorageTestSuite, singularStorage) {
  EventTypes in = {eT0};
  EventStorage s(in, policy);
  MetaEvent e(eT0);
  MetaAttribute* a = e.attribute(251);
  ASSERT_NE(a, nullptr);
  a->value().set(0,0,{1});
  s.addEvent(e);
  vector<vector<const MetaEvent*>> result;
  copy(s.begin(), s.end(), back_inserter(result));
  EXPECT_THAT(result,
    UnorderedElementsAre(
      ElementsAre(Pointee(e))
    )
  );
}

TEST_F(EventStorageTestSuite, homogeneusDualStorage) {
  EventTypes in = {eT0, eT0};
  EventStorage s(in, policy);
  MetaEvent e0(eT0);
  MetaAttribute* a = e0.attribute(251);
  ASSERT_NE(a, nullptr);
  a->value().set(0,0,{1});
  s.addEvent(e0);
  MetaEvent e1(e0);
  a = e1.attribute(251);
  ASSERT_NE(a, nullptr);
  a->value().set(0,0,{2});
  s.addEvent(e1);
  vector<vector<const MetaEvent*>> result;
  copy(s.begin(), s.end(), back_inserter(result));
  EXPECT_THAT(result,
    UnorderedElementsAre(
      ElementsAre(Pointee(e0), Pointee(e1)),
      ElementsAre(Pointee(e1), Pointee(e0))
    )
  );
}

TEST_F(EventStorageTestSuite, heterogeneusDualStorage) {
  EventTypes in = {eT0, eT1};
  EventStorage s(in, policy);
  MetaEvent e0(eT0);
  MetaAttribute* a = e0.attribute(251);
  ASSERT_NE(a, nullptr);
  a->value().set(0,0,{1});
  s.addEvent(e0);
  MetaEvent e1(eT1);
  a = e1.attribute(252);
  ASSERT_NE(a, nullptr);
  a->value().set(0,0,{2});
  s.addEvent(e1);
  vector<vector<const MetaEvent*>> result;
  copy(s.begin(), s.end(), back_inserter(result));
  EXPECT_THAT(result,
    UnorderedElementsAre(
      ElementsAre(Pointee(e0), Pointee(e1))
    )
  );

}

TEST_F(EventStorageTestSuite, largeStorage) {
  EventTypes in = {eT0, eT1, eT2};
  EventStorage s(in, policy);
  for(const EventType& eT: in)
    for(size_t i=0;i<policy.bufferSize;i++) {
      MetaEvent e(eT);
      ASSERT_GT(eT.size(), 0U);
      MetaAttribute* a = e.attribute(eT.begin()->id());
      ASSERT_NE(a, nullptr);
      a->value().set(0,0,{(double)i});
      s.addEvent(e);
    }
  vector<vector<const MetaEvent*>> result;
  copy(s.begin(), s.end(), back_inserter(result));
  EXPECT_THAT(result, SizeIs(pow(policy.bufferSize, 2U)));
  EXPECT_THAT(result, Each(SizeIs(3)));
}

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 National Research Institute of Science and
 * Technology for Environment and Agriculture (IRSTEA)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "itkFixedArray.h"
#include "itkObjectFactory.h"

// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
#include "otbWrapperApplicationFactory.h"

// Application engine
#include "otbStandardFilterWatcher.h"

// Process objects
#include "otbVectorDataToLabelImageFilter.h"
#include "otbVectorDataIntoImageProjectionFilter.h"
#include "otbStreamingStatisticsMapFromLabelImageFilter.h"
#include "otbStatisticsXMLFileWriter.h"

// Raster --> Vector
#include "otbLabelImageToVectorDataFilter.h"
#include "itkBinaryThresholdImageFilter.h"

namespace otb
{

namespace Wrapper
{

class ZonalStatistics : public Application
{
public:
  /** Standard class typedefs. */
  typedef ZonalStatistics               Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /* Typedefs */
  typedef Int32ImageType                LabelImageType;
  typedef LabelImageType::ValueType     LabelValueType;
  typedef otb::VectorData<double, 2>    VectorDataType;
  typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType,
                                                   FloatVectorImageType>             VectorDataReprojFilterType;
  typedef otb::VectorDataToLabelImageFilter<VectorDataType,
                                            LabelImageType>                   RasterizeFilterType;
  typedef VectorDataType::DataTreeType  DataTreeType;
  typedef itk::PreOrderTreeIterator<DataTreeType>
  TreeIteratorType;
  typedef VectorDataType::DataNodeType  DataNodeType;
  typedef DataNodeType::PolygonListPointerType
  PolygonListPointerType;
  typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType,
                                                          LabelImageType>                   StatsFilterType;
  typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType>
  StatsWriterType;
  typedef otb::LabelImageToVectorDataFilter<LabelImageType>
  LabelImageToVectorFilterType;
  typedef itk::BinaryThresholdImageFilter<LabelImageType,
                                          LabelImageType>                   ThresholdFilterType;

  /** Standard macro */
  itkNewMacro(Self);
  itkTypeMacro(ZonalStatistics, Application);

  void DoInit()
  {

    SetName("ZonalStatistics");
    SetDescription("This application computes zonal statistics");

    // Documentation
    SetDocName("ZonalStatistics");
    SetDocLongDescription("This application computes zonal statistics from label image, or vector data. "
                          "The application inputs one input multiband image, and a label input. "
                          "If the label input is a raster, the output statistics are exported in a XML file. If the label "
                          "input is a vector data, the output statistics are exported in a new vector data with statistics "
                          "in the attribute table. The computed statistics are mean, min, max, and standard deviation.");
    SetDocLimitations("The shapefile must fit in memory");
    SetDocAuthors("Remi Cresson");

    AddDocTag(Tags::Manip);
    AddDocTag(Tags::Analysis);

    // Input image
    AddParameter(ParameterType_InputImage, "in",   "Input Image");
    AddParameter(ParameterType_Float,      "inbv", "Background value to ignore in statistics computation");
    MandatoryOff                          ("inbv");

    // Input zone mode
    AddParameter(ParameterType_Choice, "inzone", "Type of input for the zone definitions");
    AddChoice("inzone.vector",     "Input objects from vector data");
    AddChoice("inzone.labelimage", "Input objects from label image");

    // Input for vector mode
    AddParameter(ParameterType_InputVectorData,  "inzone.vector.in",        "Input vector data");
    AddParameter(ParameterType_Bool,             "inzone.vector.reproject", "Reproject the input vector");

    // Input for label image mode
    AddParameter(ParameterType_InputImage, "inzone.labelimage.in",     "Input label image");
    AddParameter(ParameterType_Int,        "inzone.labelimage.nodata", "No-data value for the input label image");
    MandatoryOff                          ("inzone.labelimage.nodata");

    // Output stats mode
    AddParameter(ParameterType_Choice, "out", "Format of the output stats");
    AddChoice("out.vector", "Output vector data");
    AddParameter(ParameterType_OutputVectorData, "out.vector.filename", "Filename for the output vector data");
    AddChoice("out.xml", "Output XML file");
    AddParameter(ParameterType_String, "out.xml.filename", "");
//    AddChoice("out.raster", "Output raster image");
//    AddParameter(ParameterType_OutputImage, "out.raster.filename", "");

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "input.tif");
    SetDocExampleParameterValue("inzone.vector.in", "myvector.shp");
    SetDocExampleParameterValue("out.vector.filename", "myvector_with_stats.shp");

  }

  void DoUpdateParameters()
  {
    // Nothing to do here : all parameters are independent
  }

  // Returns a string of the kind "prefix_i"
  const std::string CreateFieldName(const std::string & prefix, const unsigned int i)
  {
    std::stringstream ss;
    ss << prefix << "_" << i;
    return ss.str();
  }

  // Returns a null pixel which has the same number of components per pixels as img
  FloatVectorImageType::PixelType NullPixel(FloatVectorImageType::Pointer & img)
  {
    const unsigned int nBands = img->GetNumberOfComponentsPerPixel();
    FloatVectorImageType::PixelType pix(nBands);
    pix.Fill(0);
    return pix;
  }

  void PrepareForLabelImageInput()
  {
    otbAppLogINFO("Zone definition: label image");
    // Computing stats
    m_StatsFilter->SetInputLabelImage(GetParameterInt32Image("inzone.labelimage.in"));
    m_StatsFilter->Update();
    // In this zone definition mode, the user can provide a no-data value for the labels
    if (HasUserValue("inzone.labelimage.nodata"))
      m_IntNoData = GetParameterInt("inzone.labelimage.nodata");
  }

  void PrepareForVectorDataInput()
  {
    otbAppLogINFO("Zone definition: vector");
    otbAppLogINFO("Loading vector data...");
    m_VectorDataSrc = GetParameterVectorData("inzone.vector.in");
    // Reproject vector data
    if (GetParameterInt("inzone.vector.reproject") != 0)
      {
      ReprojectVectorDataIntoInputImage();
      }
    RasterizeInputVectorData();
    // Computing stats
    m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput());
    m_StatsFilter->Update();
  }

  void ReprojectVectorDataIntoInputImage()
  {
    otbAppLogINFO("Vector data reprojection enabled");
    m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New();
    m_VectorDataReprojectionFilter->SetInputVectorData(m_VectorDataSrc.GetPointer());
    m_VectorDataReprojectionFilter->SetInputImage(m_InputImage);
    AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data");
    m_VectorDataReprojectionFilter->Update();
    m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput();
  }

  void RasterizeInputVectorData()
  {
    // Rasterize vector data
    m_RasterizeFilter = RasterizeFilterType::New();
    m_RasterizeFilter->AddVectorData(m_VectorDataSrc);
    m_RasterizeFilter->SetOutputOrigin(m_InputImage->GetOrigin());
    m_RasterizeFilter->SetOutputSpacing(m_InputImage->GetSignedSpacing());
    m_RasterizeFilter->SetOutputSize(m_InputImage->GetLargestPossibleRegion().GetSize());
    m_RasterizeFilter->SetOutputProjectionRef(m_InputImage->GetProjectionRef());
    m_RasterizeFilter->SetBurnAttribute("________");
    m_RasterizeFilter->SetDefaultBurnValue(0);
    m_RasterizeFilter->SetGlobalWarningDisplay(false);
    m_RasterizeFilter->SetBackgroundValue(m_IntNoData);
  }

  void RemoveNoDataEntry()
  {
    m_CountMap = m_StatsFilter->GetLabelPopulationMap();
    m_MeanMap = m_StatsFilter->GetMeanValueMap();
    m_StdMap = m_StatsFilter->GetStandardDeviationValueMap();
    m_MinMap = m_StatsFilter->GetMinValueMap();
    m_MaxMap = m_StatsFilter->GetMaxValueMap();
    if (( GetParameterAsString("inzone") == "labelimage" && HasUserValue("inzone.labelimage.nodata"))
        || (GetParameterAsString("inzone") == "vector")      )
      {
      otbAppLogINFO("Removing entries for label value " << m_IntNoData);

      m_CountMap.erase(m_IntNoData);
      m_MeanMap.erase(m_IntNoData);
      m_StdMap.erase(m_IntNoData);
      m_MinMap.erase(m_IntNoData);
      m_MaxMap.erase(m_IntNoData);
      }
  }

  void GenerateVectorDataFromLabelImage()
  {

    // Mask for label image
    m_ThresholdFilter = ThresholdFilterType::New();
    m_ThresholdFilter->SetInput(GetParameterInt32Image("inzone.labelimage.in"));
    m_ThresholdFilter->SetInsideValue(0);
    m_ThresholdFilter->SetOutsideValue(1);
    m_ThresholdFilter->SetLowerThreshold(m_IntNoData);
    m_ThresholdFilter->SetUpperThreshold(m_IntNoData);

    // Vectorize the image
    m_LabelImageToVectorFilter = LabelImageToVectorFilterType::New();
    m_LabelImageToVectorFilter->SetInput(GetParameterInt32Image("inzone.labelimage.in"));
    m_LabelImageToVectorFilter->SetInputMask(m_ThresholdFilter->GetOutput());
    m_LabelImageToVectorFilter->SetFieldName("polygon_id");
    AddProcess(m_LabelImageToVectorFilter, "Vectorize label image");
    m_LabelImageToVectorFilter->Update();

    // The source vector data is the vectorized label image
    m_VectorDataSrc = m_LabelImageToVectorFilter->GetOutput();

  }

  void WriteVectorData()
  {
    // Add statistics fields
    otbAppLogINFO("Writing output vector data");
    LabelValueType internalFID = -1;
    m_NewVectorData = VectorDataType::New();
    DataNodeType::Pointer root = m_NewVectorData->GetDataTree()->GetRoot()->Get();
    DataNodeType::Pointer document = DataNodeType::New();
    document->SetNodeType(otb::DOCUMENT);
    m_NewVectorData->GetDataTree()->Add(document, root);
    DataNodeType::Pointer folder = DataNodeType::New();
    folder->SetNodeType(otb::FOLDER);
    m_NewVectorData->GetDataTree()->Add(folder, document);
    m_NewVectorData->SetProjectionRef(m_VectorDataSrc->GetProjectionRef());
    TreeIteratorType itVector(m_VectorDataSrc->GetDataTree());
    itVector.GoToBegin();

    while (!itVector.IsAtEnd())
      {
      if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder())
        {

        DataNodeType::Pointer currentGeometry = itVector.Get();
        if (m_FromLabelImage)
          internalFID = currentGeometry->GetFieldAsInt("polygon_id");
        else
          internalFID++;

        // Add the geometry with the new fields
        if (m_CountMap.count(internalFID) > 0)
          {
          currentGeometry->SetFieldAsDouble("count", m_CountMap[internalFID] );
          for (unsigned int band = 0 ; band < m_InputImage->GetNumberOfComponentsPerPixel() ; band++)
            {
            currentGeometry->SetFieldAsDouble(CreateFieldName("mean",  band), m_MeanMap[internalFID][band] );
            currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), m_StdMap [internalFID][band] );
            currentGeometry->SetFieldAsDouble(CreateFieldName("min",   band), m_MinMap [internalFID][band] );
            currentGeometry->SetFieldAsDouble(CreateFieldName("max",   band), m_MaxMap [internalFID][band] );
            }
          m_NewVectorData->GetDataTree()->Add(currentGeometry, folder);
          }
        }
      ++itVector;
      } // next feature

    SetParameterOutputVectorData("out.vector.filename", m_NewVectorData);
  }

  void WriteXMLStatsFile()
  {
    // Write statistics in XML file
    const std::string outXMLFile = this->GetParameterString("out.xml.filename");
    otbAppLogINFO("Writing " + outXMLFile)
      StatsWriterType::Pointer statWriter = StatsWriterType::New();
    statWriter->SetFileName(outXMLFile);
    statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",m_CountMap);
    statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",m_MeanMap);
    statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",m_StdMap);
    statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",m_MinMap);
    statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",m_MaxMap);
    statWriter->Update();
  }

  void DoExecute()
  {
    // Get input image
    m_InputImage = GetParameterImage("in");
    // Statistics filter
    m_StatsFilter = StatsFilterType::New();
    m_StatsFilter->SetInput(m_InputImage);
    if (HasUserValue("inbv"))
      {
      m_StatsFilter->SetUseNoDataValue(true);
      m_StatsFilter->SetNoDataValue(GetParameterFloat("inbv"));
      }
    m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
    AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics");
    // Select zone definition mode
    m_FromLabelImage = (GetParameterAsString("inzone") == "labelimage");
    if (m_FromLabelImage)
      {
      PrepareForLabelImageInput();
      }
    else if (GetParameterAsString("inzone") == "vector")
      {
      PrepareForVectorDataInput();
      }
    else
      {
      otbAppLogFATAL("Unknown zone definition mode");
      }
    // Remove the no-data entry
    RemoveNoDataEntry();
    // Generate output
    if (GetParameterAsString("out") == "vector")
      {
      if (m_FromLabelImage)
        {
        GenerateVectorDataFromLabelImage();
        }
      WriteVectorData();
      }
    else if (GetParameterAsString("out") == "xml")
      {
      WriteXMLStatsFile();
      }
    else
      {
      otbAppLogFATAL("Unknown output mode");
      }

  }

  VectorDataType::Pointer m_VectorDataSrc;
  VectorDataType::Pointer m_NewVectorData;
  VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter;
  RasterizeFilterType::Pointer m_RasterizeFilter;
  StatsFilterType::Pointer m_StatsFilter;
  LabelImageToVectorFilterType::Pointer m_LabelImageToVectorFilter;
  ThresholdFilterType::Pointer m_ThresholdFilter;
  FloatVectorImageType::Pointer m_InputImage;
  LabelValueType m_IntNoData = itk::NumericTraits<LabelValueType>::max();
  bool m_FromLabelImage;
  StatsFilterType::LabelPopulationMapType m_CountMap;
  StatsFilterType::PixelValueMapType m_MeanMap;
  StatsFilterType::PixelValueMapType m_StdMap;
  StatsFilterType::PixelValueMapType m_MinMap;
  StatsFilterType::PixelValueMapType m_MaxMap;

};
}
}

OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )
<commit_msg>ENH: default initialisation of boolean<commit_after>/*
 * Copyright (C) 2017 National Research Institute of Science and
 * Technology for Environment and Agriculture (IRSTEA)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "itkFixedArray.h"
#include "itkObjectFactory.h"

// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
#include "otbWrapperApplicationFactory.h"

// Application engine
#include "otbStandardFilterWatcher.h"

// Process objects
#include "otbVectorDataToLabelImageFilter.h"
#include "otbVectorDataIntoImageProjectionFilter.h"
#include "otbStreamingStatisticsMapFromLabelImageFilter.h"
#include "otbStatisticsXMLFileWriter.h"

// Raster --> Vector
#include "otbLabelImageToVectorDataFilter.h"
#include "itkBinaryThresholdImageFilter.h"

namespace otb
{

namespace Wrapper
{

class ZonalStatistics : public Application
{
public:
  /** Standard class typedefs. */
  typedef ZonalStatistics               Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /* Typedefs */
  typedef Int32ImageType                LabelImageType;
  typedef LabelImageType::ValueType     LabelValueType;
  typedef otb::VectorData<double, 2>    VectorDataType;
  typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType,
                                                   FloatVectorImageType>             VectorDataReprojFilterType;
  typedef otb::VectorDataToLabelImageFilter<VectorDataType,
                                            LabelImageType>                   RasterizeFilterType;
  typedef VectorDataType::DataTreeType  DataTreeType;
  typedef itk::PreOrderTreeIterator<DataTreeType>
  TreeIteratorType;
  typedef VectorDataType::DataNodeType  DataNodeType;
  typedef DataNodeType::PolygonListPointerType
  PolygonListPointerType;
  typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType,
                                                          LabelImageType>                   StatsFilterType;
  typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType>
  StatsWriterType;
  typedef otb::LabelImageToVectorDataFilter<LabelImageType>
  LabelImageToVectorFilterType;
  typedef itk::BinaryThresholdImageFilter<LabelImageType,
                                          LabelImageType>                   ThresholdFilterType;

  /** Standard macro */
  itkNewMacro(Self);
  itkTypeMacro(ZonalStatistics, Application);

  void DoInit()
  {

    SetName("ZonalStatistics");
    SetDescription("This application computes zonal statistics");

    // Documentation
    SetDocName("ZonalStatistics");
    SetDocLongDescription("This application computes zonal statistics from label image, or vector data. "
                          "The application inputs one input multiband image, and a label input. "
                          "If the label input is a raster, the output statistics are exported in a XML file. If the label "
                          "input is a vector data, the output statistics are exported in a new vector data with statistics "
                          "in the attribute table. The computed statistics are mean, min, max, and standard deviation.");
    SetDocLimitations("The shapefile must fit in memory");
    SetDocAuthors("Remi Cresson");

    AddDocTag(Tags::Manip);
    AddDocTag(Tags::Analysis);

    // Input image
    AddParameter(ParameterType_InputImage, "in",   "Input Image");
    AddParameter(ParameterType_Float,      "inbv", "Background value to ignore in statistics computation");
    MandatoryOff                          ("inbv");

    // Input zone mode
    AddParameter(ParameterType_Choice, "inzone", "Type of input for the zone definitions");
    AddChoice("inzone.vector",     "Input objects from vector data");
    AddChoice("inzone.labelimage", "Input objects from label image");

    // Input for vector mode
    AddParameter(ParameterType_InputVectorData,  "inzone.vector.in",        "Input vector data");
    AddParameter(ParameterType_Bool,             "inzone.vector.reproject", "Reproject the input vector");

    // Input for label image mode
    AddParameter(ParameterType_InputImage, "inzone.labelimage.in",     "Input label image");
    AddParameter(ParameterType_Int,        "inzone.labelimage.nodata", "No-data value for the input label image");
    MandatoryOff                          ("inzone.labelimage.nodata");

    // Output stats mode
    AddParameter(ParameterType_Choice, "out", "Format of the output stats");
    AddChoice("out.vector", "Output vector data");
    AddParameter(ParameterType_OutputVectorData, "out.vector.filename", "Filename for the output vector data");
    AddChoice("out.xml", "Output XML file");
    AddParameter(ParameterType_String, "out.xml.filename", "");
//    AddChoice("out.raster", "Output raster image");
//    AddParameter(ParameterType_OutputImage, "out.raster.filename", "");

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "input.tif");
    SetDocExampleParameterValue("inzone.vector.in", "myvector.shp");
    SetDocExampleParameterValue("out.vector.filename", "myvector_with_stats.shp");

  }

  void DoUpdateParameters()
  {
    // Nothing to do here : all parameters are independent
  }

  // Returns a string of the kind "prefix_i"
  const std::string CreateFieldName(const std::string & prefix, const unsigned int i)
  {
    std::stringstream ss;
    ss << prefix << "_" << i;
    return ss.str();
  }

  // Returns a null pixel which has the same number of components per pixels as img
  FloatVectorImageType::PixelType NullPixel(FloatVectorImageType::Pointer & img)
  {
    const unsigned int nBands = img->GetNumberOfComponentsPerPixel();
    FloatVectorImageType::PixelType pix(nBands);
    pix.Fill(0);
    return pix;
  }

  void PrepareForLabelImageInput()
  {
    otbAppLogINFO("Zone definition: label image");
    // Computing stats
    m_StatsFilter->SetInputLabelImage(GetParameterInt32Image("inzone.labelimage.in"));
    m_StatsFilter->Update();
    // In this zone definition mode, the user can provide a no-data value for the labels
    if (HasUserValue("inzone.labelimage.nodata"))
      m_IntNoData = GetParameterInt("inzone.labelimage.nodata");
  }

  void PrepareForVectorDataInput()
  {
    otbAppLogINFO("Zone definition: vector");
    otbAppLogINFO("Loading vector data...");
    m_VectorDataSrc = GetParameterVectorData("inzone.vector.in");
    // Reproject vector data
    if (GetParameterInt("inzone.vector.reproject") != 0)
      {
      ReprojectVectorDataIntoInputImage();
      }
    RasterizeInputVectorData();
    // Computing stats
    m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput());
    m_StatsFilter->Update();
  }

  void ReprojectVectorDataIntoInputImage()
  {
    otbAppLogINFO("Vector data reprojection enabled");
    m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New();
    m_VectorDataReprojectionFilter->SetInputVectorData(m_VectorDataSrc.GetPointer());
    m_VectorDataReprojectionFilter->SetInputImage(m_InputImage);
    AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data");
    m_VectorDataReprojectionFilter->Update();
    m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput();
  }

  void RasterizeInputVectorData()
  {
    // Rasterize vector data
    m_RasterizeFilter = RasterizeFilterType::New();
    m_RasterizeFilter->AddVectorData(m_VectorDataSrc);
    m_RasterizeFilter->SetOutputOrigin(m_InputImage->GetOrigin());
    m_RasterizeFilter->SetOutputSpacing(m_InputImage->GetSignedSpacing());
    m_RasterizeFilter->SetOutputSize(m_InputImage->GetLargestPossibleRegion().GetSize());
    m_RasterizeFilter->SetOutputProjectionRef(m_InputImage->GetProjectionRef());
    m_RasterizeFilter->SetBurnAttribute("________");
    m_RasterizeFilter->SetDefaultBurnValue(0);
    m_RasterizeFilter->SetGlobalWarningDisplay(false);
    m_RasterizeFilter->SetBackgroundValue(m_IntNoData);
  }

  void RemoveNoDataEntry()
  {
    m_CountMap = m_StatsFilter->GetLabelPopulationMap();
    m_MeanMap = m_StatsFilter->GetMeanValueMap();
    m_StdMap = m_StatsFilter->GetStandardDeviationValueMap();
    m_MinMap = m_StatsFilter->GetMinValueMap();
    m_MaxMap = m_StatsFilter->GetMaxValueMap();
    if (( GetParameterAsString("inzone") == "labelimage" && HasUserValue("inzone.labelimage.nodata"))
        || (GetParameterAsString("inzone") == "vector")      )
      {
      otbAppLogINFO("Removing entries for label value " << m_IntNoData);

      m_CountMap.erase(m_IntNoData);
      m_MeanMap.erase(m_IntNoData);
      m_StdMap.erase(m_IntNoData);
      m_MinMap.erase(m_IntNoData);
      m_MaxMap.erase(m_IntNoData);
      }
  }

  void GenerateVectorDataFromLabelImage()
  {

    // Mask for label image
    m_ThresholdFilter = ThresholdFilterType::New();
    m_ThresholdFilter->SetInput(GetParameterInt32Image("inzone.labelimage.in"));
    m_ThresholdFilter->SetInsideValue(0);
    m_ThresholdFilter->SetOutsideValue(1);
    m_ThresholdFilter->SetLowerThreshold(m_IntNoData);
    m_ThresholdFilter->SetUpperThreshold(m_IntNoData);

    // Vectorize the image
    m_LabelImageToVectorFilter = LabelImageToVectorFilterType::New();
    m_LabelImageToVectorFilter->SetInput(GetParameterInt32Image("inzone.labelimage.in"));
    m_LabelImageToVectorFilter->SetInputMask(m_ThresholdFilter->GetOutput());
    m_LabelImageToVectorFilter->SetFieldName("polygon_id");
    AddProcess(m_LabelImageToVectorFilter, "Vectorize label image");
    m_LabelImageToVectorFilter->Update();

    // The source vector data is the vectorized label image
    m_VectorDataSrc = m_LabelImageToVectorFilter->GetOutput();

  }

  void WriteVectorData()
  {
    // Add statistics fields
    otbAppLogINFO("Writing output vector data");
    LabelValueType internalFID = -1;
    m_NewVectorData = VectorDataType::New();
    DataNodeType::Pointer root = m_NewVectorData->GetDataTree()->GetRoot()->Get();
    DataNodeType::Pointer document = DataNodeType::New();
    document->SetNodeType(otb::DOCUMENT);
    m_NewVectorData->GetDataTree()->Add(document, root);
    DataNodeType::Pointer folder = DataNodeType::New();
    folder->SetNodeType(otb::FOLDER);
    m_NewVectorData->GetDataTree()->Add(folder, document);
    m_NewVectorData->SetProjectionRef(m_VectorDataSrc->GetProjectionRef());
    TreeIteratorType itVector(m_VectorDataSrc->GetDataTree());
    itVector.GoToBegin();

    while (!itVector.IsAtEnd())
      {
      if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder())
        {

        DataNodeType::Pointer currentGeometry = itVector.Get();
        if (m_FromLabelImage)
          internalFID = currentGeometry->GetFieldAsInt("polygon_id");
        else
          internalFID++;

        // Add the geometry with the new fields
        if (m_CountMap.count(internalFID) > 0)
          {
          currentGeometry->SetFieldAsDouble("count", m_CountMap[internalFID] );
          for (unsigned int band = 0 ; band < m_InputImage->GetNumberOfComponentsPerPixel() ; band++)
            {
            currentGeometry->SetFieldAsDouble(CreateFieldName("mean",  band), m_MeanMap[internalFID][band] );
            currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), m_StdMap [internalFID][band] );
            currentGeometry->SetFieldAsDouble(CreateFieldName("min",   band), m_MinMap [internalFID][band] );
            currentGeometry->SetFieldAsDouble(CreateFieldName("max",   band), m_MaxMap [internalFID][band] );
            }
          m_NewVectorData->GetDataTree()->Add(currentGeometry, folder);
          }
        }
      ++itVector;
      } // next feature

    SetParameterOutputVectorData("out.vector.filename", m_NewVectorData);
  }

  void WriteXMLStatsFile()
  {
    // Write statistics in XML file
    const std::string outXMLFile = this->GetParameterString("out.xml.filename");
    otbAppLogINFO("Writing " + outXMLFile)
      StatsWriterType::Pointer statWriter = StatsWriterType::New();
    statWriter->SetFileName(outXMLFile);
    statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",m_CountMap);
    statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",m_MeanMap);
    statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",m_StdMap);
    statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",m_MinMap);
    statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",m_MaxMap);
    statWriter->Update();
  }

  void DoExecute()
  {
    // Get input image
    m_InputImage = GetParameterImage("in");
    // Statistics filter
    m_StatsFilter = StatsFilterType::New();
    m_StatsFilter->SetInput(m_InputImage);
    if (HasUserValue("inbv"))
      {
      m_StatsFilter->SetUseNoDataValue(true);
      m_StatsFilter->SetNoDataValue(GetParameterFloat("inbv"));
      }
    m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
    AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics");
    // Select zone definition mode
    m_FromLabelImage = (GetParameterAsString("inzone") == "labelimage");
    if (m_FromLabelImage)
      {
      PrepareForLabelImageInput();
      }
    else if (GetParameterAsString("inzone") == "vector")
      {
      PrepareForVectorDataInput();
      }
    else
      {
      otbAppLogFATAL("Unknown zone definition mode");
      }
    // Remove the no-data entry
    RemoveNoDataEntry();
    // Generate output
    if (GetParameterAsString("out") == "vector")
      {
      if (m_FromLabelImage)
        {
        GenerateVectorDataFromLabelImage();
        }
      WriteVectorData();
      }
    else if (GetParameterAsString("out") == "xml")
      {
      WriteXMLStatsFile();
      }
    else
      {
      otbAppLogFATAL("Unknown output mode");
      }

  }

  VectorDataType::Pointer m_VectorDataSrc;
  VectorDataType::Pointer m_NewVectorData;
  VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter;
  RasterizeFilterType::Pointer m_RasterizeFilter;
  StatsFilterType::Pointer m_StatsFilter;
  LabelImageToVectorFilterType::Pointer m_LabelImageToVectorFilter;
  ThresholdFilterType::Pointer m_ThresholdFilter;
  FloatVectorImageType::Pointer m_InputImage;
  LabelValueType m_IntNoData = itk::NumericTraits<LabelValueType>::max();
  bool m_FromLabelImage = false;
  StatsFilterType::LabelPopulationMapType m_CountMap;
  StatsFilterType::PixelValueMapType m_MeanMap;
  StatsFilterType::PixelValueMapType m_StdMap;
  StatsFilterType::PixelValueMapType m_MinMap;
  StatsFilterType::PixelValueMapType m_MaxMap;

};
}
}

OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkDiffusionIOMimeTypes.h"
#include "mitkIOMimeTypes.h"

namespace mitk
{

std::vector<CustomMimeType*> DiffusionIOMimeTypes::Get()
{
  std::vector<CustomMimeType*> mimeTypes;

  // order matters here (descending rank for mime types)

  mimeTypes.push_back(DWI_MIMETYPE().Clone());
  mimeTypes.push_back(DTI_MIMETYPE().Clone());
  mimeTypes.push_back(QBI_MIMETYPE().Clone());

  mimeTypes.push_back(FIBERBUNDLE_MIMETYPE().Clone());

  mimeTypes.push_back(CONNECTOMICS_MIMETYPE().Clone());

  return mimeTypes;
}

// Mime Types

CustomMimeType DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE()
{
  CustomMimeType mimeType(FIBERBUNDLE_MIMETYPE_NAME());
  std::string category = "Fiber Bundle File";
  mimeType.SetComment("Fiber Bundles");
  mimeType.SetCategory(category);
  mimeType.AddExtension("fib");
  mimeType.AddExtension("trk");
  mimeType.AddExtension("vtk");
  return mimeType;
}

CustomMimeType DiffusionIOMimeTypes::DWI_MIMETYPE()
{
  CustomMimeType mimeType(DWI_MIMETYPE_NAME());
  std::string category = "Diffusion Weighted Image";
  mimeType.SetComment("Diffusion Weighted Images");
  mimeType.SetCategory(category);
  mimeType.AddExtension("dwi");
  mimeType.AddExtension("hdwi");
  mimeType.AddExtension("fsl");
  mimeType.AddExtension("fslgz");
  return mimeType;
}

CustomMimeType DiffusionIOMimeTypes::DTI_MIMETYPE()
{
  CustomMimeType mimeType(DTI_MIMETYPE_NAME());
  std::string category = "Tensor Images";
  mimeType.SetComment("Diffusion Tensor Images");
  mimeType.SetCategory(category);
  mimeType.AddExtension("dti");
  mimeType.AddExtension("hdti");
  return mimeType;
}

CustomMimeType DiffusionIOMimeTypes::QBI_MIMETYPE()
{
  CustomMimeType mimeType(QBI_MIMETYPE_NAME());
  std::string category = "Q-Ball Images";
  mimeType.SetComment("Diffusion Q-Ball Images");
  mimeType.SetCategory(category);
  mimeType.AddExtension("qbi");
  mimeType.AddExtension("hqbi");
  return mimeType;
}

CustomMimeType DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE()
{
  CustomMimeType mimeType(CONNECTOMICS_MIMETYPE_NAME());
  std::string category = "Connectomics Networks";
  mimeType.SetComment("Connectomics Networks");
  mimeType.SetCategory(category);
  mimeType.AddExtension("cnf");
  return mimeType;
}

// Names
std::string DiffusionIOMimeTypes::DWI_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".dwi";
  return name;
}

std::string DiffusionIOMimeTypes::DTI_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".dti";
  return name;
}

std::string DiffusionIOMimeTypes::QBI_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".qbi";
  return name;
}

std::string DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".fib";
  return name;
}

std::string DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".cnf";
  return name;
}

// Descriptions
const std::string DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_DESCRIPTION = "Fiberbundles";

const std::string DiffusionIOMimeTypes::DWI_MIMETYPE_DESCRIPTION = "Diffusion Weighted Images";
const std::string DiffusionIOMimeTypes::DTI_MIMETYPE_DESCRIPTION = "Diffusion Tensor Images";
const std::string DiffusionIOMimeTypes::QBI_MIMETYPE_DESCRIPTION = "Q-Ball Images";

const std::string DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_DESCRIPTION = "Connectomics Networks";
}
<commit_msg>COMP: Disable .vtk fiber bundles for now<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkDiffusionIOMimeTypes.h"
#include "mitkIOMimeTypes.h"

namespace mitk
{

std::vector<CustomMimeType*> DiffusionIOMimeTypes::Get()
{
  std::vector<CustomMimeType*> mimeTypes;

  // order matters here (descending rank for mime types)

  mimeTypes.push_back(DWI_MIMETYPE().Clone());
  mimeTypes.push_back(DTI_MIMETYPE().Clone());
  mimeTypes.push_back(QBI_MIMETYPE().Clone());

  mimeTypes.push_back(FIBERBUNDLE_MIMETYPE().Clone());

  mimeTypes.push_back(CONNECTOMICS_MIMETYPE().Clone());

  return mimeTypes;
}

// Mime Types

CustomMimeType DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE()
{
  CustomMimeType mimeType(FIBERBUNDLE_MIMETYPE_NAME());
  std::string category = "Fiber Bundle File";
  mimeType.SetComment("Fiber Bundles");
  mimeType.SetCategory(category);
  mimeType.AddExtension("fib");
  mimeType.AddExtension("trk");
  //mimeType.AddExtension("vtk");
  return mimeType;
}

CustomMimeType DiffusionIOMimeTypes::DWI_MIMETYPE()
{
  CustomMimeType mimeType(DWI_MIMETYPE_NAME());
  std::string category = "Diffusion Weighted Image";
  mimeType.SetComment("Diffusion Weighted Images");
  mimeType.SetCategory(category);
  mimeType.AddExtension("dwi");
  mimeType.AddExtension("hdwi");
  mimeType.AddExtension("fsl");
  mimeType.AddExtension("fslgz");
  return mimeType;
}

CustomMimeType DiffusionIOMimeTypes::DTI_MIMETYPE()
{
  CustomMimeType mimeType(DTI_MIMETYPE_NAME());
  std::string category = "Tensor Images";
  mimeType.SetComment("Diffusion Tensor Images");
  mimeType.SetCategory(category);
  mimeType.AddExtension("dti");
  mimeType.AddExtension("hdti");
  return mimeType;
}

CustomMimeType DiffusionIOMimeTypes::QBI_MIMETYPE()
{
  CustomMimeType mimeType(QBI_MIMETYPE_NAME());
  std::string category = "Q-Ball Images";
  mimeType.SetComment("Diffusion Q-Ball Images");
  mimeType.SetCategory(category);
  mimeType.AddExtension("qbi");
  mimeType.AddExtension("hqbi");
  return mimeType;
}

CustomMimeType DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE()
{
  CustomMimeType mimeType(CONNECTOMICS_MIMETYPE_NAME());
  std::string category = "Connectomics Networks";
  mimeType.SetComment("Connectomics Networks");
  mimeType.SetCategory(category);
  mimeType.AddExtension("cnf");
  return mimeType;
}

// Names
std::string DiffusionIOMimeTypes::DWI_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".dwi";
  return name;
}

std::string DiffusionIOMimeTypes::DTI_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".dti";
  return name;
}

std::string DiffusionIOMimeTypes::QBI_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".qbi";
  return name;
}

std::string DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".fib";
  return name;
}

std::string DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".cnf";
  return name;
}

// Descriptions
const std::string DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_DESCRIPTION = "Fiberbundles";

const std::string DiffusionIOMimeTypes::DWI_MIMETYPE_DESCRIPTION = "Diffusion Weighted Images";
const std::string DiffusionIOMimeTypes::DTI_MIMETYPE_DESCRIPTION = "Diffusion Tensor Images";
const std::string DiffusionIOMimeTypes::QBI_MIMETYPE_DESCRIPTION = "Q-Ball Images";

const std::string DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_DESCRIPTION = "Connectomics Networks";
}
<|endoftext|>


<commit_before>#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/device/device.h"
#include "pixelboost/graphics/helper/screenHelpers.h"

#ifdef PIXELBOOST_GRAPHICS_OPENGLES1

#include <OpenGLES/ES1/gl.h>
#include <OpenGLES/ES1/glext.h>

using namespace pb;

Camera::Camera()
{

}

Camera::~Camera()
{

}

OrthographicCamera::OrthographicCamera(Vec2 position, Vec2 scale)
    : Position(position)
    , Scale(scale)
{

}

void OrthographicCamera::ApplyTransform()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrthof(-1.f, 1.f, -1.f, 1.f, -1.f, 1.f);
    glScalef(ScreenHelpers::GetWorldScale()[0] * ScreenHelpers::GetAspectRatio() * Scale[0], ScreenHelpers::GetWorldScale()[1] * Scale[1], 1.f);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(-Position[0], -Position[1], 0.f);
}

PerspectiveCamera::PerspectiveCamera()
    : FieldOfView(90.f)
    , Offset(0,0)
    , Position(0,0,0)
    , ZNear(0.1f)
    , ZFar(100.f)
{
}

void PerspectiveCamera::ApplyTransform()
{
    float aspect = ScreenHelpers::GetScreenResolution()[0]/ScreenHelpers::GetScreenResolution()[1];
    float fH = tan(FieldOfView/360*M_PI) * ZNear;
    float fW = fH * aspect;
    Vec2 offset = -Offset / ZFar;
    offset *= tan(FieldOfView/360*M_PI);
    offset *= aspect;

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glFrustumf( -fW + offset[0], fW + offset[0], -fH + offset[1], fH + offset[1], ZNear, ZFar );

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(-Position[0], -Position[1], Position[2]);
}

#endif
<commit_msg>Add missing definition in GLES1 device<commit_after>#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/device/device.h"
#include "pixelboost/graphics/helper/screenHelpers.h"

#ifdef PIXELBOOST_GRAPHICS_OPENGLES1

#include <OpenGLES/ES1/gl.h>
#include <OpenGLES/ES1/glext.h>

using namespace pb;

Camera::Camera()
{

}

Camera::~Camera()
{

}

OrthographicCamera::OrthographicCamera(Vec2 position, Vec2 scale)
    : Position(position)
    , Scale(scale)
{

}

void OrthographicCamera::ApplyTransform()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrthof(-1.f, 1.f, -1.f, 1.f, -1.f, 1.f);
    glScalef(ScreenHelpers::GetWorldScale()[0] * ScreenHelpers::GetAspectRatio() * Scale[0], ScreenHelpers::GetWorldScale()[1] * Scale[1], 1.f);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(-Position[0], -Position[1], 0.f);
}

glm::vec2 OrthographicCamera::ConvertScreenToWorld(glm::vec2 screen)
{
    glm::vec2 position = screen;

    position[0] = position[0] - ScreenHelpers::GetScreenResolution()[0]/2;
    position[1] = ScreenHelpers::GetScreenResolution()[1]/2 - position[1];

	position[0] /= ScreenHelpers::GetDpu();
	position[1] /= ScreenHelpers::GetDpu();

    position /= glm::vec2(Scale[0], Scale[1]);
    position += glm::vec2(Position[0], Position[1]);

	return position;
}

PerspectiveCamera::PerspectiveCamera()
    : FieldOfView(90.f)
    , Offset(0,0)
    , Position(0,0,0)
    , ZNear(0.1f)
    , ZFar(100.f)
{
}

void PerspectiveCamera::ApplyTransform()
{
    float aspect = ScreenHelpers::GetScreenResolution()[0]/ScreenHelpers::GetScreenResolution()[1];
    float fH = tan(FieldOfView/360*M_PI) * ZNear;
    float fW = fH * aspect;
    Vec2 offset = -Offset / ZFar;
    offset *= tan(FieldOfView/360*M_PI);
    offset *= aspect;

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glFrustumf( -fW + offset[0], fW + offset[0], -fH + offset[1], fH + offset[1], ZNear, ZFar );

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(-Position[0], -Position[1], Position[2]);
}

#endif
<|endoftext|>