<commit_before>/*
 * Copyright 2016 MovingBlocks
 *
 * 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.
 */
package org.terasology.rendering.opengl;

import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.CharStreams;
import gnu.trove.iterator.TIntIntIterator;
import gnu.trove.map.TIntIntMap;
import gnu.trove.map.hash.TIntIntHashMap;
import org.lwjgl.opengl.ARBShaderObjects;
import org.lwjgl.opengl.GL20;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.assets.AssetType;
import org.terasology.assets.ResourceUrn;
import org.terasology.config.Config;
import org.terasology.config.RenderingConfig;
import org.terasology.engine.GameThread;
import org.terasology.engine.TerasologyConstants;
import org.terasology.engine.paths.PathManager;
import org.terasology.registry.CoreRegistry;
import org.terasology.rendering.assets.shader.Shader;
import org.terasology.rendering.assets.shader.ShaderData;
import org.terasology.rendering.assets.shader.ShaderParameterMetadata;
import org.terasology.rendering.assets.shader.ShaderProgramFeature;
import org.terasology.rendering.primitives.ChunkVertexFlag;
import org.terasology.rendering.world.WorldRenderer;
import org.terasology.world.block.tiles.WorldAtlas;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;

import static org.terasology.rendering.dag.nodes.AmbientOcclusionNode.SSAO_KERNEL_ELEMENTS;
import static org.terasology.rendering.dag.nodes.AmbientOcclusionNode.SSAO_NOISE_SIZE;

/**
 * GLSL Shader Program Instance class.
 * <p>
 * Provides actual shader compilation and manipulation support.
 * </p>
 */
public class GLSLShader extends Shader {

    private static final Logger logger = LoggerFactory.getLogger(GLSLShader.class);

    private static String includedFunctionsVertex = "";
    private static String includedFunctionsFragment = "";
    private static String includedDefines = "";
    private static String includedUniforms = "";

    static {
        try (
                InputStreamReader vertStream = getInputStreamReaderFromResource("org/terasology/include/globalFunctionsVertIncl.glsl");
                InputStreamReader fragStream = getInputStreamReaderFromResource("org/terasology/include/globalFunctionsFragIncl.glsl");
                InputStreamReader uniformsStream = getInputStreamReaderFromResource("org/terasology/include/globalUniformsIncl.glsl");
                InputStreamReader definesStream = getInputStreamReaderFromResource("org/terasology/include/globalDefinesIncl.glsl")
        ) {
            includedFunctionsVertex = CharStreams.toString(vertStream);
            includedFunctionsFragment = CharStreams.toString(fragStream);
            includedDefines = CharStreams.toString(uniformsStream);
            includedUniforms = CharStreams.toString(definesStream);
        } catch (IOException e) {
            logger.error("Failed to load Include shader resources");
        }
    }

    private EnumSet<ShaderProgramFeature> availableFeatures = Sets.newEnumSet(Collections.emptyList(), ShaderProgramFeature.class);

    private ShaderData shaderProgramBase;
    private Map<String, ShaderParameterMetadata> parameters = Maps.newHashMap();

    private Config config = CoreRegistry.get(Config.class);

    private DisposalAction disposalAction;

    public GLSLShader(ResourceUrn urn, AssetType<?, ShaderData> assetType, ShaderData data) {
        super(urn, assetType);
        disposalAction = new DisposalAction(urn);
        getDisposalHook().setDisposeAction(disposalAction);
        reload(data);
    }

    private static InputStreamReader getInputStreamReaderFromResource(String resource) {
        InputStream resourceStream = GLSLShader.class.getClassLoader().getResourceAsStream(resource);
        return new InputStreamReader(resourceStream, Charsets.UTF_8);
    }

    // made package-private after CheckStyle suggestion
    Set<ShaderProgramFeature> getAvailableFeatures() {
        return availableFeatures;
    }

    // made package-private after CheckStyle suggestion
    int linkShaderProgram(int featureHash) {
        int shaderProgram = GL20.glCreateProgram();

        GL20.glAttachShader(shaderProgram, disposalAction.fragmentPrograms.get(featureHash));
        GL20.glAttachShader(shaderProgram, disposalAction.vertexPrograms.get(featureHash));
        GL20.glLinkProgram(shaderProgram);
        GL20.glValidateProgram(shaderProgram);
        return shaderProgram;
    }

    @Override
    public void recompile() {
        registerAllShaderPermutations();
        // TODO: reload materials
    }

    @Override
    public ShaderParameterMetadata getParameter(String desc) {
        return parameters.get(desc);
    }

    @Override
    public Iterable<ShaderParameterMetadata> listParameters() {
        return parameters.values();
    }

    private StringBuilder createShaderBuilder() {
        String preProcessorPreamble = "#version 120\n";

        // TODO: Implement a system for this - this has gotten way out of hand.
        WorldAtlas worldAtlas = CoreRegistry.get(WorldAtlas.class);
        if (worldAtlas != null) {
            preProcessorPreamble += "#define TEXTURE_OFFSET " + worldAtlas.getRelativeTileSize() + "\n";
        } else {
            preProcessorPreamble += "#define TEXTURE_OFFSET 0.06125\n";
        }
        RenderingConfig renderConfig = config.getRendering();

        preProcessorPreamble += "#define BLOCK_LIGHT_POW " + WorldRenderer.BLOCK_LIGHT_POW + "\n";
        preProcessorPreamble += "#define BLOCK_LIGHT_SUN_POW " + WorldRenderer.BLOCK_LIGHT_SUN_POW + "\n";
        preProcessorPreamble += "#define BLOCK_INTENSITY_FACTOR " + WorldRenderer.BLOCK_INTENSITY_FACTOR + "\n";
        preProcessorPreamble += "#define SHADOW_MAP_RESOLUTION " + (float) renderConfig.getShadowMapResolution() + "\n";
        preProcessorPreamble += "#define SSAO_KERNEL_ELEMENTS " + SSAO_KERNEL_ELEMENTS + "\n";
        preProcessorPreamble += "#define SSAO_NOISE_SIZE " + SSAO_NOISE_SIZE + "\n";
        // TODO: This shouldn't be hardcoded
        preProcessorPreamble += "#define TEXTURE_OFFSET_EFFECTS " + 0.0625f + "\n";

        StringBuilder builder = new StringBuilder().append(preProcessorPreamble);
        if (renderConfig.isVolumetricFog()) {
            builder.append("#define VOLUMETRIC_FOG");
        }

        if (renderConfig.isAnimateGrass()) {
            builder.append("#define ANIMATED_GRASS \n");
        }
        if (renderConfig.isAnimateWater()) {
            builder.append("#define ANIMATED_WATER \n");
        }
        if (renderConfig.getBlurIntensity() == 0) {
            builder.append("#define NO_BLUR \n");
        }
        if (renderConfig.isFlickeringLight()) {
            builder.append("#define FLICKERING_LIGHT \n");
        }
        if (renderConfig.isVignette()) {
            builder.append("#define VIGNETTE \n");
        }
        if (renderConfig.isBloom()) {
            builder.append("#define BLOOM \n");
        }
        if (renderConfig.isMotionBlur()) {
            builder.append("#define MOTION_BLUR \n");
        }
        if (renderConfig.isSsao()) {
            builder.append("#define SSAO \n");
        }
        if (renderConfig.isFilmGrain()) {
            builder.append("#define FILM_GRAIN \n");
        }
        if (renderConfig.isOutline()) {<commit_msg>added missing carriage return for VOLUMETRIC_FOG<commit_after>/*
 * Copyright 2016 MovingBlocks
 *
 * 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.
 */
package org.terasology.rendering.opengl;

import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.CharStreams;
import gnu.trove.iterator.TIntIntIterator;
import gnu.trove.map.TIntIntMap;
import gnu.trove.map.hash.TIntIntHashMap;
import org.lwjgl.opengl.ARBShaderObjects;
import org.lwjgl.opengl.GL20;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.assets.AssetType;
import org.terasology.assets.ResourceUrn;
import org.terasology.config.Config;
import org.terasology.config.RenderingConfig;
import org.terasology.engine.GameThread;
import org.terasology.engine.TerasologyConstants;
import org.terasology.engine.paths.PathManager;
import org.terasology.registry.CoreRegistry;
import org.terasology.rendering.assets.shader.Shader;
import org.terasology.rendering.assets.shader.ShaderData;
import org.terasology.rendering.assets.shader.ShaderParameterMetadata;
import org.terasology.rendering.assets.shader.ShaderProgramFeature;
import org.terasology.rendering.primitives.ChunkVertexFlag;
import org.terasology.rendering.world.WorldRenderer;
import org.terasology.world.block.tiles.WorldAtlas;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;

import static org.terasology.rendering.dag.nodes.AmbientOcclusionNode.SSAO_KERNEL_ELEMENTS;
import static org.terasology.rendering.dag.nodes.AmbientOcclusionNode.SSAO_NOISE_SIZE;

/**
 * GLSL Shader Program Instance class.
 * <p>
 * Provides actual shader compilation and manipulation support.
 * </p>
 */
public class GLSLShader extends Shader {

    private static final Logger logger = LoggerFactory.getLogger(GLSLShader.class);

    private static String includedFunctionsVertex = "";
    private static String includedFunctionsFragment = "";
    private static String includedDefines = "";
    private static String includedUniforms = "";

    static {
        try (
                InputStreamReader vertStream = getInputStreamReaderFromResource("org/terasology/include/globalFunctionsVertIncl.glsl");
                InputStreamReader fragStream = getInputStreamReaderFromResource("org/terasology/include/globalFunctionsFragIncl.glsl");
                InputStreamReader uniformsStream = getInputStreamReaderFromResource("org/terasology/include/globalUniformsIncl.glsl");
                InputStreamReader definesStream = getInputStreamReaderFromResource("org/terasology/include/globalDefinesIncl.glsl")
        ) {
            includedFunctionsVertex = CharStreams.toString(vertStream);
            includedFunctionsFragment = CharStreams.toString(fragStream);
            includedDefines = CharStreams.toString(uniformsStream);
            includedUniforms = CharStreams.toString(definesStream);
        } catch (IOException e) {
            logger.error("Failed to load Include shader resources");
        }
    }

    private EnumSet<ShaderProgramFeature> availableFeatures = Sets.newEnumSet(Collections.emptyList(), ShaderProgramFeature.class);

    private ShaderData shaderProgramBase;
    private Map<String, ShaderParameterMetadata> parameters = Maps.newHashMap();

    private Config config = CoreRegistry.get(Config.class);

    private DisposalAction disposalAction;

    public GLSLShader(ResourceUrn urn, AssetType<?, ShaderData> assetType, ShaderData data) {
        super(urn, assetType);
        disposalAction = new DisposalAction(urn);
        getDisposalHook().setDisposeAction(disposalAction);
        reload(data);
    }

    private static InputStreamReader getInputStreamReaderFromResource(String resource) {
        InputStream resourceStream = GLSLShader.class.getClassLoader().getResourceAsStream(resource);
        return new InputStreamReader(resourceStream, Charsets.UTF_8);
    }

    // made package-private after CheckStyle suggestion
    Set<ShaderProgramFeature> getAvailableFeatures() {
        return availableFeatures;
    }

    // made package-private after CheckStyle suggestion
    int linkShaderProgram(int featureHash) {
        int shaderProgram = GL20.glCreateProgram();

        GL20.glAttachShader(shaderProgram, disposalAction.fragmentPrograms.get(featureHash));
        GL20.glAttachShader(shaderProgram, disposalAction.vertexPrograms.get(featureHash));
        GL20.glLinkProgram(shaderProgram);
        GL20.glValidateProgram(shaderProgram);
        return shaderProgram;
    }

    @Override
    public void recompile() {
        registerAllShaderPermutations();
        // TODO: reload materials
    }

    @Override
    public ShaderParameterMetadata getParameter(String desc) {
        return parameters.get(desc);
    }

    @Override
    public Iterable<ShaderParameterMetadata> listParameters() {
        return parameters.values();
    }

    private StringBuilder createShaderBuilder() {
        String preProcessorPreamble = "#version 120\n";

        // TODO: Implement a system for this - this has gotten way out of hand.
        WorldAtlas worldAtlas = CoreRegistry.get(WorldAtlas.class);
        if (worldAtlas != null) {
            preProcessorPreamble += "#define TEXTURE_OFFSET " + worldAtlas.getRelativeTileSize() + "\n";
        } else {
            preProcessorPreamble += "#define TEXTURE_OFFSET 0.06125\n";
        }
        RenderingConfig renderConfig = config.getRendering();

        preProcessorPreamble += "#define BLOCK_LIGHT_POW " + WorldRenderer.BLOCK_LIGHT_POW + "\n";
        preProcessorPreamble += "#define BLOCK_LIGHT_SUN_POW " + WorldRenderer.BLOCK_LIGHT_SUN_POW + "\n";
        preProcessorPreamble += "#define BLOCK_INTENSITY_FACTOR " + WorldRenderer.BLOCK_INTENSITY_FACTOR + "\n";
        preProcessorPreamble += "#define SHADOW_MAP_RESOLUTION " + (float) renderConfig.getShadowMapResolution() + "\n";
        preProcessorPreamble += "#define SSAO_KERNEL_ELEMENTS " + SSAO_KERNEL_ELEMENTS + "\n";
        preProcessorPreamble += "#define SSAO_NOISE_SIZE " + SSAO_NOISE_SIZE + "\n";
        // TODO: This shouldn't be hardcoded
        preProcessorPreamble += "#define TEXTURE_OFFSET_EFFECTS " + 0.0625f + "\n";

        StringBuilder builder = new StringBuilder().append(preProcessorPreamble);
        if (renderConfig.isVolumetricFog()) {
            builder.append("#define VOLUMETRIC_FOG \n");
        }

        if (renderConfig.isAnimateGrass()) {
            builder.append("#define ANIMATED_GRASS \n");
        }
        if (renderConfig.isAnimateWater()) {
            builder.append("#define ANIMATED_WATER \n");
        }
        if (renderConfig.getBlurIntensity() == 0) {
            builder.append("#define NO_BLUR \n");
        }
        if (renderConfig.isFlickeringLight()) {
            builder.append("#define FLICKERING_LIGHT \n");
        }
        if (renderConfig.isVignette()) {
            builder.append("#define VIGNETTE \n");
        }
        if (renderConfig.isBloom()) {
            builder.append("#define BLOOM \n");
        }
        if (renderConfig.isMotionBlur()) {
            builder.append("#define MOTION_BLUR \n");
        }
        if (renderConfig.isSsao()) {
            builder.append("#define SSAO \n");
        }
        if (renderConfig.isFilmGrain()) {
            builder.append("#define FILM_GRAIN \n");
        }
        if (renderConfig.isOutline()) {
{'fraction_non_alphanumeric': 0.09717271051014137, 'fraction_numerical': 0.004671173939766442, 'mean_word_length': 3.5859639233370912, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5136961', 'n_tokens_mistral': 4674, 'n_tokens_neox': 4521, 'n_words': 938}