Skip to content

Instantly share code, notes, and snippets.

@kevinresol
Created August 22, 2015 01:44
Show Gist options
  • Save kevinresol/86e2746ea8701060feb8 to your computer and use it in GitHub Desktop.
Save kevinresol/86e2746ea8701060feb8 to your computer and use it in GitHub Desktop.
Macro to read asset paths
package util;
/**
* ...
* @author Kevin
*/
@:build(util.AssetPathsMacro.build())
class AssetPaths
{
}
package util;
import haxe.io.Path;
import haxe.macro.Context;
import haxe.macro.Expr.Field;
import sys.FileSystem;
using StringTools;
/**
* ...
* @author Kevin
*/
class AssetPathsMacro
{
macro public static function build(path:String = 'assets/'):Array<Field>
{
path = Path.addTrailingSlash(path);
path = Context.resolvePath(path);
var files = readDirectory(path);
var fields:Array<Field> = Context.getBuildFields();
for (f in files)
{
// create new field based on file references!
fields.push({
name: f.name,
doc: f.value,
access: [APublic, AStatic, AInline],
kind: FVar(macro:String, macro $v{ f.value }),
pos: Context.currentPos()
});
}
fields.push({
name: "all",
doc: "A list of all asset paths",
access: [APublic, AStatic],
kind: FVar(macro:Array<String>, macro $a{files.map(function(f) return macro $v{f.value})}),
pos: Context.currentPos(),
});
return fields;
}
private static function readDirectory(path:String)
{
path = Path.addTrailingSlash(path);
var result = [];
for(f in FileSystem.readDirectory(path))
{
var fullpath = path + f;
if (FileSystem.isDirectory(fullpath))
result = result.concat(readDirectory(fullpath));
else
result.push({name:convertPathToVarName(fullpath), value:fullpath});
}
return result;
}
private static function convertPathToVarName(path:String)
{
return path.replace("/", "__").replace(".", "_").replace(" ", "_").replace("-", "_");
}
}
package;
class Main extends luxe.Game
{
override function ready()
{
var parcel = new Parcel({
jsons: AssetPaths.all
.filter(function(f) return Path.extension(f).toLowerCase() == "json")
.map(function(f):JSONInfo return {id:f}),
textures: AssetPaths.all
.filter(function(f) return Path.extension(f).toLowerCase() == "png")
.map(function(f):TextureInfo return { id:f, load_premultiply_alpha:true } ),
fonts: [
/*{ id:AssetPaths.assets__font__Impact_fnt },*/
],
shaders:[
/*{ id:'filler', frag_id:AssetPaths.assets__shader__filler_glsl, vert_id:'default' },*/
],
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment