<commit_before>//
//  main.cpp
//  ModelViewer
//
//  Created by Mattias Bergström on 2014-01-21.
//  Copyright (c) 2014 Mattias Bergström. All rights reserved.
//

#include <iostream>
#include <thread>
#include "glm/glm.hpp"
#include <cmath>
#include "Mesh.h"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "SceneRenderer.h"
#include "Constants.h"
#include "MeshLoader.h"
#include "LightProperties.h"
#include "CameraMovement.h"
#include "ModelViewerWindow.h"
#include <glew.h>
#include <GLFW/glfw3.h>
#include <gtkmm/application.h>

#ifdef __APPLE__
#include <OpenGL/glu.h>
#else
#include <GL/glu.h>
#endif

CameraMovement* movement;
Camera camera;
SceneRenderer renderer;
bool shouldFlipNormals;
bool shouldLoadFile;
std::string filename;

static void error_callback(int error, const char* description)
{
    fputs(description, stderr);
}

static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);

    if(key == GLFW_KEY_1 && action == GLFW_PRESS) {
        camera.setCameraProjection(PROJECTION_PERSPECTIVE);
    }
    if(key == GLFW_KEY_2 && action == GLFW_PRESS) {
        camera.setCameraProjection(PROJECTION_ORTHOGONAL);
    }
    if(key == GLFW_KEY_3 && action == GLFW_PRESS) {
        camera.setCameraProjection(PROJECTION_OBLIQUE);
    }
}

static void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    renderer.updateResolution(width, height);
}

void updateInput(GLFWwindow* window) {

    movement->update();
}

void initGL() {
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
}

GLFWwindow* initGLWindow() {
    GLFWwindow* window;

    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    window = glfwCreateWindow(854, 480, "Simple example", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    glfwSetKeyCallback(window, key_callback);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // Initialize GLEW
    glewExperimental=true; // Needed in core profile
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        exit(EXIT_FAILURE);
    }

    return window;
}

std::shared_ptr<SceneNode> createSceneNode(std::string meshName) {
    auto& meshLoader = MeshLoader::getInstance();
    std::shared_ptr<Mesh> mesh = meshLoader.loadMesh(meshName);

    auto node = std::shared_ptr<SceneNode>(new SceneNode());
    mesh->material.diffuse = glm::vec4(0.5f, 0.5f, 0.7f, 1.0f);
    mesh->material.ambient = glm::vec4(0.01f, 0.01f, 0.01f, 1.0f);
    mesh->material.specular = glm::vec4(0.6f, 0.6f, 0.7f, 1.0f);
    mesh->material.shininess = 250.0f;

    node->init(mesh);

    return node;
}

int startGui(int argc, char** argv) {
    Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.modelviewer");

    ModelViewerWindow gui;
    gui.movement = movement;
    gui.lightProperties = &renderer.lights[0]->properties;
    gui.material = &renderer.nodes[0]->mesh->material;
    gui.flipNormals = &shouldFlipNormals;
    gui.fileName = &filename;
    gui.shouldLoadFile = &shouldLoadFile;

    //Shows the window and returns when it is closed.
    return app->run(gui);
}

int main(int argc, char** argv)
{
    GLFWwindow* window = initGLWindow();

    movement = new CameraMovement(window);

    initGL();

    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    renderer.init(width, height);

    camera.init(width/(float)height, 60.f, .1f, 100.f);
    camera.setCameraProjection(PROJECTION_PERSPECTIVE);

    // Floor
    std::shared_ptr<Mesh> floorMesh = std::make_shared<Mesh>(UnitQuad::CreateUnitQuad());
    floorMesh->material.diffuse = glm::vec4(0.3f, 0.6f, 0.7f, 1.0f);
    floorMesh->material.ambient = glm::vec4(0.01f, 0.01f, 0.01f, 1.0f);
    floorMesh->material.specular = glm::vec4(0.1f, 0.1f, 0.1f, 1.0f);
    floorMesh->material.shininess = 100.0f;

    std::shared_ptr<SceneNode> floor(new SceneNode);
    floor->init(floorMesh);
    floor->position = glm::vec3(0.0,-1.0, 0.0);
    floor->rotation = glm::rotate(glm::mat4(1.0f),-90.0f, glm::vec3(1.0, 0.0, 0.0));
    floor->scale = glm::scale(glm::mat4(1.0), glm::vec3(100.0f));

    LightProperties lightProperties = LightFactory::Bright(glm::vec3(0.8, 0.9, 1.0));
    lightProperties.position = glm::vec4(-2.0f, 2.0f, -1.0f, 1.0);
    lightProperties.direction = glm::vec4(0.0, -0.1, -1.0, 0.0);
    std::shared_ptr<Light> light(new Light);
    light->properties = lightProperties;
    renderer.lights.push_back(light);

    LightProperties lightProperties1 = LightFactory::Bright(glm::vec3(0.8, 0.9, 1.0));
    lightProperties1.position = glm::vec4(4.0f, 2.0f, -3.0f, 1.0);
    lightProperties1.direction = glm::vec4(-1.0, -0.1, 0.0, 0.0);
    std::shared_ptr<Light> light1(new Light);
    light1->properties = lightProperties1;
    renderer.lights.push_back(light1);

    for(int i = 0; i < 2; i++) {
        std::string path(MODEL_PATH);
        path.append("space_station.off");
        auto node = createSceneNode(path);
        node->position = glm::vec3(-2.0f, -0.5f, -3.0f * (i + 1));

        renderer.nodes.push_back(node);
    }

    renderer.nodes.push_back(floor);

    std::thread first (startGui, argc, argv);

    glfwSwapInterval(1); //0 to disable vsync, 1 to enable it

    while (!glfwWindowShouldClose(window))
    {
        if(shouldFlipNormals) {
            renderer.nodes[0]->mesh->flipNormals();
            shouldFlipNormals = false;
        }

        if(shouldLoadFile) {
            auto& meshLoader = MeshLoader::getInstance();
            std::string path(MODEL_PATH);
            path.append(filename);
            renderer.nodes[0] = createSceneNode(path);
            renderer.nodes[0]->position = glm::vec3(-2.0f, -0.5f, -3.0f);
            shouldLoadFile = false;
        }

        updateInput(window);

        glClearColor(0.0, 0.0, 0.0, 1.0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
        glClearColor(0.0, 0.0, 0.0, 0.0);

        //light->properties.position = glm::translate(glm::mat4(1.0f), glm::vec3(-2.5f +  cosf(glfwGetTime()), 0.5f, -0.0f)) * glm::vec4(1.0f);

        camera.position = movement->position;
        camera.target = camera.position + movement->lookatDirection;
        camera.update();

        renderer.proj = camera.getCameraProjectionTransform();
        renderer.view = camera.getCameraViewTransform();
        renderer.renderScene();

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    delete movement;

    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
<commit_msg>set 1st light to move and made second changeable. Changed default from space_station to cooldragon<commit_after>//
//  main.cpp
//  ModelViewer
//
//  Created by Mattias Bergström on 2014-01-21.
//  Copyright (c) 2014 Mattias Bergström. All rights reserved.
//

#include <iostream>
#include <thread>
#include "glm/glm.hpp"
#include <cmath>
#include "Mesh.h"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "SceneRenderer.h"
#include "Constants.h"
#include "MeshLoader.h"
#include "LightProperties.h"
#include "CameraMovement.h"
#include "ModelViewerWindow.h"
#include <glew.h>
#include <GLFW/glfw3.h>
#include <gtkmm/application.h>

#ifdef __APPLE__
#include <OpenGL/glu.h>
#else
#include <GL/glu.h>
#endif

CameraMovement* movement;
Camera camera;
SceneRenderer renderer;
bool shouldFlipNormals;
bool shouldLoadFile;
std::string filename;

static void error_callback(int error, const char* description)
{
    fputs(description, stderr);
}

static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);

    if(key == GLFW_KEY_1 && action == GLFW_PRESS) {
        camera.setCameraProjection(PROJECTION_PERSPECTIVE);
    }
    if(key == GLFW_KEY_2 && action == GLFW_PRESS) {
        camera.setCameraProjection(PROJECTION_ORTHOGONAL);
    }
    if(key == GLFW_KEY_3 && action == GLFW_PRESS) {
        camera.setCameraProjection(PROJECTION_OBLIQUE);
    }
}

static void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    renderer.updateResolution(width, height);
}

void updateInput(GLFWwindow* window) {

    movement->update();
}

void initGL() {
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
}

GLFWwindow* initGLWindow() {
    GLFWwindow* window;

    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    window = glfwCreateWindow(854, 480, "Simple example", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    glfwSetKeyCallback(window, key_callback);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // Initialize GLEW
    glewExperimental=true; // Needed in core profile
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        exit(EXIT_FAILURE);
    }

    return window;
}

std::shared_ptr<SceneNode> createSceneNode(std::string meshName) {
    auto& meshLoader = MeshLoader::getInstance();
    std::shared_ptr<Mesh> mesh = meshLoader.loadMesh(meshName);

    auto node = std::shared_ptr<SceneNode>(new SceneNode());
    mesh->material.diffuse = glm::vec4(0.5f, 0.5f, 0.7f, 1.0f);
    mesh->material.ambient = glm::vec4(0.01f, 0.01f, 0.01f, 1.0f);
    mesh->material.specular = glm::vec4(0.6f, 0.6f, 0.7f, 1.0f);
    mesh->material.shininess = 250.0f;

    node->init(mesh);

    return node;
}

int startGui(int argc, char** argv) {
    Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.modelviewer");

    ModelViewerWindow gui;
    gui.movement = movement;
    gui.lightProperties = &renderer.lights[1]->properties;
    gui.material = &renderer.nodes[0]->mesh->material;
    gui.flipNormals = &shouldFlipNormals;
    gui.fileName = &filename;
    gui.shouldLoadFile = &shouldLoadFile;

    //Shows the window and returns when it is closed.
    return app->run(gui);
}

int main(int argc, char** argv)
{
    GLFWwindow* window = initGLWindow();

    movement = new CameraMovement(window);

    initGL();

    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    renderer.init(width, height);

    camera.init(width/(float)height, 60.f, .1f, 100.f);
    camera.setCameraProjection(PROJECTION_PERSPECTIVE);

    // Floor
    std::shared_ptr<Mesh> floorMesh = std::make_shared<Mesh>(UnitQuad::CreateUnitQuad());
    floorMesh->material.diffuse = glm::vec4(0.3f, 0.6f, 0.7f, 1.0f);
    floorMesh->material.ambient = glm::vec4(0.01f, 0.01f, 0.01f, 1.0f);
    floorMesh->material.specular = glm::vec4(0.1f, 0.1f, 0.1f, 1.0f);
    floorMesh->material.shininess = 100.0f;

    std::shared_ptr<SceneNode> floor(new SceneNode);
    floor->init(floorMesh);
    floor->position = glm::vec3(0.0,-1.0, 0.0);
    floor->rotation = glm::rotate(glm::mat4(1.0f),-90.0f, glm::vec3(1.0, 0.0, 0.0));
    floor->scale = glm::scale(glm::mat4(1.0), glm::vec3(100.0f));

    LightProperties lightProperties = LightFactory::Bright(glm::vec3(0.8, 0.9, 1.0));
    lightProperties.position = glm::vec4(-2.0f, 2.0f, -1.0f, 1.0);
    lightProperties.direction = glm::vec4(0.0, -0.1, -1.0, 0.0);
    std::shared_ptr<Light> light(new Light);
    light->properties = lightProperties;
    renderer.lights.push_back(light);

    LightProperties lightProperties1 = LightFactory::Bright(glm::vec3(0.8, 0.9, 1.0));
    lightProperties1.position = glm::vec4(4.0f, 2.0f, -3.0f, 1.0);
    lightProperties1.direction = glm::vec4(-1.0, -0.1, 0.0, 0.0);
    std::shared_ptr<Light> light1(new Light);
    light1->properties = lightProperties1;
    renderer.lights.push_back(light1);

    for(int i = 0; i < 1; i++) {
        std::string path(MODEL_PATH);
        path.append("cooldragon.off");
        auto node = createSceneNode(path);
        node->position = glm::vec3(-2.0f, -0.5f, -3.0f * (i + 1));

        renderer.nodes.push_back(node);
    }

    renderer.nodes.push_back(floor);

    std::thread first (startGui, argc, argv);

    glfwSwapInterval(1); //0 to disable vsync, 1 to enable it

    while (!glfwWindowShouldClose(window))
    {
        if(shouldFlipNormals) {
            renderer.nodes[0]->mesh->flipNormals();
            shouldFlipNormals = false;
        }

        if(shouldLoadFile) {
            auto& meshLoader = MeshLoader::getInstance();
            std::string path(MODEL_PATH);
            path.append(filename);
            renderer.nodes[0] = createSceneNode(path);
            renderer.nodes[0]->position = glm::vec3(-2.0f, -0.5f, -3.0f);
            shouldLoadFile = false;
        }

        updateInput(window);

        glClearColor(0.0, 0.0, 0.0, 1.0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
        glClearColor(0.0, 0.0, 0.0, 0.0);

        light->properties.position = glm::translate(glm::mat4(1.0f), glm::vec3(-2.5f +  cosf(glfwGetTime()), 0.5f, -0.0f)) * glm::vec4(1.0f);

        camera.position = movement->position;
        camera.target = camera.position + movement->lookatDirection;
        camera.update();

        renderer.proj = camera.getCameraProjectionTransform();
        renderer.view = camera.getCameraViewTransform();
        renderer.renderScene();

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    delete movement;

    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>/*
 * gVirtuS -- A GPGPU transparent virtualization component.
 *
 * Copyright (C) 2009-2010  The University of Napoli Parthenope at Naples.
 *
 * This file is part of gVirtuS.
 *
 * gVirtuS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * gVirtuS 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 General Public License
 * along with gVirtuS; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Written by: Flora Giannone <flora.giannone@studenti.uniparthenope.it>,
 *             Department of Applied Science
 */

#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <cstring>
#include "CudaDrFrontend.h"
#include "CudaUtil.h"
#include "CudaDr.h"
#include <cuda.h>

#include "Encoder.h"

using namespace std;

/*Load a module's data. */
extern CUresult cuModuleLoadData(CUmodule *module, const void *image) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddStringForArguments((char *) image);
    CudaDrFrontend::Execute("cuModuleLoadData");
    if (CudaDrFrontend::Success())
        *module = (CUmodule) (CudaDrFrontend::GetOutputDevicePointer());
    return (CUresult) (CudaDrFrontend::GetExitCode());

}

/*Returns a function handle*/
extern CUresult cuModuleGetFunction(CUfunction *hfunc, CUmodule hmod, const char *name) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddStringForArguments((char*) name);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hmod);
    CudaDrFrontend::Execute("cuModuleGetFunction");
    void* tmp;
    if (CudaDrFrontend::Success()) {
        tmp = (CUfunction) (CudaDrFrontend::GetOutputDevicePointer());
        *hfunc = (CUfunction) tmp;
    }
    return (CUresult) (CudaDrFrontend::GetExitCode());
}

/*Returns a global pointer from a module.*/
extern CUresult cuModuleGetGlobal(CUdeviceptr *dptr, size_t *bytes, CUmodule hmod, const char *name) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddStringForArguments((char*) name);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hmod);
    CudaDrFrontend::Execute("cuModuleGetGlobal");
    if (CudaDrFrontend::Success()) {
        *dptr = (CUdeviceptr) (CudaDrFrontend::GetOutputDevicePointer());
        *bytes = (size_t) (CudaDrFrontend::GetOutputDevicePointer());
    }
    return (CUresult) (CudaDrFrontend::GetExitCode());
}

/*Returns a handle to a texture-reference.*/
extern CUresult cuModuleGetTexRef(CUtexref *pTexRef, CUmodule hmod, const char *name) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddStringForArguments((char*) name);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hmod);
    CudaDrFrontend::Execute("cuModuleGetTexRef");
    if (CudaDrFrontend::Success()) {
        *pTexRef = (CUtexref) (CudaDrFrontend::GetOutputDevicePointer());
    }
    return (CUresult) (CudaDrFrontend::GetExitCode());
}

/*Load a module's data with options.*/
extern CUresult cuModuleLoadDataEx(CUmodule *module, const void *image, unsigned int numOptions, CUjit_option *options, void **optionValues) {
    CudaDrFrontend::Prepare();
    char *tmp;
    char *tmp2;
    CudaDrFrontend::AddVariableForArguments(numOptions);
    CudaDrFrontend::AddHostPointerForArguments(options, numOptions);
    CudaDrFrontend::AddStringForArguments((char *) image);
    for (unsigned int i = 0; i < numOptions; i++) {
        CudaDrFrontend::AddHostPointerForArguments(&optionValues[i]);
    }
    CudaDrFrontend::Execute("cuModuleLoadDataEx");
    if (CudaDrFrontend::Success()) {
        *module = (CUmodule) (CudaDrFrontend::GetOutputDevicePointer());
        int len_str;
        for (unsigned int i = 0; i < numOptions-1; i++) {
            switch (options[i]) {
                case CU_JIT_INFO_LOG_BUFFER:
                    len_str = CudaDrFrontend::GetOutputVariable<int>();
                    if (len_str >0){
                        tmp = CudaDrFrontend::GetOutputHostPointer<char>(len_str);
                    strcpy((char *) *(optionValues + i), tmp);
                    }

                    break;
                case CU_JIT_ERROR_LOG_BUFFER:
                    tmp2 = (CudaDrFrontend::GetOutputString());
                    strcpy((char *) *(optionValues + i), tmp2);
                    break;

                default:
                    *(optionValues + i) = (void *) (*(CudaDrFrontend::GetOutputHostPointer<unsigned int>()));

            }

        }
    }
    return (CUresult) (CudaDrFrontend::GetExitCode());
}

extern CUresult cuModuleLoad(CUmodule *module, const char *fname) {
    Encoder *encoder=new Encoder();
    std::ostringstream res;
    std::ifstream input("helloWorldDriverAPI.ptx", std::ios::binary);
    encoder->Encode(input,res);
    //input >> std::noskipws;

    std::string moduleLoad = res.str();
    cout << "Encoded module:\n";
    cout << moduleLoad;
    cout << "--------------\n";

    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddStringForArguments((char *) fname);
    CudaDrFrontend::AddStringForArguments(moduleLoad.c_str());
    CudaDrFrontend::Execute("cuModuleLoad");
    if (CudaDrFrontend::Success())
        *module = (CUmodule) (CudaDrFrontend::GetOutputDevicePointer());
    return (CUresult) (CudaDrFrontend::GetExitCode());

    // FIXME: implement
    //cerr << "*** Error: cuModuleLoad not yet implemented!" << endl;
    //return (CUresult) 1;
}

extern CUresult cuModuleLoadFatBinary(CUmodule *module, const void *fatCubin) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddStringForArguments((char *) fatCubin);
    CudaDrFrontend::Execute("cuModuleLoadFatBinary");
    if (CudaDrFrontend::Success())
        *module = (CUmodule) (CudaDrFrontend::GetOutputDevicePointer());
    return (CUresult) (CudaDrFrontend::GetExitCode());
    // FIXME: implement
    //cerr << "*** Error: cuModuleLoadFatBinary not yet implemented!" << endl;
    //return (CUresult) 1;
}

extern CUresult cuModuleUnload(CUmodule hmod) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddDevicePointerForArguments((char *)hmod);
    CudaDrFrontend::Execute("cuModuleUnload");
    return (CUresult) (CudaDrFrontend::GetExitCode());
    // FIXME: implement
    //cerr << "*** Error: cuModuleUnload not yet implemented!" << endl;
    //return (CUresult) 1;
}
<commit_msg>Changed Permissions<commit_after>/*
 * gVirtuS -- A GPGPU transparent virtualization component.
 *
 * Copyright (C) 2009-2010  The University of Napoli Parthenope at Naples.
 *
 * This file is part of gVirtuS.
 *
 * gVirtuS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * gVirtuS 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 General Public License
 * along with gVirtuS; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Written by: Flora Giannone <flora.giannone@studenti.uniparthenope.it>,
 *             Department of Applied Science
 */

#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <cstring>
#include "CudaDrFrontend.h"
#include "CudaUtil.h"
#include "CudaDr.h"
#include <cuda.h>

#include "Encoder.h"

using namespace std;

/*Load a module's data. */
extern CUresult cuModuleLoadData(CUmodule *module, const void *image) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddStringForArguments((char *) image);
    CudaDrFrontend::Execute("cuModuleLoadData");
    if (CudaDrFrontend::Success())
        *module = (CUmodule) (CudaDrFrontend::GetOutputDevicePointer());
    return (CUresult) (CudaDrFrontend::GetExitCode());

}

/*Returns a function handle*/
extern CUresult cuModuleGetFunction(CUfunction *hfunc, CUmodule hmod, const char *name) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddStringForArguments((char*) name);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hmod);
    CudaDrFrontend::Execute("cuModuleGetFunction");
    void* tmp;
    if (CudaDrFrontend::Success()) {
        tmp = (CUfunction) (CudaDrFrontend::GetOutputDevicePointer());
        *hfunc = (CUfunction) tmp;
    }
    return (CUresult) (CudaDrFrontend::GetExitCode());
}

/*Returns a global pointer from a module.*/
extern CUresult cuModuleGetGlobal(CUdeviceptr *dptr, size_t *bytes, CUmodule hmod, const char *name) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddStringForArguments((char*) name);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hmod);
    CudaDrFrontend::Execute("cuModuleGetGlobal");
    if (CudaDrFrontend::Success()) {
        *dptr = (CUdeviceptr) (CudaDrFrontend::GetOutputDevicePointer());
        *bytes = (size_t) (CudaDrFrontend::GetOutputDevicePointer());
    }
    return (CUresult) (CudaDrFrontend::GetExitCode());
}

/*Returns a handle to a texture-reference.*/
extern CUresult cuModuleGetTexRef(CUtexref *pTexRef, CUmodule hmod, const char *name) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddStringForArguments((char*) name);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hmod);
    CudaDrFrontend::Execute("cuModuleGetTexRef");
    if (CudaDrFrontend::Success()) {
        *pTexRef = (CUtexref) (CudaDrFrontend::GetOutputDevicePointer());
    }
    return (CUresult) (CudaDrFrontend::GetExitCode());
}

/*Load a module's data with options.*/
extern CUresult cuModuleLoadDataEx(CUmodule *module, const void *image, unsigned int numOptions, CUjit_option *options, void **optionValues) {
    CudaDrFrontend::Prepare();
    char *tmp;
    char *tmp2;
    CudaDrFrontend::AddVariableForArguments(numOptions);
    CudaDrFrontend::AddHostPointerForArguments(options, numOptions);
    CudaDrFrontend::AddStringForArguments((char *) image);
    for (unsigned int i = 0; i < numOptions; i++) {
        CudaDrFrontend::AddHostPointerForArguments(&optionValues[i]);
    }
    CudaDrFrontend::Execute("cuModuleLoadDataEx");
    if (CudaDrFrontend::Success()) {
        *module = (CUmodule) (CudaDrFrontend::GetOutputDevicePointer());
        int len_str;
        for (unsigned int i = 0; i < numOptions-1; i++) {
            switch (options[i]) {
                case CU_JIT_INFO_LOG_BUFFER:
                    len_str = CudaDrFrontend::GetOutputVariable<int>();
                    if (len_str >0){
                        tmp = CudaDrFrontend::GetOutputHostPointer<char>(len_str);
                    strcpy((char *) *(optionValues + i), tmp);
                    }

                    break;
                case CU_JIT_ERROR_LOG_BUFFER:
                    tmp2 = (CudaDrFrontend::GetOutputString());
                    strcpy((char *) *(optionValues + i), tmp2);
                    break;

                default:
                    *(optionValues + i) = (void *) (*(CudaDrFrontend::GetOutputHostPointer<unsigned int>()));

            }

        }
    }
    return (CUresult) (CudaDrFrontend::GetExitCode());
}

extern CUresult cuModuleLoad(CUmodule *module, const char *fname) {
    Encoder *encoder=new Encoder();
    std::ostringstream res;
    std::ifstream input("helloWorldDriverAPI.ptx", std::ios::binary);
    encoder->Encode(input,res);
    //input >> std::noskipws;

    std::string moduleLoad = res.str();
    cout << "Encoded module:\n";
    cout << moduleLoad;
    cout << "--------------\n";

    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddStringForArguments((char *) fname);
    CudaDrFrontend::AddStringForArguments(moduleLoad.c_str());
    CudaDrFrontend::Execute("cuModuleLoad");
    if (CudaDrFrontend::Success())
        *module = (CUmodule) (CudaDrFrontend::GetOutputDevicePointer());
    return (CUresult) (CudaDrFrontend::GetExitCode());

    // FIXME: implement
    //cerr << "*** Error: cuModuleLoad not yet implemented!" << endl;
    //return (CUresult) 1;
}

extern CUresult cuModuleLoadFatBinary(CUmodule *module, const void *fatCubin) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddStringForArguments((char *) fatCubin);
    CudaDrFrontend::Execute("cuModuleLoadFatBinary");
    if (CudaDrFrontend::Success())
        *module = (CUmodule) (CudaDrFrontend::GetOutputDevicePointer());
    return (CUresult) (CudaDrFrontend::GetExitCode());
    // FIXME: implement
    //cerr << "*** Error: cuModuleLoadFatBinary not yet implemented!" << endl;
    //return (CUresult) 1;
}

extern CUresult cuModuleUnload(CUmodule hmod) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddDevicePointerForArguments((char *)hmod);
    CudaDrFrontend::Execute("cuModuleUnload");
    return (CUresult) (CudaDrFrontend::GetExitCode());
    // FIXME: implement
    //cerr << "*** Error: cuModuleUnload not yet implemented!" << endl;
    //return (CUresult) 1;
}
<|endoftext|>


<commit_before><commit_msg>fix debug<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <gtest/gtest.h>
#include "TestComponent.h"

using namespace facebook::react;

class LayoutableShadowNodeTest : public ::testing::Test {
 protected:
  LayoutableShadowNodeTest()
      : eventDispatcher_(std::shared_ptr<EventDispatcher const>()),
        componentDescriptor_(TestComponentDescriptor({eventDispatcher_})) {
    auto traits = TestShadowNode::BaseTraits();

    auto familyA = std::make_shared<ShadowNodeFamily>(
        ShadowNodeFamilyFragment{
            /* .tag = */ 9,
            /* .surfaceId = */ 1,
            /* .eventEmitter = */ nullptr,
        },
        eventDispatcher_,
        componentDescriptor_);

    nodeA_ = std::make_shared<TestShadowNode>(
        ShadowNodeFragment{
            /* .props = */ std::make_shared<const TestProps>(),
            /* .children = */ ShadowNode::emptySharedShadowNodeSharedList(),
        },
        familyA,
        traits);

    auto familyAA = std::make_shared<ShadowNodeFamily>(
        ShadowNodeFamilyFragment{
            /* .tag = */ 10,
            /* .surfaceId = */ 1,
            /* .eventEmitter = */ nullptr,
        },
        eventDispatcher_,
        componentDescriptor_);

    auto rootTraits = traits;
    rootTraits.set(ShadowNodeTraits::Trait::RootNodeKind);

    nodeAA_ = std::make_shared<TestShadowNode>(
        ShadowNodeFragment{
            /* .props = */ std::make_shared<const TestProps>(),
            /* .children = */ ShadowNode::emptySharedShadowNodeSharedList(),
        },
        familyAA,
        rootTraits);

    auto familyAAA = std::make_shared<ShadowNodeFamily>(
        ShadowNodeFamilyFragment{
            /* .tag = */ 11,
            /* .surfaceId = */ 1,
            /* .eventEmitter = */ nullptr,
        },
        eventDispatcher_,
        componentDescriptor_);

    nodeAAA_ = std::make_shared<TestShadowNode>(
        ShadowNodeFragment{
            /* .props = */ std::make_shared<const TestProps>(),
            /* .children = */ ShadowNode::emptySharedShadowNodeSharedList(),
        },
        familyAAA,
        traits);

    auto familyAAAA = std::make_shared<ShadowNodeFamily>(
        ShadowNodeFamilyFragment{
            /* .tag = */ 11,
            /* .surfaceId = */ 1,
            /* .eventEmitter = */ nullptr,
        },
        eventDispatcher_,
        componentDescriptor_);

    nodeAAAA_ = std::make_shared<TestShadowNode>(
        ShadowNodeFragment{
            /* .props = */ std::make_shared<const TestProps>(),
            /* .children = */ ShadowNode::emptySharedShadowNodeSharedList(),
        },
        familyAAAA,
        traits);

    nodeA_->appendChild(nodeAA_);
    nodeAA_->appendChild(nodeAAA_);
    nodeAAA_->appendChild(nodeAAAA_);
  }

  std::shared_ptr<EventDispatcher const> eventDispatcher_;
  std::shared_ptr<TestShadowNode> nodeA_;
  std::shared_ptr<TestShadowNode> nodeAA_;
  std::shared_ptr<TestShadowNode> nodeAAA_;
  std::shared_ptr<TestShadowNode> nodeAAAA_;
  TestComponentDescriptor componentDescriptor_;
};

TEST_F(LayoutableShadowNodeTest, relativeLayoutMetrics) {
  auto layoutMetrics = EmptyLayoutMetrics;
  layoutMetrics.frame.origin = {10, 20};
  layoutMetrics.frame.size = {100, 200};
  nodeA_->setLayoutMetrics(layoutMetrics);
  nodeAA_->setLayoutMetrics(layoutMetrics);

  auto relativeLayoutMetrics = nodeAA_->getRelativeLayoutMetrics(*nodeA_, {});

  // A is a parent to B, A has origin {10, 10}, B has origin {10, 10}.
  // B's relative origin to A should be {10, 10}.
  // D19447900 has more about the issue.
  EXPECT_EQ(relativeLayoutMetrics.frame.size.width, 100);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.height, 200);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.x, 10);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.y, 20);
}

TEST_F(LayoutableShadowNodeTest, relativeLayoutMetricsOnTransformedNode) {
  auto layoutMetrics = EmptyLayoutMetrics;
  layoutMetrics.frame.size = {1000, 1000};
  nodeA_->setLayoutMetrics(layoutMetrics);

  layoutMetrics.frame.origin = {10, 20};
  layoutMetrics.frame.size = {100, 200};
  nodeAA_->_transform = Transform::Scale(0.5, 0.5, 1);
  nodeAA_->setLayoutMetrics(layoutMetrics);

  auto relativeLayoutMetrics = nodeAA_->getRelativeLayoutMetrics(*nodeA_, {});

  EXPECT_EQ(relativeLayoutMetrics.frame.origin.x, 35);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.y, 70);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.width, 50);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.height, 100);

  nodeAA_->_transform = Transform::Identity();
}

TEST_F(LayoutableShadowNodeTest, relativeLayoutMetricsOnTransformedParent) {
  auto layoutMetrics = EmptyLayoutMetrics;
  layoutMetrics.frame.size = {1000, 1000};
  nodeA_->setLayoutMetrics(layoutMetrics);
  nodeAA_->setLayoutMetrics(layoutMetrics);

  layoutMetrics.frame.origin = {10, 10};
  layoutMetrics.frame.size = {100, 100};
  nodeAAA_->_transform = Transform::Scale(0.5, 0.5, 1);
  nodeAAA_->setLayoutMetrics(layoutMetrics);

  layoutMetrics.frame.origin = {10, 10};
  layoutMetrics.frame.size = {50, 50};
  nodeAAAA_->setLayoutMetrics(layoutMetrics);

  auto relativeLayoutMetrics =
      nodeAAAA_->getRelativeLayoutMetrics(*nodeAA_, {});

  EXPECT_EQ(relativeLayoutMetrics.frame.origin.x, 45);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.y, 45);

  EXPECT_EQ(relativeLayoutMetrics.frame.size.width, 25);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.height, 25);

  nodeAAA_->_transform = Transform::Identity();
}

TEST_F(LayoutableShadowNodeTest, relativeLayoutMetricsOnSameNode) {
  auto layoutMetrics = EmptyLayoutMetrics;
  layoutMetrics.frame.origin = {10, 20};
  layoutMetrics.frame.size = {100, 200};
  nodeA_->setLayoutMetrics(layoutMetrics);

  auto relativeLayoutMetrics = nodeA_->getRelativeLayoutMetrics(*nodeA_, {});

  EXPECT_EQ(relativeLayoutMetrics.frame.origin.x, 0);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.y, 0);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.width, 100);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.height, 200);
}

TEST_F(LayoutableShadowNodeTest, relativeLayoutMetricsOnSameTransformedNode) {
  auto layoutMetrics = EmptyLayoutMetrics;
  layoutMetrics.frame.origin = {10, 20};
  layoutMetrics.frame.size = {100, 200};
  nodeA_->setLayoutMetrics(layoutMetrics);
  nodeA_->_transform = Transform::Scale(2, 2, 1);

  auto relativeLayoutMetrics = nodeA_->getRelativeLayoutMetrics(*nodeA_, {});

  EXPECT_EQ(relativeLayoutMetrics.frame.origin.x, 0);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.y, 0);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.width, 200);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.height, 400);

  nodeA_->_transform = Transform::Identity();
}

TEST_F(LayoutableShadowNodeTest, relativeLayourMetricsOnClonedNode) {
  // B is cloned and mutated.
  auto nodeBRevision2 = std::static_pointer_cast<TestShadowNode>(
      componentDescriptor_.cloneShadowNode(*nodeAA_, ShadowNodeFragment{}));
  auto layoutMetrics = EmptyLayoutMetrics;
  layoutMetrics.frame.size = {500, 600};
  nodeBRevision2->setLayoutMetrics(layoutMetrics);
  nodeA_->replaceChild(*nodeAA_, nodeBRevision2);

  // Even if we ask old ShadowNode for its relative layoutMetrics, it needs to
  // return correct, new layoutMetrics. D19433873 has more about the issue.
  auto newRelativeLayoutMetrics =
      nodeAA_->getRelativeLayoutMetrics(*nodeA_, {});
  EXPECT_EQ(newRelativeLayoutMetrics.frame.size.width, 500);
  EXPECT_EQ(newRelativeLayoutMetrics.frame.size.height, 600);
}

TEST_F(
    LayoutableShadowNodeTest,
    relativeLayoutMetricsOnNodesCrossingRootKindNode) {
  auto layoutMetrics = EmptyLayoutMetrics;
  nodeA_->setLayoutMetrics(layoutMetrics);
  layoutMetrics.frame.origin = {10, 10};
  // nodeAA_ is a RootKindNode. Please check
  // ShadowNodeTraits::Traits::RootNodeKind for details.
  nodeAA_->setLayoutMetrics(layoutMetrics);
  nodeAAA_->setLayoutMetrics(layoutMetrics);

  auto relativeLayoutMetrics = nodeAAA_->getRelativeLayoutMetrics(*nodeA_, {});

  // relativeLayoutMetrics do not include offsset of nodeAA_ because it is a
  // RootKindNode.
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.x, 10);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.y, 10);
}
<commit_msg>Add view hierarchy drawings to tests<commit_after>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <gtest/gtest.h>
#include "TestComponent.h"

using namespace facebook::react;

class LayoutableShadowNodeTest : public ::testing::Test {
 protected:
  LayoutableShadowNodeTest()
      : eventDispatcher_(std::shared_ptr<EventDispatcher const>()),
        componentDescriptor_(TestComponentDescriptor({eventDispatcher_})) {
    auto traits = TestShadowNode::BaseTraits();

    auto familyA = std::make_shared<ShadowNodeFamily>(
        ShadowNodeFamilyFragment{
            /* .tag = */ 9,
            /* .surfaceId = */ 1,
            /* .eventEmitter = */ nullptr,
        },
        eventDispatcher_,
        componentDescriptor_);

    nodeA_ = std::make_shared<TestShadowNode>(
        ShadowNodeFragment{
            /* .props = */ std::make_shared<const TestProps>(),
            /* .children = */ ShadowNode::emptySharedShadowNodeSharedList(),
        },
        familyA,
        traits);

    auto familyAA = std::make_shared<ShadowNodeFamily>(
        ShadowNodeFamilyFragment{
            /* .tag = */ 10,
            /* .surfaceId = */ 1,
            /* .eventEmitter = */ nullptr,
        },
        eventDispatcher_,
        componentDescriptor_);

    auto rootTraits = traits;
    rootTraits.set(ShadowNodeTraits::Trait::RootNodeKind);

    nodeAA_ = std::make_shared<TestShadowNode>(
        ShadowNodeFragment{
            /* .props = */ std::make_shared<const TestProps>(),
            /* .children = */ ShadowNode::emptySharedShadowNodeSharedList(),
        },
        familyAA,
        rootTraits);

    auto familyAAA = std::make_shared<ShadowNodeFamily>(
        ShadowNodeFamilyFragment{
            /* .tag = */ 11,
            /* .surfaceId = */ 1,
            /* .eventEmitter = */ nullptr,
        },
        eventDispatcher_,
        componentDescriptor_);

    nodeAAA_ = std::make_shared<TestShadowNode>(
        ShadowNodeFragment{
            /* .props = */ std::make_shared<const TestProps>(),
            /* .children = */ ShadowNode::emptySharedShadowNodeSharedList(),
        },
        familyAAA,
        traits);

    auto familyAAAA = std::make_shared<ShadowNodeFamily>(
        ShadowNodeFamilyFragment{
            /* .tag = */ 11,
            /* .surfaceId = */ 1,
            /* .eventEmitter = */ nullptr,
        },
        eventDispatcher_,
        componentDescriptor_);

    nodeAAAA_ = std::make_shared<TestShadowNode>(
        ShadowNodeFragment{
            /* .props = */ std::make_shared<const TestProps>(),
            /* .children = */ ShadowNode::emptySharedShadowNodeSharedList(),
        },
        familyAAAA,
        traits);

    nodeA_->appendChild(nodeAA_);
    nodeAA_->appendChild(nodeAAA_);
    nodeAAA_->appendChild(nodeAAAA_);
  }

  std::shared_ptr<EventDispatcher const> eventDispatcher_;
  std::shared_ptr<TestShadowNode> nodeA_;
  std::shared_ptr<TestShadowNode> nodeAA_;
  std::shared_ptr<TestShadowNode> nodeAAA_;
  std::shared_ptr<TestShadowNode> nodeAAAA_;
  TestComponentDescriptor componentDescriptor_;
};

/*
 * ┌────────┐
 * │nodeA_  │
 * │        │
 * │   ┌────┴───┐
 * │   │nodeAA_ │
 * └───┤        │
 *     │        │
 *     │        │
 *     └────────┘
 */
TEST_F(LayoutableShadowNodeTest, relativeLayoutMetrics) {
  auto layoutMetrics = EmptyLayoutMetrics;
  layoutMetrics.frame.origin = {10, 20};
  layoutMetrics.frame.size = {100, 200};
  nodeA_->setLayoutMetrics(layoutMetrics);
  nodeAA_->setLayoutMetrics(layoutMetrics);

  auto relativeLayoutMetrics = nodeAA_->getRelativeLayoutMetrics(*nodeA_, {});

  // A is a parent to B, A has origin {10, 10}, B has origin {10, 10}.
  // B's relative origin to A should be {10, 10}.
  // D19447900 has more about the issue.
  EXPECT_EQ(relativeLayoutMetrics.frame.size.width, 100);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.height, 200);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.x, 10);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.y, 20);
}

/*
 * ┌────────────────────────┐
 * │nodeA_                  │
 * │      ┌────────────────┐│
 * │      │nodeAA_         ││
 * │      │                ││
 * │      └────────────────┘│
 * └────────────────────────┘
 */
TEST_F(LayoutableShadowNodeTest, relativeLayoutMetricsOnTransformedNode) {
  auto layoutMetrics = EmptyLayoutMetrics;
  layoutMetrics.frame.size = {1000, 1000};
  nodeA_->setLayoutMetrics(layoutMetrics);

  layoutMetrics.frame.origin = {10, 20};
  layoutMetrics.frame.size = {100, 200};
  nodeAA_->_transform = Transform::Scale(0.5, 0.5, 1);
  nodeAA_->setLayoutMetrics(layoutMetrics);

  auto relativeLayoutMetrics = nodeAA_->getRelativeLayoutMetrics(*nodeA_, {});

  EXPECT_EQ(relativeLayoutMetrics.frame.origin.x, 35);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.y, 70);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.width, 50);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.height, 100);
}

/*
 * ┌────────────────────────┐
 * │nodeA_                  │
 * │ ┌─────────────────────┐│
 * │ │ nodeAA_             ││
 * │ │     ┌──────────────┐││
 * │ │     │nodeAAA_      │││
 * │ │     │  ┌──────────┐│││
 * │ │     │  │nodeAAAA_ ││││
 * │ │     │  │          ││││
 * │ │     │  │          ││││
 * │ │     │  └──────────┘│││
 * │ │     └──────────────┘││
 * │ └─────────────────────┘│
 * └────────────────────────┘
 */
TEST_F(LayoutableShadowNodeTest, relativeLayoutMetricsOnTransformedParent) {
  auto layoutMetrics = EmptyLayoutMetrics;
  layoutMetrics.frame.size = {1000, 1000};
  nodeA_->setLayoutMetrics(layoutMetrics);
  layoutMetrics.frame.size = {900, 900};
  nodeAA_->setLayoutMetrics(layoutMetrics);

  layoutMetrics.frame.origin = {10, 10};
  layoutMetrics.frame.size = {100, 100};
  nodeAAA_->_transform = Transform::Scale(0.5, 0.5, 1);
  nodeAAA_->setLayoutMetrics(layoutMetrics);

  layoutMetrics.frame.origin = {10, 10};
  layoutMetrics.frame.size = {50, 50};
  nodeAAAA_->setLayoutMetrics(layoutMetrics);

  auto relativeLayoutMetrics =
      nodeAAAA_->getRelativeLayoutMetrics(*nodeAA_, {});

  EXPECT_EQ(relativeLayoutMetrics.frame.origin.x, 45);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.y, 45);

  EXPECT_EQ(relativeLayoutMetrics.frame.size.width, 25);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.height, 25);
}

TEST_F(LayoutableShadowNodeTest, relativeLayoutMetricsOnSameNode) {
  auto layoutMetrics = EmptyLayoutMetrics;
  layoutMetrics.frame.origin = {10, 20};
  layoutMetrics.frame.size = {100, 200};
  nodeA_->setLayoutMetrics(layoutMetrics);

  auto relativeLayoutMetrics = nodeA_->getRelativeLayoutMetrics(*nodeA_, {});

  EXPECT_EQ(relativeLayoutMetrics.frame.origin.x, 0);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.y, 0);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.width, 100);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.height, 200);
}

/*
 * ┌────────────────┐
 * │nodeA_          │
 * │                │
 * └────────────────┘
 */
TEST_F(LayoutableShadowNodeTest, relativeLayoutMetricsOnSameTransformedNode) {
  auto layoutMetrics = EmptyLayoutMetrics;
  layoutMetrics.frame.origin = {10, 20};
  layoutMetrics.frame.size = {100, 200};
  nodeA_->setLayoutMetrics(layoutMetrics);
  nodeA_->_transform = Transform::Scale(2, 2, 1);

  auto relativeLayoutMetrics = nodeA_->getRelativeLayoutMetrics(*nodeA_, {});

  EXPECT_EQ(relativeLayoutMetrics.frame.origin.x, 0);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.y, 0);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.width, 200);
  EXPECT_EQ(relativeLayoutMetrics.frame.size.height, 400);
}

/*
 * ┌────────────────┐
 * │nodeA_          │
 * │                │
 * └────────────────┘
 */
TEST_F(LayoutableShadowNodeTest, relativeLayourMetricsOnClonedNode) {
  // B is cloned and mutated.
  auto nodeBRevision2 = std::static_pointer_cast<TestShadowNode>(
      componentDescriptor_.cloneShadowNode(*nodeAA_, ShadowNodeFragment{}));
  auto layoutMetrics = EmptyLayoutMetrics;
  layoutMetrics.frame.size = {500, 600};
  nodeBRevision2->setLayoutMetrics(layoutMetrics);
  nodeA_->replaceChild(*nodeAA_, nodeBRevision2);

  // Even if we ask old ShadowNode for its relative layoutMetrics, it needs to
  // return correct, new layoutMetrics. D19433873 has more about the issue.
  auto newRelativeLayoutMetrics =
      nodeAA_->getRelativeLayoutMetrics(*nodeA_, {});
  EXPECT_EQ(newRelativeLayoutMetrics.frame.size.width, 500);
  EXPECT_EQ(newRelativeLayoutMetrics.frame.size.height, 600);
}

/*
 * ┌─────────────────────────┐
 * │nodeA_                   │
 * │ ┌──────────────────────┐│
 * │ │nodeAA_: rootKindNode ││
 * │ │     ┌───────────┐    ││
 * │ │     │nodeAAA_   │    ││
 * │ │     │           │    ││
 * │ │     └───────────┘    ││
 * │ └──────────────────────┘│
 * └─────────────────────────┘
 */
TEST_F(
    LayoutableShadowNodeTest,
    relativeLayoutMetricsOnNodesCrossingRootKindNode) {
  auto layoutMetrics = EmptyLayoutMetrics;
  nodeA_->setLayoutMetrics(layoutMetrics);
  layoutMetrics.frame.origin = {10, 10};
  // nodeAA_ is a RootKindNode. Please check
  // ShadowNodeTraits::Traits::RootNodeKind for details.
  nodeAA_->setLayoutMetrics(layoutMetrics);
  nodeAAA_->setLayoutMetrics(layoutMetrics);

  auto relativeLayoutMetrics = nodeAAA_->getRelativeLayoutMetrics(*nodeA_, {});

  // relativeLayoutMetrics do not include offsset of nodeAA_ because it is a
  // RootKindNode.
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.x, 10);
  EXPECT_EQ(relativeLayoutMetrics.frame.origin.y, 10);
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <mmpreparemergepage.hxx>
#include <mailmergewizard.hxx>
#include <mmconfigitem.hxx>
#include <dbui.hrc>
#include <swtypes.hxx>
#include <view.hxx>
#include <dbmgr.hxx>
#include <wrtsh.hxx>
#include <svx/dataaccessdescriptor.hxx>
#include <com/sun/star/sdbc/XConnection.hpp>
#include <swabstdlg.hxx>

#include <unomid.h>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;

SwMailMergePrepareMergePage::SwMailMergePrepareMergePage( SwMailMergeWizard* _pParent)
    : svt::OWizardPage(_pParent, "MMPreparePage", "modules/swriter/ui/mmpreparepage.ui")
    , m_pWizard(_pParent)
{
    get(m_pFirstPB, "first");
    get(m_pPrevPB, "prev");
    get(m_pRecordED, "record-nospin");
    get(m_pNextPB, "next");
    get(m_pLastPB, "last");
    get(m_pExcludeCB, "exclude");
    get(m_pEditPB, "edit");

    m_pEditPB->SetClickHdl( LINK( this, SwMailMergePrepareMergePage, EditDocumentHdl_Impl));
    Link<> aMoveLink(LINK( this, SwMailMergePrepareMergePage, MoveHdl_Impl));
    m_pFirstPB->SetClickHdl( aMoveLink );
    m_pPrevPB->SetClickHdl( aMoveLink );
    m_pNextPB->SetClickHdl( aMoveLink );
    m_pLastPB->SetClickHdl( aMoveLink );
    m_pRecordED->SetModifyHdl( aMoveLink );
    m_pExcludeCB->SetClickHdl(LINK(this, SwMailMergePrepareMergePage, ExcludeHdl_Impl));
    aMoveLink.Call(m_pRecordED);
}

SwMailMergePrepareMergePage::~SwMailMergePrepareMergePage()
{
    disposeOnce();
}

void SwMailMergePrepareMergePage::dispose()
{
    m_pFirstPB.clear();
    m_pPrevPB.clear();
    m_pRecordED.clear();
    m_pNextPB.clear();
    m_pLastPB.clear();
    m_pExcludeCB.clear();
    m_pEditPB.clear();
    m_pWizard.clear();
    svt::OWizardPage::dispose();
}

IMPL_LINK_NOARG(SwMailMergePrepareMergePage, EditDocumentHdl_Impl)
{
    m_pWizard->SetRestartPage(MM_PREPAREMERGEPAGE);
    m_pWizard->EndDialog(RET_EDIT_DOC);
    return 0;
}

IMPL_LINK( SwMailMergePrepareMergePage, MoveHdl_Impl, void*, pCtrl)
{
    SwMailMergeConfigItem& rConfigItem = m_pWizard->GetConfigItem();
    sal_Int32 nPos = rConfigItem.GetResultSetPosition();
    if (pCtrl == m_pFirstPB)
    {
        rConfigItem.MoveResultSet(1);
    }
    else if (pCtrl == m_pPrevPB)
    {
        rConfigItem.MoveResultSet(nPos - 1);
    }
    else if (pCtrl == m_pRecordED)
    {
        rConfigItem.MoveResultSet( static_cast< sal_Int32 >(m_pRecordED->GetValue()) );
    }
    else if (pCtrl == m_pNextPB)
        rConfigItem.MoveResultSet(nPos + 1);
    else if (pCtrl == m_pLastPB)
        rConfigItem.MoveResultSet(-1);

    nPos = rConfigItem.GetResultSetPosition();
    m_pRecordED->SetValue(nPos);
    bool bIsFirst;
    bool bIsLast;
    bool bValid = rConfigItem.IsResultSetFirstLast(bIsFirst, bIsLast);
    m_pFirstPB->Enable(bValid && !bIsFirst);
    m_pPrevPB->Enable(bValid && !bIsFirst);
    m_pNextPB->Enable(bValid && !bIsLast);
    m_pLastPB->Enable(bValid && !bIsLast);
    m_pExcludeCB->Check(rConfigItem.IsRecordExcluded( rConfigItem.GetResultSetPosition() ));
    //now the record has to be merged into the source document
    const SwDBData& rDBData = rConfigItem.GetCurrentDBData();

    Sequence< PropertyValue > aArgs(7);
    Sequence<Any> aSelection(1);
    aSelection[0] <<= rConfigItem.GetResultSetPosition();
    aArgs[0].Name = "Selection";
    aArgs[0].Value <<= aSelection;
    aArgs[1].Name = "DataSourceName";
    aArgs[1].Value <<= rDBData.sDataSource;
    aArgs[2].Name = "Command";
    aArgs[2].Value <<= rDBData.sCommand;
    aArgs[3].Name = "CommandType";
    aArgs[3].Value <<= rDBData.nCommandType;
    aArgs[4].Name = "ActiveConnection";
    aArgs[4].Value <<=  rConfigItem.GetConnection().getTyped();
    aArgs[5].Name = "Filter";
    aArgs[5].Value <<= rConfigItem.GetFilter();
    aArgs[6].Name = "Cursor";
    aArgs[6].Value <<= rConfigItem.GetResultSet();

    svx::ODataAccessDescriptor aDescriptor(aArgs);
    SwWrtShell& rSh = m_pWizard->GetSwView()->GetWrtShell();
    SwMergeDescriptor aMergeDesc( DBMGR_MERGE, rSh, aDescriptor );
    rSh.GetDBManager()->MergeNew(aMergeDesc);
    return 0;
}

IMPL_LINK( SwMailMergePrepareMergePage, ExcludeHdl_Impl, CheckBox*, pBox)
{
    SwMailMergeConfigItem& rConfigItem = m_pWizard->GetConfigItem();
    rConfigItem.ExcludeRecord( rConfigItem.GetResultSetPosition(), pBox->IsChecked());
    return 0;
};

void  SwMailMergePrepareMergePage::ActivatePage()
{
    MoveHdl_Impl(m_pRecordED);
}

// merge the data into a new file
bool SwMailMergePrepareMergePage::commitPage( ::svt::WizardTypes::CommitPageReason _eReason )
{
    SwMailMergeConfigItem& rConfigItem = m_pWizard->GetConfigItem();
    if(::svt::WizardTypes::eTravelForward == _eReason && !rConfigItem.IsMergeDone())
    {
        m_pWizard->CreateTargetDocument();
        m_pWizard->SetRestartPage(MM_MERGEPAGE);
        m_pWizard->EndDialog(RET_TARGET_CREATED);
    }
    return true;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>tdf#89592: use initializer list<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <mmpreparemergepage.hxx>

#include <comphelper/propertysequence.hxx>
#include <mailmergewizard.hxx>
#include <mmconfigitem.hxx>
#include <dbui.hrc>
#include <swtypes.hxx>
#include <view.hxx>
#include <dbmgr.hxx>
#include <wrtsh.hxx>
#include <svx/dataaccessdescriptor.hxx>
#include <com/sun/star/sdbc/XConnection.hpp>
#include <swabstdlg.hxx>

#include <unomid.h>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;

SwMailMergePrepareMergePage::SwMailMergePrepareMergePage( SwMailMergeWizard* _pParent)
    : svt::OWizardPage(_pParent, "MMPreparePage", "modules/swriter/ui/mmpreparepage.ui")
    , m_pWizard(_pParent)
{
    get(m_pFirstPB, "first");
    get(m_pPrevPB, "prev");
    get(m_pRecordED, "record-nospin");
    get(m_pNextPB, "next");
    get(m_pLastPB, "last");
    get(m_pExcludeCB, "exclude");
    get(m_pEditPB, "edit");

    m_pEditPB->SetClickHdl( LINK( this, SwMailMergePrepareMergePage, EditDocumentHdl_Impl));
    Link<> aMoveLink(LINK( this, SwMailMergePrepareMergePage, MoveHdl_Impl));
    m_pFirstPB->SetClickHdl( aMoveLink );
    m_pPrevPB->SetClickHdl( aMoveLink );
    m_pNextPB->SetClickHdl( aMoveLink );
    m_pLastPB->SetClickHdl( aMoveLink );
    m_pRecordED->SetModifyHdl( aMoveLink );
    m_pExcludeCB->SetClickHdl(LINK(this, SwMailMergePrepareMergePage, ExcludeHdl_Impl));
    aMoveLink.Call(m_pRecordED);
}

SwMailMergePrepareMergePage::~SwMailMergePrepareMergePage()
{
    disposeOnce();
}

void SwMailMergePrepareMergePage::dispose()
{
    m_pFirstPB.clear();
    m_pPrevPB.clear();
    m_pRecordED.clear();
    m_pNextPB.clear();
    m_pLastPB.clear();
    m_pExcludeCB.clear();
    m_pEditPB.clear();
    m_pWizard.clear();
    svt::OWizardPage::dispose();
}

IMPL_LINK_NOARG(SwMailMergePrepareMergePage, EditDocumentHdl_Impl)
{
    m_pWizard->SetRestartPage(MM_PREPAREMERGEPAGE);
    m_pWizard->EndDialog(RET_EDIT_DOC);
    return 0;
}

IMPL_LINK( SwMailMergePrepareMergePage, MoveHdl_Impl, void*, pCtrl)
{
    SwMailMergeConfigItem& rConfigItem = m_pWizard->GetConfigItem();
    sal_Int32 nPos = rConfigItem.GetResultSetPosition();
    if (pCtrl == m_pFirstPB)
    {
        rConfigItem.MoveResultSet(1);
    }
    else if (pCtrl == m_pPrevPB)
    {
        rConfigItem.MoveResultSet(nPos - 1);
    }
    else if (pCtrl == m_pRecordED)
    {
        rConfigItem.MoveResultSet( static_cast< sal_Int32 >(m_pRecordED->GetValue()) );
    }
    else if (pCtrl == m_pNextPB)
        rConfigItem.MoveResultSet(nPos + 1);
    else if (pCtrl == m_pLastPB)
        rConfigItem.MoveResultSet(-1);

    nPos = rConfigItem.GetResultSetPosition();
    m_pRecordED->SetValue(nPos);
    bool bIsFirst;
    bool bIsLast;
    bool bValid = rConfigItem.IsResultSetFirstLast(bIsFirst, bIsLast);
    m_pFirstPB->Enable(bValid && !bIsFirst);
    m_pPrevPB->Enable(bValid && !bIsFirst);
    m_pNextPB->Enable(bValid && !bIsLast);
    m_pLastPB->Enable(bValid && !bIsLast);
    m_pExcludeCB->Check(rConfigItem.IsRecordExcluded( rConfigItem.GetResultSetPosition() ));
    //now the record has to be merged into the source document
    const SwDBData& rDBData = rConfigItem.GetCurrentDBData();
    Sequence<Any> vSelection = { makeAny(rConfigItem.GetResultSetPosition()) };
    auto aArgs(::comphelper::InitPropertySequence({
        {"Selection",        makeAny(vSelection)},
        {"DataSourceNamea",  makeAny(rDBData.sDataSource)},
        {"Command",          makeAny(rDBData.sCommand)},
        {"CommandType",      makeAny(rDBData.nCommandType)},
        {"ActiveConnection", makeAny(rConfigItem.GetConnection().getTyped())},
        {"Filter",           makeAny(rConfigItem.GetFilter())},
        {"Cursor",           makeAny(rConfigItem.GetResultSet())}
    }));
    svx::ODataAccessDescriptor aDescriptor(aArgs);
    SwWrtShell& rSh = m_pWizard->GetSwView()->GetWrtShell();
    SwMergeDescriptor aMergeDesc( DBMGR_MERGE, rSh, aDescriptor );
    rSh.GetDBManager()->MergeNew(aMergeDesc);
    return 0;
}

IMPL_LINK( SwMailMergePrepareMergePage, ExcludeHdl_Impl, CheckBox*, pBox)
{
    SwMailMergeConfigItem& rConfigItem = m_pWizard->GetConfigItem();
    rConfigItem.ExcludeRecord( rConfigItem.GetResultSetPosition(), pBox->IsChecked());
    return 0;
};

void  SwMailMergePrepareMergePage::ActivatePage()
{
    MoveHdl_Impl(m_pRecordED);
}

// merge the data into a new file
bool SwMailMergePrepareMergePage::commitPage( ::svt::WizardTypes::CommitPageReason _eReason )
{
    SwMailMergeConfigItem& rConfigItem = m_pWizard->GetConfigItem();
    if(::svt::WizardTypes::eTravelForward == _eReason && !rConfigItem.IsMergeDone())
    {
        m_pWizard->CreateTargetDocument();
        m_pWizard->SetRestartPage(MM_MERGEPAGE);
        m_pWizard->EndDialog(RET_TARGET_CREATED);
    }
    return true;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015
              Vladimír Vondruš <mosra@centrum.cz>

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

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

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

#include "Magnum/Context.h"

#include <algorithm>

#include "Magnum/Extensions.h"
#include "Magnum/Math/Range.h"

namespace Magnum {

namespace {
    std::vector<std::string> KnownWorkarounds{
        #ifndef MAGNUM_TARGET_GLES
        /* Creating core context with specific version on AMD and NV
           proprietary drivers causes the context to be forced to given
           version instead of selecting latest available version */
        "amd-nv-no-forward-compatible-core-context",

        /* Using ARB_explicit_uniform_location on AMD linux drivers 13.251
           caused the GLSL compiler to crash */
        "amd-explicit-uniform-location-crash",

        #ifdef CORRADE_TARGET_WINDOWS
        /* On Windows Intel drivers ARB_shading_language_420pack is exposed in
           GLSL even though the extension (e.g. binding keyword) is not
           supported */
        "intel-windows-glsl-exposes-unsupported-shading-language-420pack",
        #endif

        /* Layout qualifier causes compiler error with GLSL 1.20 on Mesa, GLSL
           1.30 on NVidia and 1.40 on Mac OS X. Everything is fine when using
           newer GLSL version. */
        "no-layout-qualifiers-on-old-glsl",
        #endif

        #ifdef CORRADE_TARGET_NACL
        /* NaCl advertises some additional extensions but the GLESv2 library
           does not have any entrypoints for them and there is no GetProcAddress
           equivalent, thus marking them as unsupported. */
        "nacl-missing-extension-entrypoints"
        #endif
    };
}

namespace Implementation {

/* Used in Shader.cpp (duh) */
bool isShaderCompilationLogEmpty(const std::string&);
bool isShaderCompilationLogEmpty(const std::string& result) {
    #if defined(CORRADE_TARGET_WINDOWS) && !defined(MAGNUM_TARGET_GLES)
    /* Intel Windows drivers are too chatty */
    if((Context::current()->detectedDriver() & Context::DetectedDriver::IntelWindows) && result == "No errors.\n")
        return true;
    #else
    static_cast<void>(result);
    #endif

    return false;
}

/* Used in AbstractShaderProgram.cpp (duh) */
bool isProgramLinkLogEmpty(const std::string&);
bool isProgramLinkLogEmpty(const std::string& result) {
    #if defined(CORRADE_TARGET_WINDOWS) && !defined(MAGNUM_TARGET_GLES)
    /* Intel Windows drivers are too chatty */
    if((Context::current()->detectedDriver() & Context::DetectedDriver::IntelWindows) && result == "No errors.\n")
        return true;
    #else
    static_cast<void>(result);
    #endif

    return false;
}

}

auto Context::detectedDriver() -> DetectedDrivers {
    if(_detectedDrivers) return *_detectedDrivers;

    _detectedDrivers = DetectedDrivers{};

    const std::string vendor = vendorString();

    #ifndef MAGNUM_TARGET_GLES
    /* AMD binary desktop drivers */
    if(vendor.find("ATI Technologies Inc.") != std::string::npos)
        return *_detectedDrivers |= DetectedDriver::AMD;

    #ifdef CORRADE_TARGET_WINDOWS
    /* Intel Windows drivers */
    if(vendor.find("Intel") != std::string::npos)
        return *_detectedDrivers |= DetectedDriver::IntelWindows;
    #endif
    #endif

    /** @todo there is also D3D9/D3D11 distinction on webglreport.com, is it useful? */
    #ifdef MAGNUM_TARGET_GLES
    /* OpenGL ES implementation using ANGLE. Taken from these sources:
       http://stackoverflow.com/a/20149090
       http://webglreport.com
    */
    {
        Range1Di range;
        glGetIntegerv(GL_ALIASED_LINE_WIDTH_RANGE, range.data());
        if(range.min() == 1 && range.max() == 1 && vendor != "Internet Explorer")
            return *_detectedDrivers |= DetectedDriver::ProbablyAngle;
    }
    #endif

    return *_detectedDrivers;
}

void Context::disableDriverWorkaround(const std::string& workaround) {
    /* Ignore unknown workarounds */
    if(std::find(KnownWorkarounds.begin(), KnownWorkarounds.end(), workaround) == KnownWorkarounds.end()) return;
    _driverWorkarounds.emplace_back(workaround, true);
}

bool Context::isDriverWorkaroundDisabled(const std::string& workaround) {
    CORRADE_INTERNAL_ASSERT(std::find(KnownWorkarounds.begin(), KnownWorkarounds.end(), workaround) != KnownWorkarounds.end());

    /* If the workaround was already asked for or disabled, return its state,
       otherwise add it to the list as used one */
    for(const auto& i: _driverWorkarounds)
        if(i.first == workaround) return i.second;
    _driverWorkarounds.emplace_back(workaround, false);
    return false;
}

void Context::setupDriverWorkarounds() {
    #define _setRequiredVersion(extension, version)                           \
        if(_extensionRequiredVersion[Extensions::extension::Index] < Version::version) \
            _extensionRequiredVersion[Extensions::extension::Index] = Version::version

    #ifndef MAGNUM_TARGET_GLES
    if((detectedDriver() & DetectedDriver::AMD) && !isDriverWorkaroundDisabled("amd-explicit-uniform-location-crash"))
        _setRequiredVersion(GL::ARB::explicit_uniform_location, None);

    #ifdef CORRADE_TARGET_WINDOWS
    if((detectedDriver() & DetectedDriver::IntelWindows) && !isExtensionSupported<Extensions::GL::ARB::shading_language_420pack>() && !isDriverWorkaroundDisabled("intel-windows-glsl-exposes-unsupported-shading-language-420pack"))
        _setRequiredVersion(GL::ARB::shading_language_420pack, None);
    #endif

    if(!isDriverWorkaroundDisabled("no-layout-qualifiers-on-old-glsl")) {
        _setRequiredVersion(GL::ARB::explicit_attrib_location, GL320);
        _setRequiredVersion(GL::ARB::explicit_uniform_location, GL320);
        _setRequiredVersion(GL::ARB::shading_language_420pack, GL320);
    }
    #endif

    #ifdef CORRADE_TARGET_NACL
    if(!isDriverWorkaroundDisabled("nacl-missing-extension-entrypoints")) {
        _setRequiredVersion(GL::EXT::multi_draw_arrays, None);
        _setRequiredVersion(GL::EXT::debug_label, None);
        _setRequiredVersion(GL::EXT::debug_marker, None);
        _setRequiredVersion(GL::EXT::disjoint_timer_query, None);
        _setRequiredVersion(GL::EXT::separate_shader_objects, None);
        _setRequiredVersion(GL::EXT::multisampled_render_to_texture, None);
        _setRequiredVersion(GL::EXT::robustness, None);
        _setRequiredVersion(GL::KHR::debug, None);
        _setRequiredVersion(GL::NV::read_buffer_front, None);
        _setRequiredVersion(GL::OES::mapbuffer, None);
        _setRequiredVersion(GL::ANGLE::framebuffer_blit, None);
        _setRequiredVersion(GL::ANGLE::framebuffer_multisample, None);
        _setRequiredVersion(GL::ANGLE::instanced_arrays, None);
        _setRequiredVersion(GL::APPLE::framebuffer_multisample, None);
        _setRequiredVersion(GL::EXT::discard_framebuffer, None);
        _setRequiredVersion(GL::EXT::blend_minmax, None);
        _setRequiredVersion(GL::EXT::texture_storage, None);
        _setRequiredVersion(GL::EXT::map_buffer_range, None);
        _setRequiredVersion(GL::EXT::instanced_arrays, None);
        _setRequiredVersion(GL::EXT::draw_instanced, None);
        _setRequiredVersion(GL::NV::draw_buffers, None);
        _setRequiredVersion(GL::NV::fbo_color_attachments, None); // ??
        _setRequiredVersion(GL::NV::read_buffer, None);
        _setRequiredVersion(GL::NV::draw_instanced, None);
        _setRequiredVersion(GL::NV::framebuffer_blit, None);
        _setRequiredVersion(GL::NV::framebuffer_multisample, None);
        _setRequiredVersion(GL::NV::instanced_arrays, None);
        _setRequiredVersion(GL::OES::texture_3D, None);
        _setRequiredVersion(GL::OES::vertex_array_object, None);
    }
    #endif

    #undef _setRequiredVersion
}

}
<commit_msg>Removed old amd-explicit-location-crash workaround.<commit_after>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015
              Vladimír Vondruš <mosra@centrum.cz>

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

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

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

#include "Magnum/Context.h"

#include <algorithm>

#include "Magnum/Extensions.h"
#include "Magnum/Math/Range.h"

namespace Magnum {

namespace {
    std::vector<std::string> KnownWorkarounds{
        #ifndef MAGNUM_TARGET_GLES
        /* Creating core context with specific version on AMD and NV
           proprietary drivers causes the context to be forced to given
           version instead of selecting latest available version */
        "amd-nv-no-forward-compatible-core-context",

        #ifdef CORRADE_TARGET_WINDOWS
        /* On Windows Intel drivers ARB_shading_language_420pack is exposed in
           GLSL even though the extension (e.g. binding keyword) is not
           supported */
        "intel-windows-glsl-exposes-unsupported-shading-language-420pack",
        #endif

        /* Layout qualifier causes compiler error with GLSL 1.20 on Mesa, GLSL
           1.30 on NVidia and 1.40 on Mac OS X. Everything is fine when using
           newer GLSL version. */
        "no-layout-qualifiers-on-old-glsl",
        #endif

        #ifdef CORRADE_TARGET_NACL
        /* NaCl advertises some additional extensions but the GLESv2 library
           does not have any entrypoints for them and there is no GetProcAddress
           equivalent, thus marking them as unsupported. */
        "nacl-missing-extension-entrypoints"
        #endif
    };
}

namespace Implementation {

/* Used in Shader.cpp (duh) */
bool isShaderCompilationLogEmpty(const std::string&);
bool isShaderCompilationLogEmpty(const std::string& result) {
    #if defined(CORRADE_TARGET_WINDOWS) && !defined(MAGNUM_TARGET_GLES)
    /* Intel Windows drivers are too chatty */
    if((Context::current()->detectedDriver() & Context::DetectedDriver::IntelWindows) && result == "No errors.\n")
        return true;
    #else
    static_cast<void>(result);
    #endif

    return false;
}

/* Used in AbstractShaderProgram.cpp (duh) */
bool isProgramLinkLogEmpty(const std::string&);
bool isProgramLinkLogEmpty(const std::string& result) {
    #if defined(CORRADE_TARGET_WINDOWS) && !defined(MAGNUM_TARGET_GLES)
    /* Intel Windows drivers are too chatty */
    if((Context::current()->detectedDriver() & Context::DetectedDriver::IntelWindows) && result == "No errors.\n")
        return true;
    #else
    static_cast<void>(result);
    #endif

    return false;
}

}

auto Context::detectedDriver() -> DetectedDrivers {
    if(_detectedDrivers) return *_detectedDrivers;

    _detectedDrivers = DetectedDrivers{};

    const std::string vendor = vendorString();

    #ifndef MAGNUM_TARGET_GLES
    /* AMD binary desktop drivers */
    if(vendor.find("ATI Technologies Inc.") != std::string::npos)
        return *_detectedDrivers |= DetectedDriver::AMD;

    #ifdef CORRADE_TARGET_WINDOWS
    /* Intel Windows drivers */
    if(vendor.find("Intel") != std::string::npos)
        return *_detectedDrivers |= DetectedDriver::IntelWindows;
    #endif
    #endif

    /** @todo there is also D3D9/D3D11 distinction on webglreport.com, is it useful? */
    #ifdef MAGNUM_TARGET_GLES
    /* OpenGL ES implementation using ANGLE. Taken from these sources:
       http://stackoverflow.com/a/20149090
       http://webglreport.com
    */
    {
        Range1Di range;
        glGetIntegerv(GL_ALIASED_LINE_WIDTH_RANGE, range.data());
        if(range.min() == 1 && range.max() == 1 && vendor != "Internet Explorer")
            return *_detectedDrivers |= DetectedDriver::ProbablyAngle;
    }
    #endif

    return *_detectedDrivers;
}

void Context::disableDriverWorkaround(const std::string& workaround) {
    /* Ignore unknown workarounds */
    if(std::find(KnownWorkarounds.begin(), KnownWorkarounds.end(), workaround) == KnownWorkarounds.end()) return;
    _driverWorkarounds.emplace_back(workaround, true);
}

bool Context::isDriverWorkaroundDisabled(const std::string& workaround) {
    CORRADE_INTERNAL_ASSERT(std::find(KnownWorkarounds.begin(), KnownWorkarounds.end(), workaround) != KnownWorkarounds.end());

    /* If the workaround was already asked for or disabled, return its state,
       otherwise add it to the list as used one */
    for(const auto& i: _driverWorkarounds)
        if(i.first == workaround) return i.second;
    _driverWorkarounds.emplace_back(workaround, false);
    return false;
}

void Context::setupDriverWorkarounds() {
    #define _setRequiredVersion(extension, version)                           \
        if(_extensionRequiredVersion[Extensions::extension::Index] < Version::version) \
            _extensionRequiredVersion[Extensions::extension::Index] = Version::version

    #ifndef MAGNUM_TARGET_GLES
    #ifdef CORRADE_TARGET_WINDOWS
    if((detectedDriver() & DetectedDriver::IntelWindows) && !isExtensionSupported<Extensions::GL::ARB::shading_language_420pack>() && !isDriverWorkaroundDisabled("intel-windows-glsl-exposes-unsupported-shading-language-420pack"))
        _setRequiredVersion(GL::ARB::shading_language_420pack, None);
    #endif

    if(!isDriverWorkaroundDisabled("no-layout-qualifiers-on-old-glsl")) {
        _setRequiredVersion(GL::ARB::explicit_attrib_location, GL320);
        _setRequiredVersion(GL::ARB::explicit_uniform_location, GL320);
        _setRequiredVersion(GL::ARB::shading_language_420pack, GL320);
    }
    #endif

    #ifdef CORRADE_TARGET_NACL
    if(!isDriverWorkaroundDisabled("nacl-missing-extension-entrypoints")) {
        _setRequiredVersion(GL::EXT::multi_draw_arrays, None);
        _setRequiredVersion(GL::EXT::debug_label, None);
        _setRequiredVersion(GL::EXT::debug_marker, None);
        _setRequiredVersion(GL::EXT::disjoint_timer_query, None);
        _setRequiredVersion(GL::EXT::separate_shader_objects, None);
        _setRequiredVersion(GL::EXT::multisampled_render_to_texture, None);
        _setRequiredVersion(GL::EXT::robustness, None);
        _setRequiredVersion(GL::KHR::debug, None);
        _setRequiredVersion(GL::NV::read_buffer_front, None);
        _setRequiredVersion(GL::OES::mapbuffer, None);
        _setRequiredVersion(GL::ANGLE::framebuffer_blit, None);
        _setRequiredVersion(GL::ANGLE::framebuffer_multisample, None);
        _setRequiredVersion(GL::ANGLE::instanced_arrays, None);
        _setRequiredVersion(GL::APPLE::framebuffer_multisample, None);
        _setRequiredVersion(GL::EXT::discard_framebuffer, None);
        _setRequiredVersion(GL::EXT::blend_minmax, None);
        _setRequiredVersion(GL::EXT::texture_storage, None);
        _setRequiredVersion(GL::EXT::map_buffer_range, None);
        _setRequiredVersion(GL::EXT::instanced_arrays, None);
        _setRequiredVersion(GL::EXT::draw_instanced, None);
        _setRequiredVersion(GL::NV::draw_buffers, None);
        _setRequiredVersion(GL::NV::fbo_color_attachments, None); // ??
        _setRequiredVersion(GL::NV::read_buffer, None);
        _setRequiredVersion(GL::NV::draw_instanced, None);
        _setRequiredVersion(GL::NV::framebuffer_blit, None);
        _setRequiredVersion(GL::NV::framebuffer_multisample, None);
        _setRequiredVersion(GL::NV::instanced_arrays, None);
        _setRequiredVersion(GL::OES::texture_3D, None);
        _setRequiredVersion(GL::OES::vertex_array_object, None);
    }
    #endif

    #undef _setRequiredVersion
}

}
<|endoftext|>


<commit_before>/*
 * Copyright © 2008, 2009 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
#include <cstdlib>
#include <cstdio>
#include <getopt.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "ast.h"
#include "glsl_parser_extras.h"
#include "glsl_parser.h"
#include "ir_optimization.h"
#include "ir_print_visitor.h"
#include "program.h"

/* Returned string will have 'ctx' as its talloc owner. */
static char *
load_text_file(void *ctx, const char *file_name)
{
	char *text = NULL;
	struct stat st;
	ssize_t total_read = 0;
	int fd = open(file_name, O_RDONLY);

	if (fd < 0) {
		return NULL;
	}

	if (fstat(fd, & st) == 0) {
	   text = (char *) talloc_size(ctx, st.st_size + 1);
		if (text != NULL) {
			do {
				ssize_t bytes = read(fd, text + total_read,
						     st.st_size - total_read);
				if (bytes < 0) {
					free(text);
					text = NULL;
					break;
				}

				if (bytes == 0) {
					break;
				}

				total_read += bytes;
			} while (total_read < st.st_size);

			text[total_read] = '\0';
		}
	}

	close(fd);

	return text;
}

void
usage_fail(const char *name)
{
      printf("%s <filename.frag|filename.vert>\n", name);
      exit(EXIT_FAILURE);
}

int dump_ast = 0;
int dump_hir = 0;
int dump_lir = 0;
int do_link = 0;

const struct option compiler_opts[] = {
   { "dump-ast", 0, &dump_ast, 1 },
   { "dump-hir", 0, &dump_hir, 1 },
   { "dump-lir", 0, &dump_lir, 1 },
   { "link",     0, &do_link,  1 },
   { NULL, 0, NULL, 0 }
};

static void
steal_memory(ir_instruction *ir, void *new_ctx)
{
   talloc_steal(new_ctx, ir);
}

void
compile_shader(struct gl_shader *shader)
{
   struct _mesa_glsl_parse_state *state;
   struct gl_extensions ext;

   state = talloc_zero(talloc_parent(shader), struct _mesa_glsl_parse_state);

   switch (shader->Type) {
   case GL_VERTEX_SHADER:   state->target = vertex_shader; break;
   case GL_FRAGMENT_SHADER: state->target = fragment_shader; break;
   case GL_GEOMETRY_SHADER: state->target = geometry_shader; break;
   }

   state->scanner = NULL;
   state->translation_unit.make_empty();
   state->symbols = new(shader) glsl_symbol_table;
   state->info_log = talloc_strdup(shader, "");
   state->error = false;
   state->temp_index = 0;
   state->loop_or_switch_nesting = NULL;
   state->ARB_texture_rectangle_enable = true;

   memset(&ext, 0, sizeof(ext));
   state->extensions = &ext;
   state->Const.MaxDrawBuffers = 2;
   state->Const.MaxTextureCoords = 4;

   const char *source = shader->Source;
   state->error = preprocess(state, &source, &state->info_log, &ext);

   if (!state->error) {
      _mesa_glsl_lexer_ctor(state, source);
      _mesa_glsl_parse(state);
      _mesa_glsl_lexer_dtor(state);
   }

   if (dump_ast) {
      foreach_list_const(n, &state->translation_unit) {
	 ast_node *ast = exec_node_data(ast_node, n, link);
	 ast->print();
      }
      printf("\n\n");
   }

   shader->ir = new(shader) exec_list;
   if (!state->error && !state->translation_unit.is_empty())
      _mesa_ast_to_hir(shader->ir, state);

   validate_ir_tree(shader->ir);

   /* Print out the unoptimized IR. */
   if (!state->error && dump_hir) {
      _mesa_print_ir(shader->ir, state);
   }

   /* Optimization passes */
   if (!state->error && !shader->ir->is_empty()) {
      bool progress;
      do {
	 progress = false;

	 progress = do_function_inlining(shader->ir) || progress;
	 progress = do_if_simplification(shader->ir) || progress;
	 progress = do_copy_propagation(shader->ir) || progress;
	 progress = do_dead_code_local(shader->ir) || progress;
	 progress = do_dead_code_unlinked(state, shader->ir) || progress;
	 progress = do_constant_variable_unlinked(shader->ir) || progress;
	 progress = do_constant_folding(shader->ir) || progress;
	 progress = do_vec_index_to_swizzle(shader->ir) || progress;
	 progress = do_swizzle_swizzle(shader->ir) || progress;
      } while (progress);
   }

   validate_ir_tree(shader->ir);

   /* Print out the resulting IR */
   if (!state->error && dump_lir) {
      _mesa_print_ir(shader->ir, state);
   }

   shader->symbols = state->symbols;
   shader->CompileStatus = !state->error;

   if (shader->InfoLog)
      talloc_free(shader->InfoLog);

   shader->InfoLog = state->info_log;

   /* Retain any live IR, but trash the rest. */
   foreach_list(node, shader->ir) {
      visit_tree((ir_instruction *) node, steal_memory, shader);
   }

   talloc_free(state);

   return;
}

int
main(int argc, char **argv)
{
   int status = EXIT_SUCCESS;

   int c;
   int idx = 0;
   while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1)
      /* empty */ ;

   if (argc <= optind)
      usage_fail(argv[0]);

   struct gl_shader_program *whole_program;

   whole_program = talloc_zero (NULL, struct gl_shader_program);
   assert(whole_program != NULL);

   for (/* empty */; argc > optind; optind++) {
      whole_program->Shaders = (struct gl_shader **)
	 talloc_realloc(whole_program, whole_program->Shaders,
			struct gl_shader *, whole_program->NumShaders + 1);
      assert(whole_program->Shaders != NULL);

      struct gl_shader *shader = talloc_zero(whole_program, gl_shader);

      whole_program->Shaders[whole_program->NumShaders] = shader;
      whole_program->NumShaders++;

      const unsigned len = strlen(argv[optind]);
      if (len < 6)
	 usage_fail(argv[0]);

      const char *const ext = & argv[optind][len - 5];
      if (strncmp(".vert", ext, 5) == 0)
	 shader->Type = GL_VERTEX_SHADER;
      else if (strncmp(".geom", ext, 5) == 0)
	 shader->Type = GL_GEOMETRY_SHADER;
      else if (strncmp(".frag", ext, 5) == 0)
	 shader->Type = GL_FRAGMENT_SHADER;
      else
	 usage_fail(argv[0]);

      shader->Source = load_text_file(whole_program, argv[optind]);
      if (shader->Source == NULL) {
	 printf("File \"%s\" does not exist.\n", argv[optind]);
	 exit(EXIT_FAILURE);
      }

      compile_shader(shader);

      if (!shader->CompileStatus) {
	 printf("Info log for %s:\n%s\n", argv[optind], shader->InfoLog);
	 status = EXIT_FAILURE;
	 break;
      }
   }

   if ((status == EXIT_SUCCESS) && do_link)  {
      link_shaders(whole_program);
      status = (whole_program->LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;
   }

   talloc_free(whole_program);
   _mesa_glsl_release_types();

   return status;
}
<commit_msg>glsl2: Print the linking info log in the stand-alone compiler<commit_after>/*
 * Copyright © 2008, 2009 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
#include <cstdlib>
#include <cstdio>
#include <getopt.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "ast.h"
#include "glsl_parser_extras.h"
#include "glsl_parser.h"
#include "ir_optimization.h"
#include "ir_print_visitor.h"
#include "program.h"

/* Returned string will have 'ctx' as its talloc owner. */
static char *
load_text_file(void *ctx, const char *file_name)
{
	char *text = NULL;
	struct stat st;
	ssize_t total_read = 0;
	int fd = open(file_name, O_RDONLY);

	if (fd < 0) {
		return NULL;
	}

	if (fstat(fd, & st) == 0) {
	   text = (char *) talloc_size(ctx, st.st_size + 1);
		if (text != NULL) {
			do {
				ssize_t bytes = read(fd, text + total_read,
						     st.st_size - total_read);
				if (bytes < 0) {
					free(text);
					text = NULL;
					break;
				}

				if (bytes == 0) {
					break;
				}

				total_read += bytes;
			} while (total_read < st.st_size);

			text[total_read] = '\0';
		}
	}

	close(fd);

	return text;
}

void
usage_fail(const char *name)
{
      printf("%s <filename.frag|filename.vert>\n", name);
      exit(EXIT_FAILURE);
}

int dump_ast = 0;
int dump_hir = 0;
int dump_lir = 0;
int do_link = 0;

const struct option compiler_opts[] = {
   { "dump-ast", 0, &dump_ast, 1 },
   { "dump-hir", 0, &dump_hir, 1 },
   { "dump-lir", 0, &dump_lir, 1 },
   { "link",     0, &do_link,  1 },
   { NULL, 0, NULL, 0 }
};

static void
steal_memory(ir_instruction *ir, void *new_ctx)
{
   talloc_steal(new_ctx, ir);
}

void
compile_shader(struct gl_shader *shader)
{
   struct _mesa_glsl_parse_state *state;
   struct gl_extensions ext;

   state = talloc_zero(talloc_parent(shader), struct _mesa_glsl_parse_state);

   switch (shader->Type) {
   case GL_VERTEX_SHADER:   state->target = vertex_shader; break;
   case GL_FRAGMENT_SHADER: state->target = fragment_shader; break;
   case GL_GEOMETRY_SHADER: state->target = geometry_shader; break;
   }

   state->scanner = NULL;
   state->translation_unit.make_empty();
   state->symbols = new(shader) glsl_symbol_table;
   state->info_log = talloc_strdup(shader, "");
   state->error = false;
   state->temp_index = 0;
   state->loop_or_switch_nesting = NULL;
   state->ARB_texture_rectangle_enable = true;

   memset(&ext, 0, sizeof(ext));
   state->extensions = &ext;
   state->Const.MaxDrawBuffers = 2;
   state->Const.MaxTextureCoords = 4;

   const char *source = shader->Source;
   state->error = preprocess(state, &source, &state->info_log, &ext);

   if (!state->error) {
      _mesa_glsl_lexer_ctor(state, source);
      _mesa_glsl_parse(state);
      _mesa_glsl_lexer_dtor(state);
   }

   if (dump_ast) {
      foreach_list_const(n, &state->translation_unit) {
	 ast_node *ast = exec_node_data(ast_node, n, link);
	 ast->print();
      }
      printf("\n\n");
   }

   shader->ir = new(shader) exec_list;
   if (!state->error && !state->translation_unit.is_empty())
      _mesa_ast_to_hir(shader->ir, state);

   validate_ir_tree(shader->ir);

   /* Print out the unoptimized IR. */
   if (!state->error && dump_hir) {
      _mesa_print_ir(shader->ir, state);
   }

   /* Optimization passes */
   if (!state->error && !shader->ir->is_empty()) {
      bool progress;
      do {
	 progress = false;

	 progress = do_function_inlining(shader->ir) || progress;
	 progress = do_if_simplification(shader->ir) || progress;
	 progress = do_copy_propagation(shader->ir) || progress;
	 progress = do_dead_code_local(shader->ir) || progress;
	 progress = do_dead_code_unlinked(state, shader->ir) || progress;
	 progress = do_constant_variable_unlinked(shader->ir) || progress;
	 progress = do_constant_folding(shader->ir) || progress;
	 progress = do_vec_index_to_swizzle(shader->ir) || progress;
	 progress = do_swizzle_swizzle(shader->ir) || progress;
      } while (progress);
   }

   validate_ir_tree(shader->ir);

   /* Print out the resulting IR */
   if (!state->error && dump_lir) {
      _mesa_print_ir(shader->ir, state);
   }

   shader->symbols = state->symbols;
   shader->CompileStatus = !state->error;

   if (shader->InfoLog)
      talloc_free(shader->InfoLog);

   shader->InfoLog = state->info_log;

   /* Retain any live IR, but trash the rest. */
   foreach_list(node, shader->ir) {
      visit_tree((ir_instruction *) node, steal_memory, shader);
   }

   talloc_free(state);

   return;
}

int
main(int argc, char **argv)
{
   int status = EXIT_SUCCESS;

   int c;
   int idx = 0;
   while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1)
      /* empty */ ;

   if (argc <= optind)
      usage_fail(argv[0]);

   struct gl_shader_program *whole_program;

   whole_program = talloc_zero (NULL, struct gl_shader_program);
   assert(whole_program != NULL);

   for (/* empty */; argc > optind; optind++) {
      whole_program->Shaders = (struct gl_shader **)
	 talloc_realloc(whole_program, whole_program->Shaders,
			struct gl_shader *, whole_program->NumShaders + 1);
      assert(whole_program->Shaders != NULL);

      struct gl_shader *shader = talloc_zero(whole_program, gl_shader);

      whole_program->Shaders[whole_program->NumShaders] = shader;
      whole_program->NumShaders++;

      const unsigned len = strlen(argv[optind]);
      if (len < 6)
	 usage_fail(argv[0]);

      const char *const ext = & argv[optind][len - 5];
      if (strncmp(".vert", ext, 5) == 0)
	 shader->Type = GL_VERTEX_SHADER;
      else if (strncmp(".geom", ext, 5) == 0)
	 shader->Type = GL_GEOMETRY_SHADER;
      else if (strncmp(".frag", ext, 5) == 0)
	 shader->Type = GL_FRAGMENT_SHADER;
      else
	 usage_fail(argv[0]);

      shader->Source = load_text_file(whole_program, argv[optind]);
      if (shader->Source == NULL) {
	 printf("File \"%s\" does not exist.\n", argv[optind]);
	 exit(EXIT_FAILURE);
      }

      compile_shader(shader);

      if (!shader->CompileStatus) {
	 printf("Info log for %s:\n%s\n", argv[optind], shader->InfoLog);
	 status = EXIT_FAILURE;
	 break;
      }
   }

   if ((status == EXIT_SUCCESS) && do_link)  {
      link_shaders(whole_program);
      status = (whole_program->LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;

      if (strlen(whole_program->InfoLog) > 0)
	 printf("Info log for linking:\n%s\n", whole_program->InfoLog);
   }

   talloc_free(whole_program);
   _mesa_glsl_release_types();

   return status;
}
<|endoftext|>