package client.renderer;

import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;

import client.Client;
import client.renderer.chunk.ChunkRenderDispatcher;
import client.renderer.chunk.CompiledChunk;
import client.renderer.chunk.RenderChunk;
import client.renderer.chunk.VisGraph;
import client.renderer.entity.RenderManager;
import client.renderer.texture.TextureAtlasSprite;
import client.renderer.texture.TextureManager;
import client.renderer.texture.TextureMap;
import client.renderer.tileentity.TileEntityRendererDispatcher;
import client.world.ChunkClient;
import client.world.WorldClient;
import common.block.Block;
import common.block.tech.BlockChest;
import common.block.tile.BlockSign;
import common.collect.Lists;
import common.collect.Maps;
import common.collect.Sets;
import common.entity.Entity;
import common.entity.npc.EntityNPC;
import common.entity.projectile.EntityBox;
import common.entity.types.EntityLiving;
import common.init.Blocks;
import common.model.BlockLayer;
import common.rng.Random;
import common.sound.Sound;
import common.tileentity.TileEntity;
import common.tileentity.TileEntityChest;
import common.util.BlockPos;
import common.util.BoundingBox;
import common.util.InheritanceMultiMap;
import common.util.ExtMath;
import common.util.Facing;
import common.util.HitPosition;
import common.util.Vec3;
import common.util.Vector3f;
import common.world.State;
import common.world.World;

public class RenderGlobal
{
	private class ContainerLocalRenderInformation
    {
        final RenderChunk renderChunk;
        final Facing facing;
        final Set<Facing> setFacing;
        final int counter;

        private ContainerLocalRenderInformation(RenderChunk renderChunkIn, Facing facingIn, int counterIn)
        {
            this.setFacing = EnumSet.<Facing>noneOf(Facing.class);
            this.renderChunk = renderChunkIn;
            this.facing = facingIn;
            this.counter = counterIn;
        }
    }
	
	private static class DestroyBlockProgress {
		private final int id;
		private final BlockPos pos;

		private int progress;
		private int time;

		public DestroyBlockProgress(int id, BlockPos pos) {
			this.id = id;
			this.pos = pos;
		}

		public BlockPos getPosition() {
			return this.pos;
		}

		public void setPartialBlockDamage(int damage) {
			if(damage > 10) {
				damage = 10;
			}

			this.progress = damage;
		}

		public int getPartialBlockDamage() {
			return this.progress;
		}

		public void setTime(int time) {
			this.time = time;
		}

		public int getTime() {
			return this.time;
		}
	}
	
    private static final String MOON_TEX = "textures/world/moon_phases.png";
    private static final String SUN_TEX = "textures/world/sun.png";
	private static final float[] SUN_COLOR = new float[4];
	
    private final Client gm;
    private final TextureManager renderEngine;
    private final RenderManager renderManager;
    private WorldClient theWorld;
    private Set<RenderChunk> chunksToUpdate = new LinkedHashSet<RenderChunk>();
    private List<RenderGlobal.ContainerLocalRenderInformation> renderInfos = new ArrayList<ContainerLocalRenderInformation>(69696);
    private final Set<TileEntity> setTileEntities = Sets.<TileEntity>newHashSet();
    private ViewFrustum viewFrustum;
    private VertexFormat vertexBufferFormat;
    private VertexBuffer starVBO;
    private VertexBuffer dstarVBO;
    private VertexBuffer skyVBO;
    private VertexBuffer sky2VBO;
    private int cloudTickCounter;
    private final Map<Integer, DestroyBlockProgress> damagedBlocks = Maps.<Integer, DestroyBlockProgress>newHashMap();
    private final Map<BlockPos, Sound> mapSoundPositions = Maps.<BlockPos, Sound>newHashMap();
    private final TextureAtlasSprite[] destroyBlockIcons = new TextureAtlasSprite[10];
    private double frustumUpdatePosX = Double.MIN_VALUE;
    private double frustumUpdatePosY = Double.MIN_VALUE;
    private double frustumUpdatePosZ = Double.MIN_VALUE;
    private int frustumUpdatePosChunkX = Integer.MIN_VALUE;
    private int frustumUpdatePosChunkY = Integer.MIN_VALUE;
    private int frustumUpdatePosChunkZ = Integer.MIN_VALUE;
    private double lastViewEntityX = Double.MIN_VALUE;
    private double lastViewEntityY = Double.MIN_VALUE;
    private double lastViewEntityZ = Double.MIN_VALUE;
    private double lastViewEntityPitch = Double.MIN_VALUE;
    private double lastViewEntityYaw = Double.MIN_VALUE;
    private final ChunkRenderDispatcher renderDispatcher = new ChunkRenderDispatcher();
    private double viewEntityX;
    private double viewEntityY;
    private double viewEntityZ;
    private List<RenderChunk> renderChunks = new ArrayList<RenderChunk>(17424);
    private boolean initialized;
    private int renderDistanceChunks = -1;
    private int renderEntitiesStartupCounter = 2;
    private int countEntitiesTotal;
    private int countEntitiesRendered;
    private int countEntitiesHidden;
    private double prevRenderSortX;
    private double prevRenderSortY;
    private double prevRenderSortZ;
    private boolean displayListEntitiesDirty = true;

    public RenderGlobal(Client gmIn)
    {
        this.gm = gmIn;
        this.renderManager = gmIn.getRenderManager();
        this.renderEngine = gmIn.getTextureManager();
        GlState.bindTexture(0);
        this.updateDestroyBlockIcons();

        this.vertexBufferFormat = new VertexFormat();
        this.vertexBufferFormat.addElement(new VertexFormatElement(0, VertexFormatElement.EnumType.FLOAT, VertexFormatElement.EnumUsage.POSITION, 3));
        this.generateStars();
        this.generateDeepStars();
        this.generateSky();
        this.generateSky2();
    }

    public void onReload()
    {
        this.updateDestroyBlockIcons();
    }

    private void updateDestroyBlockIcons()
    {
        TextureMap texturemap = this.gm.getTextureMapBlocks();

        for (int i = 0; i < this.destroyBlockIcons.length; ++i)
        {
            this.destroyBlockIcons[i] = texturemap.getAtlasSprite("blocks/destroy_stage_" + i);
        }
    }

    private void generateSky2()
    {
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();

        if (this.sky2VBO != null)
        {
            this.sky2VBO.deleteGlBuffers();
        }

//        if (this.glSkyList2 >= 0)
//        {
//            GLAllocation.deleteDisplayLists(this.glSkyList2);
//            this.glSkyList2 = -1;
//        }

//        if (this.vboEnabled)
//        {
            this.sky2VBO = new VertexBuffer(this.vertexBufferFormat);
            this.renderSky(worldrenderer, -16.0F, true);
            worldrenderer.finishDrawing();
            worldrenderer.reset();
            this.sky2VBO.bufferData(worldrenderer.getByteBuffer());
//        }
//        else
//        {
//            this.glSkyList2 = GLAllocation.generateDisplayLists(1);
//            SKC.glNewList(this.glSkyList2, SKC.GL_COMPILE);
//            this.renderSky(worldrenderer, -16.0F, true);
//            tessellator.draw();
//            SKC.glEndList();
//        }
    }

    private void generateSky()
    {
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();

        if (this.skyVBO != null)
        {
            this.skyVBO.deleteGlBuffers();
        }

//        if (this.glSkyList >= 0)
//        {
//            GLAllocation.deleteDisplayLists(this.glSkyList);
//            this.glSkyList = -1;
//        }

//        if (this.vboEnabled)
//        {
            this.skyVBO = new VertexBuffer(this.vertexBufferFormat);
            this.renderSky(worldrenderer, 16.0F, false);
            worldrenderer.finishDrawing();
            worldrenderer.reset();
            this.skyVBO.bufferData(worldrenderer.getByteBuffer());
//        }
//        else
//        {
//            this.glSkyList = GLAllocation.generateDisplayLists(1);
//            SKC.glNewList(this.glSkyList, SKC.GL_COMPILE);
//            this.renderSky(worldrenderer, 16.0F, false);
//            tessellator.draw();
//            SKC.glEndList();
//        }
    }

    private void renderSky(RenderBuffer worldRendererIn, float posY, boolean reverseX)
    {
        int i = 64;
        int j = 6;
        worldRendererIn.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION);

        for (int k = -384; k <= 384; k += 64)
        {
            for (int l = -384; l <= 384; l += 64)
            {
                float f = (float)k;
                float f1 = (float)(k + 64);

                if (reverseX)
                {
                    f1 = (float)k;
                    f = (float)(k + 64);
                }

                worldRendererIn.pos((double)f, (double)posY, (double)l).endVertex();
                worldRendererIn.pos((double)f1, (double)posY, (double)l).endVertex();
                worldRendererIn.pos((double)f1, (double)posY, (double)(l + 64)).endVertex();
                worldRendererIn.pos((double)f, (double)posY, (double)(l + 64)).endVertex();
            }
        }
    }

    private void generateStars()
    {
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();

        if (this.starVBO != null)
        {
            this.starVBO.deleteGlBuffers();
        }

//        if (this.starGLCallList >= 0)
//        {
//            GLAllocation.deleteDisplayLists(this.starGLCallList);
//            this.starGLCallList = -1;
//        }

//        if (this.vboEnabled)
//        {
            this.starVBO = new VertexBuffer(this.vertexBufferFormat);
            this.renderStars(worldrenderer, 10842L, 1500, 0.15f, 0.25f);
            worldrenderer.finishDrawing();
            worldrenderer.reset();
            this.starVBO.bufferData(worldrenderer.getByteBuffer());
//        }
//        else
//        {
//            this.starGLCallList = GLAllocation.generateDisplayLists(1);
//            GlState.pushMatrix();
//            SKC.glNewList(this.starGLCallList, SKC.GL_COMPILE);
//            this.renderStars(worldrenderer, 10842L, 1500, 0.15f, 0.25f);
//            tessellator.draw();
//            SKC.glEndList();
//            GlState.popMatrix();
//        }
    }

    private void generateDeepStars()
    {
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();

        if (this.dstarVBO != null)
        {
            this.dstarVBO.deleteGlBuffers();
        }

//        if (this.dstarGLCallList >= 0)
//        {
//            GLAllocation.deleteDisplayLists(this.dstarGLCallList);
//            this.dstarGLCallList = -1;
//        }

//        if (this.vboEnabled)
//        {
            this.dstarVBO = new VertexBuffer(this.vertexBufferFormat);
            this.renderStars(worldrenderer, 0x59616f69L, 5000, 0.025f, 0.15f);
            worldrenderer.finishDrawing();
            worldrenderer.reset();
            this.dstarVBO.bufferData(worldrenderer.getByteBuffer());
//        }
//        else
//        {
//            this.dstarGLCallList = GLAllocation.generateDisplayLists(1);
//            GlState.pushMatrix();
//            SKC.glNewList(this.dstarGLCallList, SKC.GL_COMPILE);
//            this.renderStars(worldrenderer, 0x59616f69L, 5000, 0.025f, 0.15f);
//            tessellator.draw();
//            SKC.glEndList();
//            GlState.popMatrix();
//        }
    }

    private void renderStars(RenderBuffer rend, long seed, int nstars, float min, float max)
    {
    	max -= min;
        Random rand = new Random(seed);
        rend.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION);

        for (int n = 0; n < nstars; ++n)
        {
            double x = (double)(rand.floatv() * 2.0F - 1.0F);
            double y = (double)(rand.floatv() * 2.0F - 1.0F);
            double z = (double)(rand.floatv() * 2.0F - 1.0F);
            double size = (double)(min + rand.floatv() * max);
            double dist = x * x + y * y + z * z;

            if (dist < 1.0D && dist > 0.01D)
            {
                dist = 1.0D / Math.sqrt(dist);
                x = x * dist;
                y = y * dist;
                z = z * dist;
                double xm = x * 100.0D;
                double ym = y * 100.0D;
                double zm = z * 100.0D;
                double axz = Math.atan2(x, z);
                double sxz = Math.sin(axz);
                double cxz = Math.cos(axz);
                double ahz = Math.atan2(Math.sqrt(x * x + z * z), y);
                double shz = Math.sin(ahz);
                double chz = Math.cos(ahz);
                double arn = rand.doublev() * Math.PI * 2.0D;
                double shn = Math.sin(arn);
                double chn = Math.cos(arn);

                for (int v = 0; v < 4; ++v)
                {
//                    double d17 = 0.0D;
                    double sa = (double)((v & 2) - 1) * size;
                    double sb = (double)((v + 1 & 2) - 1) * size;
//                    double d20 = 0.0D;
                    double ra = sa * chn - sb * shn;
                    double rb = sb * chn + sa * shn;
                    double yo = ra * shz + 0.0D * chz;
                    double rot = 0.0D * shz - ra * chz;
                    double xo = rot * sxz - rb * cxz;
                    double zo = rb * sxz + rot * cxz;
                    rend.pos(xm + xo, ym + yo, zm + zo).endVertex();
                }
            }
        }
    }

    /**
     * set null to clear
     */
    public void setWorldAndLoadRenderers(WorldClient worldClientIn)
    {
//        if (this.theWorld != null)
//        {
//            this.theWorld.setWorldAccess(null);
//        }

        this.frustumUpdatePosX = Double.MIN_VALUE;
        this.frustumUpdatePosY = Double.MIN_VALUE;
        this.frustumUpdatePosZ = Double.MIN_VALUE;
        this.frustumUpdatePosChunkX = Integer.MIN_VALUE;
        this.frustumUpdatePosChunkY = Integer.MIN_VALUE;
        this.frustumUpdatePosChunkZ = Integer.MIN_VALUE;
        this.renderManager.set(worldClientIn);
        this.theWorld = worldClientIn;

        if (worldClientIn != null)
        {
//            worldClientIn.setWorldAccess(this);
            this.loadRenderers();
        }
    }

    /**
     * Loads all the renderers and sets up the basic settings usage
     */
    public void loadRenderers()
    {
        if (this.theWorld != null)
        {
            this.displayListEntitiesDirty = true;
            
            this.renderDistanceChunks = this.gm.renderDistance;

            if (this.viewFrustum != null)
            {
                this.viewFrustum.deleteGlResources();
            }

            this.stopChunkUpdates();

            synchronized (this.setTileEntities)
            {
                this.setTileEntities.clear();
            }

            this.viewFrustum = new ViewFrustum(this.theWorld, this.gm.renderDistance, this);

            if (this.theWorld != null)
            {
                Entity entity = this.gm.getRenderViewEntity();

                if (entity != null)
                {
                    this.viewFrustum.updateChunkPositions(entity.posX, entity.posY, entity.posZ);
                }
            }

            this.renderEntitiesStartupCounter = 2;
        }
    }
    
    public void stopChunkBuilders() {
    	this.renderDispatcher.kill();
    }

    protected void stopChunkUpdates()
    {
        this.chunksToUpdate.clear();
        this.renderDispatcher.stopChunkUpdates();
    }

    public void renderEntities(Entity renderViewEntity, float partialTicks)
    {
        if (this.renderEntitiesStartupCounter > 0)
        {
            --this.renderEntitiesStartupCounter;
        }
        else
        {
            double d0 = renderViewEntity.prevX + (renderViewEntity.posX - renderViewEntity.prevX) * (double)partialTicks;
            double d1 = renderViewEntity.prevY + (renderViewEntity.posY - renderViewEntity.prevY) * (double)partialTicks;
            double d2 = renderViewEntity.prevZ + (renderViewEntity.posZ - renderViewEntity.prevZ) * (double)partialTicks;
            TileEntityRendererDispatcher.instance.cacheActiveRenderInfo(this.theWorld, this.gm.getTextureManager(), this.gm.getRenderViewEntity(), partialTicks);
            this.renderManager.cacheActiveRenderInfo(this.theWorld, this.gm.getRenderViewEntity(), this.gm.getPointedEntity(), this.gm, partialTicks);
            this.countEntitiesTotal = 0;
            this.countEntitiesRendered = 0;
            this.countEntitiesHidden = 0;
            Entity entity = this.gm.getRenderViewEntity();
            double d3 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double)partialTicks;
            double d4 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double)partialTicks;
            double d5 = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double)partialTicks;
            TileEntityRendererDispatcher.staticPlayerX = d3;
            TileEntityRendererDispatcher.staticPlayerY = d4;
            TileEntityRendererDispatcher.staticPlayerZ = d5;
            this.renderManager.setRenderPosition(d3, d4, d5);
            this.gm.entityRenderer.enableLightmap();
            List<Entity> list = this.theWorld.getLoadedEntityList();
            this.countEntitiesTotal = list.size();

            for (int i = 0; i < this.theWorld.effects.size(); ++i)
            {
                Entity entity1 = (Entity)this.theWorld.effects.get(i);
                ++this.countEntitiesRendered;

                if (entity1.isInRangeToRender3d(d0, d1, d2))
                {
                    this.renderManager.renderEntity(entity1, partialTicks);
                }
            }

            if (this.gm.tileOverlay)
            {
                GlState.depthFunc(GL11.GL_ALWAYS);
                GlState.disableFog();
                ItemRenderer.disableStandardItemLighting();
                GlState.enableBlend();
                GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
                GL11.glLineWidth(2.0F);
                GlState.disableTexture2D();
                GlState.depthMask(false);

                List<TileEntity> tiles = this.theWorld.getLoadedTileList();
                
                for (int j = 0; j < tiles.size(); ++j)
                {
                	TileEntity te = tiles.get(j);
                	BoundingBox bb = new BoundingBox(te.getPos(), te.getPos().add(1, 1, 1));
                    if(Frustum.isInFrustum(bb))
                    {
                    	int c = te.getColor();
                    	float r = (float)(c >> 16 & 255) / 255.0F;
                    	float g = (float)(c >> 8 & 255) / 255.0F;
                    	float b = (float)(c & 255) / 255.0F;
                        GlState.color(r, g, b, 0.8F);
                        drawSelectionBoundingBox(bb.offset(-d0, -d1, -d2));
                    }
                }
                
                ItemRenderer.enableStandardItemLighting();
                GlState.enableTexture2D();
//                GlState.depthMask(false);
                GlState.enableLighting();
                GlState.depthMask(true);
                GlState.enableFog();
                GlState.enableColorMaterial();
                GlState.depthFunc(GL11.GL_LEQUAL);
                GlState.enableDepth();
                GlState.enableAlpha();
            }

            if (this.gm.renderOutlines && this.gm.player != null)
            {
                GlState.depthFunc(GL11.GL_ALWAYS);
                GlState.disableFog();
                ItemRenderer.disableStandardItemLighting();
                GlState.enableBlend();
                GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
                GL11.glLineWidth(2.0F);
                GlState.disableTexture2D();
                GlState.depthMask(false);

                for (int j = 0; j < list.size(); ++j)
                {
                    Entity entity3 = list.get(j);
                    if ((entity3 != this.gm.getRenderViewEntity() || this.gm.thirdPersonView != 0) && 
                    		entity3 instanceof EntityLiving && entity3.isInRangeToRender3d(d0, d1, d2) && (entity3.noFrustumCheck || Frustum.isInFrustum(entity3.getEntityBoundingBox()) || entity3.passenger == this.gm.player))
                    {
//                        this.renderManager.renderEntity(entity3, partialTicks);
                    	int c = ((EntityLiving)entity3).getColor();
                    	float r = (float)(c >> 16 & 255) / 255.0F;
                    	float g = (float)(c >> 8 & 255) / 255.0F;
                    	float b = (float)(c & 255) / 255.0F;
                        GlState.color(r, g, b, 0.8F);
                        drawSelectionBoundingBox(entity3.getEntityBoundingBox().offset(-d0, -d1, -d2));
                    }
                }
                
                ItemRenderer.enableStandardItemLighting();
                GlState.enableTexture2D();
//                GlState.depthMask(false);
                GlState.enableLighting();
                GlState.depthMask(true);
                GlState.enableFog();
                GlState.enableColorMaterial();
                GlState.depthFunc(GL11.GL_LEQUAL);
                GlState.enableDepth();
                GlState.enableAlpha();
            }
            
            label738:

            for (RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation : this.renderInfos)
            {
            	ChunkClient chunk = this.theWorld.getChunk(renderglobal$containerlocalrenderinformation.renderChunk.getPosition());
                InheritanceMultiMap<Entity> classinheritancemultimap = chunk.getEntities()[ExtMath.clampi(renderglobal$containerlocalrenderinformation.renderChunk.getPosition().getY() / 16, 0, 31)];

                if (!classinheritancemultimap.isEmpty())
                {
                    Iterator iterator = classinheritancemultimap.iterator();

                    while (true)
                    {
                        Entity entity2;
                        boolean flag2;

                        while (true)
                        {
                            if (!iterator.hasNext())
                            {
                                continue label738;
                            }

                            entity2 = (Entity)iterator.next();
                            flag2 = this.renderManager.shouldRender(entity2, d0, d1, d2) || entity2.passenger == this.gm.player;

                            if (!flag2)
                            {
                                break;
                            }

//                            boolean flag3 = this.gm.getRenderViewEntity() instanceof EntityLivingBase ? ((EntityLivingBase)this.gm.getRenderViewEntity()).isPlayerSleeping() : false;

                            if (entity2.posY < (double)(-World.MAX_SIZE_Y) || entity2.posY >= (double)World.MAX_SIZE_Y || this.theWorld.isBlockLoaded(new BlockPos(entity2)))
                            {
                            	if((entity2 != this.gm.getRenderViewEntity() || this.gm.thirdPersonView != 0 /* || flag3 */)) {
	                                ++this.countEntitiesRendered;
	                                this.renderManager.renderEntity(entity2, partialTicks);
                            	}
                            	else {
                            		this.renderManager.renderBox(entity2, partialTicks);
                            	}
                                break;
                            }
                        }

                        if (!flag2 && entity2 instanceof EntityBox)
                        {
                            this.gm.getRenderManager().renderFloatingBox(entity2, partialTicks);
                        }
                    }
                }
            }
            
            ItemRenderer.enableStandardItemLighting();

            for (RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation1 : this.renderInfos)
            {
                List<TileEntity> list1 = renderglobal$containerlocalrenderinformation1.renderChunk.getCompiledChunk().getTileEntities();

                if (!list1.isEmpty())
                {
                    for (TileEntity tileentity2 : list1)
                    {
                        TileEntityRendererDispatcher.instance.renderTileEntity(tileentity2, partialTicks, -1);
                    }
                }
            }

            synchronized (this.setTileEntities)
            {
                for (TileEntity tileentity : this.setTileEntities)
                {
                    TileEntityRendererDispatcher.instance.renderTileEntity(tileentity, partialTicks, -1);
                }
            }

            this.preRenderDamagedBlocks();

            for (DestroyBlockProgress destroyblockprogress : this.damagedBlocks.values())
            {
                BlockPos blockpos = destroyblockprogress.getPosition();
                TileEntity tileentity1 = this.theWorld.getTileEntity(blockpos);

                if (tileentity1 instanceof TileEntityChest)
                {
                    TileEntityChest tileentitychest = (TileEntityChest)tileentity1;

                    if (tileentitychest.adjacentChestXNeg != null)
                    {
                        blockpos = blockpos.offset(Facing.WEST);
                        tileentity1 = this.theWorld.getTileEntity(blockpos);
                    }
                    else if (tileentitychest.adjacentChestZNeg != null)
                    {
                        blockpos = blockpos.offset(Facing.NORTH);
                        tileentity1 = this.theWorld.getTileEntity(blockpos);
                    }
                }

                Block block = this.theWorld.getState(blockpos).getBlock();

                if (tileentity1 != null && (block instanceof BlockChest || block instanceof BlockSign))
                {
                    TileEntityRendererDispatcher.instance.renderTileEntity(tileentity1, partialTicks, destroyblockprogress.getPartialBlockDamage());
                }
            }

            this.postRenderDamagedBlocks();
            this.gm.entityRenderer.disableLightmap();
        }
    }

    /**
     * Gets the render info for use on the Debug screen
     */
    public String getDebugInfoRenders()
    {
        int i = this.viewFrustum.renderChunks.length;
        int j = 0;

        for (RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation : this.renderInfos)
        {
            CompiledChunk compiledchunk = renderglobal$containerlocalrenderinformation.renderChunk.compiledChunk;

            if (compiledchunk != CompiledChunk.DUMMY && !compiledchunk.isEmpty())
            {
                ++j;
            }
        }

        return String.format("Chunks: %d/%d (%d Chunk-Update%s) D: %d, %s", j, i, this.gm.chunksUpdated, this.gm.chunksUpdated != 1 ? "s" : "", 
        		/* this.gm.renderChunksMany ? "(s) " : "", */ this.renderDistanceChunks, this.renderDispatcher.getDebugInfo());
    }

    /**
     * Gets the entities info for use on the Debug screen
     */
    public String getDebugInfoEntities()
    {
        return "Objekte: " + this.countEntitiesRendered + "/" + this.countEntitiesTotal + ", V: " + this.countEntitiesHidden + ", I: " + (this.countEntitiesTotal - this.countEntitiesHidden - this.countEntitiesRendered);
    }

    public void setupTerrain(Entity viewEntity, double partialTicks, int frameCount, boolean playerSpectator)
    {
        if (this.gm.renderDistance != this.renderDistanceChunks)
        {
            this.loadRenderers();
        }
        double d0 = viewEntity.posX - this.frustumUpdatePosX;
        double d1 = viewEntity.posY - this.frustumUpdatePosY;
        double d2 = viewEntity.posZ - this.frustumUpdatePosZ;
        int prev = this.frustumUpdatePosChunkY;

        if (this.frustumUpdatePosChunkX != viewEntity.chunkCoordX || this.frustumUpdatePosChunkY != viewEntity.chunkCoordY || this.frustumUpdatePosChunkZ != viewEntity.chunkCoordZ || d0 * d0 + d1 * d1 + d2 * d2 > 16.0D)
        {
            this.frustumUpdatePosX = viewEntity.posX;
            this.frustumUpdatePosY = viewEntity.posY;
            this.frustumUpdatePosZ = viewEntity.posZ;
            this.frustumUpdatePosChunkX = viewEntity.chunkCoordX;
            this.frustumUpdatePosChunkY = viewEntity.chunkCoordY;
            this.frustumUpdatePosChunkZ = viewEntity.chunkCoordZ;
            this.viewFrustum.updateChunkPositions(viewEntity.posX, viewEntity.posY, viewEntity.posZ);
        }
        double d3 = viewEntity.lastTickPosX + (viewEntity.posX - viewEntity.lastTickPosX) * partialTicks;
        double d4 = viewEntity.lastTickPosY + (viewEntity.posY - viewEntity.lastTickPosY) * partialTicks;
        double d5 = viewEntity.lastTickPosZ + (viewEntity.posZ - viewEntity.lastTickPosZ) * partialTicks;
        this.initialize(d3, d4, d5);
        BlockPos blockpos1 = new BlockPos(d3, d4 + (double)viewEntity.getEyeHeight(), d5);
        RenderChunk renderchunk = this.viewFrustum.getRenderChunk(blockpos1);
        BlockPos blockpos = new BlockPos(ExtMath.floord(d3 / 16.0D) * 16, ExtMath.floord(d4 / 16.0D) * 16, ExtMath.floord(d5 / 16.0D) * 16);
        this.displayListEntitiesDirty = this.displayListEntitiesDirty || !this.chunksToUpdate.isEmpty() || viewEntity.posX != this.lastViewEntityX || viewEntity.posY != this.lastViewEntityY || viewEntity.posZ != this.lastViewEntityZ || (double)viewEntity.rotPitch != this.lastViewEntityPitch || (double)viewEntity.rotYaw != this.lastViewEntityYaw;
        this.lastViewEntityX = viewEntity.posX;
        this.lastViewEntityY = viewEntity.posY;
        this.lastViewEntityZ = viewEntity.posZ;
        this.lastViewEntityPitch = (double)viewEntity.rotPitch;
        this.lastViewEntityYaw = (double)viewEntity.rotYaw;
//        boolean flag = this.debugFixedClippingHelper != null;

        if (/* !flag && */ this.displayListEntitiesDirty)
        {
            this.displayListEntitiesDirty = false;
            this.renderInfos = Lists.<RenderGlobal.ContainerLocalRenderInformation>newArrayList();
            Queue<RenderGlobal.ContainerLocalRenderInformation> queue = new LinkedList<ContainerLocalRenderInformation>();
            boolean vision = true; // this.gm.renderChunksMany;

            if (renderchunk != null)
            {
                boolean flag2 = false;
                RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation3 = new RenderGlobal.ContainerLocalRenderInformation(renderchunk, (Facing)null, 0);
                Set<Facing> set1 = this.getVisibleFacings(blockpos1);

                if (set1.size() == 1)
                {
                    Vector3f vector3f = this.getViewVector(viewEntity, partialTicks);
                    Facing enumfacing = Facing.getFacingFromVector(vector3f.x, vector3f.y, vector3f.z).getOpposite();
                    set1.remove(enumfacing);
                }

                if (set1.isEmpty())
                {
                    flag2 = true;
                }

                if (flag2 && !playerSpectator)
                {
                    this.renderInfos.add(renderglobal$containerlocalrenderinformation3);
                }
                else
                {
                    if (playerSpectator && this.theWorld.getState(blockpos1).getBlock().isOpaqueCube())
                    {
                        vision = false;
                    }

                    renderchunk.setFrameIndex(frameCount);
                    queue.add(renderglobal$containerlocalrenderinformation3);
                }
            }
            else
            {
//                int i = blockpos1.getY() > 0 ? 248 : 8;
//                int i = blockpos1.getY() > 0 ? 504 : 8;

                for (int j = -this.renderDistanceChunks; j <= this.renderDistanceChunks; ++j)
                {
                    for (int k = -this.renderDistanceChunks; k <= this.renderDistanceChunks; ++k)
                    {
                        for (int i = -this.renderDistanceChunks; i <= this.renderDistanceChunks; ++i)
                        {
	                        RenderChunk renderchunk1 = this.viewFrustum.getRenderChunk(new BlockPos((j << 4) + 8, (i << 4) + 8, (k << 4) + 8));
	
	                        if (renderchunk1 != null && Frustum.isInFrustum(renderchunk1.boundingBox))
	                        {
	                            renderchunk1.setFrameIndex(frameCount);
	                            queue.add(new RenderGlobal.ContainerLocalRenderInformation(renderchunk1, (Facing)null, 0));
	                        }
                        }
                    }
                }
            }
            
//            int n = queue.size();
//            Log.RENDER.info("** " + n + " render");

            while (!((Queue)queue).isEmpty())
            {
                RenderGlobal.ContainerLocalRenderInformation render1 = (RenderGlobal.ContainerLocalRenderInformation)queue.poll();
                RenderChunk chunk1 = render1.renderChunk;
                Facing face1 = this.gm.xrayActive ? null : render1.facing;
                BlockPos pos1 = chunk1.getPosition();
                this.renderInfos.add(render1);

                for (Facing face2 : Facing.values())
                {
                    RenderChunk chunk2 = this.getRenderChunkOffset(blockpos, chunk1, face2);

                    if ((!vision || !render1.setFacing.contains(face2.getOpposite())) 
                    		&& (!vision || face1 == null || chunk1.getCompiledChunk().isVisible(face1.getOpposite(), face2)) 
                    		&& chunk2 != null && chunk2.setFrameIndex(frameCount) && Frustum.isInFrustum(chunk2.boundingBox))
                    {
                        RenderGlobal.ContainerLocalRenderInformation render2 = 
                        		new RenderGlobal.ContainerLocalRenderInformation(chunk2, face2, render1.counter + 1);
                        render2.setFacing.addAll(render1.setFacing);
                        render2.setFacing.add(face2);
                        queue.add(render2);
//                        n++;
                    }
                }
            }
            
//            Log.RENDER.info("+ " + n + " render");
        }

//        if (this.debugFixTerrainFrustum)
//        {
//            this.fixTerrainFrustum(d3, d4, d5);
//            this.debugFixTerrainFrustum = false;
//        }

        this.renderDispatcher.clearChunkUpdates();
        Set<RenderChunk> set = this.chunksToUpdate;
        this.chunksToUpdate = new LinkedHashSet<RenderChunk>();

        for (RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation2 : this.renderInfos)
        {
            RenderChunk renderchunk4 = renderglobal$containerlocalrenderinformation2.renderChunk;

            if (renderchunk4.isNeedsUpdate() || set.contains(renderchunk4))
            {
                this.displayListEntitiesDirty = true;

                if (this.isPositionInRenderChunk(blockpos, renderglobal$containerlocalrenderinformation2.renderChunk))
                {
                    this.renderDispatcher.updateChunkNow(renderchunk4);
                    renderchunk4.setNeedsUpdate(false);
                }
                else
                {
                    this.chunksToUpdate.add(renderchunk4);
                }
            }
        }

        this.chunksToUpdate.addAll(set);
        
    	if(prev != Integer.MIN_VALUE && viewEntity.chunkCoordY != prev) {
    		for (int j = -this.renderDistanceChunks; j <= this.renderDistanceChunks; ++j)
            {
                for (int k = -this.renderDistanceChunks; k <= this.renderDistanceChunks; ++k)
                {
                    for (int i = -this.renderDistanceChunks; i <= this.renderDistanceChunks; ++i)
                    {
                        RenderChunk renderchunk1 = this.viewFrustum.getRenderChunk(new BlockPos((j << 4) + 8, (i << 4) + 8, (k << 4) + 8));

                        if (renderchunk1 != null)
                        {
                            renderchunk1.setNeedsUpdate(true);
                        }
                    }
                }
            }
    	}
    }

    private boolean isPositionInRenderChunk(BlockPos pos, RenderChunk renderChunkIn)
    {
        BlockPos blockpos = renderChunkIn.getPosition();
        return ExtMath.absi(pos.getX() - blockpos.getX()) > 16 ? false : (ExtMath.absi(pos.getY() - blockpos.getY()) > 16 ? false : ExtMath.absi(pos.getZ() - blockpos.getZ()) <= 16);
    }

    private Set<Facing> getVisibleFacings(BlockPos pos)
    {
        VisGraph visgraph = new VisGraph();
        BlockPos blockpos = new BlockPos(pos.getX() >> 4 << 4, pos.getY() >> 4 << 4, pos.getZ() >> 4 << 4);
        ChunkClient chunk = this.theWorld.getChunk(blockpos);

        for (BlockPos.MutableBlockPos blockpos$mutableblockpos : BlockPos.getAllInBoxMutable(blockpos, blockpos.add(15, 15, 15)))
        {
            if (chunk.getBlock(blockpos$mutableblockpos).isOpaqueCube())
            {
                visgraph.func_178606_a(blockpos$mutableblockpos);
            }
        }
        return visgraph.func_178609_b(pos);
    }

    /**
     * Returns RenderChunk offset from given RenderChunk in given direction, or null if it can't be seen by player at
     * given BlockPos.
     */
    private RenderChunk getRenderChunkOffset(BlockPos playerPos, RenderChunk renderChunkBase, Facing facing)
    {
        BlockPos blockpos = renderChunkBase.getBlockPosOffset16(facing);
        return ExtMath.absi(playerPos.getX() - blockpos.getX()) > this.renderDistanceChunks * 16 ? null : (ExtMath.absi(playerPos.getY() - blockpos.getY()) <= this.renderDistanceChunks * 16 ? (ExtMath.absi(playerPos.getZ() - blockpos.getZ()) > this.renderDistanceChunks * 16 ? null : this.viewFrustum.getRenderChunk(blockpos)) : null);
    }

    protected Vector3f getViewVector(Entity entityIn, double partialTicks)
    {
        float f = (float)((double)entityIn.prevPitch + (double)(entityIn.rotPitch - entityIn.prevPitch) * partialTicks);
        float f1 = (float)((double)entityIn.prevYaw + (double)(entityIn.rotYaw - entityIn.prevYaw) * partialTicks);

        if (Client.CLIENT.thirdPersonView == 2)
        {
            f += 180.0F;
        }

        float f2 = ExtMath.cos(-f1 * 0.017453292F - (float)Math.PI);
        float f3 = ExtMath.sin(-f1 * 0.017453292F - (float)Math.PI);
        float f4 = -ExtMath.cos(-f * 0.017453292F);
        float f5 = ExtMath.sin(-f * 0.017453292F);
        return new Vector3f(f3 * f4, f5, f2 * f4);
    }

    public int renderBlockLayer(BlockLayer blockLayerIn, double partialTicks, Entity entityIn)
    {
        ItemRenderer.disableStandardItemLighting();

        if (blockLayerIn == BlockLayer.TRANSLUCENT)
        {
            double d0 = entityIn.posX - this.prevRenderSortX;
            double d1 = entityIn.posY - this.prevRenderSortY;
            double d2 = entityIn.posZ - this.prevRenderSortZ;

            if (d0 * d0 + d1 * d1 + d2 * d2 > 1.0D)
            {
                this.prevRenderSortX = entityIn.posX;
                this.prevRenderSortY = entityIn.posY;
                this.prevRenderSortZ = entityIn.posZ;
                int k = 0;

                for (RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation : this.renderInfos)
                {
                    if (renderglobal$containerlocalrenderinformation.renderChunk.compiledChunk.isLayerStarted(blockLayerIn) && k++ < 15)
                    {
                        this.renderDispatcher.updateTransparencyLater(renderglobal$containerlocalrenderinformation.renderChunk);
                    }
                }
            }
        }
        int l = 0;
        boolean flag = blockLayerIn == BlockLayer.TRANSLUCENT;
        int i1 = flag ? this.renderInfos.size() - 1 : 0;
        int i = flag ? -1 : this.renderInfos.size();
        int j1 = flag ? -1 : 1;

        for (int j = i1; j != i; j += j1)
        {
            RenderChunk renderchunk = ((RenderGlobal.ContainerLocalRenderInformation)this.renderInfos.get(j)).renderChunk;

            if (!renderchunk.getCompiledChunk().isLayerEmpty(blockLayerIn))
            {
                ++l;
                this.addRenderChunk(renderchunk, blockLayerIn);
            }
        }
        this.renderBlockLayer(blockLayerIn);
        return l;
    }

    
    private void renderBlockLayer(BlockLayer blockLayerIn)
    {
        this.gm.entityRenderer.enableLightmap();

//        if (OpenGl.useVbo())
//        {
            GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
            GL13.glClientActiveTexture(GL13.GL_TEXTURE0);
            GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
            GL13.glClientActiveTexture(GL13.GL_TEXTURE1);
            GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
            GL13.glClientActiveTexture(GL13.GL_TEXTURE0);
            GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);
//        }

        this.renderChunkLayer(blockLayerIn);

//        if (OpenGl.useVbo())
//        {
            for (VertexFormatElement vertexformatelement : DefaultVertexFormats.BLOCK.getElements())
            {
                VertexFormatElement.EnumUsage vertexformatelement$enumusage = vertexformatelement.usage();
                int i = vertexformatelement.index();

                switch (vertexformatelement$enumusage)
                {
                    case POSITION:
					GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
                        break;

                    case UV:
					GL13.glClientActiveTexture(GL13.GL_TEXTURE0 + i);
					GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
					GL13.glClientActiveTexture(GL13.GL_TEXTURE0);
                        break;

                    case COLOR:
					GL11.glDisableClientState(GL11.GL_COLOR_ARRAY);
                        GlState.resetColor();
                }
            }
//        }

        this.gm.entityRenderer.disableLightmap();
    }

    private void cleanupDamagedBlocks(Iterator<DestroyBlockProgress> iteratorIn)
    {
        while (iteratorIn.hasNext())
        {
            DestroyBlockProgress destroyblockprogress = (DestroyBlockProgress)iteratorIn.next();
            int i = destroyblockprogress.getTime();

            if (this.cloudTickCounter - i > 400)
            {
                iteratorIn.remove();
            }
        }
    }

    public void updateClouds()
    {
        ++this.cloudTickCounter;

        if (this.cloudTickCounter % 20 == 0)
        {
            this.cleanupDamagedBlocks(this.damagedBlocks.values().iterator());
        }
    }

    private void renderSkyBox(String texture)
    {
        GlState.disableFog();
        GlState.disableAlpha();
        GlState.enableBlend();
        GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
        ItemRenderer.disableStandardItemLighting();
        GlState.depthMask(false);
        this.renderEngine.bindTexture(texture);
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();

        for (int i = 0; i < 6; ++i)
        {
            GL11.glPushMatrix();

            if (i == 1)
            {
                GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F);
            }

            if (i == 2)
            {
                GL11.glRotatef(-90.0F, 1.0F, 0.0F, 0.0F);
            }

            if (i == 3)
            {
                GL11.glRotatef(180.0F, 1.0F, 0.0F, 0.0F);
            }

            if (i == 4)
            {
                GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F);
            }

            if (i == 5)
            {
                GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F);
            }

            worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            worldrenderer.pos(-100.0D, -100.0D, -100.0D).tex(0.0D, 0.0D).color(40, 40, 40, 255).endVertex();
            worldrenderer.pos(-100.0D, -100.0D, 100.0D).tex(0.0D, 16.0D).color(40, 40, 40, 255).endVertex();
            worldrenderer.pos(100.0D, -100.0D, 100.0D).tex(16.0D, 16.0D).color(40, 40, 40, 255).endVertex();
            worldrenderer.pos(100.0D, -100.0D, -100.0D).tex(16.0D, 0.0D).color(40, 40, 40, 255).endVertex();
            Tessellator.draw();
            GL11.glPopMatrix();
        }

        GlState.depthMask(true);
        GlState.enableTexture2D();
        GlState.enableAlpha();
    }

    public void renderSky(float partialTicks)
    {
        if (this.gm.world.dimension.getSkyBoxTexture() != null)
        {
            this.renderSkyBox(this.gm.world.dimension.getSkyBoxTexture());
        }
        else if (this.gm.world.dimension.getType().sky)
        {
            GlState.disableTexture2D();
            Vec3 vec3 = this.theWorld.getSkyColor(this.gm.getRenderViewEntity(), partialTicks);
            float f = (float)vec3.xCoord;
            float f1 = (float)vec3.yCoord;
            float f2 = (float)vec3.zCoord;

//            if (pass != 2)
//            {
//                float f3 = (f * 30.0F + f1 * 59.0F + f2 * 11.0F) / 100.0F;
//                float f4 = (f * 30.0F + f1 * 70.0F) / 100.0F;
//                float f5 = (f * 30.0F + f2 * 70.0F) / 100.0F;
//                f = f3;
//                f1 = f4;
//                f2 = f5;
//            }

            float fog = 1.0f - this.theWorld.getFogStrength();
            GlState.color(f, f1, f2, fog);
//            Tessellator tessellator = Tessellator.getInstance();
            RenderBuffer worldrenderer = Tessellator.getBuffer();
            GlState.depthMask(false);
            GlState.enableFog();
            GlState.color(f, f1, f2, fog);

//            if (this.vboEnabled)
//            {
                this.skyVBO.bindBuffer();
                GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
                GL11.nglVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
                this.skyVBO.drawArrays(GL11.GL_QUADS);
                this.skyVBO.unbindBuffer();
                GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
//            }
//            else
//            {
//                GlState.callList(this.glSkyList);
//            }

            GlState.disableFog();
            GlState.disableAlpha();
            GlState.enableBlend();
            GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
            ItemRenderer.disableStandardItemLighting();

            float[] afloat = this.theWorld.dimension.getType().days ? 
            		RenderGlobal.calcSunriseSunsetColors(this.theWorld.getCelestialAngle(partialTicks), partialTicks) : null;
            if (afloat != null)
            {
                GlState.disableTexture2D();
                GlState.shadeModel(GL11.GL_SMOOTH);
                GL11.glPushMatrix();
                GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F);
                GL11.glRotatef(ExtMath.sin(this.theWorld.getCelestialAngleRadians(partialTicks)) < 0.0F ? 180.0F : 0.0F, 0.0F, 0.0F, 1.0F);
                GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F);
                float f6 = afloat[0];
                float f7 = afloat[1];
                float f8 = afloat[2];

//                if (pass != 2)
//                {
//                    float f9 = (f6 * 30.0F + f7 * 59.0F + f8 * 11.0F) / 100.0F;
//                    float f10 = (f6 * 30.0F + f7 * 70.0F) / 100.0F;
//                    float f11 = (f6 * 30.0F + f8 * 70.0F) / 100.0F;
//                    f6 = f9;
//                    f7 = f10;
//                    f8 = f11;
//                }

                worldrenderer.begin(GL11.GL_TRIANGLE_FAN, DefaultVertexFormats.POSITION_COLOR);
                worldrenderer.pos(0.0D, 100.0D, 0.0D).color(f6, f7, f8, afloat[3]).endVertex();
                int j = 16;

                for (int l = 0; l <= 16; ++l)
                {
                    float f21 = (float)l * (float)Math.PI * 2.0F / 16.0F;
                    float f12 = ExtMath.sin(f21);
                    float f13 = ExtMath.cos(f21);
                    worldrenderer.pos((double)(f12 * 120.0F), (double)(f13 * 120.0F), (double)(-f13 * 40.0F * afloat[3])).color(afloat[0], afloat[1], afloat[2], 0.0F).endVertex();
                }

                Tessellator.draw();
                GL11.glPopMatrix();
                GlState.shadeModel(GL11.GL_FLAT);
            }

            GlState.enableTexture2D();
            GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ZERO);
            GL11.glPushMatrix();
            float f16 = 1.0F - Math.max(this.theWorld.getRainStrength(), this.theWorld.getFogStrength());
            GlState.color(1.0F, 1.0F, 1.0F, f16);
            GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
            GL11.glRotatef(this.theWorld.getCelestialAngle(partialTicks) * 360.0F, 1.0F, 0.0F, 0.0F);
            if(this.gm.world.dimension.getType().sun) {
	            float size = 30.0F;
	            this.renderEngine.bindTexture(SUN_TEX);
	            worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
	            worldrenderer.pos((double)(-size), 100.0D, (double)(-size)).tex(0.0D, 0.0D).endVertex();
	            worldrenderer.pos((double)size, 100.0D, (double)(-size)).tex(1.0D, 0.0D).endVertex();
	            worldrenderer.pos((double)size, 100.0D, (double)size).tex(1.0D, 1.0D).endVertex();
	            worldrenderer.pos((double)(-size), 100.0D, (double)size).tex(0.0D, 1.0D).endVertex();
	            Tessellator.draw();
            }
            if(this.gm.world.dimension.getType().moon) {
            	float size = 20.0F;
	            this.renderEngine.bindTexture(MOON_TEX);
	            int i = this.theWorld.getMoonPhase();
	            int k = i % 4;
	            int i1 = i / 4 % 2;
	            float f22 = (float)(k + 0) / 4.0F;
	            float f23 = (float)(i1 + 0) / 2.0F;
	            float f24 = (float)(k + 1) / 4.0F;
	            float f14 = (float)(i1 + 1) / 2.0F;
	            worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
	            worldrenderer.pos((double)(-size), -100.0D, (double)size).tex((double)f24, (double)f14).endVertex();
	            worldrenderer.pos((double)size, -100.0D, (double)size).tex((double)f22, (double)f14).endVertex();
	            worldrenderer.pos((double)size, -100.0D, (double)(-size)).tex((double)f22, (double)f23).endVertex();
	            worldrenderer.pos((double)(-size), -100.0D, (double)(-size)).tex((double)f24, (double)f23).endVertex();
	            Tessellator.draw();
            }
            GlState.disableTexture2D();
            
            float f15 = this.theWorld.getStarBrightness(partialTicks) * f16;
            if (f15 > 0.0F)
            {
            	int stars = this.theWorld.dimension.getStarColor(this.theWorld.getDayTime());
            	if(stars == 0xffffffff) {
            		GlState.color(f15, f15, f15, f15);
            	}
            	else {
                	Vec3 color = new Vec3(stars);
            		GlState.color((float)color.xCoord, (float)color.yCoord, (float)color.zCoord, f15);
            	}

//                if (this.vboEnabled)
//                {
                    this.starVBO.bindBuffer();
                    GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
                    GL11.nglVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
                    this.starVBO.drawArrays(GL11.GL_QUADS);
                    this.starVBO.unbindBuffer();
                    GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
//                }
//                else
//                {
//                    GlState.callList(this.starGLCallList);
//                }
            }
            
            f15 = this.theWorld.getDeepStarBrightness(partialTicks) * f16;
            if (f15 > 0.0F)
            {
            	int stars = this.theWorld.dimension.getDeepStarColor(this.theWorld.getDayTime());
            	if(stars == 0xffffffff) {
            		GlState.color(f15, f15, f15, f15);
            	}
            	else {
                	Vec3 color = new Vec3(stars);
            		GlState.color((float)color.xCoord, (float)color.yCoord, (float)color.zCoord, f15);
            	}

//                if (this.vboEnabled)
//                {
                    this.dstarVBO.bindBuffer();
                    GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
                    GL11.nglVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
                    this.dstarVBO.drawArrays(GL11.GL_QUADS);
                    this.dstarVBO.unbindBuffer();
                    GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
//                }
//                else
//                {
//                    GlState.callList(this.dstarGLCallList);
//                }
            }

            GlState.color(1.0F, 1.0F, 1.0F, 1.0F);
            GlState.disableBlend();
            GlState.enableAlpha();
            GlState.enableFog();
            GL11.glPopMatrix();
            GlState.enableTexture2D();
            GlState.depthMask(true);
        }
    }

    public void renderClouds(float partialTicks)
    {
        GlState.disableCull();
        float f = (float)(this.gm.getRenderViewEntity().lastTickPosY + (this.gm.getRenderViewEntity().posY - this.gm.getRenderViewEntity().lastTickPosY) * (double)partialTicks);
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();
        float f1 = 12.0F;
        float f2 = 4.0F;
        double d0 = (double)((float)this.cloudTickCounter + partialTicks);
        double d1 = (this.gm.getRenderViewEntity().prevX + (this.gm.getRenderViewEntity().posX - this.gm.getRenderViewEntity().prevX) * (double)partialTicks + d0 * 0.029999999329447746D) / 12.0D;
        double d2 = (this.gm.getRenderViewEntity().prevZ + (this.gm.getRenderViewEntity().posZ - this.gm.getRenderViewEntity().prevZ) * (double)partialTicks) / 12.0D + 0.33000001311302185D;
        float f3 = this.theWorld.dimension.getCloudHeight() - f + 0.33F;
        int i = ExtMath.floord(d1 / 2048.0D);
        int j = ExtMath.floord(d2 / 2048.0D);
        d1 = d1 - (double)(i * 2048);
        d2 = d2 - (double)(j * 2048);
        this.renderEngine.bindTexture(this.gm.world.dimension.getCloudTexture());
        GlState.enableBlend();
        GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
        Vec3 vec3 = this.theWorld.getCloudColour(this.gm.getRenderViewEntity(), partialTicks);
        float f4 = (float)vec3.xCoord;
        float f5 = (float)vec3.yCoord;
        float f6 = (float)vec3.zCoord;

//        if (pass != 2)
//        {
//            float f7 = (f4 * 30.0F + f5 * 59.0F + f6 * 11.0F) / 100.0F;
//            float f8 = (f4 * 30.0F + f5 * 70.0F) / 100.0F;
//            float f9 = (f4 * 30.0F + f6 * 70.0F) / 100.0F;
//            f4 = f7;
//            f5 = f8;
//            f6 = f9;
//        }

        float f26 = f4 * 0.9F;
        float f27 = f5 * 0.9F;
        float f28 = f6 * 0.9F;
        float f10 = f4 * 0.7F;
        float f11 = f5 * 0.7F;
        float f12 = f6 * 0.7F;
        float f13 = f4 * 0.8F;
        float f14 = f5 * 0.8F;
        float f15 = f6 * 0.8F;
        float f16 = 0.00390625F;
        float f17 = (float)ExtMath.floord(d1) * 0.00390625F;
        float f18 = (float)ExtMath.floord(d2) * 0.00390625F;
        float f19 = (float)(d1 - (double)ExtMath.floord(d1));
        float f20 = (float)(d2 - (double)ExtMath.floord(d2));
        int k = 8;
        int l = 4;
        float f21 = 9.765625E-4F;
        GL11.glScalef(12.0F, 1.0F, 12.0F);

        for (int i1 = 0; i1 < 2; ++i1)
        {
            if (i1 == 0)
            {
                GlState.colorMask(false, false, false, false);
            }
            else
            {
//                switch (pass)
//                {
//                    case 0:
//                        GlState.colorMask(false, true, true, true);
//                        break;
//
//                    case 1:
//                        GlState.colorMask(true, false, false, true);
//                        break;
//
//                    case 2:
                 GlState.colorMask(true, true, true, true);
//                }
            }

            for (int j1 = -3; j1 <= 4; ++j1)
            {
                for (int k1 = -3; k1 <= 4; ++k1)
                {
                    worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR_NORMAL);
                    float f22 = (float)(j1 * 8);
                    float f23 = (float)(k1 * 8);
                    float f24 = f22 - f19;
                    float f25 = f23 - f20;

                    if (f3 > -5.0F)
                    {
                        worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 0.0F), (double)(f25 + 8.0F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f10, f11, f12, 0.8F).normal(0.0F, -1.0F, 0.0F).endVertex();
                        worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 0.0F), (double)(f25 + 8.0F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f10, f11, f12, 0.8F).normal(0.0F, -1.0F, 0.0F).endVertex();
                        worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 0.0F), (double)(f25 + 0.0F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f10, f11, f12, 0.8F).normal(0.0F, -1.0F, 0.0F).endVertex();
                        worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 0.0F), (double)(f25 + 0.0F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f10, f11, f12, 0.8F).normal(0.0F, -1.0F, 0.0F).endVertex();
                    }

                    if (f3 <= 5.0F)
                    {
                        worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 4.0F - 9.765625E-4F), (double)(f25 + 8.0F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f4, f5, f6, 0.8F).normal(0.0F, 1.0F, 0.0F).endVertex();
                        worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 4.0F - 9.765625E-4F), (double)(f25 + 8.0F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f4, f5, f6, 0.8F).normal(0.0F, 1.0F, 0.0F).endVertex();
                        worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 4.0F - 9.765625E-4F), (double)(f25 + 0.0F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f4, f5, f6, 0.8F).normal(0.0F, 1.0F, 0.0F).endVertex();
                        worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 4.0F - 9.765625E-4F), (double)(f25 + 0.0F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f4, f5, f6, 0.8F).normal(0.0F, 1.0F, 0.0F).endVertex();
                    }

                    if (j1 > -1)
                    {
                        for (int l1 = 0; l1 < 8; ++l1)
                        {
                            worldrenderer.pos((double)(f24 + (float)l1 + 0.0F), (double)(f3 + 0.0F), (double)(f25 + 8.0F)).tex((double)((f22 + (float)l1 + 0.5F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f26, f27, f28, 0.8F).normal(-1.0F, 0.0F, 0.0F).endVertex();
                            worldrenderer.pos((double)(f24 + (float)l1 + 0.0F), (double)(f3 + 4.0F), (double)(f25 + 8.0F)).tex((double)((f22 + (float)l1 + 0.5F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f26, f27, f28, 0.8F).normal(-1.0F, 0.0F, 0.0F).endVertex();
                            worldrenderer.pos((double)(f24 + (float)l1 + 0.0F), (double)(f3 + 4.0F), (double)(f25 + 0.0F)).tex((double)((f22 + (float)l1 + 0.5F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f26, f27, f28, 0.8F).normal(-1.0F, 0.0F, 0.0F).endVertex();
                            worldrenderer.pos((double)(f24 + (float)l1 + 0.0F), (double)(f3 + 0.0F), (double)(f25 + 0.0F)).tex((double)((f22 + (float)l1 + 0.5F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f26, f27, f28, 0.8F).normal(-1.0F, 0.0F, 0.0F).endVertex();
                        }
                    }

                    if (j1 <= 1)
                    {
                        for (int i2 = 0; i2 < 8; ++i2)
                        {
                            worldrenderer.pos((double)(f24 + (float)i2 + 1.0F - 9.765625E-4F), (double)(f3 + 0.0F), (double)(f25 + 8.0F)).tex((double)((f22 + (float)i2 + 0.5F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f26, f27, f28, 0.8F).normal(1.0F, 0.0F, 0.0F).endVertex();
                            worldrenderer.pos((double)(f24 + (float)i2 + 1.0F - 9.765625E-4F), (double)(f3 + 4.0F), (double)(f25 + 8.0F)).tex((double)((f22 + (float)i2 + 0.5F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f26, f27, f28, 0.8F).normal(1.0F, 0.0F, 0.0F).endVertex();
                            worldrenderer.pos((double)(f24 + (float)i2 + 1.0F - 9.765625E-4F), (double)(f3 + 4.0F), (double)(f25 + 0.0F)).tex((double)((f22 + (float)i2 + 0.5F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f26, f27, f28, 0.8F).normal(1.0F, 0.0F, 0.0F).endVertex();
                            worldrenderer.pos((double)(f24 + (float)i2 + 1.0F - 9.765625E-4F), (double)(f3 + 0.0F), (double)(f25 + 0.0F)).tex((double)((f22 + (float)i2 + 0.5F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f26, f27, f28, 0.8F).normal(1.0F, 0.0F, 0.0F).endVertex();
                        }
                    }

                    if (k1 > -1)
                    {
                        for (int j2 = 0; j2 < 8; ++j2)
                        {
                            worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 4.0F), (double)(f25 + (float)j2 + 0.0F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + (float)j2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, 0.8F).normal(0.0F, 0.0F, -1.0F).endVertex();
                            worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 4.0F), (double)(f25 + (float)j2 + 0.0F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + (float)j2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, 0.8F).normal(0.0F, 0.0F, -1.0F).endVertex();
                            worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 0.0F), (double)(f25 + (float)j2 + 0.0F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + (float)j2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, 0.8F).normal(0.0F, 0.0F, -1.0F).endVertex();
                            worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 0.0F), (double)(f25 + (float)j2 + 0.0F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + (float)j2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, 0.8F).normal(0.0F, 0.0F, -1.0F).endVertex();
                        }
                    }

                    if (k1 <= 1)
                    {
                        for (int k2 = 0; k2 < 8; ++k2)
                        {
                            worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 4.0F), (double)(f25 + (float)k2 + 1.0F - 9.765625E-4F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + (float)k2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, 0.8F).normal(0.0F, 0.0F, 1.0F).endVertex();
                            worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 4.0F), (double)(f25 + (float)k2 + 1.0F - 9.765625E-4F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + (float)k2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, 0.8F).normal(0.0F, 0.0F, 1.0F).endVertex();
                            worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 0.0F), (double)(f25 + (float)k2 + 1.0F - 9.765625E-4F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + (float)k2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, 0.8F).normal(0.0F, 0.0F, 1.0F).endVertex();
                            worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 0.0F), (double)(f25 + (float)k2 + 1.0F - 9.765625E-4F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + (float)k2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, 0.8F).normal(0.0F, 0.0F, 1.0F).endVertex();
                        }
                    }

                    Tessellator.draw();
                }
            }
        }

        GlState.color(1.0F, 1.0F, 1.0F, 1.0F);
        GlState.disableBlend();
        GlState.enableCull();
    }

    public void updateChunks(long finishTimeNano)
    {
        this.displayListEntitiesDirty |= this.renderDispatcher.runChunkUploads(finishTimeNano);

        if (!this.chunksToUpdate.isEmpty())
        {
            Iterator<RenderChunk> iterator = this.chunksToUpdate.iterator();

            while (iterator.hasNext())
            {
                RenderChunk renderchunk = (RenderChunk)iterator.next();

                if (!this.renderDispatcher.updateChunkLater(renderchunk))
                {
                    break;
                }

                renderchunk.setNeedsUpdate(false);
                iterator.remove();
                long i = finishTimeNano - System.nanoTime();

                if (i < 0L)
                {
                    break;
                }
            }
        }
    }

    private void preRenderDamagedBlocks()
    {
        GlState.tryBlendFuncSeparate(GL11.GL_DST_COLOR, GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO);
        GlState.enableBlend();
        GlState.color(1.0F, 1.0F, 1.0F, 0.5F);
        GlState.doPolygonOffset(-3.0F, -3.0F);
        GlState.enablePolygonOffset();
        GlState.alphaFunc(GL11.GL_GREATER, 0.1F);
        GlState.enableAlpha();
        GL11.glPushMatrix();
    }

    private void postRenderDamagedBlocks()
    {
        GlState.disableAlpha();
        GlState.doPolygonOffset(0.0F, 0.0F);
        GlState.disablePolygonOffset();
        GlState.enableAlpha();
        GlState.depthMask(true);
        GL11.glPopMatrix();
    }

    public void drawBlockDamageTexture(RenderBuffer worldRendererIn, Entity entityIn, float partialTicks)
    {
        double d0 = entityIn.lastTickPosX + (entityIn.posX - entityIn.lastTickPosX) * (double)partialTicks;
        double d1 = entityIn.lastTickPosY + (entityIn.posY - entityIn.lastTickPosY) * (double)partialTicks;
        double d2 = entityIn.lastTickPosZ + (entityIn.posZ - entityIn.lastTickPosZ) * (double)partialTicks;

        if (!this.damagedBlocks.isEmpty())
        {
            this.renderEngine.bindTexture(TextureMap.locationBlocksTexture);
            this.preRenderDamagedBlocks();
            worldRendererIn.begin(GL11.GL_QUADS, DefaultVertexFormats.BLOCK);
            worldRendererIn.setTranslation(-d0, -d1, -d2);
            worldRendererIn.noColor();
            Iterator<DestroyBlockProgress> iterator = this.damagedBlocks.values().iterator();

            while (iterator.hasNext())
            {
                DestroyBlockProgress destroyblockprogress = (DestroyBlockProgress)iterator.next();
                BlockPos blockpos = destroyblockprogress.getPosition();
                double d3 = (double)blockpos.getX() - d0;
                double d4 = (double)blockpos.getY() - d1;
                double d5 = (double)blockpos.getZ() - d2;
                Block block = this.theWorld.getState(blockpos).getBlock();

                if (!(block instanceof BlockChest) && !(block instanceof BlockSign))
                {
                    if (d3 * d3 + d4 * d4 + d5 * d5 > 1024.0D)
                    {
                        iterator.remove();
                    }
                    else
                    {
                        State iblockstate = this.theWorld.getState(blockpos);

                        if (iblockstate.getBlock() != Blocks.air)
                        {
                            int i = destroyblockprogress.getPartialBlockDamage();
                            TextureAtlasSprite textureatlassprite = this.destroyBlockIcons[i];
                            BlockRenderer blockrendererdispatcher = this.gm.getBlockRendererDispatcher();
                            blockrendererdispatcher.renderBlockDamage(iblockstate, blockpos, textureatlassprite, this.theWorld);
                        }
                    }
                }
            }

            Tessellator.draw();
            worldRendererIn.setTranslation(0.0D, 0.0D, 0.0D);
            this.postRenderDamagedBlocks();
        }
    }

    /**
     * Draws the selection box for the player. Args: entityPlayer, rayTraceHit, i, itemStack, partialTickTime
     *  
     * @param execute If equals to 0 the method is executed
     */
    public void drawSelectionBox(EntityNPC player, HitPosition movingObjectPositionIn, float partialTicks)
    {
        if (movingObjectPositionIn.type == HitPosition.ObjectType.BLOCK)
        {
            GlState.enableBlend();
            GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
            GlState.color(0.0F, 0.0F, 0.0F, 0.4F);
            GL11.glLineWidth(2.0F);
            GlState.disableTexture2D();
            GlState.depthMask(false);
            float f = 0.002F;
            BlockPos blockpos = movingObjectPositionIn.block;
            Block block = this.theWorld.getState(blockpos).getBlock();

            if (block != Blocks.air) // && this.theWorld.getWorldBorder().contains(blockpos))
            {
                block.setBlockBoundsBasedOnState(this.theWorld, blockpos);
                double d0 = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double)partialTicks;
                double d1 = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double)partialTicks;
                double d2 = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double)partialTicks;
                drawSelectionBoundingBox(block.getSelectedBoundingBox(this.theWorld, blockpos).expand(0.0020000000949949026D, 0.0020000000949949026D, 0.0020000000949949026D).offset(-d0, -d1, -d2));
            }

            GlState.depthMask(true);
            GlState.enableTexture2D();
            GlState.disableBlend();
        }
    }

    public static void drawSelectionBoundingBox(BoundingBox boundingBox)
    {
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();
        worldrenderer.begin(GL11.GL_LINE_STRIP, DefaultVertexFormats.POSITION);
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex();
        Tessellator.draw();
        worldrenderer.begin(GL11.GL_LINE_STRIP, DefaultVertexFormats.POSITION);
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex();
        Tessellator.draw();
        worldrenderer.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION);
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).endVertex();
        Tessellator.draw();
    }

    public static void drawOutlinedBoundingBox(BoundingBox boundingBox, int red, int green, int blue, int alpha)
    {
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();
        worldrenderer.begin(GL11.GL_LINE_STRIP, DefaultVertexFormats.POSITION_COLOR);
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        Tessellator.draw();
        worldrenderer.begin(GL11.GL_LINE_STRIP, DefaultVertexFormats.POSITION_COLOR);
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        Tessellator.draw();
        worldrenderer.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION_COLOR);
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        Tessellator.draw();
    }

    /**
     * Marks the blocks in the given range for update
     */
    public void markBlocksForUpdate(int x1, int y1, int z1, int x2, int y2, int z2)
    {
        this.viewFrustum.markBlocksForUpdate(x1, y1, z1, x2, y2, z2);
    }

    public void sendBlockBreakProgress(int breakerId, BlockPos pos, int progress)
    {
        if (progress >= 0 && progress < 10)
        {
            DestroyBlockProgress destroyblockprogress = (DestroyBlockProgress)this.damagedBlocks.get(Integer.valueOf(breakerId));

            if (destroyblockprogress == null || destroyblockprogress.getPosition().getX() != pos.getX() || destroyblockprogress.getPosition().getY() != pos.getY() || destroyblockprogress.getPosition().getZ() != pos.getZ())
            {
                destroyblockprogress = new DestroyBlockProgress(breakerId, pos);
                this.damagedBlocks.put(Integer.valueOf(breakerId), destroyblockprogress);
            }

            destroyblockprogress.setPartialBlockDamage(progress);
            destroyblockprogress.setTime(this.cloudTickCounter);
        }
        else
        {
            this.damagedBlocks.remove(Integer.valueOf(breakerId));
        }
    }

    public void setDisplayListEntitiesDirty()
    {
        this.displayListEntitiesDirty = true;
    }

    public void updateTileEntities(Collection<TileEntity> tileEntitiesToRemove, Collection<TileEntity> tileEntitiesToAdd)
    {
        synchronized (this.setTileEntities)
        {
            this.setTileEntities.removeAll(tileEntitiesToRemove);
            this.setTileEntities.addAll(tileEntitiesToAdd);
        }
    }
    
    private void initialize(double viewEntityXIn, double viewEntityYIn, double viewEntityZIn)
    {
        this.initialized = true;
        this.renderChunks.clear();
        this.viewEntityX = viewEntityXIn;
        this.viewEntityY = viewEntityYIn;
        this.viewEntityZ = viewEntityZIn;
    }

    private void preRenderChunk(RenderChunk renderChunkIn)
    {
        BlockPos blockpos = renderChunkIn.getPosition();
        GL11.glTranslatef((float)((double)blockpos.getX() - this.viewEntityX), (float)((double)blockpos.getY() - this.viewEntityY), (float)((double)blockpos.getZ() - this.viewEntityZ));
    }

    private void addRenderChunk(RenderChunk renderChunkIn, BlockLayer layer)
    {
        this.renderChunks.add(renderChunkIn);
    }
    
    private void renderChunkLayer(BlockLayer layer)
    {
        if (this.initialized)
        {
            for (RenderChunk renderchunk : this.renderChunks)
            {
                VertexBuffer vertexbuffer = renderchunk.getVertexBufferByLayer(layer.ordinal());
                GL11.glPushMatrix();
                this.preRenderChunk(renderchunk);
                renderchunk.multModelviewMatrix();
                vertexbuffer.bindBuffer();
                this.setupArrayPointers();
                vertexbuffer.drawArrays(GL11.GL_QUADS);
                GL11.glPopMatrix();
            }

            GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
            GlState.resetColor();
            this.renderChunks.clear();
        }
    }

    private void setupArrayPointers()
    {
        GL11.nglVertexPointer(3, GL11.GL_FLOAT, 28, 0L);
        GL11.nglColorPointer(4, GL11.GL_UNSIGNED_BYTE, 28, 12L);
        GL11.glTexCoordPointer(2, GL11.GL_FLOAT, 28, 16L);
        GL13.glClientActiveTexture(GL13.GL_TEXTURE1);
        GL11.glTexCoordPointer(2, GL11.GL_SHORT, 28, 24L);
        GL13.glClientActiveTexture(GL13.GL_TEXTURE0);
    }

    public void renderStarField(int w, int h, int bg, int color, float ticks, Random rand) {
    	long seed = rand.getSeed();
        Vec3 stars = new Vec3(color);
    	ticks *= 5.0f;
        GlState.disableCull();
		GlState.disableLighting();
        GlState.disableDepth();
        Drawing.drawRect(0, 0, w, h, bg | 0xff000000);
//    	Gui.drawRect(0, 0, w, h, bg | 0xff000000);
    	for(int z = 0; z < 6; z++) {
	        GL11.glMatrixMode(GL11.GL_MODELVIEW);
	        GL11.glLoadIdentity();
	        float shift = ticks % 30.0f - (float)z * 30.0f;
	        int n = z + (int)(ticks / 30.0f);
//	        WCF.glTranslatef(0.0f, 0.0f, (float)n * -30.0f);
	        rand.setSeed((long)n * 8436723957L);
	        GL11.glRotatef(rand.floatv() * 360.0f, 0.0f, 0.0f, 1.0f);
	        float timer = (float)((double)(System.nanoTime() / 1000L) / 1000000.0) * 0.12f;
	//    	Project.gluLookAt(0.0f, 0.0f, shift, ExtMath.sin(timer), ExtMath.cos(timer * 2.0f), shift + ExtMath.cos(timer * 0.33f), 0.0f, ExtMath.sin(timer), ExtMath.cos(timer));
	    	Project.gluLookAt(0.0f, 0.0f, shift, 0.0f, 0.0f, shift + 1.0f, 0.0f, 1.0f, 0.0f);
	        GL11.glMatrixMode(GL11.GL_PROJECTION);
	        GL11.glLoadIdentity();
	        Project.gluPerspective(90.0f, (float)w / (float)h, 0.05f, 1024.0f);
	//        WCF.glTranslatef(w / 2.0f, h / 2.0f, 0.0f);
	//        GlState.disableDepth();
	        GlState.disableTexture2D();
	        GlState.depthMask(false);
	//        this.skyVBO.bindBuffer();
	//        WCF.glEnableClientState(WCF.GL_VERTEX_ARRAY);
	//        WCF.glVertexPointer(3, WCF.GL_FLOAT, 12, 0L);
	//        this.skyVBO.drawArrays(GL11.GL_QUADS);
	//        this.skyVBO.unbindBuffer();
	//        WCF.glDisableClientState(WCF.GL_VERTEX_ARRAY);
	        GlState.disableAlpha();
	        GlState.enableBlend();
	        GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ZERO);
	        ItemRenderer.disableStandardItemLighting();
	    	GlState.color((float)stars.xCoord, (float)stars.yCoord, (float)stars.zCoord, 1.0f);
	    	this.starVBO.bindBuffer();
	        GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
	        GL11.nglVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
	        this.starVBO.drawArrays(GL11.GL_QUADS);
	        this.starVBO.unbindBuffer();
	        GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
	        this.dstarVBO.bindBuffer();
	        GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
	        GL11.nglVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
	        this.dstarVBO.drawArrays(GL11.GL_QUADS);
	        this.dstarVBO.unbindBuffer();
	        GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
	        GlState.enableTexture2D();
	        GL11.glMatrixMode(GL11.GL_PROJECTION);
	        GL11.glLoadIdentity();
	        GL11.glMatrixMode(GL11.GL_MODELVIEW);
	        GL11.glLoadIdentity();
    	}
        GlState.enableCull();
        this.gm.setupOverlay();
        rand.setSeed(seed);
    }

    public static float[] calcSunriseSunsetColors(float celestialAngle, float partialTicks) {
		float f = 0.4F;
		float f1 = ExtMath.cos(celestialAngle * (float)Math.PI * 2.0F) - 0.0F;
		float f2 = -0.0F;
	
		if(f1 >= f2 - f && f1 <= f2 + f) {
			float f3 = (f1 - f2) / f * 0.5F + 0.5F;
			float f4 = 1.0F - (1.0F - ExtMath.sin(f3 * (float)Math.PI)) * 0.99F;
			f4 = f4 * f4;
			SUN_COLOR[0] = f3 * 0.3F + 0.7F;
			SUN_COLOR[1] = f3 * f3 * 0.7F + 0.2F;
			SUN_COLOR[2] = f3 * f3 * 0.0F + 0.2F;
			SUN_COLOR[3] = f4;
			return SUN_COLOR;
		}
		else {
			return null;
		}
	}
}
