Ejemplo n.º 1
0
  /**
   * Loads the specified file with one of the loaders registered with this ModelLoaderRegistry. Uses
   * the extension to determine which loader to use. The comparison of extensions is done case
   * insensitive.
   *
   * @param file the file to be loaded
   * @param hints the {@link ModelLoaderHints} to use
   * @return the {@link Model}
   * @throws GdxRuntimeException in case the model could not be loaded.
   */
  public static Model load(FileHandle file, ModelLoaderHints hints) {
    String name = file.name();
    int dotIndex = name.lastIndexOf('.');
    if (dotIndex == -1)
      throw new GdxRuntimeException(
          "file '"
              + file.name()
              + "' does not have an extension that can be matched to a ModelLoader");
    String extension = name.substring(dotIndex + 1).toLowerCase();

    Array<ModelLoader> loaders = ModelLoaderRegistry.loaders.get(extension);
    if (loaders == null)
      throw new GdxRuntimeException("no loaders for extension '" + extension + "'");

    Model model = null;
    StringBuilder errors = new StringBuilder();
    for (int i = 0; i < loaders.size; i++) {
      ModelLoader loader = loaders.get(i);
      try {
        model = loader.load(file, hints);
      } catch (GdxRuntimeException e) {
        errors.append(
            "Couldn't load '"
                + file.name()
                + "' with loader of type "
                + loader.getClass().getSimpleName()
                + ": "
                + e.getMessage()
                + "\n");
      }
    }

    if (model == null) throw new GdxRuntimeException(errors.toString());
    else return model;
  }
 private void loadAllAssetsInPath(String folder, Class type, String suffix) {
   logger.debug("Loading '" + folder + "'");
   for (FileHandle f : getAssetsPath(folder).list()) {
     String msg = "  Found: " + f.name();
     if (suffix == null) {
       assetManager.load(folder + "/" + f.name(), type);
     } else if (f.name().toLowerCase().endsWith(suffix))
       assetManager.load(folder + "/" + f.name(), type);
     else msg += " ...ignoring";
     logger.debug(msg);
   }
 }
Ejemplo n.º 3
0
 public void buildScenes(String targetPath) {
   ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
   String srcPath =
       projectManager.getCurrentWorkingPath()
           + "/"
           + projectManager.currentProjectVO.projectName
           + "/scenes";
   FileHandle scenesDirectoryHandle = Gdx.files.absolute(srcPath);
   File fileTarget = new File(targetPath + "/" + scenesDirectoryHandle.name());
   try {
     FileUtils.copyDirectory(scenesDirectoryHandle.file(), fileTarget);
   } catch (IOException e) {
     e.printStackTrace();
   }
   // copy project dt
   try {
     FileUtils.copyFile(
         new File(
             projectManager.getCurrentWorkingPath()
                 + "/"
                 + projectManager.currentProjectVO.projectName
                 + "/project.dt"),
         new File(targetPath + "/project.dt"));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 4
0
  /**
   * If the PSH file contains a line starting with {@link PolygonRegionParameters#texturePrefix
   * params.texturePrefix}, an {@link AssetDescriptor} for the file referenced on that line will be
   * added to the returned Array. Otherwise a sibling of the given file with the same name and the
   * first found extension in {@link PolygonRegionParameters#textureExtensions
   * params.textureExtensions} will be used. If no suitable file is found, the returned Array will
   * be empty.
   */
  @Override
  public Array<AssetDescriptor> getDependencies(
      String fileName, FileHandle file, PolygonRegionParameters params) {
    if (params == null) params = defaultParameters;
    String image = null;
    try {
      BufferedReader reader = file.reader(params.readerBuffer);
      for (String line = reader.readLine(); line != null; line = reader.readLine())
        if (line.startsWith(params.texturePrefix)) {
          image = line.substring(params.texturePrefix.length());
          break;
        }
      reader.close();
    } catch (IOException e) {
      throw new GdxRuntimeException("Error reading " + fileName, e);
    }

    if (image == null && params.textureExtensions != null)
      for (String extension : params.textureExtensions) {
        FileHandle sibling = file.sibling(file.nameWithoutExtension().concat("." + extension));
        if (sibling.exists()) image = sibling.name();
      }

    if (image != null) {
      Array<AssetDescriptor> deps = new Array<AssetDescriptor>(1);
      deps.add(new AssetDescriptor<Texture>(file.sibling(image), Texture.class));
      return deps;
    }

    return null;
  }
Ejemplo n.º 5
0
  private void rebuildUsagesTable() {
    usagesTable.clear();
    usagesTable.left();
    usagesTable.defaults().left();

    for (FileItem item : items) {

      FileHandle file = item.getFile();
      boolean canAnalyze = usageAnalyzer.canAnalyzeUsages(file);

      if (canAnalyze == false) {
        usagesTable.add(new VisLabel("Can't analyze usages for: '" + file.name() + "'"));
        usagesTable.row();
      } else {
        AssetsUsages usages = usageAnalyzer.analyzeUsages(file);
        usagesTable.add(new VisLabel(usages.toPrettyString()));

        if (usages.count() > 0) {
          VisTextButton viewUsages = new VisTextButton("View " + usages.file.name() + " Usages");
          usagesTable.add(viewUsages);

          viewUsages.addListener(
              new VisChangeListener((event, actor) -> openSpecificUsagesTab(usages)));
        }

        usagesTable.row();
      }
    }
  }
Ejemplo n.º 6
0
  private Table makeGameFileRow(final FileHandle gameSaveFile) {
    GameSave towerData;
    try {
      towerData = GameSaveFactory.readMetadata(gameSaveFile.read());
    } catch (Exception e) {
      Gdx.app.log(TAG, "Failed to parse file.", e);
      return null;
    }

    FileHandle imageFile =
        Gdx.files.external(TowerConsts.GAME_SAVE_DIRECTORY + gameSaveFile.name() + ".png");

    Actor imageActor = null;
    if (imageFile.exists()) {
      try {
        imageActor = new Image(loadTowerImage(imageFile), Scaling.fit, Align.top);
      } catch (Exception ignored) {
        imageActor = null;
      }
    }

    if (imageActor == null) {
      imageActor = FontManager.Default.makeLabel("No image.");
    }

    Table fileRow = new Table();
    fileRow.defaults().fillX().pad(Display.devicePixel(10)).space(Display.devicePixel(10));
    fileRow.row();
    fileRow.add(imageActor).width(Display.devicePixel(64)).height(Display.devicePixel(64)).center();
    fileRow.add(makeGameFileInfoBox(fileRow, gameSaveFile, towerData)).expandX().top();
    fileRow.row().fillX();
    fileRow.add(new HorizontalRule(Color.DARK_GRAY, 2)).colspan(2);

    return fileRow;
  }
Ejemplo n.º 7
0
 public ArrayList<String> available() {
   ArrayList<String> scenes = new ArrayList<String>();
   FileHandle[] files = Gdx.files.internal("bdx/scenes/").list("bdx");
   for (FileHandle file : files) {
     scenes.add(file.name().replace(".bdx", ""));
   }
   return scenes;
 }
Ejemplo n.º 8
0
  public void parseLevel(FileHandle file) throws Exception {

    Element root = new XmlReader().parse(file);

    this.pathway = Pathway.parsePathway(root);

    // Loading game objects
    Element entities = root.getChildByName("entities");
    this.gameObjects = new ArrayList<GameObject>();
    if (entities != null) {
      for (int i = 0; i < entities.getChildCount(); i++) {
        Element gameObject = entities.getChild(i);
        this.gameObjects.add(GameObject.parseGameObject(gameObject));
      }
    }

    // Loading universal objects
    Element universalObjects = root.getChildByName("drawings");
    this.universalObjects = new ArrayList<GameObject>();
    if (universalObjects != null) {
      for (int i = 0; i < universalObjects.getChildCount(); i++) {
        Element universalObject = universalObjects.getChild(i);
        this.universalObjects.add(GameObject.parseGameObject(universalObject));
      }
    }

    // Loading car
    Element car = root.getChildByName(Car.name);
    this.car = Car.parseCar(car);

    // Loading start
    Element start = root.getChildByName(Start.name);
    this.start = (Start) GameObject.parseGameObject(start);

    // Loading finish
    Element finish = root.getChildByName(Finish.name);
    this.finish = (Finish) GameObject.parseGameObject(finish);

    // Background
    Element background = root.getChildByName("background");
    this.background = LevelBackground.parseLevelBackground(background);

    // Time limit
    this.timeLimit = root.getFloat("timeLimit");

    Element difficulty = root.getChildByName("difficulty");
    this.setDifficulty(Difficulty.valueOf(difficulty.getText()));

    System.out.println("Loading level \"" + file.name() + "\" done.");
  }
Ejemplo n.º 9
0
  /**
   * Loads a language from a {@link FileHandle}
   *
   * @param file The {@link FileHandle} of the language file to load
   * @return True on success, otherwise false
   */
  protected static boolean loadFile(FileHandle file) {
    if (!file.isDirectory() && file.extension().equalsIgnoreCase("lang")) {
      try {
        LanguageEntry lang = languages.get(file.name());

        if (lang == null) {
          lang = new LanguageEntry(new Properties());
          languages.put(file.nameWithoutExtension(), lang);
        }

        lang.addProperties(file);

      } catch (Exception io) {
        Gdx.app.error(
            TAG, "Could not load language file with name " + file.nameWithoutExtension(), io);
        return false;
      }

    } else {
      Gdx.app.debug(TAG, "Ignored " + file.name() + " while loading language file");
    }

    return true;
  }
 public SubMesh[] loadMeshes(FileHandle file) {
   InputStream in = null;
   try {
     in = file.read();
     return loadMesh(in);
   } catch (Throwable t) {
     throw new GdxRuntimeException("Couldn't load file '" + file.name() + "'", t);
   } finally {
     if (in != null)
       try {
         in.close();
       } catch (Exception e) {
       }
   }
 }
Ejemplo n.º 11
0
  /**
   * Creates a {@link ModelEntity}. This method should only be invoked if the return value of the
   * {@link #save()} method was true.
   */
  public void createSceneElement() {
    ModelEntity savedElement =
        this.controller.getTemplates().createSceneElement(this.savePath.path());

    Actor rootGroup = scaledView.getGroupEditorDragListener().getRootGroup();

    Actor scaledAct = rootGroup == null ? scaledView : rootGroup;

    savedElement.setScaleX(1 / scaledAct.getScaleX());
    savedElement.setScaleY(1 / scaledAct.getScaleY());
    Vector2 pos = mesh.getPosition();

    savedElement.setX(pos.x - scaledAct.getX());
    savedElement.setY(pos.y - scaledAct.getY());

    Q.getComponent(savedElement, RepoElement.class).setThumbnail(thumbSavePath.name());

    this.controller.action(AddSceneElement.class, savedElement);
  }
Ejemplo n.º 12
0
  static {
    languages = new HashMap<String, LanguageEntry>();
    vanilla = new ArrayList<Locale>();

    try {
      Gdx.app.debug(TAG, "Reading default languages");

      List<String> langs = FileUtil.readSimpleFile(Gdx.files.internal(DIRECTORY + "index"));

      for (String s : langs) {
        FileHandle file = Gdx.files.internal(DIRECTORY + s);

        if (file != null) {
          vanilla.add(new Locale(file.name()));
          loadFile(file);
        } else throw new Exception("Could not find file for: " + s);
      }

    } catch (Exception ex) {
      Gdx.app.error(TAG, "Error reading default languages", ex);
    }
  }
  void loadSkeleton(final FileHandle skeletonFile) {
    if (skeletonFile == null) return;

    try {
      // Setup a texture atlas that uses a white image for images not found in the atlas.
      Pixmap pixmap = new Pixmap(32, 32, Format.RGBA8888);
      pixmap.setColor(new Color(1, 1, 1, 0.33f));
      pixmap.fill();
      final AtlasRegion fake = new AtlasRegion(new Texture(pixmap), 0, 0, 32, 32);
      pixmap.dispose();

      String atlasFileName = skeletonFile.nameWithoutExtension();
      if (atlasFileName.endsWith(".json"))
        atlasFileName = new FileHandle(atlasFileName).nameWithoutExtension();
      FileHandle atlasFile = skeletonFile.sibling(atlasFileName + ".atlas");
      if (!atlasFile.exists()) atlasFile = skeletonFile.sibling(atlasFileName + ".atlas.txt");
      TextureAtlasData data =
          !atlasFile.exists() ? null : new TextureAtlasData(atlasFile, atlasFile.parent(), false);
      TextureAtlas atlas =
          new TextureAtlas(data) {
            public AtlasRegion findRegion(String name) {
              AtlasRegion region = super.findRegion(name);
              if (region == null) {
                // Look for separate image file.
                FileHandle file = skeletonFile.sibling(name + ".png");
                if (file.exists()) {
                  Texture texture = new Texture(file);
                  texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
                  region = new AtlasRegion(texture, 0, 0, texture.getWidth(), texture.getHeight());
                  region.name = name;
                }
              }
              return region != null ? region : fake;
            }
          };

      // Load skeleton data.
      String extension = skeletonFile.extension();
      if (extension.equalsIgnoreCase("json") || extension.equalsIgnoreCase("txt")) {
        SkeletonJson json = new SkeletonJson(atlas);
        json.setScale(ui.scaleSlider.getValue());
        skeletonData = json.readSkeletonData(skeletonFile);
      } else {
        SkeletonBinary binary = new SkeletonBinary(atlas);
        binary.setScale(ui.scaleSlider.getValue());
        skeletonData = binary.readSkeletonData(skeletonFile);
        if (skeletonData.getBones().size == 0) throw new Exception("No bones in skeleton data.");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      ui.toast("Error loading skeleton: " + skeletonFile.name());
      lastModifiedCheck = 5;
      return;
    }

    skeleton = new Skeleton(skeletonData);
    skeleton.setToSetupPose();
    skeleton = new Skeleton(skeleton); // Tests copy constructors.
    skeleton.updateWorldTransform();

    state = new AnimationState(new AnimationStateData(skeletonData));
    state.addListener(
        new AnimationStateAdapter() {
          public void event(TrackEntry entry, Event event) {
            ui.toast(event.getData().getName());
          }
        });

    this.skeletonFile = skeletonFile;
    prefs.putString("lastFile", skeletonFile.path());
    prefs.flush();
    lastModified = skeletonFile.lastModified();
    lastModifiedCheck = checkModifiedInterval;

    // Populate UI.

    ui.window.getTitleLabel().setText(skeletonFile.name());
    {
      Array<String> items = new Array();
      for (Skin skin : skeletonData.getSkins()) items.add(skin.getName());
      ui.skinList.setItems(items);
    }
    {
      Array<String> items = new Array();
      for (Animation animation : skeletonData.getAnimations()) items.add(animation.getName());
      ui.animationList.setItems(items);
    }
    ui.trackButtons.getButtons().first().setChecked(true);

    // Configure skeleton from UI.

    if (ui.skinList.getSelected() != null) skeleton.setSkin(ui.skinList.getSelected());
    setAnimation();

    // ui.animationList.clearListeners();
    // state.setAnimation(0, "walk", true);
  }