asset walker (WIP)
This commit is contained in:
+140
@@ -0,0 +1,140 @@
|
||||
package p.packer.repositories;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.packer.exceptions.PackerRegistryException;
|
||||
import p.packer.messages.PackerProjectContext;
|
||||
import p.packer.models.PackerRegistryEntry;
|
||||
import p.packer.models.PackerRegistryState;
|
||||
import p.packer.PackerWorkspacePaths;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
|
||||
public final class FileSystemPackerRegistryRepository implements PackerRegistryRepository {
|
||||
private static final int REGISTRY_SCHEMA_VERSION = 1;
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public FileSystemPackerRegistryRepository(final ObjectMapper mapper) {
|
||||
this.mapper = Objects.requireNonNull(mapper, "mapper");
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackerRegistryState load(PackerProjectContext project) {
|
||||
final Path registryPath = PackerWorkspacePaths.registryPath(project);
|
||||
if (!Files.isRegularFile(registryPath)) {
|
||||
return emptyState();
|
||||
}
|
||||
|
||||
try {
|
||||
final RegistryDocument document = mapper.readValue(registryPath.toFile(), RegistryDocument.class);
|
||||
final int schemaVersion = document.schemaVersion <= 0 ? REGISTRY_SCHEMA_VERSION : document.schemaVersion;
|
||||
if (schemaVersion != REGISTRY_SCHEMA_VERSION) {
|
||||
throw new PackerRegistryException("Unsupported registry schema_version: " + schemaVersion);
|
||||
}
|
||||
final List<PackerRegistryEntry> entries = new ArrayList<>();
|
||||
if (document.assets != null) {
|
||||
for (RegistryAssetDocument asset : document.assets) {
|
||||
if (asset == null) {
|
||||
continue;
|
||||
}
|
||||
entries.add(new PackerRegistryEntry(
|
||||
asset.assetId,
|
||||
asset.assetUuid,
|
||||
normalizeRoot(asset.root),
|
||||
asset.includedInBuild == null || asset.includedInBuild));
|
||||
}
|
||||
}
|
||||
validateEntries(entries);
|
||||
final int nextAssetId = document.nextAssetId > 0
|
||||
? document.nextAssetId
|
||||
: entries.stream().mapToInt(PackerRegistryEntry::assetId).max().orElse(0) + 1;
|
||||
return new PackerRegistryState(
|
||||
schemaVersion,
|
||||
nextAssetId,
|
||||
entries.stream().sorted(Comparator.comparingInt(PackerRegistryEntry::assetId)).toList());
|
||||
} catch (IOException exception) {
|
||||
throw new p.packer.exceptions.PackerRegistryException("Unable to load registry: " + registryPath, exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(PackerProjectContext project, PackerRegistryState state) {
|
||||
final Path registryDirectory = PackerWorkspacePaths.registryDirectory(project);
|
||||
final Path registryPath = PackerWorkspacePaths.registryPath(project);
|
||||
validateEntries(state.assets());
|
||||
try {
|
||||
Files.createDirectories(registryDirectory);
|
||||
final RegistryDocument document = new RegistryDocument();
|
||||
document.schemaVersion = state.schemaVersion();
|
||||
document.nextAssetId = state.nextAssetId();
|
||||
document.assets = state.assets().stream()
|
||||
.map(entry -> new RegistryAssetDocument(
|
||||
entry.assetId(),
|
||||
entry.assetUuid(),
|
||||
entry.root(),
|
||||
entry.includedInBuild()))
|
||||
.toList();
|
||||
mapper.writerWithDefaultPrettyPrinter().writeValue(registryPath.toFile(), document);
|
||||
} catch (IOException exception) {
|
||||
throw new p.packer.exceptions.PackerRegistryException("Unable to save registry: " + registryPath, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private PackerRegistryState emptyState() {
|
||||
return new PackerRegistryState(REGISTRY_SCHEMA_VERSION, 1, List.of());
|
||||
}
|
||||
|
||||
private void validateEntries(List<PackerRegistryEntry> entries) throws PackerRegistryException {
|
||||
final Set<Integer> assetIds = new HashSet<>();
|
||||
final Set<String> assetUuids = new HashSet<>();
|
||||
final Set<String> roots = new HashSet<>();
|
||||
for (PackerRegistryEntry entry : entries) {
|
||||
if (!assetIds.add(entry.assetId())) {
|
||||
throw new PackerRegistryException("Duplicate asset_id in registry: " + entry.assetId());
|
||||
}
|
||||
if (!assetUuids.add(entry.assetUuid())) {
|
||||
throw new PackerRegistryException("Duplicate asset_uuid in registry: " + entry.assetUuid());
|
||||
}
|
||||
if (!roots.add(entry.root())) {
|
||||
throw new PackerRegistryException("Duplicate asset root in registry: " + entry.root());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String normalizeRoot(String root) {
|
||||
if (root == null || root.isBlank()) {
|
||||
throw new PackerRegistryException("Registry asset root must not be blank");
|
||||
}
|
||||
final String normalized = root.trim().replace('\\', '/');
|
||||
final Path normalizedPath = Path.of(normalized).normalize();
|
||||
if (normalizedPath.isAbsolute() || normalizedPath.startsWith("..")) {
|
||||
throw new PackerRegistryException("Registry asset root is outside the trusted assets boundary: " + normalized);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
private static final class RegistryDocument {
|
||||
@JsonProperty("schema_version")
|
||||
public int schemaVersion;
|
||||
|
||||
@JsonProperty("next_asset_id")
|
||||
public int nextAssetId;
|
||||
|
||||
@JsonProperty("assets")
|
||||
public List<RegistryAssetDocument> assets = List.of();
|
||||
}
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
private record RegistryAssetDocument(
|
||||
@JsonProperty("asset_id") int assetId,
|
||||
@JsonProperty("asset_uuid") String assetUuid,
|
||||
@JsonProperty("root") String root,
|
||||
@JsonProperty("included_in_build") Boolean includedInBuild) {
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package p.packer.repositories;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.tika.Tika;
|
||||
import p.packer.messages.diagnostics.PackerDiagnosticCategory;
|
||||
import p.packer.messages.diagnostics.PackerDiagnosticSeverity;
|
||||
import p.packer.models.PackerDiagnostic;
|
||||
import p.packer.models.PackerFileProbe;
|
||||
import p.packer.models.PackerProbeResult;
|
||||
import p.packer.models.PackerWalkResult;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
public abstract class PackerAbstractBankWalker<R> {
|
||||
private final Tika tika = new Tika();
|
||||
protected final ObjectMapper mapper;
|
||||
|
||||
protected PackerAbstractBankWalker(ObjectMapper mapper) {
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
protected abstract Set<String> getSupportedMimeTypes();
|
||||
protected abstract PackerProbeResult processFileProbe(PackerFileProbe fileProbe, R requirements);
|
||||
|
||||
private Optional<PackerFileProbe> getFileProbeIfSupported(
|
||||
final Path filePath,
|
||||
final Set<String> supportedMimeTypes) throws IOException {
|
||||
final var bytes = Files.readAllBytes(filePath);
|
||||
final var mimeType = tika.detect(bytes);
|
||||
if (!supportedMimeTypes.contains(mimeType)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
final var lastModified = filePath.toFile().lastModified();
|
||||
final var fileProbe = new PackerFileProbe(filePath, mimeType, lastModified, bytes);
|
||||
return Optional.of(fileProbe);
|
||||
}
|
||||
|
||||
private List<Path> retrieveValidPaths(final Path assetRoot) throws IOException {
|
||||
try (final var paths = Files.list(assetRoot)
|
||||
.filter(Files::isRegularFile)
|
||||
.filter(path -> !isAssetManifest(path))) {
|
||||
return paths.toList();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isAssetManifest(final Path path) {
|
||||
return path.getFileName().toString().equalsIgnoreCase("asset.json");
|
||||
}
|
||||
|
||||
private List<PackerFileProbe> processFileProbeWhenSupported(
|
||||
final Path assetRoot,
|
||||
final Set<String> supportedMimeTypes,
|
||||
final List<PackerDiagnostic> diagnostics) {
|
||||
final List<PackerFileProbe> supportedFileProbes = new ArrayList<>();
|
||||
try {
|
||||
final var validPaths = retrieveValidPaths(assetRoot);
|
||||
for (final var filePath : validPaths) {
|
||||
final var fileProbeMaybe = getFileProbeIfSupported(filePath, supportedMimeTypes);
|
||||
if (fileProbeMaybe.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
final var fileProbe = fileProbeMaybe.get();
|
||||
supportedFileProbes.add(fileProbe);
|
||||
}
|
||||
} catch (IOException exception) {
|
||||
diagnostics.add(new PackerDiagnostic(
|
||||
PackerDiagnosticSeverity.ERROR,
|
||||
PackerDiagnosticCategory.STRUCTURAL,
|
||||
"Unable to walk tile asset root: " + exception.getMessage(),
|
||||
assetRoot,
|
||||
true
|
||||
));
|
||||
}
|
||||
return supportedFileProbes;
|
||||
}
|
||||
|
||||
public PackerWalkResult walk(
|
||||
final Path assetRoot,
|
||||
final R requirements) {
|
||||
final List<PackerDiagnostic> rootDiagnostics = new ArrayList<>();
|
||||
final List<PackerProbeResult> probeResults = new ArrayList<>();
|
||||
processFileProbeWhenSupported(assetRoot, getSupportedMimeTypes(), rootDiagnostics)
|
||||
.forEach(fileProbe -> probeResults.add(processFileProbe(fileProbe, requirements)));
|
||||
return new PackerWalkResult(probeResults, rootDiagnostics);
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
package p.packer.repositories;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.commons.collections4.MapUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import p.packer.messages.assets.OutputFormatCatalog;
|
||||
import p.packer.messages.diagnostics.PackerDiagnosticCategory;
|
||||
import p.packer.messages.diagnostics.PackerDiagnosticSeverity;
|
||||
import p.packer.models.*;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class PackerAssetWalker {
|
||||
private static final Set<OutputFormatCatalog> TILE_BANK_SUPPORTED_FORMATS = Set.of(
|
||||
OutputFormatCatalog.TILES_INDEXED_V1
|
||||
);
|
||||
|
||||
private static final Set<OutputFormatCatalog> SOUND_BANK_SUPPORTED_FORMATS = Set.of(
|
||||
OutputFormatCatalog.SOUND_V1
|
||||
);
|
||||
|
||||
private final PackerTileBankWalker tileBankWalker;
|
||||
private final PackerSoundBankWalker soundBankWalker;
|
||||
|
||||
public PackerAssetWalker(final ObjectMapper mapper) {
|
||||
this.tileBankWalker = new PackerTileBankWalker(mapper);
|
||||
this.soundBankWalker = new PackerSoundBankWalker(mapper);
|
||||
}
|
||||
|
||||
public PackerWalkResult walk(
|
||||
final Path assetRoot,
|
||||
final PackerAssetDeclaration declaration) {
|
||||
final List<PackerDiagnostic> diagnostics = new ArrayList<>();
|
||||
switch (declaration.assetFamily()) {
|
||||
case TILE_BANK -> {
|
||||
var metadata = declaration.outputMetadata();
|
||||
if (MapUtils.isEmpty(metadata)) {
|
||||
diagnostics.add(new PackerDiagnostic(
|
||||
PackerDiagnosticSeverity.WARNING,
|
||||
PackerDiagnosticCategory.HYGIENE,
|
||||
"Output metadata for tile bank cannot be empty, using default values",
|
||||
assetRoot,
|
||||
false));
|
||||
metadata = Map.of("tile_size", "16x16");
|
||||
}
|
||||
final var requirementBuildResult = buildTileBankRequirements(declaration, metadata);
|
||||
if (requirementBuildResult.hasError()) {
|
||||
diagnostics.add(new PackerDiagnostic(
|
||||
PackerDiagnosticSeverity.ERROR,
|
||||
PackerDiagnosticCategory.STRUCTURAL,
|
||||
requirementBuildResult.errorMessage(),
|
||||
assetRoot,
|
||||
true));
|
||||
return new PackerWalkResult(List.of(), diagnostics);
|
||||
}
|
||||
final var walkResult = tileBankWalker.walk(assetRoot, requirementBuildResult.requirements);
|
||||
diagnostics.addAll(walkResult.diagnostics());
|
||||
return new PackerWalkResult(walkResult.probeResults(), diagnostics);
|
||||
}
|
||||
case SOUND_BANK -> {
|
||||
var metadata = declaration.outputMetadata();
|
||||
if (MapUtils.isEmpty(metadata)) {
|
||||
diagnostics.add(new PackerDiagnostic(
|
||||
PackerDiagnosticSeverity.WARNING,
|
||||
PackerDiagnosticCategory.HYGIENE,
|
||||
"Output metadata for tile bank cannot be empty, using default values",
|
||||
assetRoot,
|
||||
false));
|
||||
metadata = Map.of("sample_rate", "44100", "channels", "1");
|
||||
}
|
||||
final var result = buildSoundBankRequirements(declaration, metadata);
|
||||
if (result.hasError()) {
|
||||
diagnostics.add(new PackerDiagnostic(
|
||||
PackerDiagnosticSeverity.ERROR,
|
||||
PackerDiagnosticCategory.STRUCTURAL,
|
||||
result.errorMessage(),
|
||||
assetRoot,
|
||||
true));
|
||||
return new PackerWalkResult(List.of(), diagnostics);
|
||||
}
|
||||
final var walkResult = soundBankWalker.walk(assetRoot, result.requirements);
|
||||
diagnostics.addAll(walkResult.diagnostics());
|
||||
return new PackerWalkResult(walkResult.probeResults(), diagnostics);
|
||||
}
|
||||
case UNKNOWN -> {
|
||||
diagnostics.add(new PackerDiagnostic(
|
||||
PackerDiagnosticSeverity.WARNING,
|
||||
PackerDiagnosticCategory.STRUCTURAL,
|
||||
"Unknown asset family for declaration, skipping content walk",
|
||||
assetRoot,
|
||||
false));
|
||||
return new PackerWalkResult(List.of(), diagnostics);
|
||||
}
|
||||
}
|
||||
return PackerWalkResult.EMPTY;
|
||||
}
|
||||
|
||||
private RequirementBuildResult<PackerTileBankRequirements> buildTileBankRequirements(
|
||||
final PackerAssetDeclaration declaration,
|
||||
final Map<String, String> metadata) {
|
||||
if (!TILE_BANK_SUPPORTED_FORMATS.contains(declaration.outputFormat())) {
|
||||
return RequirementBuildResult.fail("Unsupported output format for tile bank: " + declaration.outputFormat());
|
||||
}
|
||||
final var tileSizeStr = metadata.get("tile_size");
|
||||
if (StringUtils.isBlank(tileSizeStr)) {
|
||||
return RequirementBuildResult.fail("Tile size metadata for tile bank cannot be empty");
|
||||
}
|
||||
final int tileSize;
|
||||
switch (tileSizeStr) {
|
||||
case "8x8": {
|
||||
tileSize = 8;
|
||||
} break;
|
||||
case "16x16": {
|
||||
tileSize = 16;
|
||||
} break;
|
||||
case "32x32": {
|
||||
tileSize = 32;
|
||||
} break;
|
||||
default: {
|
||||
return RequirementBuildResult.fail("Unsupported tile size for tile bank: " + tileSizeStr);
|
||||
}
|
||||
}
|
||||
return RequirementBuildResult.success(new PackerTileBankRequirements(tileSize));
|
||||
}
|
||||
|
||||
private RequirementBuildResult<PackerSoundBankRequirements> buildSoundBankRequirements(
|
||||
final PackerAssetDeclaration declaration,
|
||||
final Map<String, String> metadata) {
|
||||
if (!SOUND_BANK_SUPPORTED_FORMATS.contains(declaration.outputFormat())) {
|
||||
return RequirementBuildResult.fail("Unsupported output format for sound bank: " + declaration.outputFormat());
|
||||
}
|
||||
final var sampleRateStr = metadata.get("sample_rate");
|
||||
if (StringUtils.isBlank(sampleRateStr)) {
|
||||
return RequirementBuildResult.fail("Missing sample rate for sound bank");
|
||||
}
|
||||
final var sampleRate = Integer.parseInt(sampleRateStr);
|
||||
final var channelsStr = metadata.get("");
|
||||
if (StringUtils.isBlank(channelsStr)) {
|
||||
return RequirementBuildResult.fail("Missing channels for sound bank");
|
||||
}
|
||||
final var channels = Integer.parseInt(channelsStr);
|
||||
return RequirementBuildResult.success(new PackerSoundBankRequirements(sampleRate, channels));
|
||||
}
|
||||
|
||||
private record RequirementBuildResult<T>(
|
||||
T requirements,
|
||||
String errorMessage) {
|
||||
static <T> RequirementBuildResult<T> success(T requirements) {
|
||||
return new RequirementBuildResult<>(requirements, null);
|
||||
}
|
||||
|
||||
static <T> RequirementBuildResult<T> fail(String errorMessage) {
|
||||
return new RequirementBuildResult<>(null, errorMessage);
|
||||
}
|
||||
|
||||
public boolean hasError() {
|
||||
return StringUtils.isNotBlank(errorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package p.packer.repositories;
|
||||
|
||||
import p.packer.messages.PackerProjectContext;
|
||||
import p.packer.models.PackerRegistryState;
|
||||
|
||||
public interface PackerRegistryRepository {
|
||||
PackerRegistryState load(PackerProjectContext project);
|
||||
|
||||
void save(PackerProjectContext project, PackerRegistryState state);
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package p.packer.repositories;
|
||||
|
||||
import p.packer.messages.InitWorkspaceRequest;
|
||||
import p.packer.messages.PackerProjectContext;
|
||||
import p.packer.models.PackerRuntimeAsset;
|
||||
import p.packer.models.PackerRuntimeSnapshot;
|
||||
import p.packer.services.PackerAssetDeclarationParser;
|
||||
import p.packer.services.PackerWorkspaceFoundation;
|
||||
import p.packer.PackerWorkspacePaths;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public final class PackerRuntimeLoader implements PackerRuntimeSnapshotLoader {
|
||||
private final PackerWorkspaceFoundation workspaceFoundation;
|
||||
private final PackerAssetDeclarationParser parser;
|
||||
private final PackerAssetWalker assetWalker;
|
||||
|
||||
public PackerRuntimeLoader(
|
||||
final PackerWorkspaceFoundation workspaceFoundation,
|
||||
final PackerAssetDeclarationParser parser,
|
||||
final PackerAssetWalker assetWalker) {
|
||||
this.workspaceFoundation = Objects.requireNonNull(workspaceFoundation, "workspaceFoundation");
|
||||
this.parser = Objects.requireNonNull(parser, "parser");
|
||||
this.assetWalker = Objects.requireNonNull(assetWalker, "assetWalker");
|
||||
}
|
||||
|
||||
private boolean isAssetJson(Path path, BasicFileAttributes attrs) {
|
||||
return attrs.isRegularFile() && path.getFileName().toString().equals("asset.json");
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackerRuntimeSnapshot load(PackerProjectContext project, long generation) {
|
||||
final var safeProject = Objects.requireNonNull(project, "project");
|
||||
workspaceFoundation.initWorkspace(new InitWorkspaceRequest(safeProject));
|
||||
|
||||
final var registry = workspaceFoundation.loadRegistry(safeProject);
|
||||
final var registryByRoot = registry
|
||||
.assets()
|
||||
.stream()
|
||||
.collect(Collectors.toMap(
|
||||
entry -> PackerWorkspacePaths.assetRoot(safeProject, entry.root()),
|
||||
entry -> entry));
|
||||
|
||||
final List<PackerRuntimeAsset> assets = new ArrayList<>();
|
||||
final var assetsRoot = PackerWorkspacePaths.assetsRoot(safeProject);
|
||||
if (Files.isDirectory(assetsRoot)) {
|
||||
try (final var paths = Files.find(assetsRoot, Integer.MAX_VALUE, this::isAssetJson)) {
|
||||
final var manifests = paths
|
||||
.map(path -> path.toAbsolutePath().normalize())
|
||||
.sorted(Comparator.naturalOrder())
|
||||
.toList();
|
||||
for (final var manifestPath : manifests) {
|
||||
final var assetRoot = manifestPath.getParent();
|
||||
final var registryEntry = Optional.ofNullable(registryByRoot.get(assetRoot));
|
||||
final var parseResult = parser.parse(manifestPath);
|
||||
if (parseResult.valid()) {
|
||||
final var walkResult = assetWalker.walk(assetRoot, parseResult.declaration());
|
||||
|
||||
}
|
||||
final var runtimeAsset = new PackerRuntimeAsset(assetRoot, manifestPath, registryEntry, parseResult);
|
||||
assets.add(runtimeAsset);
|
||||
}
|
||||
} catch (IOException exception) {
|
||||
throw new p.packer.exceptions.PackerRegistryException(
|
||||
"Unable to build runtime snapshot for " + safeProject.projectId(),
|
||||
exception);
|
||||
}
|
||||
}
|
||||
|
||||
return new PackerRuntimeSnapshot(generation, registry, assets);
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package p.packer.repositories;
|
||||
|
||||
import p.packer.messages.PackerProjectContext;
|
||||
import p.packer.models.PackerRuntimeSnapshot;
|
||||
import p.packer.services.PackerProjectRuntime;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
public final class PackerRuntimeRegistry {
|
||||
private final PackerRuntimeSnapshotLoader loader;
|
||||
private final ConcurrentMap<ProjectKey, PackerProjectRuntime> runtimes = new ConcurrentHashMap<>();
|
||||
private final AtomicLong nextGeneration = new AtomicLong(1L);
|
||||
|
||||
public PackerRuntimeRegistry(PackerRuntimeSnapshotLoader loader) {
|
||||
this.loader = Objects.requireNonNull(loader, "loader");
|
||||
}
|
||||
|
||||
public PackerProjectRuntime getOrLoad(PackerProjectContext project) {
|
||||
final PackerProjectContext safeProject = Objects.requireNonNull(project, "project");
|
||||
final ProjectKey key = ProjectKey.from(safeProject);
|
||||
return runtimes.compute(key, (ignored, current) -> {
|
||||
if (current != null && !current.disposed()) {
|
||||
return current;
|
||||
}
|
||||
return new PackerProjectRuntime(safeProject, loader.load(safeProject, nextGeneration.getAndIncrement()));
|
||||
});
|
||||
}
|
||||
|
||||
public Optional<PackerProjectRuntime> find(PackerProjectContext project) {
|
||||
return Optional.ofNullable(runtimes.get(ProjectKey.from(Objects.requireNonNull(project, "project"))));
|
||||
}
|
||||
|
||||
public PackerProjectRuntime refresh(PackerProjectContext project) {
|
||||
final PackerProjectContext safeProject = Objects.requireNonNull(project, "project");
|
||||
final ProjectKey key = ProjectKey.from(safeProject);
|
||||
return runtimes.compute(key, (ignored, current) -> {
|
||||
final var snapshot = loader.load(safeProject, nextGeneration.getAndIncrement());
|
||||
if (current == null || current.disposed()) {
|
||||
return new PackerProjectRuntime(safeProject, snapshot);
|
||||
}
|
||||
current.replaceSnapshot(snapshot);
|
||||
return current;
|
||||
});
|
||||
}
|
||||
|
||||
public PackerProjectRuntime update(
|
||||
PackerProjectContext project,
|
||||
BiFunction<PackerRuntimeSnapshot, Long, PackerRuntimeSnapshot> updater) {
|
||||
final PackerProjectContext safeProject = Objects.requireNonNull(project, "project");
|
||||
final BiFunction<PackerRuntimeSnapshot, Long, PackerRuntimeSnapshot> safeUpdater =
|
||||
Objects.requireNonNull(updater, "updater");
|
||||
final ProjectKey key = ProjectKey.from(safeProject);
|
||||
return runtimes.compute(key, (ignored, current) -> {
|
||||
if (current == null || current.disposed()) {
|
||||
return new PackerProjectRuntime(safeProject, loader.load(safeProject, nextGeneration.getAndIncrement()));
|
||||
}
|
||||
try {
|
||||
final long generation = nextGeneration.getAndIncrement();
|
||||
current.updateSnapshot(snapshot -> safeUpdater.apply(snapshot, generation));
|
||||
} catch (RuntimeException exception) {
|
||||
current.replaceSnapshot(loader.load(safeProject, nextGeneration.getAndIncrement()));
|
||||
}
|
||||
return current;
|
||||
});
|
||||
}
|
||||
|
||||
public void dispose(PackerProjectContext project) {
|
||||
final PackerProjectRuntime removed = runtimes.remove(ProjectKey.from(Objects.requireNonNull(project, "project")));
|
||||
if (removed != null) {
|
||||
removed.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public void disposeAll() {
|
||||
runtimes.values().forEach(PackerProjectRuntime::dispose);
|
||||
runtimes.clear();
|
||||
}
|
||||
|
||||
private record ProjectKey(
|
||||
String projectId,
|
||||
Path rootPath) {
|
||||
|
||||
private static ProjectKey from(PackerProjectContext project) {
|
||||
return new ProjectKey(
|
||||
Objects.requireNonNull(project.projectId(), "projectId"),
|
||||
Objects.requireNonNull(project.rootPath(), "rootPath").toAbsolutePath().normalize());
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package p.packer.repositories;
|
||||
|
||||
import p.packer.messages.PackerProjectContext;
|
||||
import p.packer.models.PackerRuntimeSnapshot;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface PackerRuntimeSnapshotLoader {
|
||||
PackerRuntimeSnapshot load(PackerProjectContext project, long generation);
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package p.packer.repositories;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.packer.models.PackerDiagnostic;
|
||||
import p.packer.models.PackerFileProbe;
|
||||
import p.packer.models.PackerProbeResult;
|
||||
import p.packer.models.PackerSoundBankRequirements;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class PackerSoundBankWalker extends PackerAbstractBankWalker<PackerSoundBankRequirements> {
|
||||
private static final Set<String> SUPPORTED_MIME_TYPES = Set.of("audio/wav");
|
||||
|
||||
public PackerSoundBankWalker(ObjectMapper mapper) {
|
||||
super(mapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Set<String> getSupportedMimeTypes() {
|
||||
return SUPPORTED_MIME_TYPES;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected PackerProbeResult processFileProbe(
|
||||
final PackerFileProbe fileProbe,
|
||||
final PackerSoundBankRequirements requirements) {
|
||||
final List<PackerDiagnostic> diagnostics = new ArrayList<>();
|
||||
return new PackerProbeResult(fileProbe, Map.of(), diagnostics);
|
||||
}
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
package p.packer.repositories;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.packer.messages.diagnostics.PackerDiagnosticCategory;
|
||||
import p.packer.messages.diagnostics.PackerDiagnosticSeverity;
|
||||
import p.packer.models.*;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
|
||||
public class PackerTileBankWalker extends PackerAbstractBankWalker<PackerTileBankRequirements> {
|
||||
private static final int MAX_COLORS_PER_PALETTE = 15;
|
||||
private static final int COLOR_KEY_RGB = 0x00FF00FF;
|
||||
private static final Set<String> SUPPORTED_MIME_TYPES = Set.of(
|
||||
"image/png"
|
||||
);
|
||||
|
||||
public PackerTileBankWalker(ObjectMapper mapper) {
|
||||
super(mapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Set<String> getSupportedMimeTypes() {
|
||||
return SUPPORTED_MIME_TYPES;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected PackerProbeResult processFileProbe(
|
||||
final PackerFileProbe fileProbe,
|
||||
final PackerTileBankRequirements requirements) {
|
||||
final List<PackerDiagnostic> diagnostics = new ArrayList<>();
|
||||
|
||||
final var image = readImage(fileProbe, diagnostics);
|
||||
if (image == null) {
|
||||
diagnostics.add(new PackerDiagnostic(
|
||||
PackerDiagnosticSeverity.ERROR,
|
||||
PackerDiagnosticCategory.STRUCTURAL,
|
||||
"Unable to decode tile image content: " + fileProbe.path().getFileName(),
|
||||
fileProbe.path(),
|
||||
true
|
||||
));
|
||||
return new PackerProbeResult(fileProbe, Map.of(), diagnostics);
|
||||
}
|
||||
|
||||
final var width = image.getWidth();
|
||||
final var height = image.getHeight();
|
||||
if (width != requirements.tileSize() || height != requirements.tileSize()) {
|
||||
diagnostics.add(new PackerDiagnostic(
|
||||
PackerDiagnosticSeverity.ERROR,
|
||||
PackerDiagnosticCategory.STRUCTURAL,
|
||||
"Invalid tile dimensions for " + fileProbe.path().getFileName()
|
||||
+ ": expected " + requirements.tileSize() + "x" + requirements.tileSize()
|
||||
+ " but got " + width + "x" + height,
|
||||
fileProbe.path(),
|
||||
true
|
||||
));
|
||||
}
|
||||
|
||||
final Map<Integer, Integer> paletteIndexByRgb = new LinkedHashMap<>();
|
||||
final byte[] paletteIndices = new byte[image.getWidth() * image.getHeight()];
|
||||
boolean partialAlphaFound = false;
|
||||
boolean exceededPaletteLimit = false;
|
||||
|
||||
int offset = 0;
|
||||
for (var y = 0; y < image.getHeight(); y++) {
|
||||
for (var x = 0; x < image.getWidth(); x++) {
|
||||
final int argb = image.getRGB(x, y);
|
||||
final int alpha = (argb >>> 24) & 0xFF;
|
||||
final int rgb = argb & 0x00FFFFFF;
|
||||
|
||||
if (alpha == 0 || rgb == COLOR_KEY_RGB) {
|
||||
paletteIndices[offset++] = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (alpha < 0xFF) {
|
||||
partialAlphaFound = true;
|
||||
}
|
||||
|
||||
Integer paletteIndex = paletteIndexByRgb.get(rgb);
|
||||
if (paletteIndex == null) {
|
||||
if (paletteIndexByRgb.size() >= MAX_COLORS_PER_PALETTE) {
|
||||
exceededPaletteLimit = true;
|
||||
paletteIndices[offset++] = 0;
|
||||
continue;
|
||||
}
|
||||
paletteIndex = paletteIndexByRgb.size() + 1;
|
||||
paletteIndexByRgb.put(rgb, paletteIndex);
|
||||
}
|
||||
|
||||
paletteIndices[offset++] = paletteIndex.byteValue();
|
||||
}
|
||||
}
|
||||
|
||||
if (partialAlphaFound) {
|
||||
diagnostics.add(new PackerDiagnostic(
|
||||
PackerDiagnosticSeverity.WARNING,
|
||||
PackerDiagnosticCategory.HYGIENE,
|
||||
"Tile contains partial alpha; flattening to RGB and ignoring alpha channel",
|
||||
fileProbe.path(),
|
||||
false
|
||||
));
|
||||
}
|
||||
|
||||
if (exceededPaletteLimit) {
|
||||
diagnostics.add(new PackerDiagnostic(
|
||||
PackerDiagnosticSeverity.ERROR,
|
||||
PackerDiagnosticCategory.STRUCTURAL,
|
||||
"Tile image exceeds color limit for " + fileProbe.path().getFileName()
|
||||
+ ": expected at most " + MAX_COLORS_PER_PALETTE + " colors for indices 1..15",
|
||||
fileProbe.path(),
|
||||
true
|
||||
));
|
||||
}
|
||||
|
||||
if (diagnostics.stream().anyMatch(PackerDiagnostic::blocking)) {
|
||||
return new PackerProbeResult(fileProbe, Map.of(), diagnostics);
|
||||
}
|
||||
|
||||
final var tile = new PackerTileIndexedV1(image.getWidth(), image.getHeight(), paletteIndices);
|
||||
final var palette = buildPalette(paletteIndexByRgb);
|
||||
serializeProbeArtifacts(fileProbe, tile, palette, diagnostics);
|
||||
return new PackerProbeResult(fileProbe, Map.of("tile", tile, "palette", palette), diagnostics);
|
||||
}
|
||||
|
||||
private void serializeProbeArtifacts(
|
||||
final PackerFileProbe fileProbe,
|
||||
final PackerTileIndexedV1 tile,
|
||||
final PackerPaletteV1 palette,
|
||||
final List<PackerDiagnostic> diagnostics) {
|
||||
final Path basePath = baseOutputPath(fileProbe.path());
|
||||
final Path tileOutputPath = Path.of(basePath + ".tile.json");
|
||||
final Path paletteOutputPath = Path.of(basePath + ".palette.json");
|
||||
|
||||
try {
|
||||
Files.createDirectories(Objects.requireNonNull(tileOutputPath.getParent()));
|
||||
mapper.writerWithDefaultPrettyPrinter().writeValue(tileOutputPath.toFile(), toTilePayload(tile));
|
||||
mapper.writerWithDefaultPrettyPrinter().writeValue(paletteOutputPath.toFile(), toPalettePayload(palette));
|
||||
} catch (IOException exception) {
|
||||
diagnostics.add(new PackerDiagnostic(
|
||||
PackerDiagnosticSeverity.ERROR,
|
||||
PackerDiagnosticCategory.STRUCTURAL,
|
||||
"Unable to serialize tile/palette artifacts for " + fileProbe.path().getFileName()
|
||||
+ ": " + exception.getMessage(),
|
||||
fileProbe.path(),
|
||||
true
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private Path baseOutputPath(final Path sourcePath) {
|
||||
final String fileName = sourcePath.getFileName().toString();
|
||||
final int extensionStart = fileName.lastIndexOf('.');
|
||||
final String outputBaseName = extensionStart > 0 ? fileName.substring(0, extensionStart) : fileName;
|
||||
final Path parent = sourcePath.getParent();
|
||||
if (parent == null) {
|
||||
return Path.of(outputBaseName);
|
||||
}
|
||||
return parent.resolve(outputBaseName);
|
||||
}
|
||||
|
||||
private Map<String, Object> toTilePayload(final PackerTileIndexedV1 tile) {
|
||||
final List<Integer> indices = new ArrayList<>(tile.paletteIndices().length);
|
||||
for (final byte value : tile.paletteIndices()) {
|
||||
indices.add(Byte.toUnsignedInt(value));
|
||||
}
|
||||
|
||||
return Map.of(
|
||||
"width", tile.width(),
|
||||
"height", tile.height(),
|
||||
"paletteIndices", indices
|
||||
);
|
||||
}
|
||||
|
||||
private Map<String, Object> toPalettePayload(final PackerPaletteV1 palette) {
|
||||
final List<Integer> convertedRgb565 = new ArrayList<>(palette.convertedRgb565().length);
|
||||
for (final short value : palette.convertedRgb565()) {
|
||||
convertedRgb565.add(Short.toUnsignedInt(value));
|
||||
}
|
||||
|
||||
return Map.of(
|
||||
"originalArgb8888", palette.originalArgb8888(),
|
||||
"convertedRgb565", convertedRgb565
|
||||
);
|
||||
}
|
||||
|
||||
private PackerPaletteV1 buildPalette(final Map<Integer, Integer> paletteIndexByRgb) {
|
||||
final int[] originalArgb8888 = new int[paletteIndexByRgb.size()];
|
||||
final short[] convertedRgb565 = new short[paletteIndexByRgb.size()];
|
||||
for (final var entry : paletteIndexByRgb.entrySet()) {
|
||||
final int rgb = entry.getKey();
|
||||
final int index = entry.getValue() - 1;
|
||||
final int argb = 0xFF000000 | rgb;
|
||||
originalArgb8888[index] = argb;
|
||||
convertedRgb565[index] = convertToRgb565(argb);
|
||||
}
|
||||
return new PackerPaletteV1(originalArgb8888, convertedRgb565);
|
||||
}
|
||||
|
||||
private short convertToRgb565(final int argb) {
|
||||
final int red = (argb >> 16) & 0xFF;
|
||||
final int green = (argb >> 8) & 0xFF;
|
||||
final int blue = argb & 0xFF;
|
||||
|
||||
final int r5 = (red >> 3) & 0x1F;
|
||||
final int g6 = (green >> 2) & 0x3F;
|
||||
final int b5 = (blue >> 3) & 0x1F;
|
||||
return (short) ((r5 << 11) | (g6 << 5) | b5);
|
||||
}
|
||||
|
||||
private java.awt.image.BufferedImage readImage(
|
||||
final PackerFileProbe fileProbe,
|
||||
final List<PackerDiagnostic> diagnostics) {
|
||||
try {
|
||||
return ImageIO.read(new ByteArrayInputStream(fileProbe.content()));
|
||||
} catch (Exception exception) {
|
||||
diagnostics.add(new PackerDiagnostic(
|
||||
PackerDiagnosticSeverity.ERROR,
|
||||
PackerDiagnosticCategory.STRUCTURAL,
|
||||
"Unable to decode tile image content: " + exception.getMessage(),
|
||||
fileProbe.path(),
|
||||
true
|
||||
));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user