001package net.minecraftforge.client.model.obj;
002
003import net.minecraft.client.renderer.Tessellator;
004import net.minecraft.util.Vec3;
005import cpw.mods.fml.relauncher.Side;
006import cpw.mods.fml.relauncher.SideOnly;
007
008@SideOnly(Side.CLIENT)
009public class Face
010{
011
012    public Vertex[] vertices;
013    public Vertex[] vertexNormals;
014    public Vertex faceNormal;
015    public TextureCoordinate[] textureCoordinates;
016
017    public void addFaceForRender(Tessellator tessellator)
018    {
019        addFaceForRender(tessellator, 0.0005F);
020    }
021
022    public void addFaceForRender(Tessellator tessellator, float textureOffset)
023    {
024        if (faceNormal == null)
025        {
026            faceNormal = this.calculateFaceNormal();
027        }
028
029        tessellator.setNormal(faceNormal.x, faceNormal.y, faceNormal.z);
030
031        float averageU = 0F;
032        float averageV = 0F;
033
034        if (textureCoordinates.length != 0)
035        {
036            for (int i = 0; i < textureCoordinates.length; ++i)
037            {
038                averageU += textureCoordinates[i].u;
039                averageV += textureCoordinates[i].v;
040            }
041
042            averageU = averageU / textureCoordinates.length;
043            averageV = averageV / textureCoordinates.length;
044        }
045
046        float offsetU, offsetV;
047
048        for (int i = 0; i < vertices.length; ++i)
049        {
050
051            if (textureCoordinates.length != 0)
052            {
053                offsetU = textureOffset;
054                offsetV = textureOffset;
055
056                if (textureCoordinates[i].u > averageU)
057                {
058                    offsetU = -offsetU;
059                }
060                if (textureCoordinates[i].v > averageV)
061                {
062                    offsetV = -offsetV;
063                }
064
065                tessellator.addVertexWithUV(vertices[i].x, vertices[i].y, vertices[i].z, textureCoordinates[i].u + offsetU, textureCoordinates[i].v + offsetV);
066            }
067            else
068            {
069                tessellator.addVertex(vertices[i].x, vertices[i].y, vertices[i].z);
070            }
071        }
072    }
073
074    public Vertex calculateFaceNormal()
075    {
076        Vec3 v1 = Vec3.createVectorHelper(vertices[1].x - vertices[0].x, vertices[1].y - vertices[0].y, vertices[1].z - vertices[0].z);
077        Vec3 v2 = Vec3.createVectorHelper(vertices[2].x - vertices[0].x, vertices[2].y - vertices[0].y, vertices[2].z - vertices[0].z);
078        Vec3 normalVector = null;
079
080        normalVector = v1.crossProduct(v2).normalize();
081
082        return new Vertex((float) normalVector.xCoord, (float) normalVector.yCoord, (float) normalVector.zCoord);
083    }
084}