Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从相对路径错误加载Wavefont.obj文件 首先,感谢您抽出时间阅读本文。_Java_File_3d_Relative Path_Wavefront - Fatal编程技术网

Java 从相对路径错误加载Wavefont.obj文件 首先,感谢您抽出时间阅读本文。

Java 从相对路径错误加载Wavefont.obj文件 首先,感谢您抽出时间阅读本文。,java,file,3d,relative-path,wavefront,Java,File,3d,Relative Path,Wavefront,我正在读这本书。第8章展示了如何加载Wavefront.obj文件。 我的obj文件位于C://pathToMyWorkspace//ProjectName//res//coffeCup.obj 当我尝试加载Wavefront.obj文件时,编译器向我抛出错误: java.io.FileNotFoundException: res\coffe at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<

我正在读这本书。第8章展示了如何加载Wavefront.obj文件。 我的obj文件位于C://pathToMyWorkspace//ProjectName//res//coffeCup.obj

当我尝试加载Wavefront.obj文件时,编译器向我抛出错误:

java.io.FileNotFoundException: res\coffe
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.io.FileReader.<init>(FileReader.java:72)
at com.base.graphics.graphics3D.ObjectLoader.parseFile(ObjectLoader.java:141)
at com.base.graphics.graphics3D.ObjectLoader$ObjLineParser.parseLine(ObjectLoader.java:228)
at com.base.graphics.graphics3D.ObjectLoader.parseFile(ObjectLoader.java:169)
at com.base.graphics.graphics3D.ObjectLoader.loadObject(ObjectLoader.java:116)
at com.testGame.Texture3DTest.createPolygons(Texture3DTest.java:69)
at com.base.graphics.GameCore3D.init(GameCore3D.java:24)
at com.testGame.Texture3DTest.init(Texture3DTest.java:45)
at com.base.graphics.GameCore.start(GameCore.java:49)
at com.testGame.Texture3DTest.main(Texture3DTest.java:41)
PS:我正在使用eclipse

非常感谢

(此答案涉及问题的一部分。此问题已根据此答案进行更新。有关详细信息,请参阅评论)

这里的问题是
ObjectLoader
类的路径处理是错误的。相关的调用顺序可以在下面的示例中看到:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;

import stackoverflow.objload.ObjectLoader.LineParser;
import stackoverflow.objload.ObjectLoader.Material;
import stackoverflow.objload.ObjectLoader.MtlLineParser;
import stackoverflow.objload.ObjectLoader.ObjLineParser;

public class ObjectLoaderTest
{
    public static void main(String[] args)
    {
        ObjectLoader objLoader = new ObjectLoader();

        try {
            PolygonGroup object = objLoader.loadObject("res/", "coffeCup.obj");
        } catch (IOException e) { 
            e.printStackTrace();
        }    

    }
}

class PolygonGroup
{
    public PolygonGroup(String name)
    {
    }

    public PolygonGroup()
    {
    }

    public void setFilename(String filename)
    {
    }

    public void addPolygonGroup(PolygonGroup currentGroup)
    {
    }
}
class Vector3D
{
    public Vector3D(float parseFloat, float parseFloat2, float parseFloat3)
    {
    }
}

class ObjectLoader {

    /**
     * The Material class wraps a ShadedTexture.
     */
    public static class Material {
        public File sourceFile;
    }

    /**
     * A LineParser is an interface to parse a line in a text file. Separate
     * LineParsers and are used for OBJ and MTL files.
     */
    protected interface LineParser {
        public void parseLine(String line) throws IOException, NumberFormatException, NoSuchElementException;
    }

    protected File path;
    protected List vertices;
    protected Material currentMaterial;
    protected HashMap materials;
    protected List lights;
    protected float ambientLightIntensity;
    protected HashMap parsers;
    private PolygonGroup object;
    private PolygonGroup currentGroup;

    /**
     * Creates a new ObjectLoader.
     */
    public ObjectLoader() {
        materials = new HashMap();
        vertices = new ArrayList();
        parsers = new HashMap();
        parsers.put("obj", new ObjLineParser());
        parsers.put("mtl", new MtlLineParser());
        currentMaterial = null;
        setLights(new ArrayList(), 1);
    }

    /**
     * Sets the lights used for the polygons in the parsed objects. After
     * calling this method calls to loadObject use these lights.
     */
    public void setLights(List lights, float ambientLightIntensity) {
        this.lights = lights;
        this.ambientLightIntensity = ambientLightIntensity;
    }

    /**
     * Loads an OBJ file as a PolygonGroup.
     */
    public PolygonGroup loadObject(String parent, String filename) throws IOException {
        object = new PolygonGroup();
        object.setFilename(filename);
        path = new File(parent);

        vertices.clear();
        currentGroup = object;
        parseFile(filename);

        return object;
    }

    /**
     * Gets a Vector3D from the list of vectors in the file. Negative indeces
     * count from the end of the list, postive indeces count from the beginning.
     * 1 is the first index, -1 is the last. 0 is invalid and throws an
     * exception.
     */
    protected Vector3D getVector(String indexStr) {
        int index = Integer.parseInt(indexStr);
        if (index < 0) {
            index = vertices.size() + index + 1;
        }
        return (Vector3D) vertices.get(index - 1);
    }

    /**
     * Parses an OBJ (ends with ".obj") or MTL file (ends with ".mtl").
     */
    protected void parseFile(String filename) throws IOException {
        // get the file relative to the source path
        File file = new File(path, filename);

        System.out.println("Reading "+file+", exists "+file.exists());
        BufferedReader reader = new BufferedReader(new FileReader(file));

        // get the parser based on the file extention
        LineParser parser = null;
        int extIndex = filename.lastIndexOf('.');
        if (extIndex != -1) {
            String ext = filename.substring(extIndex + 1);
            parser = (LineParser) parsers.get(ext.toLowerCase());
        }
        if (parser == null) {
            parser = (LineParser) parsers.get("obj");
        }

        // parse every line in the file
        while (true) {
            String line = reader.readLine();
            // no more lines to read
            if (line == null) {
                reader.close();
                return;
            }

            line = line.trim();

            // ignore blank lines and comments
            if (line.length() > 0 && !line.startsWith("#")) {
                // interpret the line
                try {
                    parser.parseLine(line);
                } catch (NumberFormatException ex) {
                    throw new IOException(ex.getMessage());
                } catch (NoSuchElementException ex) {
                    throw new IOException(ex.getMessage());
                }
            }

        }
    }

    /**
     * Parses a line in an OBJ file.
     */
    protected class ObjLineParser implements LineParser {

        public void parseLine(String line) throws IOException, NumberFormatException, NoSuchElementException {
            StringTokenizer tokenizer = new StringTokenizer(line);
            String command = tokenizer.nextToken();
            if (command.equals("v")) {
                // create a new vertex
                vertices.add(new Vector3D(Float.parseFloat(tokenizer.nextToken()), Float.parseFloat(tokenizer.nextToken()), Float.parseFloat(tokenizer.nextToken())));
            } else if (command.equals("f")) {
                // create a new face (flat, convex polygon)
                List currVertices = new ArrayList();
                while (tokenizer.hasMoreTokens()) {
                    String indexStr = tokenizer.nextToken();

                    // ignore texture and normal coords
                    int endIndex = indexStr.indexOf('/');
                    if (endIndex != -1) {
                        indexStr = indexStr.substring(0, endIndex);
                    }

                    currVertices.add(getVector(indexStr));
                }

                // create textured polygon
                Vector3D[] array = new Vector3D[currVertices.size()];
                currVertices.toArray(array);

            } else if (command.equals("g")) {
                // define the current group
                if (tokenizer.hasMoreTokens()) {
                    String name = tokenizer.nextToken();
                    currentGroup = new PolygonGroup(name);
                } else {
                    currentGroup = new PolygonGroup();
                }
                object.addPolygonGroup(currentGroup);
            } else if (command.equals("mtllib")) {
                // load materials from file
                String name = tokenizer.nextToken();
                parseFile(name);
            } else if (command.equals("usemtl")) {
                // define the current material
                String name = tokenizer.nextToken();
                currentMaterial = (Material) materials.get(name);
                if (currentMaterial == null) {
                    System.out.println("no material: " + name);
                }
            } else {
                // unknown command - ignore it
            }

        }
    }

    /**
     * Parses a line in a material MTL file.
     */
    protected class MtlLineParser implements LineParser {

        public void parseLine(String line) throws NoSuchElementException {
            StringTokenizer tokenizer = new StringTokenizer(line);
            String command = tokenizer.nextToken();

            if (command.equals("newmtl")) {
                // create a new material if needed
                String name = tokenizer.nextToken();
                currentMaterial = (Material) materials.get(name);
                if (currentMaterial == null) {
                    currentMaterial = new Material();
                    materials.put(name, currentMaterial);
                }
            } else if (command.equals("map_Kd")) {
                // give the current material a texture
                String name = tokenizer.nextToken();
                File file = new File(path, name);
                if (!file.equals(currentMaterial.sourceFile)) {
                    currentMaterial.sourceFile = file;
                }
            } else {
                // unknown command - ignore it
            }
        }
    }
}
它从给定的文件中获取“父文件”(即文件所在的目录),并将其存储为
路径
。稍后,文件名将再次附加到此路径,以获得最终文件名。因此,当
文件名
以相对路径前缀开头时(就像您的例子中的
res/
一样),这一部分是重复的

(顺便说一句:他存储路径的原因是,
OBJ
文件可能包含对假定位于同一目录中的其他文件的引用,例如
MTL
文件,该文件又可能包含对纹理文件的进一步引用)

我现在可以想象的“最简单”的解决方案是手动处理路径和文件名。这里概述了基本思想,应该可以将其转移到原始的
ObjectLoader
类:


编辑:一个MVCE,通过删除原始代码中导致编译错误的所有内容而创建

导入java.io.BufferedReader;
导入java.io.File;
导入java.io.FileReader;
导入java.io.IOException;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.List;
导入java.util.NoSuchElementException;
导入java.util.StringTokenizer;
导入stackoverflow.objload.ObjectLoader.LineParser;
导入stackoverflow.objload.ObjectLoader.Material;
导入stackoverflow.objload.ObjectLoader.mtlInParser;
导入stackoverflow.objload.ObjectLoader.ObjLineParser;
公共类ObjectLoaderTest
{
公共静态void main(字符串[]args)
{
ObjectLoader objLoader=新ObjectLoader();
试一试{
PolygonGroup object=objLoader.loadObject(“res/”,“coffeCup.obj”);
}捕获(IOE){
e、 printStackTrace();
}    
}
}
类多工群
{
公共多边形组(字符串名称)
{
}
公共多边形组()
{
}
public void setFilename(字符串文件名)
{
}
public void addPolygongGroup(PolygongGroup当前组)
{
}
}
类向量3D
{
公共向量3D(float-parseFloat、float-parseFloat2、float-parseFloat3)
{
}
}
类对象加载器{
/**
*Material类包装一个ShadedTexture。
*/
公共静态类材料{
公共文件源文件;
}
/**
*LineParser是解析文本文件中的行的接口。Separate
*行分析器和用于OBJ和MTL文件。
*/
受保护接口行分析器{
public void parseLine(字符串行)抛出IOException、NumberFormatException、NoTouchElementException;
}
受保护的文件路径;
受保护的列表顶点;
受保护材料;
受保护的HashMap材料;
受保护的列表灯;
受保护的漂浮环境光强度;
受保护的HashMap解析器;
私有多工组对象;
私有多工组;
/**
*创建一个新的ObjectLoader。
*/
公共对象加载器(){
materials=新HashMap();
顶点=新的ArrayList();
parsers=newhashmap();
put(“obj”,新的ObjLineParser());
put(“mtl”,新的MtlLineParser());
currentMaterial=null;
设置灯光(新的ArrayList(),1);
}
/**
*设置用于已解析对象中多边形的灯光。之后
*调用此方法调用loadObject使用这些灯光。
*/
公共空间设置灯(列表灯、浮动环境光强度){
这个。灯=灯;
this.ambientLightIntensity=ambientLightIntensity;
}
/**
*将OBJ文件作为多边形组加载。
*/
公共PolygonGroup加载对象(字符串父级,字符串文件名)引发IOException{
对象=新的PolygongGroup();
setFilename(文件名);
路径=新文件(父级);
顶点。清除();
当前组=对象;
解析文件(文件名);
返回对象;
}
/**
*从文件中的向量列表中获取Vector3D。负索引
*从列表的末尾开始计数,从列表的开头开始计数。
*1是第一个索引,-1是最后一个索引。0无效并引发
*例外。
*/
受保护向量3D getVector(字符串索引){
int index=Integer.parseInt(indexStr);
如果(指数<0){
索引=顶点。大小()+索引+1;
}
返回(Vector3D)顶点。获取(索引-1);
}
/**
*解析OBJ(以“.OBJ”结尾)或MTL文件(以“.MTL”结尾)。
*/
受保护的空解析文件(字符串文件名)引发IOException{
//获取相对于源路径的文件
文件=新文件(路径、文件名);
System.out.println(“读取“+file+”,存在“+file.exists());
BufferedReader reader=新的BufferedReader(新文件读取器(文件));
//根据文件扩展名获取解析器
LineParser=null;
int extendex=filename.lastIndexOf('.');
如果(灭绝指数!=-1){
String ext=filename.substring(dex+1);
parser=(LineParser)parsers.get(ext.toLowerCase());
}
if(解析器==null){
parser=(LineParser)parsers.get(“obj”);
}
//解析
package com.testGame;

import java.awt.event.KeyEvent;
import java.io.IOException;

import com.base.graphics.GameCore3D;
import com.base.graphics.graphics3D.ObjectLoader;
import com.base.graphics.graphics3D.Rectangle3D;
import com.base.graphics.graphics3D.Texture;
import com.base.graphics.graphics3D.ZBufferedRenderer;
import com.base.input.GameAction;
import com.base.input.InputManager;
import com.base.input.Mouse;
import com.base.math.PolygonGroup;
import com.base.math.TexturedPolygon3D;
import com.base.math.Transform3D;
import com.base.math.Vector3D;
import com.base.math.ViewWindow;

public class Texture3DTest extends GameCore3D {

    protected InputManager inputManager;
    protected GameAction exit = new GameAction("exit", GameAction.DETECT_INITAL_PRESS_ONLY);

    protected GameAction moveForward = new GameAction("moveForward");
    protected GameAction moveBackward = new GameAction("moveBackward");
    protected GameAction moveUp = new GameAction("moveUp");
    protected GameAction moveDown = new GameAction("moveDown");
    protected GameAction moveLeft = new GameAction("moveLeft");
    protected GameAction moveRight = new GameAction("moveRight");

    protected GameAction rootUp = new GameAction("rootUp");
    protected GameAction rootDown = new GameAction("rootDown");
    protected GameAction rootLeft = new GameAction("rootLeft");
    protected GameAction rootRight = new GameAction("rootRight");

    protected final int SPEED = 6;
    protected final float ROOTATION_SPEED = 0.01f;

    public static void main(String[] args) {
        new Texture3DTest().start();
    }

    public void init() {
        super.init();
        Mouse.hide(frame);

        inputManager = new InputManager(frame);

        inputManager.mapToKey(exit, KeyEvent.VK_ESCAPE);

        inputManager.mapToKey(moveForward, KeyEvent.VK_W);
        inputManager.mapToKey(moveBackward, KeyEvent.VK_S);
        inputManager.mapToKey(moveLeft, KeyEvent.VK_A);
        inputManager.mapToKey(moveRight, KeyEvent.VK_D);
        inputManager.mapToKey(moveUp, KeyEvent.VK_SPACE);
        inputManager.mapToKey(moveDown, KeyEvent.VK_SHIFT);

        inputManager.mapToKey(rootUp, KeyEvent.VK_UP);
        inputManager.mapToKey(rootDown, KeyEvent.VK_DOWN);
        inputManager.mapToKey(rootLeft, KeyEvent.VK_LEFT);
        inputManager.mapToKey(rootRight, KeyEvent.VK_RIGHT);
    }

    public void createPolygons() {
        ObjectLoader objLoader = new ObjectLoader();

        try {
            PolygonGroup object = objLoader.loadObject("res/", "coffeCup.obj");
            polygons.add(object);
        } catch (IOException e) { 
            e.printStackTrace();
        }
    }

    public void setTexture(TexturedPolygon3D poly, Texture texture) {
        Vector3D origin = poly.getVertex(0);

        Vector3D dv = new Vector3D(poly.getVertex(1));
        dv.subtract(origin);

        Vector3D du = new Vector3D();
        du.setToCrossProduct(poly.getNormal(), dv);

        Rectangle3D textureBounds = new Rectangle3D(origin, du, dv, texture.getWidth(), texture.getHeight());

        poly.setTexture(texture, textureBounds);
    }

    public void update() {
        if (exit.isPressed())
            System.exit(0);

        Transform3D camera = polygonRenderer.getCamera();
        Vector3D cameraLoc = polygonRenderer.getCamera().getLocation();

        if (moveForward.isPressed()) {
            cameraLoc.x -= SPEED * camera.getSinAngleY();
            cameraLoc.z -= SPEED * camera.getCosAngleY();
        }

        if (moveBackward.isPressed()) {
            cameraLoc.x += SPEED * camera.getSinAngleY();
            cameraLoc.z += SPEED * camera.getCosAngleY();
        }

        if (moveLeft.isPressed()) {
            cameraLoc.x -= SPEED * camera.getCosAngleY();
            cameraLoc.z += SPEED * camera.getSinAngleY();
        }

        if (moveRight.isPressed()) {
            cameraLoc.x += SPEED * camera.getCosAngleY();
            cameraLoc.z -= SPEED * camera.getSinAngleY();
        }

        if (moveUp.isPressed()) {
            camera.getLocation().y += SPEED;
        }

        if (moveDown.isPressed()) {
            camera.getLocation().y -= SPEED;
        }

        if (rootUp.isPressed())
            camera.rotateAngleX(ROOTATION_SPEED);

        if (rootDown.isPressed())
            camera.rotateAngleX(-ROOTATION_SPEED);

        if (rootLeft.isPressed())
            camera.rotateAngleY(ROOTATION_SPEED);

        if (rootRight.isPressed())
            camera.rotateAngleY(-ROOTATION_SPEED);
    }

    public Texture loadTexture(String imageName) {
        return Texture.createTexture(imageName, true);
    }

    public void createPolygonRenderer() {
        viewWindow = new ViewWindow(0, 0, frame.getWidth(), frame.getHeight(), (float) Math.toRadians(75));

        Transform3D camera = new Transform3D(0, 100, 0);
        polygonRenderer = new ZBufferedRenderer(camera, viewWindow);
    }
}
import java.io.File;

public class FilePathTest
{
    public static void main(String[] args)
    {
        loadObject("res/SomeFile.txt");
        loadObject("SomeFile.txt");
    }

    static File path;

    static void loadObject(String filename)
    {
        File file = new File(filename);
        path = file.getParentFile();        
        parseFile(filename);
    }

    static void parseFile(String filename)
    {
        File file = new File(path, filename);
        System.out.println("File: "+file+" exists? "+file.exists());
    }
}
import java.io.File;

public class FilePathTest
{
    public static void main(String[] args)
    {
        loadObject("res/", "SomeFile.obj");
    }

    static File path;

    static void loadObject(String parent, String filename)
    {
        File file = new File(parent+File.separator+filename);
        path = new File(parent);        
        parseFile(file);
    }

    static void parseFile(File file)
    {
        System.out.println("File: "+file+" exists? "+file.exists());

        String mtlName = "SomeFile.mtl";
        File mtlFile = new File(path, mtlName);

        System.out.println("MTL file: "+mtlFile+" exists? "+mtlFile.exists());
    }
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;

import stackoverflow.objload.ObjectLoader.LineParser;
import stackoverflow.objload.ObjectLoader.Material;
import stackoverflow.objload.ObjectLoader.MtlLineParser;
import stackoverflow.objload.ObjectLoader.ObjLineParser;

public class ObjectLoaderTest
{
    public static void main(String[] args)
    {
        ObjectLoader objLoader = new ObjectLoader();

        try {
            PolygonGroup object = objLoader.loadObject("res/", "coffeCup.obj");
        } catch (IOException e) { 
            e.printStackTrace();
        }    

    }
}

class PolygonGroup
{
    public PolygonGroup(String name)
    {
    }

    public PolygonGroup()
    {
    }

    public void setFilename(String filename)
    {
    }

    public void addPolygonGroup(PolygonGroup currentGroup)
    {
    }
}
class Vector3D
{
    public Vector3D(float parseFloat, float parseFloat2, float parseFloat3)
    {
    }
}

class ObjectLoader {

    /**
     * The Material class wraps a ShadedTexture.
     */
    public static class Material {
        public File sourceFile;
    }

    /**
     * A LineParser is an interface to parse a line in a text file. Separate
     * LineParsers and are used for OBJ and MTL files.
     */
    protected interface LineParser {
        public void parseLine(String line) throws IOException, NumberFormatException, NoSuchElementException;
    }

    protected File path;
    protected List vertices;
    protected Material currentMaterial;
    protected HashMap materials;
    protected List lights;
    protected float ambientLightIntensity;
    protected HashMap parsers;
    private PolygonGroup object;
    private PolygonGroup currentGroup;

    /**
     * Creates a new ObjectLoader.
     */
    public ObjectLoader() {
        materials = new HashMap();
        vertices = new ArrayList();
        parsers = new HashMap();
        parsers.put("obj", new ObjLineParser());
        parsers.put("mtl", new MtlLineParser());
        currentMaterial = null;
        setLights(new ArrayList(), 1);
    }

    /**
     * Sets the lights used for the polygons in the parsed objects. After
     * calling this method calls to loadObject use these lights.
     */
    public void setLights(List lights, float ambientLightIntensity) {
        this.lights = lights;
        this.ambientLightIntensity = ambientLightIntensity;
    }

    /**
     * Loads an OBJ file as a PolygonGroup.
     */
    public PolygonGroup loadObject(String parent, String filename) throws IOException {
        object = new PolygonGroup();
        object.setFilename(filename);
        path = new File(parent);

        vertices.clear();
        currentGroup = object;
        parseFile(filename);

        return object;
    }

    /**
     * Gets a Vector3D from the list of vectors in the file. Negative indeces
     * count from the end of the list, postive indeces count from the beginning.
     * 1 is the first index, -1 is the last. 0 is invalid and throws an
     * exception.
     */
    protected Vector3D getVector(String indexStr) {
        int index = Integer.parseInt(indexStr);
        if (index < 0) {
            index = vertices.size() + index + 1;
        }
        return (Vector3D) vertices.get(index - 1);
    }

    /**
     * Parses an OBJ (ends with ".obj") or MTL file (ends with ".mtl").
     */
    protected void parseFile(String filename) throws IOException {
        // get the file relative to the source path
        File file = new File(path, filename);

        System.out.println("Reading "+file+", exists "+file.exists());
        BufferedReader reader = new BufferedReader(new FileReader(file));

        // get the parser based on the file extention
        LineParser parser = null;
        int extIndex = filename.lastIndexOf('.');
        if (extIndex != -1) {
            String ext = filename.substring(extIndex + 1);
            parser = (LineParser) parsers.get(ext.toLowerCase());
        }
        if (parser == null) {
            parser = (LineParser) parsers.get("obj");
        }

        // parse every line in the file
        while (true) {
            String line = reader.readLine();
            // no more lines to read
            if (line == null) {
                reader.close();
                return;
            }

            line = line.trim();

            // ignore blank lines and comments
            if (line.length() > 0 && !line.startsWith("#")) {
                // interpret the line
                try {
                    parser.parseLine(line);
                } catch (NumberFormatException ex) {
                    throw new IOException(ex.getMessage());
                } catch (NoSuchElementException ex) {
                    throw new IOException(ex.getMessage());
                }
            }

        }
    }

    /**
     * Parses a line in an OBJ file.
     */
    protected class ObjLineParser implements LineParser {

        public void parseLine(String line) throws IOException, NumberFormatException, NoSuchElementException {
            StringTokenizer tokenizer = new StringTokenizer(line);
            String command = tokenizer.nextToken();
            if (command.equals("v")) {
                // create a new vertex
                vertices.add(new Vector3D(Float.parseFloat(tokenizer.nextToken()), Float.parseFloat(tokenizer.nextToken()), Float.parseFloat(tokenizer.nextToken())));
            } else if (command.equals("f")) {
                // create a new face (flat, convex polygon)
                List currVertices = new ArrayList();
                while (tokenizer.hasMoreTokens()) {
                    String indexStr = tokenizer.nextToken();

                    // ignore texture and normal coords
                    int endIndex = indexStr.indexOf('/');
                    if (endIndex != -1) {
                        indexStr = indexStr.substring(0, endIndex);
                    }

                    currVertices.add(getVector(indexStr));
                }

                // create textured polygon
                Vector3D[] array = new Vector3D[currVertices.size()];
                currVertices.toArray(array);

            } else if (command.equals("g")) {
                // define the current group
                if (tokenizer.hasMoreTokens()) {
                    String name = tokenizer.nextToken();
                    currentGroup = new PolygonGroup(name);
                } else {
                    currentGroup = new PolygonGroup();
                }
                object.addPolygonGroup(currentGroup);
            } else if (command.equals("mtllib")) {
                // load materials from file
                String name = tokenizer.nextToken();
                parseFile(name);
            } else if (command.equals("usemtl")) {
                // define the current material
                String name = tokenizer.nextToken();
                currentMaterial = (Material) materials.get(name);
                if (currentMaterial == null) {
                    System.out.println("no material: " + name);
                }
            } else {
                // unknown command - ignore it
            }

        }
    }

    /**
     * Parses a line in a material MTL file.
     */
    protected class MtlLineParser implements LineParser {

        public void parseLine(String line) throws NoSuchElementException {
            StringTokenizer tokenizer = new StringTokenizer(line);
            String command = tokenizer.nextToken();

            if (command.equals("newmtl")) {
                // create a new material if needed
                String name = tokenizer.nextToken();
                currentMaterial = (Material) materials.get(name);
                if (currentMaterial == null) {
                    currentMaterial = new Material();
                    materials.put(name, currentMaterial);
                }
            } else if (command.equals("map_Kd")) {
                // give the current material a texture
                String name = tokenizer.nextToken();
                File file = new File(path, name);
                if (!file.equals(currentMaterial.sourceFile)) {
                    currentMaterial.sourceFile = file;
                }
            } else {
                // unknown command - ignore it
            }
        }
    }
}