complete Studio core and JavaFX boundary migration
Intrepid/Prometeu/Studio/pipeline/pr-master Build started...
JaCoCo Coverage #### Project Overview
No changes detected, that affect the code coverage.
* Line Coverage: 64.01% (20482/31999)
* Branch Coverage: 54.22% (8240/15196)
* Lines of Code: 31999
* Cyclomatic Complexity: 13164
#### Quality Gates Summary
Output truncated.
Test / Build skipped: 15, passed: 715
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Intrepid/Prometeu/Studio/pipeline/pr-master Build started...
JaCoCo Coverage #### Project Overview
No changes detected, that affect the code coverage.
* Line Coverage: 64.01% (20482/31999)
* Branch Coverage: 54.22% (8240/15196)
* Lines of Code: 31999
* Cyclomatic Complexity: 13164
#### Quality Gates Summary
Output truncated.
Test / Build skipped: 15, passed: 715
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
package p.studio.core;
|
||||
|
||||
public final class StudioCore {
|
||||
private StudioCore() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package p.studio.core.assets;
|
||||
|
||||
final class AssetsModule {
|
||||
private AssetsModule() {
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package p.studio.core.assets;
|
||||
|
||||
import p.studio.api.assets.AssetCapacityLevel;
|
||||
import p.studio.api.assets.AssetCapacityPolicy;
|
||||
import p.studio.api.assets.AssetCapacityState;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class DefaultAssetCapacityPolicy implements AssetCapacityPolicy {
|
||||
private static final int TILE_ATLAS_SIZE_PX = 256;
|
||||
private static final long SOUND_BANK_MAX_BYTES = 1024L * 1024L;
|
||||
|
||||
@Override
|
||||
public AssetCapacityState evaluate(AssetFamily family, int artifactCount, Map<String, String> metadata,
|
||||
Map<String, Object> pipeline, long usedBytes) {
|
||||
final AssetFamily safeFamily = Objects.requireNonNullElse(family, AssetFamily.UNKNOWN);
|
||||
final Map<String, String> safeMetadata = Map.copyOf(Objects.requireNonNull(metadata, "metadata"));
|
||||
final Map<String, Object> safePipeline = Map.copyOf(Objects.requireNonNull(pipeline, "pipeline"));
|
||||
return switch (safeFamily) {
|
||||
case GLYPH_BANK -> evaluateGlyphBank(artifactCount, safeMetadata);
|
||||
case SCENE_BANK -> new AssetCapacityState(0, AssetCapacityLevel.SAFE, false, artifactCount + " support files", "");
|
||||
case SOUND_BANK -> evaluateSoundBank(resolveSoundBankUsedBytes(safePipeline, usedBytes));
|
||||
case UNKNOWN -> new AssetCapacityState(0, AssetCapacityLevel.SAFE, false, artifactCount + " selected", "");
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public int maxArtifactsForGlyphBank(Map<String, String> metadata) {
|
||||
return switch (Objects.requireNonNull(metadata, "metadata").getOrDefault("tile_size", "16x16")) {
|
||||
case "8x8" -> slotsForTileSize(8);
|
||||
case "32x32" -> slotsForTileSize(32);
|
||||
default -> slotsForTileSize(16);
|
||||
};
|
||||
}
|
||||
|
||||
private AssetCapacityState evaluateGlyphBank(int count, Map<String, String> metadata) {
|
||||
final int maximum = maxArtifactsForGlyphBank(metadata);
|
||||
final int used = Math.max(0, count);
|
||||
final double progress = maximum <= 0 ? 0 : (double) used / maximum;
|
||||
final boolean blocked = used >= maximum;
|
||||
return new AssetCapacityState(progress, levelFor(progress), blocked, used + " / " + maximum,
|
||||
blocked ? "Glyph bank slot capacity reached." : "");
|
||||
}
|
||||
|
||||
private AssetCapacityState evaluateSoundBank(long usedBytes) {
|
||||
final long used = Math.max(0, usedBytes);
|
||||
final double progress = (double) used / SOUND_BANK_MAX_BYTES;
|
||||
final boolean blocked = used >= SOUND_BANK_MAX_BYTES;
|
||||
return new AssetCapacityState(progress, levelFor(progress), blocked,
|
||||
used + " / " + SOUND_BANK_MAX_BYTES + " bytes",
|
||||
blocked ? "Sound bank byte capacity reached." : "");
|
||||
}
|
||||
|
||||
private long resolveSoundBankUsedBytes(Map<String, Object> pipeline, long fallback) {
|
||||
final Object samplesNode = pipeline.get("samples");
|
||||
if (!(samplesNode instanceof Map<?, ?> samples)) {
|
||||
return Math.max(0, fallback);
|
||||
}
|
||||
long maximum = 0;
|
||||
for (Object value : samples.values()) {
|
||||
if (value instanceof Map<?, ?> sample) {
|
||||
maximum = Math.max(maximum, Math.max(0, longValue(sample.get("offset")))
|
||||
+ Math.max(0, Math.max(longValue(sample.get("len")), longValue(sample.get("length")))));
|
||||
}
|
||||
}
|
||||
return Math.max(maximum, Math.max(0, fallback));
|
||||
}
|
||||
|
||||
private long longValue(Object value) {
|
||||
if (value instanceof Number number) return number.longValue();
|
||||
if (value instanceof String text) {
|
||||
try { return Long.parseLong(text.trim()); } catch (NumberFormatException ignored) { return 0; }
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private int slotsForTileSize(int tileSize) {
|
||||
final int perAxis = Math.max(1, TILE_ATLAS_SIZE_PX / tileSize);
|
||||
return perAxis * perAxis;
|
||||
}
|
||||
|
||||
private AssetCapacityLevel levelFor(double progress) {
|
||||
if (progress >= 0.95) return AssetCapacityLevel.EXHAUSTED;
|
||||
if (progress >= 0.65) return AssetCapacityLevel.WARNING;
|
||||
return AssetCapacityLevel.SAFE;
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package p.studio.core.assets;
|
||||
|
||||
import p.studio.api.assets.AssetWorkspacePreparation;
|
||||
import p.studio.api.assets.AssetWorkspaceStorage;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class FileSystemAssetWorkspaceStorage implements AssetWorkspaceStorage {
|
||||
@Override
|
||||
public Path assetsRoot(ProjectReference projectReference) {
|
||||
return Objects.requireNonNull(projectReference, "projectReference")
|
||||
.rootPath()
|
||||
.resolve("assets")
|
||||
.toAbsolutePath()
|
||||
.normalize();
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetWorkspacePreparation prepare(ProjectReference projectReference) {
|
||||
final Path root = assetsRoot(projectReference);
|
||||
try {
|
||||
Files.createDirectories(root);
|
||||
return new AssetWorkspacePreparation(true, root, "");
|
||||
} catch (IOException exception) {
|
||||
return new AssetWorkspacePreparation(false, root, Objects.requireNonNullElse(exception.getMessage(), "Unable to prepare assets directory."));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean assetManifestExists(ProjectReference projectReference, String relativeAssetRoot) {
|
||||
final String candidate = Objects.requireNonNullElse(relativeAssetRoot, "").trim();
|
||||
if (candidate.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
final Path root = assetsRoot(projectReference);
|
||||
final Path assetRoot = root.resolve(candidate).toAbsolutePath().normalize();
|
||||
return assetRoot.startsWith(root) && Files.isRegularFile(assetRoot.resolve("asset.json"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package p.studio.core.assets;
|
||||
|
||||
import p.packer.PackerWorkspaceService;
|
||||
import p.packer.messages.ListAssetsRequest;
|
||||
import p.studio.api.assets.AssetBuildParticipation;
|
||||
import p.studio.api.assets.AssetCatalog;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import p.studio.api.assets.AssetReference;
|
||||
import p.studio.api.assets.AssetRegistrationState;
|
||||
import p.studio.api.assets.AssetSummary;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class PackerAssetCatalog implements AssetCatalog {
|
||||
private final PackerWorkspaceService packer;
|
||||
|
||||
public PackerAssetCatalog(PackerWorkspaceService packer) {
|
||||
this.packer = Objects.requireNonNull(packer, "packer");
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AssetSummary> list(ProjectReference projectReference, boolean deepSync) {
|
||||
final var context = new p.packer.messages.PackerProjectContext(
|
||||
projectReference.name(),
|
||||
projectReference.rootPath());
|
||||
return packer.listAssets(new ListAssetsRequest(context, deepSync)).assets().stream()
|
||||
.map(summary -> new AssetSummary(
|
||||
AssetReference.of(summary.assetReference().value()),
|
||||
summary.identity().assetName(),
|
||||
AssetRegistrationState.valueOf(summary.state().name()),
|
||||
AssetBuildParticipation.valueOf(summary.buildParticipation().name()),
|
||||
summary.identity().assetId(),
|
||||
AssetFamily.valueOf(summary.assetFamily().name()),
|
||||
summary.identity().assetRoot(),
|
||||
summary.preloadEnabled(),
|
||||
summary.hasDiagnostics()))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package p.studio.core.assets;
|
||||
|
||||
import p.packer.PackerWorkspaceService;
|
||||
import p.packer.messages.*;
|
||||
import p.packer.messages.assets.AssetFamilyCatalog;
|
||||
import p.packer.messages.assets.OutputCodecCatalog;
|
||||
import p.packer.messages.assets.OutputFormatCatalog;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.AssetReference;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class PackerAssetCommands implements AssetCommands {
|
||||
private final PackerWorkspaceService packer;
|
||||
|
||||
public PackerAssetCommands(PackerWorkspaceService packer) {
|
||||
this.packer = Objects.requireNonNull(packer, "packer");
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetMutationResult create(ProjectReference project, String assetRoot, String assetName,
|
||||
AssetFamily assetFamily, String outputFormat, String outputCodec, boolean preloadEnabled) {
|
||||
final var result = packer.createAsset(new CreateAssetRequest(
|
||||
context(project), assetRoot, assetName,
|
||||
AssetFamilyCatalog.valueOf(assetFamily.name()),
|
||||
OutputFormatCatalog.valueOf(outputFormat),
|
||||
OutputCodecCatalog.valueOf(outputCodec),
|
||||
preloadEnabled));
|
||||
return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath());
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetMutationResult move(ProjectReference project, AssetReference assetReference, String targetRoot) {
|
||||
final var result = packer.moveAsset(new MoveAssetRequest(context(project), reference(assetReference), targetRoot));
|
||||
return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath());
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetMutationResult register(ProjectReference project, AssetReference assetReference) {
|
||||
final var result = packer.registerAsset(new RegisterAssetRequest(context(project), reference(assetReference)));
|
||||
return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath());
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetMutationResult delete(ProjectReference project, AssetReference assetReference) {
|
||||
final var result = packer.deleteAsset(new DeleteAssetRequest(context(project), reference(assetReference)));
|
||||
return mutation(result.status(), result.summary(), reference(assetReference), result.assetRoot(), result.manifestPath());
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetMutationResult updateBuildParticipation(ProjectReference project, AssetReference assetReference,
|
||||
boolean includeInBuild) {
|
||||
final var result = packer.updateAssetBuildParticipation(new UpdateAssetBuildParticipationRequest(
|
||||
context(project), reference(assetReference), includeInBuild));
|
||||
return mutation(result.status(), result.summary(), result.assetReference(), null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetUpdateResult updateContract(ProjectReference project, AssetReference assetReference, boolean preload,
|
||||
String outputCodec, Map<String, String> codecFieldValues, Map<String, String> metadataFieldValues) {
|
||||
final var result = packer.updateAssetContract(new UpdateAssetContractRequest(
|
||||
context(project), reference(assetReference), preload, OutputCodecCatalog.valueOf(outputCodec),
|
||||
codecFieldValues, metadataFieldValues));
|
||||
return new AssetUpdateResult(result.success(), result.errorMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetUpdateResult applyBankComposition(ProjectReference project, AssetReference assetReference,
|
||||
List<String> selectedPaths) {
|
||||
final var result = packer.applyBankComposition(new ApplyBankCompositionRequest(
|
||||
context(project), reference(assetReference), selectedPaths));
|
||||
return new AssetUpdateResult(result.success(), result.errorMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetUpdateResult applyPaletteOverhauling(ProjectReference project, AssetReference assetReference,
|
||||
List<Map<String, Object>> selectedPalettes) {
|
||||
final var result = packer.applyPaletteOverhauling(new ApplyPaletteOverhaulingRequest(
|
||||
context(project), reference(assetReference), selectedPalettes));
|
||||
return new AssetUpdateResult(result.success(), result.errorMessage());
|
||||
}
|
||||
|
||||
private static PackerProjectContext context(ProjectReference project) {
|
||||
return new PackerProjectContext(project.name(), project.rootPath());
|
||||
}
|
||||
|
||||
private static p.packer.messages.AssetReference reference(AssetReference reference) {
|
||||
return p.packer.messages.AssetReference.of(reference.value());
|
||||
}
|
||||
|
||||
private static AssetMutationResult mutation(PackerOperationStatus status, String summary,
|
||||
p.packer.messages.AssetReference reference, java.nio.file.Path assetRoot, java.nio.file.Path manifestPath) {
|
||||
return new AssetMutationResult(
|
||||
AssetOperationStatus.valueOf(status.name()),
|
||||
summary,
|
||||
reference == null ? null : AssetReference.of(reference.value()),
|
||||
assetRoot,
|
||||
manifestPath);
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package p.studio.core.assets;
|
||||
|
||||
import p.packer.messages.assets.AssetFamilyCatalog;
|
||||
import p.packer.messages.assets.OutputCodecCatalog;
|
||||
import p.packer.messages.assets.OutputFormatCatalog;
|
||||
import p.studio.api.assets.AssetCreationCatalog;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public final class PackerAssetCreationCatalog implements AssetCreationCatalog {
|
||||
@Override
|
||||
public List<AssetFamily> supportedFamilies() {
|
||||
return Arrays.stream(AssetFamilyCatalog.values())
|
||||
.filter(family -> family != AssetFamilyCatalog.UNKNOWN)
|
||||
.map(family -> AssetFamily.valueOf(family.name()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> supportedFormats(AssetFamily family) {
|
||||
if (family == null || family == AssetFamily.UNKNOWN) {
|
||||
return List.of();
|
||||
}
|
||||
return OutputFormatCatalog.supportedFor(AssetFamilyCatalog.valueOf(family.name())).stream()
|
||||
.map(Enum::name)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> availableCodecs(String outputFormat) {
|
||||
final OutputFormatCatalog format = format(outputFormat);
|
||||
return format == null ? List.of() : format.availableCodecs().stream().map(Enum::name).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(String outputFormat, String outputCodec) {
|
||||
final OutputFormatCatalog format = format(outputFormat);
|
||||
final OutputCodecCatalog codec = codec(outputCodec);
|
||||
return format != null && codec != null && format.supports(codec);
|
||||
}
|
||||
|
||||
private OutputFormatCatalog format(String value) {
|
||||
try {
|
||||
return OutputFormatCatalog.valueOf(value);
|
||||
} catch (IllegalArgumentException | NullPointerException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private OutputCodecCatalog codec(String value) {
|
||||
try {
|
||||
return OutputCodecCatalog.valueOf(value);
|
||||
} catch (IllegalArgumentException | NullPointerException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package p.studio.core.assets;
|
||||
|
||||
import p.packer.PackerWorkspaceService;
|
||||
import p.packer.dtos.PackerBankCompositionDetailsDTO;
|
||||
import p.packer.dtos.PackerBankCompositionFileDTO;
|
||||
import p.packer.dtos.PackerCodecConfigurationFieldDTO;
|
||||
import p.packer.dtos.PackerDiagnosticDTO;
|
||||
import p.packer.messages.GetAssetActionsRequest;
|
||||
import p.packer.messages.GetAssetDetailsRequest;
|
||||
import p.packer.messages.PackerProjectContext;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.AssetReference;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public final class PackerAssetDetails implements AssetDetails {
|
||||
private final PackerWorkspaceService packer;
|
||||
|
||||
public PackerAssetDetails(PackerWorkspaceService packer) {
|
||||
this.packer = Objects.requireNonNull(packer, "packer");
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetDetailsSnapshot get(ProjectReference project, AssetReference assetReference) {
|
||||
final var context = new PackerProjectContext(project.name(), project.rootPath());
|
||||
final var reference = p.packer.messages.AssetReference.of(assetReference.value());
|
||||
final var detailsResult = packer.getAssetDetails(new GetAssetDetailsRequest(context, reference));
|
||||
final var actionsResult = packer.getAssetActions(new GetAssetActionsRequest(context, reference));
|
||||
final var details = detailsResult.details();
|
||||
final var codecFields = details.codecConfigurationFieldsByCodec().entrySet().stream()
|
||||
.collect(Collectors.toMap(
|
||||
entry -> entry.getKey().name(),
|
||||
entry -> entry.getValue().stream().map(PackerAssetDetails::field).toList(),
|
||||
(left, right) -> left,
|
||||
LinkedHashMap::new));
|
||||
final List<AssetDiagnostic> diagnostics = java.util.stream.Stream
|
||||
.concat(details.diagnostics().stream(), detailsResult.diagnostics().stream())
|
||||
.distinct()
|
||||
.map(PackerAssetDetails::diagnostic)
|
||||
.toList();
|
||||
return new AssetDetailsSnapshot(
|
||||
summary(details.summary()),
|
||||
actionsResult.actions().stream()
|
||||
.map(action -> new AssetActionAvailability(
|
||||
action.action().name(), action.enabled(), action.visible(), action.reason()))
|
||||
.toList(),
|
||||
details.outputFormat().name(),
|
||||
details.outputCodec().name(),
|
||||
details.availableOutputCodecs().stream().map(Enum::name).toList(),
|
||||
codecFields,
|
||||
details.metadataFields().stream().map(PackerAssetDetails::field).toList(),
|
||||
details.outputPipeline(),
|
||||
bank(details.bankComposition()),
|
||||
details.pipelinePalettes(),
|
||||
diagnostics);
|
||||
}
|
||||
|
||||
private static AssetSummary summary(p.packer.dtos.PackerAssetSummaryDTO summary) {
|
||||
return new AssetSummary(
|
||||
AssetReference.of(summary.assetReference().value()),
|
||||
summary.identity().assetName(),
|
||||
AssetRegistrationState.valueOf(summary.state().name()),
|
||||
AssetBuildParticipation.valueOf(summary.buildParticipation().name()),
|
||||
summary.identity().assetId(),
|
||||
AssetFamily.valueOf(summary.assetFamily().name()),
|
||||
summary.identity().assetRoot(),
|
||||
summary.preloadEnabled(),
|
||||
summary.hasDiagnostics());
|
||||
}
|
||||
|
||||
private static AssetConfigurationField field(PackerCodecConfigurationFieldDTO field) {
|
||||
return new AssetConfigurationField(
|
||||
field.key(), field.label(), field.fieldType().name(), field.value(), field.required(), field.options());
|
||||
}
|
||||
|
||||
private static AssetDiagnostic diagnostic(PackerDiagnosticDTO diagnostic) {
|
||||
return new AssetDiagnostic(
|
||||
diagnostic.severity().name(), diagnostic.category().name(), diagnostic.message(),
|
||||
diagnostic.evidencePath(), diagnostic.blocking());
|
||||
}
|
||||
|
||||
private static AssetBankComposition bank(PackerBankCompositionDetailsDTO bank) {
|
||||
return new AssetBankComposition(
|
||||
bank.availableFiles().stream().map(PackerAssetDetails::bankFile).toList(),
|
||||
bank.selectedFiles().stream().map(PackerAssetDetails::bankFile).toList(),
|
||||
bank.measuredBankSizeBytes());
|
||||
}
|
||||
|
||||
private static AssetBankFile bankFile(PackerBankCompositionFileDTO file) {
|
||||
return new AssetBankFile(
|
||||
file.path(), file.displayName(), file.size(), file.lastModified(), file.fingerprint(), file.metadata());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package p.studio.core.assets;
|
||||
|
||||
import p.packer.PackerWorkspaceService;
|
||||
import p.packer.messages.*;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.operation.OperationExecutor;
|
||||
import p.studio.api.operation.OperationHandle;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public final class PackerAssetPacking implements AssetPacking {
|
||||
private final PackerWorkspaceService packer;
|
||||
private final OperationExecutor operations;
|
||||
|
||||
public PackerAssetPacking(PackerWorkspaceService packer, OperationExecutor operations) {
|
||||
this.packer = Objects.requireNonNull(packer, "packer");
|
||||
this.operations = Objects.requireNonNull(operations, "operations");
|
||||
}
|
||||
|
||||
@Override
|
||||
public OperationHandle<AssetSyncResult> deepSync(ProjectReference project) {
|
||||
return operations.submit("Synchronize project assets", () -> deepSyncNow(project));
|
||||
}
|
||||
|
||||
private AssetSyncResult deepSyncNow(ProjectReference project) {
|
||||
final var result = packer.listAssets(new ListAssetsRequest(context(project), true));
|
||||
return new AssetSyncResult(status(result.status()), result.summary());
|
||||
}
|
||||
|
||||
@Override
|
||||
public OperationHandle<AssetPackSummary> summarize(ProjectReference project) {
|
||||
return operations.submit("Summarize project assets", () -> summarizeNow(project));
|
||||
}
|
||||
|
||||
private AssetPackSummary summarizeNow(ProjectReference project) {
|
||||
final var result = packer.getPackWorkspaceSummary(new PackWorkspaceSummaryRequest(context(project)));
|
||||
return new AssetPackSummary(
|
||||
status(result.status()), result.summary(), result.packSummary().totalIncludedAssetCount(),
|
||||
result.packSummary().assets().stream()
|
||||
.map(asset -> new AssetPackSummaryItem(
|
||||
asset.assetId(), asset.assetName(), AssetFamily.valueOf(asset.assetFamily().name()),
|
||||
asset.artifactCount(), asset.outputMetadata(), asset.outputPipeline()))
|
||||
.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public OperationHandle<AssetPackValidation> validate(ProjectReference project) {
|
||||
return operations.submit("Validate project asset pack", () -> validateNow(project));
|
||||
}
|
||||
|
||||
private AssetPackValidation validateNow(ProjectReference project) {
|
||||
final var result = packer.validatePackWorkspace(new ValidatePackWorkspaceRequest(context(project)));
|
||||
return new AssetPackValidation(status(result.status()), result.summary(), result.assets().stream()
|
||||
.map(asset -> new AssetPackValidationItem(
|
||||
asset.assetId(), asset.assetName(), asset.assetPath(), asset.lastModified(),
|
||||
asset.diagnostics().stream()
|
||||
.map(diagnostic -> new AssetPackDiagnostic(
|
||||
diagnostic.severity().name(), diagnostic.message(), diagnostic.blocking()))
|
||||
.toList()))
|
||||
.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public OperationHandle<AssetPackExecution> pack(ProjectReference project) {
|
||||
return operations.submit("Pack project assets", () -> packNow(project));
|
||||
}
|
||||
|
||||
private AssetPackExecution packNow(ProjectReference project) {
|
||||
final var result = packer.packWorkspace(new PackWorkspaceRequest(context(project)));
|
||||
return new AssetPackExecution(
|
||||
status(result.status()), result.summary(), result.result().canonicalArtifactName(),
|
||||
result.result().packedAssetCount(), result.result().elapsedMillis(),
|
||||
result.result().emittedArtifacts().stream()
|
||||
.map(artifact -> new AssetEmittedArtifact(
|
||||
artifact.label(), artifact.path(), artifact.canonical(), artifact.sizeBytes()))
|
||||
.toList());
|
||||
}
|
||||
|
||||
private static PackerProjectContext context(ProjectReference project) {
|
||||
return new PackerProjectContext(project.name(), project.rootPath());
|
||||
}
|
||||
|
||||
private static AssetOperationStatus status(PackerOperationStatus status) {
|
||||
return AssetOperationStatus.valueOf(status.name());
|
||||
}
|
||||
}
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
package p.studio.core.assets.bank;
|
||||
|
||||
import p.studio.api.assets.AssetCapacityPolicy;
|
||||
import p.studio.api.assets.AssetCapacityState;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import p.studio.api.assets.bank.AssetBankCompositionSession;
|
||||
import p.studio.api.assets.bank.AssetBankCompositionState;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceAssetDetails;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceBankCompositionFile;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class DefaultAssetBankCompositionSession implements AssetBankCompositionSession {
|
||||
private static final long MAX_SOUND_BANK_BYTES = 1024L * 1024L;
|
||||
|
||||
private final AssetCapacityPolicy capacityPolicy;
|
||||
private CompositionRules rules;
|
||||
private Draft source;
|
||||
private Draft draft;
|
||||
private boolean editing;
|
||||
|
||||
public DefaultAssetBankCompositionSession(AssetCapacityPolicy capacityPolicy) {
|
||||
this.capacityPolicy = Objects.requireNonNull(capacityPolicy, "capacityPolicy");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void replaceDetails(AssetWorkspaceAssetDetails details) {
|
||||
if (details == null) {
|
||||
rules = null;
|
||||
source = null;
|
||||
draft = null;
|
||||
editing = false;
|
||||
return;
|
||||
}
|
||||
rules = rulesFor(details);
|
||||
final Draft replacement = createDraft(details);
|
||||
if (!Objects.equals(source, replacement)) {
|
||||
source = replacement;
|
||||
draft = replacement;
|
||||
editing = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean ready() {
|
||||
return rules != null && source != null && draft != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beginEdit() {
|
||||
if (ready()) {
|
||||
editing = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void apply() {
|
||||
if (ready()) {
|
||||
source = draft;
|
||||
editing = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
if (ready()) {
|
||||
draft = source;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
if (ready()) {
|
||||
draft = source;
|
||||
editing = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void moveToSelected(List<AssetWorkspaceBankCompositionFile> files) {
|
||||
if (!ready() || !editing) {
|
||||
return;
|
||||
}
|
||||
final List<AssetWorkspaceBankCompositionFile> requested = List.copyOf(files);
|
||||
final var requestedSet = new LinkedHashSet<>(requested);
|
||||
final List<AssetWorkspaceBankCompositionFile> accepted = new ArrayList<>();
|
||||
for (AssetWorkspaceBankCompositionFile file : draft.availableFiles()) {
|
||||
if (requestedSet.contains(file) && rules.canAdd(draft, accepted, file)) {
|
||||
accepted.add(file);
|
||||
}
|
||||
}
|
||||
draft = draft.removeFromAvailable(accepted).appendToSelected(accepted);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void moveToAvailable(List<AssetWorkspaceBankCompositionFile> files) {
|
||||
if (!ready() || !editing) {
|
||||
return;
|
||||
}
|
||||
final List<AssetWorkspaceBankCompositionFile> returned = new ArrayList<>(files);
|
||||
returned.sort(java.util.Comparator.comparing(AssetWorkspaceBankCompositionFile::path, String.CASE_INSENSITIVE_ORDER));
|
||||
draft = draft.removeFromSelected(files).appendToAvailable(returned);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void moveUp(int selectedIndex) {
|
||||
if (!ready() || !editing || selectedIndex <= 0 || selectedIndex >= draft.selectedFiles().size()) {
|
||||
return;
|
||||
}
|
||||
final List<AssetWorkspaceBankCompositionFile> reordered = new ArrayList<>(draft.selectedFiles());
|
||||
final AssetWorkspaceBankCompositionFile moved = reordered.remove(selectedIndex);
|
||||
reordered.add(selectedIndex - 1, moved);
|
||||
draft = new Draft(draft.availableFiles(), reordered);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void moveDown(int selectedIndex) {
|
||||
if (!ready() || !editing || selectedIndex < 0 || selectedIndex >= draft.selectedFiles().size() - 1) {
|
||||
return;
|
||||
}
|
||||
final List<AssetWorkspaceBankCompositionFile> reordered = new ArrayList<>(draft.selectedFiles());
|
||||
final AssetWorkspaceBankCompositionFile moved = reordered.remove(selectedIndex);
|
||||
reordered.add(selectedIndex + 1, moved);
|
||||
draft = new Draft(draft.availableFiles(), reordered);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetBankCompositionState state() {
|
||||
if (!ready()) {
|
||||
return new AssetBankCompositionState(false, false, List.of(), List.of(), emptyCapacity());
|
||||
}
|
||||
return new AssetBankCompositionState(
|
||||
editing,
|
||||
!Objects.equals(source, draft),
|
||||
draft.availableFiles(),
|
||||
draft.selectedFiles(),
|
||||
rules.evaluate(draft));
|
||||
}
|
||||
|
||||
private Draft createDraft(AssetWorkspaceAssetDetails details) {
|
||||
final List<AssetWorkspaceBankCompositionFile> selected = details.bankComposition().selectedFiles();
|
||||
final var selectedPaths = selected.stream()
|
||||
.map(AssetWorkspaceBankCompositionFile::path)
|
||||
.collect(java.util.stream.Collectors.toSet());
|
||||
final List<AssetWorkspaceBankCompositionFile> available = details.bankComposition().availableFiles().stream()
|
||||
.filter(file -> !selectedPaths.contains(file.path()))
|
||||
.toList();
|
||||
return new Draft(available, selected);
|
||||
}
|
||||
|
||||
private CompositionRules rulesFor(AssetWorkspaceAssetDetails details) {
|
||||
if (details.summary().assetFamily() == AssetFamily.GLYPH_BANK) {
|
||||
final String tileSize = details.metadataFields().stream()
|
||||
.filter(field -> field.key().equals("tile_size"))
|
||||
.map(field -> field.value())
|
||||
.findFirst()
|
||||
.orElse("16x16");
|
||||
final Map<String, String> metadata = Map.of("tile_size", tileSize);
|
||||
final int maximum = capacityPolicy.maxArtifactsForGlyphBank(metadata);
|
||||
return new CompositionRules() {
|
||||
@Override
|
||||
public boolean canAdd(Draft current, List<AssetWorkspaceBankCompositionFile> accepted,
|
||||
AssetWorkspaceBankCompositionFile candidate) {
|
||||
return current.selectedFiles().size() + accepted.size() < maximum;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetCapacityState evaluate(Draft current) {
|
||||
return capacityPolicy.evaluate(AssetFamily.GLYPH_BANK, current.selectedFiles().size(), metadata, Map.of(), 0L);
|
||||
}
|
||||
};
|
||||
}
|
||||
if (details.summary().assetFamily() == AssetFamily.SOUND_BANK) {
|
||||
final Map<String, Object> outputPipeline = details.outputPipeline();
|
||||
return new CompositionRules() {
|
||||
@Override
|
||||
public boolean canAdd(Draft current, List<AssetWorkspaceBankCompositionFile> accepted,
|
||||
AssetWorkspaceBankCompositionFile candidate) {
|
||||
return selectedBytes(current.selectedFiles()) + selectedBytes(accepted) + candidate.size() <= MAX_SOUND_BANK_BYTES;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetCapacityState evaluate(Draft current) {
|
||||
return capacityPolicy.evaluate(AssetFamily.SOUND_BANK, current.selectedFiles().size(), Map.of(),
|
||||
outputPipeline, selectedBytes(current.selectedFiles()));
|
||||
}
|
||||
};
|
||||
}
|
||||
return new CompositionRules() {
|
||||
@Override
|
||||
public boolean canAdd(Draft current, List<AssetWorkspaceBankCompositionFile> accepted,
|
||||
AssetWorkspaceBankCompositionFile candidate) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetCapacityState evaluate(Draft current) {
|
||||
return capacityPolicy.evaluate(AssetFamily.UNKNOWN, current.selectedFiles().size(), Map.of(), Map.of(), 0L);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static long selectedBytes(List<AssetWorkspaceBankCompositionFile> files) {
|
||||
return files.stream().mapToLong(AssetWorkspaceBankCompositionFile::size).sum();
|
||||
}
|
||||
|
||||
private static AssetCapacityState emptyCapacity() {
|
||||
return new AssetCapacityState(0.0d, null, false, "", "");
|
||||
}
|
||||
|
||||
private interface CompositionRules {
|
||||
boolean canAdd(Draft current, List<AssetWorkspaceBankCompositionFile> accepted,
|
||||
AssetWorkspaceBankCompositionFile candidate);
|
||||
AssetCapacityState evaluate(Draft current);
|
||||
}
|
||||
|
||||
private record Draft(
|
||||
List<AssetWorkspaceBankCompositionFile> availableFiles,
|
||||
List<AssetWorkspaceBankCompositionFile> selectedFiles) {
|
||||
private Draft {
|
||||
availableFiles = List.copyOf(availableFiles);
|
||||
selectedFiles = List.copyOf(selectedFiles);
|
||||
}
|
||||
|
||||
private Draft removeFromAvailable(List<AssetWorkspaceBankCompositionFile> files) {
|
||||
final var removed = new LinkedHashSet<>(files);
|
||||
return new Draft(availableFiles.stream().filter(file -> !removed.contains(file)).toList(), selectedFiles);
|
||||
}
|
||||
|
||||
private Draft appendToSelected(List<AssetWorkspaceBankCompositionFile> files) {
|
||||
final List<AssetWorkspaceBankCompositionFile> next = new ArrayList<>(selectedFiles);
|
||||
next.addAll(files);
|
||||
return new Draft(availableFiles, next);
|
||||
}
|
||||
|
||||
private Draft removeFromSelected(List<AssetWorkspaceBankCompositionFile> files) {
|
||||
final var removed = new LinkedHashSet<>(files);
|
||||
return new Draft(availableFiles, selectedFiles.stream().filter(file -> !removed.contains(file)).toList());
|
||||
}
|
||||
|
||||
private Draft appendToAvailable(List<AssetWorkspaceBankCompositionFile> files) {
|
||||
final List<AssetWorkspaceBankCompositionFile> next = new ArrayList<>(availableFiles);
|
||||
next.addAll(files);
|
||||
return new Draft(next, selectedFiles);
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package p.studio.core.assets.bank;
|
||||
|
||||
import p.studio.api.assets.AssetCapacityPolicy;
|
||||
import p.studio.api.assets.bank.AssetBankCompositionSession;
|
||||
import p.studio.api.assets.bank.AssetBankCompositionSessionFactory;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public final class DefaultAssetBankCompositionSessionFactory implements AssetBankCompositionSessionFactory {
|
||||
private final AssetCapacityPolicy capacityPolicy;
|
||||
|
||||
public DefaultAssetBankCompositionSessionFactory(AssetCapacityPolicy capacityPolicy) {
|
||||
this.capacityPolicy = Objects.requireNonNull(capacityPolicy, "capacityPolicy");
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetBankCompositionSession createSession() {
|
||||
return new DefaultAssetBankCompositionSession(capacityPolicy);
|
||||
}
|
||||
}
|
||||
+408
@@ -0,0 +1,408 @@
|
||||
package p.studio.core.assets.metadata;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import p.studio.api.assets.metadata.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
public final class AssetStudioMetadataService implements AssetMetadataService {
|
||||
public static final String STUDIO_ASSET_METADATA_FILE = "studio.asset.json";
|
||||
public static final String SCENE_BANK_SUPPORT_FILE = "scene-bank.studio.json";
|
||||
public static final String GLYPH_MATERIAL_SUPPORT_FILE = "glyph-material.json";
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public AssetStudioMetadataService(ObjectMapper mapper) {
|
||||
this.mapper = Objects.requireNonNull(mapper, "mapper");
|
||||
}
|
||||
|
||||
public AssetStudioMetadataService() {
|
||||
this(new ObjectMapper());
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetStudioMetadataSnapshot read(Path assetRoot, AssetFamily assetFamily) {
|
||||
final Path normalizedAssetRoot = Objects.requireNonNull(assetRoot, "assetRoot").toAbsolutePath().normalize();
|
||||
return new AssetStudioMetadataSnapshot(
|
||||
readGlyphSpecialization(normalizedAssetRoot, assetFamily),
|
||||
readSceneBankMetadata(normalizedAssetRoot, assetFamily),
|
||||
readGlyphMaterialMetadata(normalizedAssetRoot, assetFamily));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetMetadataWriteResult writeSceneBankMetadata(Path assetRoot, AssetStudioSceneBankMetadata metadata) {
|
||||
try {
|
||||
writeSceneBankMetadataFile(assetRoot, metadata);
|
||||
return AssetMetadataWriteResult.success();
|
||||
} catch (IOException exception) {
|
||||
return AssetMetadataWriteResult.failure(message("Unable to write scene-bank metadata.", exception));
|
||||
}
|
||||
}
|
||||
|
||||
private void writeSceneBankMetadataFile(Path assetRoot, AssetStudioSceneBankMetadata metadata) throws IOException {
|
||||
final Path normalizedAssetRoot = Objects.requireNonNull(assetRoot, "assetRoot").toAbsolutePath().normalize();
|
||||
final AssetStudioSceneBankMetadata normalized = Objects.requireNonNull(metadata, "metadata");
|
||||
final var root = mapper.createObjectNode();
|
||||
root.put("schema_version", 1);
|
||||
root.put("map_width", normalized.mapWidth());
|
||||
root.put("map_height", normalized.mapHeight());
|
||||
root.put("layer_count", normalized.layerCount());
|
||||
final ArrayNode layers = root.putArray("layers");
|
||||
for (AssetStudioSceneLayerBinding binding : normalized.layerBindings()) {
|
||||
final var layer = layers.addObject();
|
||||
layer.put("index", binding.index());
|
||||
layer.put("enabled", binding.enabled());
|
||||
layer.put("name", binding.layerName());
|
||||
layer.put("width", binding.width());
|
||||
layer.put("height", binding.height());
|
||||
layer.put("tilemap", binding.tilemap());
|
||||
layer.put("tileset_asset_root", binding.tilesetAssetRoot());
|
||||
layer.put("parallax_factor_x", binding.parallaxFactorX());
|
||||
layer.put("parallax_factor_y", binding.parallaxFactorY());
|
||||
layer.put("default_palette_id", binding.defaultPaletteId());
|
||||
if (binding.tiles().stream().anyMatch(AssetStudioSceneTile::active)) {
|
||||
final ArrayNode tiles = layer.putArray("tiles");
|
||||
for (AssetStudioSceneTile tile : binding.tiles()) {
|
||||
final var tileNode = tiles.addObject();
|
||||
tileNode.put("active", tile.active());
|
||||
tileNode.put("glyph_id", tile.glyphId());
|
||||
tileNode.put("palette_id", tile.paletteId());
|
||||
tileNode.put("flip_x", tile.flipX());
|
||||
tileNode.put("flip_y", tile.flipY());
|
||||
}
|
||||
}
|
||||
}
|
||||
mapper.writerWithDefaultPrettyPrinter().writeValue(
|
||||
normalizedAssetRoot.resolve(SCENE_BANK_SUPPORT_FILE).toFile(),
|
||||
root);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetMetadataWriteResult writeGlyphSpecialization(Path assetRoot, AssetStudioGlyphSpecialization specialization) {
|
||||
try {
|
||||
writeGlyphSpecializationFile(assetRoot, specialization);
|
||||
return AssetMetadataWriteResult.success();
|
||||
} catch (IOException exception) {
|
||||
return AssetMetadataWriteResult.failure(message("Unable to write glyph specialization metadata.", exception));
|
||||
}
|
||||
}
|
||||
|
||||
private void writeGlyphSpecializationFile(Path assetRoot, AssetStudioGlyphSpecialization specialization) throws IOException {
|
||||
final Path metadataPath = Objects.requireNonNull(assetRoot, "assetRoot")
|
||||
.toAbsolutePath()
|
||||
.normalize()
|
||||
.resolve(STUDIO_ASSET_METADATA_FILE);
|
||||
final AssetStudioGlyphSpecialization normalized = Objects.requireNonNullElse(
|
||||
specialization,
|
||||
AssetStudioGlyphSpecialization.NONE);
|
||||
if (normalized == AssetStudioGlyphSpecialization.NONE) {
|
||||
Files.deleteIfExists(metadataPath);
|
||||
return;
|
||||
}
|
||||
final var root = mapper.createObjectNode();
|
||||
root.put("schema_version", 1);
|
||||
root.put("glyph_bank_specialization", normalized.manifestValue());
|
||||
mapper.writerWithDefaultPrettyPrinter().writeValue(metadataPath.toFile(), root);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetMetadataWriteResult writeGlyphMaterialMetadata(Path assetRoot, AssetStudioGlyphMaterialMetadata metadata) {
|
||||
try {
|
||||
writeGlyphMaterialMetadataFile(assetRoot, metadata);
|
||||
return AssetMetadataWriteResult.success();
|
||||
} catch (IOException exception) {
|
||||
return AssetMetadataWriteResult.failure(message("Unable to write glyph-material metadata.", exception));
|
||||
}
|
||||
}
|
||||
|
||||
private void writeGlyphMaterialMetadataFile(Path assetRoot, AssetStudioGlyphMaterialMetadata metadata) throws IOException {
|
||||
final Path normalizedAssetRoot = Objects.requireNonNull(assetRoot, "assetRoot").toAbsolutePath().normalize();
|
||||
final AssetStudioGlyphMaterialMetadata normalized = Objects.requireNonNull(metadata, "metadata");
|
||||
final var root = mapper.createObjectNode();
|
||||
root.put("schema_version", 1);
|
||||
final ArrayNode schemas = root.putArray("schemas");
|
||||
for (AssetStudioGlyphMaterialSchema schema : normalized.schemas()) {
|
||||
final var schemaNode = schemas.addObject();
|
||||
schemaNode.put("schema_id", schema.schemaId());
|
||||
schemaNode.put("status", schema.status().manifestValue());
|
||||
schemaNode.put("version", schema.version());
|
||||
final var materialIndicesNode = schemaNode.putObject("material_indices");
|
||||
schema.materialIndices().entrySet().stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
.forEach(entry -> materialIndicesNode.put(String.valueOf(entry.getKey()), entry.getValue()));
|
||||
final ArrayNode bindingsNode = schemaNode.putArray("artifact_bindings");
|
||||
for (AssetStudioGlyphMaterialArtifactBinding binding : schema.artifactBindings()) {
|
||||
final var bindingNode = bindingsNode.addObject();
|
||||
bindingNode.put("artifact_id", binding.artifactId());
|
||||
bindingNode.put("fingerprint", binding.fingerprint());
|
||||
}
|
||||
}
|
||||
final ArrayNode palettes = root.putArray("palettes");
|
||||
for (AssetStudioGlyphMaterialPalette palette : normalized.palettes()) {
|
||||
final var paletteNode = palettes.addObject();
|
||||
paletteNode.put("palette_id", palette.paletteId());
|
||||
if (palette.displayName() != null) {
|
||||
paletteNode.put("name", palette.displayName());
|
||||
}
|
||||
paletteNode.put("schema_id", palette.schemaId());
|
||||
paletteNode.put("version", palette.version());
|
||||
final ArrayNode colorsNode = paletteNode.putArray("colors");
|
||||
palette.colors().forEach(colorsNode::add);
|
||||
}
|
||||
mapper.writerWithDefaultPrettyPrinter().writeValue(
|
||||
normalizedAssetRoot.resolve(GLYPH_MATERIAL_SUPPORT_FILE).toFile(),
|
||||
root);
|
||||
}
|
||||
|
||||
private static String message(String fallback, IOException exception) {
|
||||
return exception.getMessage() == null || exception.getMessage().isBlank()
|
||||
? fallback
|
||||
: exception.getMessage();
|
||||
}
|
||||
|
||||
private AssetStudioGlyphSpecialization readGlyphSpecialization(Path assetRoot, AssetFamily assetFamily) {
|
||||
if (assetFamily != AssetFamily.GLYPH_BANK) {
|
||||
return AssetStudioGlyphSpecialization.NONE;
|
||||
}
|
||||
final Path metadataPath = assetRoot.resolve(STUDIO_ASSET_METADATA_FILE);
|
||||
if (!Files.isRegularFile(metadataPath)) {
|
||||
return AssetStudioGlyphSpecialization.NONE;
|
||||
}
|
||||
try {
|
||||
final JsonNode root = mapper.readTree(metadataPath.toFile());
|
||||
if (root == null || !root.isObject()) {
|
||||
return AssetStudioGlyphSpecialization.NONE;
|
||||
}
|
||||
return AssetStudioGlyphSpecialization.fromManifestValue(root.path("glyph_bank_specialization").asText(null));
|
||||
} catch (IOException ignored) {
|
||||
return AssetStudioGlyphSpecialization.NONE;
|
||||
}
|
||||
}
|
||||
|
||||
private AssetStudioSceneBankMetadata readSceneBankMetadata(Path assetRoot, AssetFamily assetFamily) {
|
||||
if (assetFamily != AssetFamily.SCENE_BANK) {
|
||||
return null;
|
||||
}
|
||||
final Path supportFile = assetRoot.resolve(SCENE_BANK_SUPPORT_FILE);
|
||||
if (!Files.isRegularFile(supportFile)) {
|
||||
return defaultSceneBankMetadata(supportFile);
|
||||
}
|
||||
try {
|
||||
final JsonNode root = mapper.readTree(supportFile.toFile());
|
||||
if (root == null || !root.isObject()) {
|
||||
return null;
|
||||
}
|
||||
final int mapWidth = root.path("map_width").asInt(0);
|
||||
final int mapHeight = root.path("map_height").asInt(0);
|
||||
final int layerCount = root.path("layer_count").asInt(0);
|
||||
if (mapWidth <= 0 || mapHeight <= 0 || layerCount != 4) {
|
||||
return null;
|
||||
}
|
||||
if (!(root.path("layers") instanceof ArrayNode layersNode) || layersNode.size() != layerCount) {
|
||||
return null;
|
||||
}
|
||||
final List<AssetStudioSceneLayerBinding> bindings = new ArrayList<>();
|
||||
final Set<Integer> indexes = new HashSet<>();
|
||||
for (JsonNode layerNode : layersNode) {
|
||||
final int index = layerNode.path("index").asInt(0);
|
||||
final boolean enabled = layerNode.path("enabled").asBoolean(false);
|
||||
final String layerName = layerNode.path("name").asText("").trim();
|
||||
final int width = layerNode.path("width").asInt(mapWidth);
|
||||
final int height = layerNode.path("height").asInt(mapHeight);
|
||||
final String tilemap = layerNode.path("tilemap").asText("").trim();
|
||||
final String tilesetAssetRoot = layerNode.path("tileset_asset_root").asText("").trim();
|
||||
final float parallaxFactorX = (float) layerNode.path("parallax_factor_x").asDouble(1.0d);
|
||||
final float parallaxFactorY = (float) layerNode.path("parallax_factor_y").asDouble(1.0d);
|
||||
final int defaultPaletteId = layerNode.path("default_palette_id").asInt(0);
|
||||
if (index < 1 || index > layerCount || layerName.isBlank() || width <= 0 || height <= 0 || tilemap.isBlank() || !indexes.add(index)) {
|
||||
return null;
|
||||
}
|
||||
final List<AssetStudioSceneTile> tiles = readSceneTiles(layerNode.path("tiles"), width, height, defaultPaletteId);
|
||||
if (tiles == null) {
|
||||
return null;
|
||||
}
|
||||
bindings.add(new AssetStudioSceneLayerBinding(
|
||||
enabled,
|
||||
index,
|
||||
layerName,
|
||||
width,
|
||||
height,
|
||||
tilemap,
|
||||
tilesetAssetRoot,
|
||||
parallaxFactorX,
|
||||
parallaxFactorY,
|
||||
defaultPaletteId,
|
||||
tiles));
|
||||
}
|
||||
bindings.sort(Comparator.comparingInt(AssetStudioSceneLayerBinding::index));
|
||||
return new AssetStudioSceneBankMetadata(mapWidth, mapHeight, layerCount, bindings, supportFile);
|
||||
} catch (IOException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private AssetStudioGlyphMaterialMetadata readGlyphMaterialMetadata(Path assetRoot, AssetFamily assetFamily) {
|
||||
if (assetFamily != AssetFamily.GLYPH_BANK) {
|
||||
return null;
|
||||
}
|
||||
final Path supportFile = assetRoot.resolve(GLYPH_MATERIAL_SUPPORT_FILE);
|
||||
if (!Files.isRegularFile(supportFile)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
final JsonNode root = mapper.readTree(supportFile.toFile());
|
||||
if (root == null || !root.isObject()) {
|
||||
return null;
|
||||
}
|
||||
if (!(root.path("schemas") instanceof ArrayNode schemasNode) || !(root.path("palettes") instanceof ArrayNode palettesNode)) {
|
||||
return null;
|
||||
}
|
||||
final List<AssetStudioGlyphMaterialSchema> schemas = new ArrayList<>();
|
||||
final Set<String> schemaIds = new HashSet<>();
|
||||
for (JsonNode schemaNode : schemasNode) {
|
||||
final String schemaId = schemaNode.path("schema_id").asText("").trim();
|
||||
final AssetStudioGlyphMaterialSchemaStatus status = AssetStudioGlyphMaterialSchemaStatus.fromManifestValue(
|
||||
schemaNode.path("status").asText(null));
|
||||
final int version = schemaNode.path("version").asInt(0);
|
||||
if (schemaId.isBlank() || status == null || version <= 0 || !schemaIds.add(schemaId)) {
|
||||
return null;
|
||||
}
|
||||
final JsonNode materialIndicesNode = schemaNode.path("material_indices");
|
||||
if (!materialIndicesNode.isObject()) {
|
||||
return null;
|
||||
}
|
||||
final Map<Integer, String> materialIndices = new java.util.TreeMap<>();
|
||||
materialIndicesNode.fields().forEachRemaining(entry -> {
|
||||
try {
|
||||
final int index = Integer.parseInt(entry.getKey());
|
||||
final String color = normalizeHtmlColor(entry.getValue().asText(null));
|
||||
if (index >= 0 && index <= 15 && color != null) {
|
||||
materialIndices.put(index, color);
|
||||
}
|
||||
} catch (NumberFormatException ignored) {
|
||||
// handled below through validation
|
||||
}
|
||||
});
|
||||
if (materialIndices.isEmpty()
|
||||
|| materialIndices.size() != materialIndicesNode.size()
|
||||
|| !denseIndices(materialIndices.keySet())) {
|
||||
return null;
|
||||
}
|
||||
if (!(schemaNode.path("artifact_bindings") instanceof ArrayNode bindingsNode) || bindingsNode.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
final List<AssetStudioGlyphMaterialArtifactBinding> bindings = new ArrayList<>();
|
||||
final Set<String> artifactIds = new HashSet<>();
|
||||
for (JsonNode bindingNode : bindingsNode) {
|
||||
final String artifactId = bindingNode.path("artifact_id").asText("").trim();
|
||||
final String fingerprint = bindingNode.path("fingerprint").asText("").trim();
|
||||
if (artifactId.isBlank() || fingerprint.isBlank() || !artifactIds.add(artifactId)) {
|
||||
return null;
|
||||
}
|
||||
bindings.add(new AssetStudioGlyphMaterialArtifactBinding(artifactId, fingerprint));
|
||||
}
|
||||
schemas.add(new AssetStudioGlyphMaterialSchema(schemaId, status, version, materialIndices, bindings));
|
||||
}
|
||||
final List<AssetStudioGlyphMaterialPalette> palettes = new ArrayList<>();
|
||||
final Set<String> paletteIds = new HashSet<>();
|
||||
for (JsonNode paletteNode : palettesNode) {
|
||||
final String paletteId = paletteNode.path("palette_id").asText("").trim();
|
||||
final String displayName = paletteNode.path("name").asText(null);
|
||||
final String schemaId = paletteNode.path("schema_id").asText("").trim();
|
||||
final int version = paletteNode.path("version").asInt(0);
|
||||
if (paletteId.isBlank() || schemaId.isBlank() || version <= 0 || !paletteIds.add(paletteId) || !schemaIds.contains(schemaId)) {
|
||||
return null;
|
||||
}
|
||||
if (!(paletteNode.path("colors") instanceof ArrayNode colorsNode)) {
|
||||
return null;
|
||||
}
|
||||
final List<String> colors = new ArrayList<>();
|
||||
for (JsonNode colorNode : colorsNode) {
|
||||
final String color = normalizeHtmlColor(colorNode.asText(null));
|
||||
if (color == null) {
|
||||
return null;
|
||||
}
|
||||
colors.add(color);
|
||||
}
|
||||
palettes.add(new AssetStudioGlyphMaterialPalette(paletteId, displayName, schemaId, version, colors));
|
||||
}
|
||||
return new AssetStudioGlyphMaterialMetadata(schemas, palettes, supportFile);
|
||||
} catch (IOException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean denseIndices(Set<Integer> indices) {
|
||||
if (indices.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
int expected = 0;
|
||||
for (Integer index : new java.util.TreeSet<>(indices)) {
|
||||
if (index == null || index != expected) {
|
||||
return false;
|
||||
}
|
||||
expected += 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private String normalizeHtmlColor(String value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
final String normalized = value.trim().toUpperCase();
|
||||
return normalized.matches("^#[0-9A-F]{6}([0-9A-F]{2})?$") ? normalized : null;
|
||||
}
|
||||
|
||||
private AssetStudioSceneBankMetadata defaultSceneBankMetadata(Path supportFile) {
|
||||
return new AssetStudioSceneBankMetadata(
|
||||
16,
|
||||
16,
|
||||
4,
|
||||
List.of(
|
||||
new AssetStudioSceneLayerBinding(false, 1, "Layer 1", 16, 16, "scene.tmx", "", 1.0f, 1.0f, 0),
|
||||
new AssetStudioSceneLayerBinding(false, 2, "Layer 2", 16, 16, "scene.tmx", "", 1.0f, 1.0f, 0),
|
||||
new AssetStudioSceneLayerBinding(false, 3, "Layer 3", 16, 16, "scene.tmx", "", 1.0f, 1.0f, 0),
|
||||
new AssetStudioSceneLayerBinding(false, 4, "Layer 4", 16, 16, "scene.tmx", "", 1.0f, 1.0f, 0)),
|
||||
supportFile);
|
||||
}
|
||||
|
||||
private List<AssetStudioSceneTile> readSceneTiles(JsonNode tilesNode, int width, int height, int defaultPaletteId) {
|
||||
final int tileCount = width * height;
|
||||
if (!(tilesNode instanceof ArrayNode arrayNode)) {
|
||||
final List<AssetStudioSceneTile> defaults = new ArrayList<>(tileCount);
|
||||
for (int index = 0; index < tileCount; index += 1) {
|
||||
defaults.add(AssetStudioSceneTile.inactive(defaultPaletteId));
|
||||
}
|
||||
return List.copyOf(defaults);
|
||||
}
|
||||
if (arrayNode.size() != tileCount) {
|
||||
return null;
|
||||
}
|
||||
final List<AssetStudioSceneTile> tiles = new ArrayList<>(tileCount);
|
||||
for (JsonNode tileNode : arrayNode) {
|
||||
final boolean active = tileNode.path("active").asBoolean(false);
|
||||
final int glyphId = tileNode.path("glyph_id").asInt(0);
|
||||
final int paletteId = tileNode.path("palette_id").asInt(defaultPaletteId);
|
||||
final boolean flipX = tileNode.path("flip_x").asBoolean(false);
|
||||
final boolean flipY = tileNode.path("flip_y").asBoolean(false);
|
||||
if (glyphId < 0 || paletteId < 0) {
|
||||
return null;
|
||||
}
|
||||
tiles.add(new AssetStudioSceneTile(active, glyphId, paletteId, flipX, flipY));
|
||||
}
|
||||
return List.copyOf(tiles);
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package p.studio.core.assets.palette;
|
||||
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceBankCompositionFile;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
record AssetPaletteDraft(
|
||||
List<AssetWorkspaceBankCompositionFile> previewTileFiles,
|
||||
List<AssetWorkspaceBankCompositionFile> allFiles,
|
||||
List<AssetWorkspaceBankCompositionFile> availableFiles,
|
||||
List<AssetWorkspaceBankCompositionFile> selectedFiles,
|
||||
String previewTilePath,
|
||||
String previewPalettePath) {
|
||||
private static final int MIN_SELECTED = 1;
|
||||
private static final int MAX_SELECTED = 64;
|
||||
|
||||
AssetPaletteDraft {
|
||||
previewTileFiles = List.copyOf(Objects.requireNonNull(previewTileFiles, "previewTileFiles"));
|
||||
allFiles = List.copyOf(Objects.requireNonNull(allFiles, "allFiles"));
|
||||
availableFiles = List.copyOf(Objects.requireNonNull(availableFiles, "availableFiles"));
|
||||
selectedFiles = List.copyOf(Objects.requireNonNull(selectedFiles, "selectedFiles"));
|
||||
previewTilePath = normalize(previewTilePath);
|
||||
previewPalettePath = normalize(previewPalettePath);
|
||||
}
|
||||
|
||||
AssetPaletteDraft moveToSelected(List<AssetWorkspaceBankCompositionFile> files) {
|
||||
final List<AssetWorkspaceBankCompositionFile> accepted = new ArrayList<>();
|
||||
for (AssetWorkspaceBankCompositionFile file : files) {
|
||||
if (file == null || !availableFiles.contains(file) || selectedFiles.contains(file)) {
|
||||
continue;
|
||||
}
|
||||
if (selectedFiles.size() + accepted.size() >= MAX_SELECTED) {
|
||||
break;
|
||||
}
|
||||
accepted.add(file);
|
||||
}
|
||||
if (accepted.isEmpty()) {
|
||||
return this;
|
||||
}
|
||||
|
||||
final List<AssetWorkspaceBankCompositionFile> nextAvailable = new ArrayList<>(availableFiles);
|
||||
nextAvailable.removeAll(accepted);
|
||||
final List<AssetWorkspaceBankCompositionFile> nextSelected = new ArrayList<>(selectedFiles);
|
||||
nextSelected.addAll(accepted);
|
||||
final String nextPreviewPalettePath = previewPalettePath == null ? accepted.getFirst().path() : previewPalettePath;
|
||||
return new AssetPaletteDraft(previewTileFiles, allFiles, nextAvailable, nextSelected, previewTilePath, nextPreviewPalettePath);
|
||||
}
|
||||
|
||||
AssetPaletteDraft moveToAvailable(List<AssetWorkspaceBankCompositionFile> files) {
|
||||
final List<AssetWorkspaceBankCompositionFile> removed = new ArrayList<>();
|
||||
for (AssetWorkspaceBankCompositionFile file : files) {
|
||||
if (file != null && selectedFiles.contains(file)) {
|
||||
removed.add(file);
|
||||
}
|
||||
}
|
||||
if (removed.isEmpty() || selectedFiles.size() - removed.size() < MIN_SELECTED) {
|
||||
return this;
|
||||
}
|
||||
|
||||
final List<AssetWorkspaceBankCompositionFile> nextSelected = new ArrayList<>(selectedFiles);
|
||||
nextSelected.removeAll(removed);
|
||||
final List<AssetWorkspaceBankCompositionFile> nextAvailable = new ArrayList<>(availableFiles);
|
||||
nextAvailable.addAll(removed);
|
||||
final String nextPreviewPalettePath = removed.stream().anyMatch(file -> file.path().equals(previewPalettePath))
|
||||
? nextSelected.getFirst().path()
|
||||
: previewPalettePath;
|
||||
return new AssetPaletteDraft(previewTileFiles, allFiles, nextAvailable, nextSelected, previewTilePath, nextPreviewPalettePath);
|
||||
}
|
||||
|
||||
AssetPaletteDraft selectPreviewTile(String path) {
|
||||
final String normalized = normalize(path);
|
||||
if (normalized == null || previewTileFiles.stream().noneMatch(file -> file.path().equals(normalized))) {
|
||||
return this;
|
||||
}
|
||||
return new AssetPaletteDraft(previewTileFiles, allFiles, availableFiles, selectedFiles, normalized, previewPalettePath);
|
||||
}
|
||||
|
||||
AssetPaletteDraft selectPreviewPalette(String path) {
|
||||
final String normalized = normalize(path);
|
||||
if (normalized == null || allFiles.stream().noneMatch(file -> file.path().equals(normalized))) {
|
||||
return this;
|
||||
}
|
||||
return new AssetPaletteDraft(previewTileFiles, allFiles, availableFiles, selectedFiles, previewTilePath, normalized);
|
||||
}
|
||||
|
||||
private static String normalize(String path) {
|
||||
if (path == null) {
|
||||
return null;
|
||||
}
|
||||
final String trimmed = path.trim();
|
||||
return trimmed.isBlank() ? null : trimmed;
|
||||
}
|
||||
}
|
||||
+652
@@ -0,0 +1,652 @@
|
||||
package p.studio.core.assets.palette;
|
||||
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import p.studio.api.assets.palette.AssetPaletteSession;
|
||||
import p.studio.api.assets.palette.AssetPaletteState;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceAssetDetails;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceBankCompositionFile;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialArtifactBinding;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialMetadata;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialPalette;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialSchema;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialSchemaStatus;
|
||||
import p.studio.api.assets.schema.AssetColorSchemaRules;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public final class DefaultAssetPaletteSession implements AssetPaletteSession {
|
||||
private final AssetColorSchemaRules schemaRules;
|
||||
private AssetPaletteDraft source;
|
||||
private AssetPaletteDraft draft;
|
||||
private boolean editing;
|
||||
private AssetWorkspaceAssetDetails details;
|
||||
private AssetStudioGlyphMaterialMetadata localMaterialMetadata;
|
||||
|
||||
public DefaultAssetPaletteSession(AssetColorSchemaRules schemaRules) {
|
||||
this.schemaRules = Objects.requireNonNull(schemaRules, "schemaRules");
|
||||
}
|
||||
|
||||
public void replaceDetails(AssetWorkspaceAssetDetails details) {
|
||||
this.details = details;
|
||||
if (details == null || details.summary().assetFamily() != AssetFamily.GLYPH_BANK) {
|
||||
source = null;
|
||||
draft = null;
|
||||
editing = false;
|
||||
localMaterialMetadata = null;
|
||||
return;
|
||||
}
|
||||
localMaterialMetadata = details.glyphMaterialMetadata();
|
||||
rebuildSession();
|
||||
}
|
||||
|
||||
public void replaceMaterialMetadata(AssetStudioGlyphMaterialMetadata metadata) {
|
||||
if (details == null || details.summary().assetFamily() != AssetFamily.GLYPH_BANK) {
|
||||
return;
|
||||
}
|
||||
localMaterialMetadata = Objects.requireNonNull(metadata, "metadata");
|
||||
rebuildSession();
|
||||
}
|
||||
|
||||
private void rebuildSession() {
|
||||
final List<AssetWorkspaceBankCompositionFile> allFiles = paletteFiles(details);
|
||||
final List<AssetWorkspaceBankCompositionFile> previewTileFiles = details.bankComposition().selectedFiles().stream()
|
||||
.filter(DefaultAssetPaletteSession::supportsPalettePreview)
|
||||
.toList();
|
||||
final List<AssetWorkspaceBankCompositionFile> initialSelected = initialSelectedPaletteFiles(details, allFiles);
|
||||
|
||||
final List<AssetWorkspaceBankCompositionFile> available = new ArrayList<>(allFiles);
|
||||
available.removeAll(initialSelected);
|
||||
final AssetPaletteDraft replacement = new AssetPaletteDraft(
|
||||
previewTileFiles,
|
||||
allFiles,
|
||||
available,
|
||||
initialSelected,
|
||||
previewTileFiles.isEmpty() ? null : previewTileFiles.getFirst().path(),
|
||||
initialSelected.isEmpty()
|
||||
? allFiles.isEmpty() ? null : allFiles.getFirst().path()
|
||||
: initialSelected.getFirst().path());
|
||||
if (source == null) {
|
||||
source = replacement;
|
||||
draft = replacement;
|
||||
editing = false;
|
||||
return;
|
||||
}
|
||||
if (!Objects.equals(source, replacement)) {
|
||||
if (editing) {
|
||||
final AssetPaletteDraft currentDraft = draft;
|
||||
source = replacement;
|
||||
draft = rebindDraft(currentDraft, replacement);
|
||||
return;
|
||||
}
|
||||
source = replacement;
|
||||
draft = replacement;
|
||||
editing = false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean ready() {
|
||||
return source != null && draft != null;
|
||||
}
|
||||
|
||||
public AssetWorkspaceAssetDetails details() {
|
||||
return details;
|
||||
}
|
||||
|
||||
public void beginEdit() {
|
||||
if (ready()) {
|
||||
editing = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void apply() {
|
||||
if (ready()) {
|
||||
source = draft;
|
||||
editing = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
if (ready()) {
|
||||
draft = source;
|
||||
}
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
if (ready()) {
|
||||
draft = source;
|
||||
editing = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void moveToSelected(List<AssetWorkspaceBankCompositionFile> files) {
|
||||
if (ready() && editing) {
|
||||
final List<AssetWorkspaceBankCompositionFile> validFiles = files.stream()
|
||||
.filter(DefaultAssetPaletteSession::paletteIsValid)
|
||||
.toList();
|
||||
draft = draft.moveToSelected(validFiles);
|
||||
}
|
||||
}
|
||||
|
||||
public void moveToAvailable(List<AssetWorkspaceBankCompositionFile> files) {
|
||||
if (ready() && editing) {
|
||||
draft = draft.moveToAvailable(files);
|
||||
}
|
||||
}
|
||||
|
||||
public void selectPreviewTile(AssetWorkspaceBankCompositionFile file) {
|
||||
if (ready() && file != null) {
|
||||
draft = draft.selectPreviewTile(file.path());
|
||||
}
|
||||
}
|
||||
|
||||
public void selectPreviewPalette(AssetWorkspaceBankCompositionFile file) {
|
||||
if (ready() && file != null) {
|
||||
draft = draft.selectPreviewPalette(file.path());
|
||||
}
|
||||
}
|
||||
|
||||
public AssetPaletteState state() {
|
||||
if (!ready()) {
|
||||
return new AssetPaletteState(false, false, List.of(), List.of(), List.of(), List.of(), null, null, 0);
|
||||
}
|
||||
|
||||
final AssetWorkspaceBankCompositionFile previewPaletteFile = fileByPath(draft.allFiles(), draft.previewPalettePath());
|
||||
final List<AssetWorkspaceBankCompositionFile> schemaPreviewTileFiles = previewTileFilesForPalette(
|
||||
draft.previewTileFiles(),
|
||||
previewPaletteFile);
|
||||
final AssetWorkspaceBankCompositionFile previewTileFile = Optional
|
||||
.ofNullable(fileByPath(schemaPreviewTileFiles, draft.previewTilePath()))
|
||||
.orElse(schemaPreviewTileFiles.isEmpty() ? null : schemaPreviewTileFiles.getFirst());
|
||||
return new AssetPaletteState(
|
||||
editing,
|
||||
!Objects.equals(source, draft),
|
||||
schemaPreviewTileFiles,
|
||||
draft.allFiles(),
|
||||
draft.availableFiles(),
|
||||
draft.selectedFiles(),
|
||||
previewTileFile,
|
||||
previewPaletteFile,
|
||||
draft.allFiles().size());
|
||||
}
|
||||
|
||||
public List<AssetStudioGlyphMaterialSchema> readySchemas() {
|
||||
return materialMetadata().schemas().stream()
|
||||
.filter(schema -> schema.status() == AssetStudioGlyphMaterialSchemaStatus.OK)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public String nextPaletteId() {
|
||||
int next = 1;
|
||||
final Set<String> ids = materialMetadata().palettes().stream()
|
||||
.map(AssetStudioGlyphMaterialPalette::paletteId)
|
||||
.collect(java.util.stream.Collectors.toSet());
|
||||
while (ids.contains("palette-" + next)) {
|
||||
next += 1;
|
||||
}
|
||||
return "palette-" + next;
|
||||
}
|
||||
|
||||
public boolean duplicatePaletteExists(String paletteId, String schemaId, List<String> colors) {
|
||||
final List<String> normalized = colors.stream().map(DefaultAssetPaletteSession::normalizeHtmlColor).toList();
|
||||
return allPaletteRecords().stream()
|
||||
.filter(record -> !Objects.equals(record.paletteId(), paletteId))
|
||||
.anyMatch(record -> record.schemaId().equals(schemaId) && record.colors().equals(normalized));
|
||||
}
|
||||
|
||||
public AssetStudioGlyphMaterialMetadata upsertPalette(String paletteId, String displayName, String schemaId, List<String> colors) {
|
||||
final AssetStudioGlyphMaterialMetadata current = materialMetadata();
|
||||
final List<String> normalized = colors.stream().map(DefaultAssetPaletteSession::normalizeHtmlColor).toList();
|
||||
final int schemaVersion = current.findSchema(schemaId).map(AssetStudioGlyphMaterialSchema::version).orElse(1);
|
||||
final String resolvedDisplayName = displayName == null || displayName.trim().isBlank()
|
||||
? generatedDisplayName(normalized)
|
||||
: displayName.trim();
|
||||
final AssetStudioGlyphMaterialPalette next = new AssetStudioGlyphMaterialPalette(
|
||||
paletteId,
|
||||
resolvedDisplayName,
|
||||
schemaId,
|
||||
schemaVersion,
|
||||
normalized);
|
||||
final List<AssetStudioGlyphMaterialPalette> palettes = new ArrayList<>();
|
||||
boolean replaced = false;
|
||||
for (AssetStudioGlyphMaterialPalette palette : current.palettes()) {
|
||||
if (palette.paletteId().equals(paletteId)) {
|
||||
palettes.add(next);
|
||||
replaced = true;
|
||||
} else {
|
||||
palettes.add(palette);
|
||||
}
|
||||
}
|
||||
if (!replaced) {
|
||||
palettes.add(next);
|
||||
}
|
||||
palettes.sort(Comparator.comparing(AssetStudioGlyphMaterialPalette::paletteId, String.CASE_INSENSITIVE_ORDER));
|
||||
return new AssetStudioGlyphMaterialMetadata(current.schemas(), palettes, current.supportFile());
|
||||
}
|
||||
|
||||
public AssetStudioGlyphMaterialMetadata removePalette(String paletteId) {
|
||||
final AssetWorkspaceBankCompositionFile paletteFile = paletteFileById(paletteId);
|
||||
if (paletteFile != null && Boolean.TRUE.equals(paletteFile.metadata().get("derivedOriginal"))) {
|
||||
throw new IllegalStateException("Original schema palettes are derived and cannot be removed.");
|
||||
}
|
||||
final AssetStudioGlyphMaterialMetadata current = materialMetadata();
|
||||
final List<AssetStudioGlyphMaterialPalette> palettes = current.palettes().stream()
|
||||
.filter(palette -> !palette.paletteId().equals(paletteId))
|
||||
.toList();
|
||||
return new AssetStudioGlyphMaterialMetadata(current.schemas(), palettes, current.supportFile());
|
||||
}
|
||||
|
||||
public AssetWorkspaceBankCompositionFile paletteFileById(String paletteId) {
|
||||
if (paletteId == null || !ready()) {
|
||||
return null;
|
||||
}
|
||||
return paletteFiles(details).stream()
|
||||
.filter(file -> paletteId.equals(file.metadata().get("paletteId")))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public static boolean supportsPalettePreview(AssetWorkspaceBankCompositionFile file) {
|
||||
if (file == null) {
|
||||
return false;
|
||||
}
|
||||
return nestedMap(file.metadata(), "tile") != null && nestedMap(file.metadata(), "palette") != null;
|
||||
}
|
||||
|
||||
public static boolean paletteIsValid(AssetWorkspaceBankCompositionFile file) {
|
||||
return !Boolean.FALSE.equals(file.metadata().get("valid"));
|
||||
}
|
||||
|
||||
public boolean paletteIsOriginal(AssetWorkspaceBankCompositionFile file) {
|
||||
return file != null && Boolean.TRUE.equals(file.metadata().get("derivedOriginal"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static Map<String, Object> nestedMap(Map<String, Object> metadata, String key) {
|
||||
final Object value = metadata.get(key);
|
||||
if (value instanceof Map<?, ?> nested) {
|
||||
return (Map<String, Object>) nested;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private AssetStudioGlyphMaterialMetadata materialMetadata() {
|
||||
if (details == null) {
|
||||
return new AssetStudioGlyphMaterialMetadata(List.of(), List.of(), null);
|
||||
}
|
||||
return localMaterialMetadata == null
|
||||
? new AssetStudioGlyphMaterialMetadata(List.of(), List.of(), null)
|
||||
: localMaterialMetadata;
|
||||
}
|
||||
|
||||
private List<AssetWorkspaceBankCompositionFile> paletteFiles(AssetWorkspaceAssetDetails details) {
|
||||
final Map<String, AssetWorkspaceBankCompositionFile> ordered = new LinkedHashMap<>();
|
||||
for (PaletteRecord record : allPaletteRecords()) {
|
||||
final AssetWorkspaceBankCompositionFile file = toPaletteFile(record);
|
||||
ordered.putIfAbsent(file.path(), file);
|
||||
}
|
||||
return List.copyOf(ordered.values());
|
||||
}
|
||||
|
||||
private List<PaletteRecord> allPaletteRecords() {
|
||||
final AssetStudioGlyphMaterialMetadata metadata = materialMetadata();
|
||||
final List<PaletteRecord> records = new ArrayList<>();
|
||||
for (AssetStudioGlyphMaterialSchema schema : metadata.schemas()) {
|
||||
final AssetStudioGlyphMaterialSchemaStatus effectiveSchemaStatus = schemaRules.effectiveStatus(
|
||||
schema,
|
||||
details.bankComposition().selectedFiles());
|
||||
final List<String> originalColors = schema.materialIndices().entrySet().stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
.map(Map.Entry::getValue)
|
||||
.toList();
|
||||
records.add(new PaletteRecord(
|
||||
"schema-" + schema.schemaId() + "-original",
|
||||
null,
|
||||
schema.schemaId(),
|
||||
schema.version(),
|
||||
originalColors,
|
||||
schema.materialIndices(),
|
||||
schemaArtifactIds(schema),
|
||||
true,
|
||||
effectiveSchemaStatus == AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
effectiveSchemaStatus == AssetStudioGlyphMaterialSchemaStatus.OK
|
||||
? null
|
||||
: "Schema is inconsistent."));
|
||||
}
|
||||
for (AssetStudioGlyphMaterialPalette palette : metadata.palettes()) {
|
||||
final AssetStudioGlyphMaterialSchema schema = metadata.findSchema(palette.schemaId()).orElse(null);
|
||||
final AssetStudioGlyphMaterialSchemaStatus effectiveSchemaStatus = schema == null
|
||||
? AssetStudioGlyphMaterialSchemaStatus.INCONSISTENT
|
||||
: schemaRules.effectiveStatus(schema, details.bankComposition().selectedFiles());
|
||||
final boolean valid = schema != null
|
||||
&& effectiveSchemaStatus == AssetStudioGlyphMaterialSchemaStatus.OK
|
||||
&& palette.version() >= schema.version();
|
||||
final String invalidReason;
|
||||
if (schema == null) {
|
||||
invalidReason = "Schema is missing.";
|
||||
} else if (effectiveSchemaStatus != AssetStudioGlyphMaterialSchemaStatus.OK) {
|
||||
invalidReason = "Schema is inconsistent.";
|
||||
} else if (palette.version() < schema.version()) {
|
||||
invalidReason = "Palette is stale and must be updated.";
|
||||
} else {
|
||||
invalidReason = null;
|
||||
}
|
||||
records.add(new PaletteRecord(
|
||||
palette.paletteId(),
|
||||
palette.displayName(),
|
||||
palette.schemaId(),
|
||||
palette.version(),
|
||||
palette.colors(),
|
||||
schema == null ? Map.of() : schema.materialIndices(),
|
||||
schema == null ? Set.of() : schemaArtifactIds(schema),
|
||||
false,
|
||||
valid,
|
||||
invalidReason));
|
||||
}
|
||||
records.sort(Comparator.comparing(PaletteRecord::paletteId, String.CASE_INSENSITIVE_ORDER));
|
||||
return List.copyOf(records);
|
||||
}
|
||||
|
||||
private AssetWorkspaceBankCompositionFile toPaletteFile(PaletteRecord record) {
|
||||
final List<Integer> argb = record.colors().stream()
|
||||
.map(DefaultAssetPaletteSession::htmlToArgb8888)
|
||||
.toList();
|
||||
final List<Integer> rgba = record.colors().stream()
|
||||
.map(DefaultAssetPaletteSession::htmlToRgba8888)
|
||||
.toList();
|
||||
final Map<String, Object> palette = Map.of(
|
||||
"originalArgb8888", argb,
|
||||
"rgba8888", rgba);
|
||||
final Map<String, Object> metadata = new LinkedHashMap<>();
|
||||
metadata.put("palette", palette);
|
||||
metadata.put("paletteId", record.paletteId());
|
||||
metadata.put("paletteDisplayName", displayName(record));
|
||||
if (record.displayName() != null) {
|
||||
metadata.put("explicitPaletteDisplayName", record.displayName());
|
||||
}
|
||||
metadata.put("schemaId", record.schemaId());
|
||||
metadata.put("schemaMaterialIndices", record.materialIndices());
|
||||
metadata.put("schemaArtifactIds", List.copyOf(record.artifactIds()));
|
||||
metadata.put("paletteVersion", record.version());
|
||||
metadata.put("derivedOriginal", record.derivedOriginal());
|
||||
metadata.put("valid", record.valid());
|
||||
if (record.invalidReason() != null) {
|
||||
metadata.put("invalidReason", record.invalidReason());
|
||||
}
|
||||
return new AssetWorkspaceBankCompositionFile(
|
||||
record.paletteId(),
|
||||
displayName(record),
|
||||
0L,
|
||||
0L,
|
||||
null,
|
||||
metadata);
|
||||
}
|
||||
|
||||
public String generatedDisplayName(List<String> colors) {
|
||||
final List<ColorSample> samples = colors.stream()
|
||||
.map(DefaultAssetPaletteSession::toColorSample)
|
||||
.toList();
|
||||
if (samples.isEmpty()) {
|
||||
return "quiet shade";
|
||||
}
|
||||
final ColorSample anchor = samples.stream()
|
||||
.min(Comparator.comparingDouble(sample -> sample.saturation < 0.16 ? sample.lightness : -sample.saturation))
|
||||
.orElse(samples.getFirst());
|
||||
final double averageLightness = samples.stream()
|
||||
.mapToDouble(sample -> sample.lightness)
|
||||
.average()
|
||||
.orElse(anchor.lightness);
|
||||
final double averageSaturation = samples.stream()
|
||||
.mapToDouble(sample -> sample.saturation)
|
||||
.average()
|
||||
.orElse(anchor.saturation);
|
||||
final double lightnessRange = samples.stream().mapToDouble(sample -> sample.lightness).max().orElse(anchor.lightness)
|
||||
- samples.stream().mapToDouble(sample -> sample.lightness).min().orElse(anchor.lightness);
|
||||
return baseName(anchor, averageLightness, averageSaturation) + " " + moodName(averageLightness, averageSaturation, lightnessRange, samples.size());
|
||||
}
|
||||
|
||||
private static String baseName(ColorSample sample, double averageLightness, double averageSaturation) {
|
||||
if (averageSaturation < 0.12) {
|
||||
if (averageLightness > 0.88) {
|
||||
return "snow";
|
||||
}
|
||||
if (averageLightness > 0.68) {
|
||||
return "fog";
|
||||
}
|
||||
if (averageLightness < 0.24) {
|
||||
return "ink";
|
||||
}
|
||||
return "ash";
|
||||
}
|
||||
final double hue = sample.hue;
|
||||
if (hue < 18 || hue >= 345) {
|
||||
return sample.lightness > 0.62 ? "rose" : "ember";
|
||||
}
|
||||
if (hue < 42) {
|
||||
return sample.lightness > 0.62 ? "honey" : "copper";
|
||||
}
|
||||
if (hue < 72) {
|
||||
return sample.lightness > 0.68 ? "sun" : "ochre";
|
||||
}
|
||||
if (hue < 155) {
|
||||
return sample.lightness > 0.58 ? "moss" : "pine";
|
||||
}
|
||||
if (hue < 195) {
|
||||
return sample.lightness > 0.62 ? "mint" : "jade";
|
||||
}
|
||||
if (hue < 245) {
|
||||
return sample.lightness > 0.62 ? "sky" : "cobalt";
|
||||
}
|
||||
if (hue < 290) {
|
||||
return sample.lightness > 0.62 ? "lilac" : "violet";
|
||||
}
|
||||
return sample.lightness > 0.62 ? "orchid" : "plum";
|
||||
}
|
||||
|
||||
private static String moodName(double averageLightness, double averageSaturation, double lightnessRange, int colorCount) {
|
||||
if (averageSaturation < 0.12 && averageLightness > 0.86) {
|
||||
return "white";
|
||||
}
|
||||
if (colorCount > 1 && lightnessRange > 0.42) {
|
||||
return "twist";
|
||||
}
|
||||
if (averageLightness > 0.78) {
|
||||
return averageSaturation > 0.45 ? "glow" : "veil";
|
||||
}
|
||||
if (averageLightness < 0.26) {
|
||||
return averageSaturation > 0.34 ? "deep" : "shade";
|
||||
}
|
||||
if (averageSaturation > 0.62) {
|
||||
return "bloom";
|
||||
}
|
||||
if (averageSaturation < 0.22) {
|
||||
return "haze";
|
||||
}
|
||||
return "drift";
|
||||
}
|
||||
|
||||
private static ColorSample toColorSample(String htmlColor) {
|
||||
final int rgb = Integer.parseInt(normalizeHtmlColor(htmlColor).substring(1, 7), 16);
|
||||
final double red = ((rgb >> 16) & 0xFF) / 255.0;
|
||||
final double green = ((rgb >> 8) & 0xFF) / 255.0;
|
||||
final double blue = (rgb & 0xFF) / 255.0;
|
||||
final double max = Math.max(red, Math.max(green, blue));
|
||||
final double min = Math.min(red, Math.min(green, blue));
|
||||
final double delta = max - min;
|
||||
final double lightness = (max + min) / 2.0;
|
||||
final double saturation = delta == 0.0
|
||||
? 0.0
|
||||
: delta / (1.0 - Math.abs((2.0 * lightness) - 1.0));
|
||||
final double hue;
|
||||
if (delta == 0.0) {
|
||||
hue = 0.0;
|
||||
} else if (max == red) {
|
||||
hue = 60.0 * (((green - blue) / delta) % 6.0);
|
||||
} else if (max == green) {
|
||||
hue = 60.0 * (((blue - red) / delta) + 2.0);
|
||||
} else {
|
||||
hue = 60.0 * (((red - green) / delta) + 4.0);
|
||||
}
|
||||
return new ColorSample(hue < 0.0 ? hue + 360.0 : hue, saturation, lightness);
|
||||
}
|
||||
|
||||
private String displayName(PaletteRecord record) {
|
||||
if (record.derivedOriginal()) {
|
||||
return record.schemaId() + " / original";
|
||||
}
|
||||
return record.displayName() == null || record.displayName().isBlank()
|
||||
? generatedDisplayName(record.colors())
|
||||
: record.displayName();
|
||||
}
|
||||
|
||||
private List<AssetWorkspaceBankCompositionFile> initialSelectedPaletteFiles(
|
||||
AssetWorkspaceAssetDetails details,
|
||||
List<AssetWorkspaceBankCompositionFile> allFiles) {
|
||||
final List<AssetWorkspaceBankCompositionFile> selected = new ArrayList<>();
|
||||
for (Map<String, Object> palette : details.pipelinePalettes()) {
|
||||
for (AssetWorkspaceBankCompositionFile file : allFiles) {
|
||||
if (!selected.contains(file) && paletteEquals(palette, nestedMap(file.metadata(), "palette"))) {
|
||||
selected.add(file);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.copyOf(selected);
|
||||
}
|
||||
|
||||
private static boolean paletteEquals(Map<String, Object> left, Map<String, Object> right) {
|
||||
if (left == null || right == null) {
|
||||
return false;
|
||||
}
|
||||
final Object leftRgba = left.get("rgba8888");
|
||||
final Object rightRgba = right.get("rgba8888");
|
||||
if (leftRgba != null || rightRgba != null) {
|
||||
return Objects.equals(leftRgba, rightRgba);
|
||||
}
|
||||
return Objects.equals(left.get("originalArgb8888"), right.get("originalArgb8888"));
|
||||
}
|
||||
|
||||
private static int htmlToArgb8888(String htmlColor) {
|
||||
final String normalized = normalizeHtmlColor(htmlColor);
|
||||
final int rgb = Integer.parseInt(normalized.substring(1, 7), 16);
|
||||
final int alpha = normalized.length() == 9
|
||||
? Integer.parseInt(normalized.substring(7, 9), 16)
|
||||
: 0xFF;
|
||||
return (alpha << 24) | rgb;
|
||||
}
|
||||
|
||||
private static int htmlToRgba8888(String htmlColor) {
|
||||
final String normalized = normalizeHtmlColor(htmlColor);
|
||||
final int rgb = Integer.parseInt(normalized.substring(1, 7), 16);
|
||||
final int alpha = normalized.length() == 9
|
||||
? Integer.parseInt(normalized.substring(7, 9), 16)
|
||||
: 0xFF;
|
||||
return (rgb << 8) | alpha;
|
||||
}
|
||||
|
||||
private static String normalizeHtmlColor(String color) {
|
||||
final String normalized = Objects.requireNonNull(color, "color").trim().toUpperCase();
|
||||
if (!normalized.matches("^#[0-9A-F]{6}([0-9A-F]{2})?$")) {
|
||||
throw new IllegalArgumentException("color must use #RRGGBB or #RRGGBBAA format");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static AssetWorkspaceBankCompositionFile fileByPath(List<AssetWorkspaceBankCompositionFile> files, String path) {
|
||||
if (path == null) {
|
||||
return null;
|
||||
}
|
||||
return files.stream()
|
||||
.filter(file -> path.equals(file.path()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private static AssetPaletteDraft rebindDraft(
|
||||
AssetPaletteDraft draft,
|
||||
AssetPaletteDraft source) {
|
||||
final Set<String> selectedPaths = draft.selectedFiles().stream()
|
||||
.map(AssetWorkspaceBankCompositionFile::path)
|
||||
.collect(java.util.stream.Collectors.toCollection(LinkedHashSet::new));
|
||||
final List<AssetWorkspaceBankCompositionFile> selected = source.allFiles().stream()
|
||||
.filter(file -> selectedPaths.contains(file.path()))
|
||||
.toList();
|
||||
final List<AssetWorkspaceBankCompositionFile> available = source.allFiles().stream()
|
||||
.filter(file -> !selectedPaths.contains(file.path()))
|
||||
.toList();
|
||||
final String previewPalettePath = fileByPath(source.allFiles(), draft.previewPalettePath()) == null
|
||||
? source.previewPalettePath()
|
||||
: draft.previewPalettePath();
|
||||
final String previewTilePath = fileByPath(source.previewTileFiles(), draft.previewTilePath()) == null
|
||||
? source.previewTilePath()
|
||||
: draft.previewTilePath();
|
||||
return new AssetPaletteDraft(
|
||||
source.previewTileFiles(),
|
||||
source.allFiles(),
|
||||
available,
|
||||
selected,
|
||||
previewTilePath,
|
||||
previewPalettePath);
|
||||
}
|
||||
|
||||
private static Set<String> schemaArtifactIds(AssetStudioGlyphMaterialSchema schema) {
|
||||
return schema.artifactBindings().stream()
|
||||
.map(AssetStudioGlyphMaterialArtifactBinding::artifactId)
|
||||
.collect(java.util.stream.Collectors.toCollection(LinkedHashSet::new));
|
||||
}
|
||||
|
||||
private static List<AssetWorkspaceBankCompositionFile> previewTileFilesForPalette(
|
||||
List<AssetWorkspaceBankCompositionFile> previewTileFiles,
|
||||
AssetWorkspaceBankCompositionFile previewPaletteFile) {
|
||||
if (previewPaletteFile == null) {
|
||||
return previewTileFiles;
|
||||
}
|
||||
final Set<String> schemaArtifactIds = schemaArtifactIds(previewPaletteFile);
|
||||
if (schemaArtifactIds.isEmpty()) {
|
||||
return previewTileFiles;
|
||||
}
|
||||
return previewTileFiles.stream()
|
||||
.filter(file -> schemaArtifactIds.contains(artifactId(file)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static Set<String> schemaArtifactIds(AssetWorkspaceBankCompositionFile previewPaletteFile) {
|
||||
final Object artifactIds = previewPaletteFile.metadata().get("schemaArtifactIds");
|
||||
if (!(artifactIds instanceof Iterable<?> iterable)) {
|
||||
return Set.of();
|
||||
}
|
||||
final Set<String> ids = new LinkedHashSet<>();
|
||||
for (Object artifactId : iterable) {
|
||||
if (artifactId instanceof String value && !value.isBlank()) {
|
||||
ids.add(value.trim());
|
||||
}
|
||||
}
|
||||
return Set.copyOf(ids);
|
||||
}
|
||||
|
||||
private static String artifactId(AssetWorkspaceBankCompositionFile file) {
|
||||
if (file == null) {
|
||||
return null;
|
||||
}
|
||||
final Object artifactId = file.metadata().get("artifactId");
|
||||
if (artifactId instanceof String value && !value.isBlank()) {
|
||||
return value.trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private record PaletteRecord(
|
||||
String paletteId,
|
||||
String displayName,
|
||||
String schemaId,
|
||||
int version,
|
||||
List<String> colors,
|
||||
Map<Integer, String> materialIndices,
|
||||
Set<String> artifactIds,
|
||||
boolean derivedOriginal,
|
||||
boolean valid,
|
||||
String invalidReason) {
|
||||
}
|
||||
|
||||
private record ColorSample(double hue, double saturation, double lightness) {
|
||||
}
|
||||
}
|
||||
+358
@@ -0,0 +1,358 @@
|
||||
package p.studio.core.assets.scene;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import p.studio.api.assets.AssetDiagnostic;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.assets.AssetCatalog;
|
||||
import p.studio.api.assets.scene.SceneBankWorkflow;
|
||||
import p.studio.api.assets.scene.SceneBankWorkflowResult;
|
||||
import p.studio.api.assets.metadata.AssetStudioSceneBankMetadata;
|
||||
import p.studio.api.assets.metadata.AssetStudioSceneLayerBinding;
|
||||
import p.studio.api.assets.metadata.AssetStudioSceneTile;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceAssetDetails;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceSceneBankStatus;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceSceneBankValidation;
|
||||
|
||||
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.Objects;
|
||||
|
||||
public final class SceneBankWorkflowService implements SceneBankWorkflow {
|
||||
public static final String ACCEPTED_REQUEST_FILE = "scene-bank.pack-request.json";
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
private final SceneBankGlyphAssetResolver glyphAssetResolver;
|
||||
|
||||
public SceneBankWorkflowService(AssetCatalog assetCatalog, ObjectMapper mapper) {
|
||||
this((SceneBankGlyphAssetResolver) (projectReference, tilesetAssetRoot) -> Objects.requireNonNull(assetCatalog, "assetCatalog")
|
||||
.list(projectReference, false)
|
||||
.stream()
|
||||
.filter(asset -> asset.family() == AssetFamily.GLYPH_BANK)
|
||||
.filter(asset -> projectReference.rootPath()
|
||||
.resolve("assets")
|
||||
.resolve(tilesetAssetRoot)
|
||||
.toAbsolutePath()
|
||||
.normalize()
|
||||
.equals(asset.root().toAbsolutePath().normalize()))
|
||||
.findFirst()
|
||||
.map(asset -> asset.assetId() == null ? -1 : asset.assetId())
|
||||
.orElse(-1), mapper);
|
||||
}
|
||||
|
||||
SceneBankWorkflowService(SceneBankGlyphAssetResolver glyphAssetResolver) {
|
||||
this(glyphAssetResolver, new ObjectMapper());
|
||||
}
|
||||
|
||||
SceneBankWorkflowService(SceneBankGlyphAssetResolver glyphAssetResolver, ObjectMapper mapper) {
|
||||
this.glyphAssetResolver = Objects.requireNonNull(glyphAssetResolver, "glyphAssetResolver");
|
||||
this.mapper = Objects.requireNonNull(mapper, "mapper");
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBankWorkflowResult inspect(ProjectReference projectReference, AssetWorkspaceAssetDetails details) {
|
||||
if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) {
|
||||
return new SceneBankWorkflowResult(true, "", AssetWorkspaceSceneBankValidation.NOT_APPLICABLE, List.of());
|
||||
}
|
||||
final List<AssetDiagnostic> diagnostics = new ArrayList<>(validateDiagnostics(projectReference, details));
|
||||
if (diagnostics.stream().noneMatch(AssetDiagnostic::blocking)) {
|
||||
try {
|
||||
writeAcceptedRequest(
|
||||
details.summary().assetRoot().resolve(ACCEPTED_REQUEST_FILE),
|
||||
buildCanonicalRequest(projectReference, details));
|
||||
} catch (IOException | IllegalArgumentException exception) {
|
||||
diagnostics.add(error(
|
||||
"Unable to persist canonical scene-pack request: " + exception.getMessage(),
|
||||
details.summary().assetRoot().resolve(ACCEPTED_REQUEST_FILE)));
|
||||
}
|
||||
}
|
||||
final AssetWorkspaceSceneBankValidation validation = validationState(diagnostics);
|
||||
return new SceneBankWorkflowResult(
|
||||
diagnostics.stream().noneMatch(AssetDiagnostic::blocking),
|
||||
messageFor(validation),
|
||||
validation,
|
||||
List.copyOf(diagnostics));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBankWorkflowResult validate(ProjectReference projectReference, AssetWorkspaceAssetDetails details) {
|
||||
return inspect(projectReference, details);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBankWorkflowResult accept(ProjectReference projectReference, AssetWorkspaceAssetDetails details) {
|
||||
return inspect(projectReference, details);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBankWorkflowResult inspectLayer(ProjectReference projectReference, AssetWorkspaceAssetDetails details, int layerIndex) {
|
||||
return inspect(projectReference, details);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBankWorkflowResult validateLayer(ProjectReference projectReference, AssetWorkspaceAssetDetails details, int layerIndex) {
|
||||
return inspect(projectReference, details);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBankWorkflowResult acceptLayer(ProjectReference projectReference, AssetWorkspaceAssetDetails details, int layerIndex) {
|
||||
return inspect(projectReference, details);
|
||||
}
|
||||
|
||||
private List<AssetDiagnostic> validateDiagnostics(ProjectReference projectReference, AssetWorkspaceAssetDetails details) {
|
||||
final List<AssetDiagnostic> diagnostics = new ArrayList<>();
|
||||
final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata();
|
||||
if (metadata == null) {
|
||||
diagnostics.add(error("Scene Bank support metadata is missing or invalid.",
|
||||
details.summary().assetRoot().resolve("scene-bank.studio.json")));
|
||||
return diagnostics;
|
||||
}
|
||||
final SceneLayerRuntimeDefaults sceneDefaults =
|
||||
resolveSceneLayerRuntimeDefaults(projectReference, metadata.layerBindings());
|
||||
for (AssetStudioSceneLayerBinding binding : metadata.layerBindings()) {
|
||||
if (!binding.enabled()) {
|
||||
if (resolveLayerRuntimeDefaults(projectReference, binding, sceneDefaults) == null) {
|
||||
diagnostics.add(error(
|
||||
"Unable to resolve runtime glyph/tile_size defaults for inactive layer " + binding.index() + ".",
|
||||
metadata.supportFile()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (binding.tilesetAssetRoot().isBlank()) {
|
||||
diagnostics.add(error("Layer " + binding.index() + " is missing tileset_asset_root.", metadata.supportFile()));
|
||||
continue;
|
||||
}
|
||||
if (binding.tiles().size() != binding.width() * binding.height()) {
|
||||
diagnostics.add(error("Canonical scene tile count does not match width * height for layer " + binding.index() + ".",
|
||||
metadata.supportFile()));
|
||||
continue;
|
||||
}
|
||||
if (resolveGlyphAssetId(projectReference, binding.tilesetAssetRoot()) < 0) {
|
||||
diagnostics.add(error("Unable to resolve glyph_asset_id for layer " + binding.index() + ": " + binding.tilesetAssetRoot(),
|
||||
metadata.supportFile()));
|
||||
}
|
||||
if (resolveTileSize(projectReference, binding.tilesetAssetRoot()) <= 0) {
|
||||
diagnostics.add(error("Unable to resolve tile_size for layer " + binding.index() + ": " + binding.tilesetAssetRoot(),
|
||||
metadata.supportFile()));
|
||||
}
|
||||
for (AssetStudioSceneTile tile : binding.tiles()) {
|
||||
if (tile.glyphId() < 0) {
|
||||
diagnostics.add(error("Canonical scene tile glyph_id must be non-negative for layer " + binding.index() + ".",
|
||||
metadata.supportFile()));
|
||||
break;
|
||||
}
|
||||
if (tile.paletteId() < 0) {
|
||||
diagnostics.add(error("Canonical scene tile palette_id must be non-negative for layer " + binding.index() + ".",
|
||||
metadata.supportFile()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.copyOf(diagnostics);
|
||||
}
|
||||
|
||||
private ScenePackRequest buildCanonicalRequest(ProjectReference projectReference, AssetWorkspaceAssetDetails details) throws IOException {
|
||||
final AssetStudioSceneBankMetadata metadata = Objects.requireNonNull(details.sceneBankMetadata(), "sceneBankMetadata");
|
||||
final SceneLayerRuntimeDefaults sceneDefaults =
|
||||
resolveSceneLayerRuntimeDefaults(projectReference, metadata.layerBindings());
|
||||
final List<ScenePackLayerRequest> layers = new ArrayList<>();
|
||||
for (AssetStudioSceneLayerBinding binding : metadata.layerBindings()) {
|
||||
if (!binding.enabled()) {
|
||||
layers.add(inactiveLayer(projectReference, binding, sceneDefaults));
|
||||
continue;
|
||||
}
|
||||
layers.add(activeLayer(projectReference, binding));
|
||||
}
|
||||
return new ScenePackRequest(1, layers);
|
||||
}
|
||||
|
||||
private ScenePackLayerRequest inactiveLayer(ProjectReference projectReference,
|
||||
AssetStudioSceneLayerBinding binding,
|
||||
SceneLayerRuntimeDefaults sceneDefaults) {
|
||||
final SceneLayerRuntimeDefaults defaults = resolveLayerRuntimeDefaults(projectReference, binding, sceneDefaults);
|
||||
if (defaults == null) {
|
||||
throw new IllegalArgumentException("Unable to resolve runtime defaults for inactive layer " + binding.index());
|
||||
}
|
||||
final List<ScenePackTileRequest> tiles = new ArrayList<>(binding.tiles().size());
|
||||
for (AssetStudioSceneTile tile : binding.tiles()) {
|
||||
tiles.add(new ScenePackTileRequest(false, 0, tile.paletteId(), false, false));
|
||||
}
|
||||
return new ScenePackLayerRequest(
|
||||
false,
|
||||
defaults.glyphAssetId(),
|
||||
defaults.tileSize(),
|
||||
binding.parallaxFactorX(),
|
||||
binding.parallaxFactorY(),
|
||||
binding.width(),
|
||||
binding.height(),
|
||||
tiles);
|
||||
}
|
||||
|
||||
private ScenePackLayerRequest activeLayer(ProjectReference projectReference, AssetStudioSceneLayerBinding binding) throws IOException {
|
||||
final int glyphAssetId = resolveGlyphAssetId(projectReference, binding.tilesetAssetRoot());
|
||||
if (glyphAssetId < 0) {
|
||||
throw new IllegalArgumentException("Unable to resolve glyph_asset_id for " + binding.tilesetAssetRoot());
|
||||
}
|
||||
final int tileSize = resolveTileSize(projectReference, binding.tilesetAssetRoot());
|
||||
if (tileSize <= 0) {
|
||||
throw new IllegalArgumentException("Unable to resolve tile_size for " + binding.tilesetAssetRoot());
|
||||
}
|
||||
final List<ScenePackTileRequest> tiles = new ArrayList<>(binding.tiles().size());
|
||||
for (AssetStudioSceneTile tile : binding.tiles()) {
|
||||
if (!tile.active()) {
|
||||
tiles.add(new ScenePackTileRequest(false, 0, tile.paletteId(), false, false));
|
||||
continue;
|
||||
}
|
||||
tiles.add(new ScenePackTileRequest(true, tile.glyphId(), tile.paletteId(), tile.flipX(), tile.flipY()));
|
||||
}
|
||||
return new ScenePackLayerRequest(
|
||||
true,
|
||||
glyphAssetId,
|
||||
tileSize,
|
||||
binding.parallaxFactorX(),
|
||||
binding.parallaxFactorY(),
|
||||
binding.width(),
|
||||
binding.height(),
|
||||
tiles);
|
||||
}
|
||||
|
||||
private SceneLayerRuntimeDefaults resolveSceneLayerRuntimeDefaults(ProjectReference projectReference,
|
||||
List<AssetStudioSceneLayerBinding> bindings) {
|
||||
for (AssetStudioSceneLayerBinding binding : bindings) {
|
||||
final SceneLayerRuntimeDefaults defaults = resolveLayerOwnRuntimeDefaults(projectReference, binding);
|
||||
if (defaults != null) {
|
||||
return defaults;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private SceneLayerRuntimeDefaults resolveLayerRuntimeDefaults(ProjectReference projectReference,
|
||||
AssetStudioSceneLayerBinding binding,
|
||||
SceneLayerRuntimeDefaults sceneDefaults) {
|
||||
final SceneLayerRuntimeDefaults ownDefaults = resolveLayerOwnRuntimeDefaults(projectReference, binding);
|
||||
return ownDefaults != null ? ownDefaults : sceneDefaults;
|
||||
}
|
||||
|
||||
private SceneLayerRuntimeDefaults resolveLayerOwnRuntimeDefaults(ProjectReference projectReference,
|
||||
AssetStudioSceneLayerBinding binding) {
|
||||
if (binding.tilesetAssetRoot().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
final int glyphAssetId = resolveGlyphAssetId(projectReference, binding.tilesetAssetRoot());
|
||||
final int tileSize = resolveTileSize(projectReference, binding.tilesetAssetRoot());
|
||||
if (glyphAssetId < 0 || tileSize <= 0) {
|
||||
return null;
|
||||
}
|
||||
return new SceneLayerRuntimeDefaults(glyphAssetId, tileSize);
|
||||
}
|
||||
|
||||
private void writeAcceptedRequest(Path path, ScenePackRequest request) throws IOException {
|
||||
final var root = mapper.createObjectNode();
|
||||
root.put("schema_version", 1);
|
||||
root.put("format", "SCENE/tilemap_v1");
|
||||
root.put("version", request.version());
|
||||
final var layersNode = root.putArray("layers");
|
||||
for (ScenePackLayerRequest layer : request.layers()) {
|
||||
final var layerNode = layersNode.addObject();
|
||||
layerNode.put("active", layer.active());
|
||||
layerNode.put("glyph_asset_id", layer.glyphAssetId());
|
||||
layerNode.put("tile_size", layer.tileSize());
|
||||
layerNode.put("parallax_factor_x", layer.parallaxFactorX());
|
||||
layerNode.put("parallax_factor_y", layer.parallaxFactorY());
|
||||
layerNode.put("width", layer.width());
|
||||
layerNode.put("height", layer.height());
|
||||
final var tilesNode = layerNode.putArray("tiles");
|
||||
for (ScenePackTileRequest tile : layer.tiles()) {
|
||||
final var tileNode = tilesNode.addObject();
|
||||
tileNode.put("active", tile.active());
|
||||
tileNode.put("glyph_id", tile.glyphId());
|
||||
tileNode.put("palette_id", tile.paletteId());
|
||||
tileNode.put("flip_x", tile.flipX());
|
||||
tileNode.put("flip_y", tile.flipY());
|
||||
}
|
||||
}
|
||||
mapper.writerWithDefaultPrettyPrinter().writeValue(path.toFile(), root);
|
||||
}
|
||||
|
||||
private int resolveGlyphAssetId(ProjectReference projectReference, String tilesetAssetRoot) {
|
||||
try {
|
||||
return glyphAssetResolver.resolveGlyphAssetId(projectReference, tilesetAssetRoot);
|
||||
} catch (IOException exception) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private int resolveTileSize(ProjectReference projectReference, String tilesetAssetRoot) {
|
||||
final Path declarationPath = projectReference.rootPath()
|
||||
.resolve("assets")
|
||||
.resolve(tilesetAssetRoot)
|
||||
.resolve("asset.json")
|
||||
.toAbsolutePath()
|
||||
.normalize();
|
||||
if (!Files.isRegularFile(declarationPath)) {
|
||||
return -1;
|
||||
}
|
||||
try {
|
||||
final JsonNode root = mapper.readTree(declarationPath.toFile());
|
||||
final String value = root.path("output").path("metadata").path("tile_size").asText("").trim().toLowerCase();
|
||||
return switch (value) {
|
||||
case "8x8" -> 8;
|
||||
case "16x16" -> 16;
|
||||
case "32x32" -> 32;
|
||||
default -> -1;
|
||||
};
|
||||
} catch (IOException exception) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private AssetWorkspaceSceneBankValidation validationState(List<AssetDiagnostic> diagnostics) {
|
||||
if (diagnostics.stream().anyMatch(AssetDiagnostic::blocking)) {
|
||||
return new AssetWorkspaceSceneBankValidation(
|
||||
AssetWorkspaceSceneBankStatus.VALIDATION_FAILED,
|
||||
false,
|
||||
false,
|
||||
"",
|
||||
"",
|
||||
"");
|
||||
}
|
||||
return new AssetWorkspaceSceneBankValidation(
|
||||
AssetWorkspaceSceneBankStatus.READY,
|
||||
false,
|
||||
false,
|
||||
"",
|
||||
"",
|
||||
"");
|
||||
}
|
||||
|
||||
private String messageFor(AssetWorkspaceSceneBankValidation validation) {
|
||||
return switch (validation.status()) {
|
||||
case NOT_APPLICABLE -> "";
|
||||
case PENDING_VALIDATION, VALIDATED_PENDING_ACCEPTANCE -> "Scene Bank canonical workflow no longer uses validation/acceptance staging.";
|
||||
case READY -> "Scene Bank canonical scene is ready.";
|
||||
case VALIDATION_FAILED -> "Scene Bank validation failed.";
|
||||
};
|
||||
}
|
||||
|
||||
private AssetDiagnostic error(String message, Path path) {
|
||||
return new AssetDiagnostic(
|
||||
"ERROR",
|
||||
"STRUCTURAL",
|
||||
message,
|
||||
path,
|
||||
true);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface SceneBankGlyphAssetResolver {
|
||||
int resolveGlyphAssetId(ProjectReference projectReference, String tilesetAssetRoot) throws IOException;
|
||||
}
|
||||
|
||||
private record SceneLayerRuntimeDefaults(int glyphAssetId, int tileSize) {
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package p.studio.core.assets.scene;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record ScenePackLayerRequest(
|
||||
boolean active,
|
||||
int glyphAssetId,
|
||||
int tileSize,
|
||||
float parallaxFactorX,
|
||||
float parallaxFactorY,
|
||||
int width,
|
||||
int height,
|
||||
List<ScenePackTileRequest> tiles) {
|
||||
|
||||
public ScenePackLayerRequest {
|
||||
tiles = List.copyOf(Objects.requireNonNull(tiles, "tiles"));
|
||||
if (glyphAssetId < 0) {
|
||||
throw new IllegalArgumentException("glyphAssetId must be non-negative");
|
||||
}
|
||||
if (tileSize < 0) {
|
||||
throw new IllegalArgumentException("tileSize must be non-negative");
|
||||
}
|
||||
if (width <= 0 || height <= 0) {
|
||||
throw new IllegalArgumentException("width and height must be positive");
|
||||
}
|
||||
if (!Float.isFinite(parallaxFactorX) || parallaxFactorX < 0.0f) {
|
||||
throw new IllegalArgumentException("parallaxFactorX must be finite and non-negative");
|
||||
}
|
||||
if (!Float.isFinite(parallaxFactorY) || parallaxFactorY < 0.0f) {
|
||||
throw new IllegalArgumentException("parallaxFactorY must be finite and non-negative");
|
||||
}
|
||||
if (tiles.size() != width * height) {
|
||||
throw new IllegalArgumentException("tiles size must match width * height");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package p.studio.core.assets.scene;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record ScenePackRequest(
|
||||
int version,
|
||||
List<ScenePackLayerRequest> layers) {
|
||||
|
||||
public ScenePackRequest {
|
||||
layers = List.copyOf(Objects.requireNonNull(layers, "layers"));
|
||||
if (version <= 0) {
|
||||
throw new IllegalArgumentException("version must be positive");
|
||||
}
|
||||
if (layers.size() != 4) {
|
||||
throw new IllegalArgumentException("layers must contain exactly 4 entries");
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package p.studio.core.assets.scene;
|
||||
|
||||
public record ScenePackTileRequest(
|
||||
boolean active,
|
||||
int glyphId,
|
||||
int paletteId,
|
||||
boolean flipX,
|
||||
boolean flipY) {
|
||||
|
||||
public ScenePackTileRequest {
|
||||
if (glyphId < 0) {
|
||||
throw new IllegalArgumentException("glyphId must be non-negative");
|
||||
}
|
||||
if (paletteId < 0) {
|
||||
throw new IllegalArgumentException("paletteId must be non-negative");
|
||||
}
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package p.studio.core.assets.schema;
|
||||
|
||||
import p.studio.api.assets.schema.AssetColorSchemaRules;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceBankCompositionFile;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
|
||||
record AssetColorSchemaDraft(
|
||||
String schemaId,
|
||||
boolean existingSchema,
|
||||
boolean removeRequested,
|
||||
List<AssetWorkspaceBankCompositionFile> availableTiles,
|
||||
List<AssetWorkspaceBankCompositionFile> assignedTiles,
|
||||
List<String> preferredColors,
|
||||
boolean deriveColorsFromTiles) {
|
||||
|
||||
AssetColorSchemaDraft {
|
||||
availableTiles = List.copyOf(availableTiles);
|
||||
assignedTiles = List.copyOf(assignedTiles);
|
||||
preferredColors = normalize(preferredColors);
|
||||
}
|
||||
|
||||
static AssetColorSchemaDraft noSelection() {
|
||||
return new AssetColorSchemaDraft(null, false, false, List.of(), List.of(), List.of(), false);
|
||||
}
|
||||
|
||||
AssetColorSchemaDraft moveToAssigned(List<AssetWorkspaceBankCompositionFile> files, AssetColorSchemaRules rules) {
|
||||
final List<AssetWorkspaceBankCompositionFile> nextAvailable = new ArrayList<>(availableTiles);
|
||||
final List<AssetWorkspaceBankCompositionFile> nextAssigned = new ArrayList<>(assignedTiles);
|
||||
for (AssetWorkspaceBankCompositionFile file : files) {
|
||||
if (nextAvailable.remove(file) && !nextAssigned.contains(file)) {
|
||||
nextAssigned.add(file);
|
||||
}
|
||||
}
|
||||
return withTiles(nextAvailable, nextAssigned, rules);
|
||||
}
|
||||
|
||||
AssetColorSchemaDraft moveToAvailable(List<AssetWorkspaceBankCompositionFile> files, AssetColorSchemaRules rules) {
|
||||
final List<AssetWorkspaceBankCompositionFile> nextAvailable = new ArrayList<>(availableTiles);
|
||||
final List<AssetWorkspaceBankCompositionFile> nextAssigned = new ArrayList<>(assignedTiles);
|
||||
for (AssetWorkspaceBankCompositionFile file : files) {
|
||||
if (nextAssigned.remove(file) && !nextAvailable.contains(file)) {
|
||||
nextAvailable.add(file);
|
||||
}
|
||||
}
|
||||
return withTiles(nextAvailable, nextAssigned, rules);
|
||||
}
|
||||
|
||||
AssetColorSchemaDraft moveAssignedUp(int index, AssetColorSchemaRules rules) {
|
||||
if (index <= 0 || index >= assignedTiles.size()) {
|
||||
return this;
|
||||
}
|
||||
final List<AssetWorkspaceBankCompositionFile> nextAssigned = new ArrayList<>(assignedTiles);
|
||||
final AssetWorkspaceBankCompositionFile file = nextAssigned.remove(index);
|
||||
nextAssigned.add(index - 1, file);
|
||||
return withTiles(availableTiles, nextAssigned, rules);
|
||||
}
|
||||
|
||||
AssetColorSchemaDraft moveAssignedDown(int index, AssetColorSchemaRules rules) {
|
||||
if (index < 0 || index >= assignedTiles.size() - 1) {
|
||||
return this;
|
||||
}
|
||||
final List<AssetWorkspaceBankCompositionFile> nextAssigned = new ArrayList<>(assignedTiles);
|
||||
final AssetWorkspaceBankCompositionFile file = nextAssigned.remove(index);
|
||||
nextAssigned.add(index + 1, file);
|
||||
return withTiles(availableTiles, nextAssigned, rules);
|
||||
}
|
||||
|
||||
AssetColorSchemaDraft markForRemoval() {
|
||||
if (schemaId == null || schemaId.isBlank()) {
|
||||
return this;
|
||||
}
|
||||
return new AssetColorSchemaDraft(schemaId, existingSchema, true, availableTiles, assignedTiles,
|
||||
preferredColors, deriveColorsFromTiles);
|
||||
}
|
||||
|
||||
AssetColorSchemaDraft asUpdateDraft(AssetColorSchemaRules rules) {
|
||||
return new AssetColorSchemaDraft(schemaId, existingSchema, false, availableTiles, assignedTiles,
|
||||
orderedColors(rules), true);
|
||||
}
|
||||
|
||||
List<String> orderedColors(AssetColorSchemaRules rules) {
|
||||
if (!deriveColorsFromTiles) {
|
||||
return preferredColors;
|
||||
}
|
||||
final LinkedHashSet<String> active = new LinkedHashSet<>();
|
||||
for (AssetWorkspaceBankCompositionFile tile : assignedTiles) {
|
||||
rules.tileColors(tile).stream().map(AssetColorSchemaDraft::normalize).forEach(active::add);
|
||||
}
|
||||
final List<String> ordered = new ArrayList<>();
|
||||
for (String preferredColor : preferredColors) {
|
||||
if (active.contains(preferredColor) && !ordered.contains(preferredColor)) {
|
||||
ordered.add(preferredColor);
|
||||
}
|
||||
}
|
||||
for (String color : active) {
|
||||
if (!ordered.contains(color)) {
|
||||
ordered.add(color);
|
||||
}
|
||||
}
|
||||
return List.copyOf(ordered);
|
||||
}
|
||||
|
||||
private AssetColorSchemaDraft withTiles(
|
||||
List<AssetWorkspaceBankCompositionFile> nextAvailable,
|
||||
List<AssetWorkspaceBankCompositionFile> nextAssigned,
|
||||
AssetColorSchemaRules rules) {
|
||||
return new AssetColorSchemaDraft(schemaId, existingSchema, false, nextAvailable, nextAssigned,
|
||||
orderedColors(rules), true);
|
||||
}
|
||||
|
||||
private static List<String> normalize(List<String> colors) {
|
||||
final List<String> normalized = new ArrayList<>();
|
||||
for (String color : colors) {
|
||||
if (color != null && !color.isBlank()) {
|
||||
normalized.add(normalize(color));
|
||||
}
|
||||
}
|
||||
return List.copyOf(normalized);
|
||||
}
|
||||
|
||||
private static String normalize(String color) {
|
||||
return color.trim().toUpperCase();
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package p.studio.core.assets.schema;
|
||||
|
||||
import p.studio.api.assets.schema.AssetColorSchemaFactory;
|
||||
import p.studio.api.assets.schema.AssetColorSchemaRules;
|
||||
import p.studio.api.assets.schema.AssetColorSchemaSession;
|
||||
import p.studio.api.assets.palette.AssetPaletteSession;
|
||||
import p.studio.core.assets.palette.DefaultAssetPaletteSession;
|
||||
|
||||
public final class DefaultAssetColorSchemaFactory implements AssetColorSchemaFactory {
|
||||
private final AssetColorSchemaRules rules = new DefaultAssetColorSchemaRules();
|
||||
|
||||
@Override
|
||||
public AssetColorSchemaSession createSession() {
|
||||
return new DefaultAssetColorSchemaSession(rules);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetColorSchemaRules rules() {
|
||||
return rules;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetPaletteSession createPaletteSession() {
|
||||
return new DefaultAssetPaletteSession(rules);
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package p.studio.core.assets.schema;
|
||||
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialArtifactBinding;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialSchema;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialSchemaStatus;
|
||||
import p.studio.api.assets.schema.AssetColorSchemaRules;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceBankCompositionFile;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class DefaultAssetColorSchemaRules implements AssetColorSchemaRules {
|
||||
@Override
|
||||
public AssetStudioGlyphMaterialSchemaStatus effectiveStatus(
|
||||
AssetStudioGlyphMaterialSchema schema,
|
||||
List<AssetWorkspaceBankCompositionFile> selectedTiles) {
|
||||
if (schema.status() == AssetStudioGlyphMaterialSchemaStatus.INCONSISTENT) {
|
||||
return AssetStudioGlyphMaterialSchemaStatus.INCONSISTENT;
|
||||
}
|
||||
final Map<String, AssetWorkspaceBankCompositionFile> selectedByArtifactId = new HashMap<>();
|
||||
for (AssetWorkspaceBankCompositionFile tile : selectedTiles) {
|
||||
final String artifactId = artifactId(tile);
|
||||
if (artifactId != null) {
|
||||
selectedByArtifactId.put(artifactId, tile);
|
||||
}
|
||||
}
|
||||
for (AssetStudioGlyphMaterialArtifactBinding binding : schema.artifactBindings()) {
|
||||
final AssetWorkspaceBankCompositionFile selectedTile = selectedByArtifactId.get(binding.artifactId());
|
||||
if (selectedTile == null || !Objects.equals(binding.fingerprint(), fingerprint(selectedTile))) {
|
||||
return AssetStudioGlyphMaterialSchemaStatus.INCONSISTENT;
|
||||
}
|
||||
}
|
||||
return AssetStudioGlyphMaterialSchemaStatus.OK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsSchemaAuthoring(AssetWorkspaceBankCompositionFile file) {
|
||||
return file != null && artifactId(file) != null && fingerprint(file) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String artifactId(AssetWorkspaceBankCompositionFile file) {
|
||||
if (file == null) {
|
||||
return null;
|
||||
}
|
||||
final Object artifactId = file.metadata().get("artifactId");
|
||||
if (artifactId instanceof String value && !value.isBlank()) {
|
||||
return value.trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String fingerprint(AssetWorkspaceBankCompositionFile file) {
|
||||
if (file == null) {
|
||||
return null;
|
||||
}
|
||||
if (file.fingerprint() != null && !file.fingerprint().isBlank()) {
|
||||
return file.fingerprint().trim();
|
||||
}
|
||||
final Object selectedFingerprint = file.metadata().get("selectedFingerprint");
|
||||
if (selectedFingerprint instanceof String value && !value.isBlank()) {
|
||||
return value.trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> tileColors(AssetWorkspaceBankCompositionFile file) {
|
||||
final Map<String, Object> palette = nestedMap(file.metadata(), "palette");
|
||||
if (palette == null) {
|
||||
return List.of();
|
||||
}
|
||||
final List<String> colors = new ArrayList<>();
|
||||
final Object rgbaColors = palette.get("rgba8888");
|
||||
if (rgbaColors instanceof Iterable<?> rgbaIterable) {
|
||||
for (Object item : rgbaIterable) {
|
||||
if (!(item instanceof Number number)) {
|
||||
continue;
|
||||
}
|
||||
final int value = number.intValue();
|
||||
final int alpha = value & 0xFF;
|
||||
colors.add(alpha == 0xFF
|
||||
? String.format("#%02X%02X%02X", (value >>> 24) & 0xFF, (value >>> 16) & 0xFF, (value >>> 8) & 0xFF)
|
||||
: String.format("#%02X%02X%02X%02X", (value >>> 24) & 0xFF, (value >>> 16) & 0xFF, (value >>> 8) & 0xFF, alpha));
|
||||
}
|
||||
if (!colors.isEmpty()) {
|
||||
return List.copyOf(colors);
|
||||
}
|
||||
}
|
||||
final Object originalColors = palette.get("originalArgb8888");
|
||||
if (originalColors instanceof Iterable<?> argbIterable) {
|
||||
for (Object item : argbIterable) {
|
||||
if (item instanceof Number number) {
|
||||
colors.add(String.format("#%02X%02X%02X", (number.intValue() >> 16) & 0xFF,
|
||||
(number.intValue() >> 8) & 0xFF, number.intValue() & 0xFF));
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.copyOf(colors);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> nestedMap(Map<String, Object> metadata, String key) {
|
||||
final Object value = metadata.get(key);
|
||||
return value instanceof Map<?, ?> nested ? (Map<String, Object>) nested : null;
|
||||
}
|
||||
}
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
package p.studio.core.assets.schema;
|
||||
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceAssetDetails;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceBankCompositionFile;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialArtifactBinding;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialMetadata;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialPalette;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialSchema;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialSchemaStatus;
|
||||
import p.studio.api.assets.schema.AssetColorSchemaRules;
|
||||
import p.studio.api.assets.schema.AssetColorSchemaSession;
|
||||
import p.studio.api.assets.schema.AssetColorSchemaState;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public final class DefaultAssetColorSchemaSession implements AssetColorSchemaSession {
|
||||
private final AssetColorSchemaRules rules;
|
||||
private AssetWorkspaceAssetDetails details;
|
||||
private AssetStudioGlyphMaterialMetadata localMaterialMetadata;
|
||||
private AssetColorSchemaDraft source;
|
||||
private AssetColorSchemaDraft draft;
|
||||
private boolean editing;
|
||||
|
||||
public DefaultAssetColorSchemaSession(AssetColorSchemaRules rules) {
|
||||
this.rules = Objects.requireNonNull(rules, "rules");
|
||||
}
|
||||
|
||||
public void replaceDetails(AssetWorkspaceAssetDetails details) {
|
||||
this.details = details;
|
||||
this.localMaterialMetadata = details == null ? null : details.glyphMaterialMetadata();
|
||||
if (!ready()) {
|
||||
source = null;
|
||||
draft = null;
|
||||
editing = false;
|
||||
return;
|
||||
}
|
||||
selectSchema(defaultSchemaId());
|
||||
}
|
||||
|
||||
public void replaceMaterialMetadata(AssetStudioGlyphMaterialMetadata metadata) {
|
||||
this.localMaterialMetadata = Objects.requireNonNull(metadata, "metadata");
|
||||
if (ready() && !editing) {
|
||||
final String selected = draft == null ? null : draft.schemaId();
|
||||
selectSchema(findSchema(selected).isPresent() ? selected : defaultSchemaId());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean ready() {
|
||||
return details != null && details.summary().assetFamily() == AssetFamily.GLYPH_BANK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beginEdit() {
|
||||
if (ready()) {
|
||||
source = AssetColorSchemaDraft.noSelection();
|
||||
draft = source;
|
||||
editing = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void apply() {
|
||||
if (draft != null) {
|
||||
source = draft;
|
||||
editing = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
if (source != null) {
|
||||
draft = source;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
reset();
|
||||
editing = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void selectSchema(String schemaId) {
|
||||
if (!ready()) {
|
||||
return;
|
||||
}
|
||||
final AssetColorSchemaDraft selected = schemaId == null ? AssetColorSchemaDraft.noSelection() : sourceDraft(schemaId);
|
||||
if (editing) {
|
||||
draft = selected.asUpdateDraft(rules);
|
||||
} else {
|
||||
source = selected;
|
||||
draft = selected;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createSchema() {
|
||||
if (ready() && editing) {
|
||||
draft = sourceDraft(nextSchemaId()).asUpdateDraft(rules);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markSelectedSchemaForRemoval() {
|
||||
if (!editing || draft == null) {
|
||||
return;
|
||||
}
|
||||
draft = draft.existingSchema() ? draft.markForRemoval() : AssetColorSchemaDraft.noSelection();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void moveToAssigned(List<AssetWorkspaceBankCompositionFile> files) {
|
||||
if (editing && draft != null) {
|
||||
draft = draft.moveToAssigned(files, rules);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void moveToAvailable(List<AssetWorkspaceBankCompositionFile> files) {
|
||||
if (editing && draft != null) {
|
||||
draft = draft.moveToAvailable(files, rules);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void moveAssignedUp(int index) {
|
||||
if (editing && draft != null) {
|
||||
draft = draft.moveAssignedUp(index, rules);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void moveAssignedDown(int index) {
|
||||
if (editing && draft != null) {
|
||||
draft = draft.moveAssignedDown(index, rules);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetColorSchemaState state() {
|
||||
if (draft == null) {
|
||||
return new AssetColorSchemaState(false, false, null, false, false, List.of(), List.of(), List.of());
|
||||
}
|
||||
return new AssetColorSchemaState(
|
||||
editing,
|
||||
!Objects.equals(source, draft),
|
||||
draft.schemaId(),
|
||||
draft.existingSchema(),
|
||||
draft.removeRequested(),
|
||||
draft.availableTiles(),
|
||||
draft.assignedTiles(),
|
||||
draft.orderedColors(rules));
|
||||
}
|
||||
|
||||
public AssetStudioGlyphMaterialMetadata metadata() {
|
||||
if (!ready() || localMaterialMetadata == null) {
|
||||
return new AssetStudioGlyphMaterialMetadata(List.of(), List.of(), null);
|
||||
}
|
||||
return localMaterialMetadata;
|
||||
}
|
||||
|
||||
public List<AssetStudioGlyphMaterialSchema> schemas() {
|
||||
return metadata().schemas();
|
||||
}
|
||||
|
||||
public List<AssetWorkspaceBankCompositionFile> selectedTiles() {
|
||||
if (!ready()) {
|
||||
return List.of();
|
||||
}
|
||||
return details.bankComposition().selectedFiles().stream()
|
||||
.filter(rules::supportsSchemaAuthoring)
|
||||
.filter(file -> rules.artifactId(file) != null)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<AssetWorkspaceBankCompositionFile> availableTilesForCreate() {
|
||||
final Set<String> reservedArtifactIds = new HashSet<>();
|
||||
for (AssetStudioGlyphMaterialSchema schema : schemas()) {
|
||||
schema.artifactBindings().forEach(binding -> reservedArtifactIds.add(binding.artifactId()));
|
||||
}
|
||||
return selectedTiles().stream()
|
||||
.filter(file -> !reservedArtifactIds.contains(rules.artifactId(file)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<AssetWorkspaceBankCompositionFile> availableTilesForEdit(String schemaId) {
|
||||
final AssetStudioGlyphMaterialSchema schema = findSchema(schemaId).orElse(null);
|
||||
if (schema == null) {
|
||||
return availableTilesForCreate();
|
||||
}
|
||||
final Set<String> current = schema.artifactBindings().stream()
|
||||
.map(AssetStudioGlyphMaterialArtifactBinding::artifactId)
|
||||
.collect(java.util.stream.Collectors.toCollection(LinkedHashSet::new));
|
||||
final Set<String> reservedElsewhere = new HashSet<>();
|
||||
for (AssetStudioGlyphMaterialSchema candidate : schemas()) {
|
||||
if (candidate.schemaId().equals(schemaId)) {
|
||||
continue;
|
||||
}
|
||||
candidate.artifactBindings().forEach(binding -> reservedElsewhere.add(binding.artifactId()));
|
||||
}
|
||||
return selectedTiles().stream()
|
||||
.filter(file -> current.contains(rules.artifactId(file)) || !reservedElsewhere.contains(rules.artifactId(file)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public boolean canRemove(String schemaId) {
|
||||
return metadata().palettes().stream().noneMatch(palette -> palette.schemaId().equals(schemaId));
|
||||
}
|
||||
|
||||
public Optional<AssetStudioGlyphMaterialSchema> findSchema(String schemaId) {
|
||||
return schemas().stream().filter(schema -> schema.schemaId().equals(schemaId)).findFirst();
|
||||
}
|
||||
|
||||
public AssetStudioGlyphMaterialMetadata upsertSchema(
|
||||
String schemaId,
|
||||
List<AssetWorkspaceBankCompositionFile> assignedTiles,
|
||||
List<String> orderedColors) {
|
||||
final AssetStudioGlyphMaterialMetadata current = metadata();
|
||||
final AssetStudioGlyphMaterialSchema existing = current.findSchema(schemaId).orElse(null);
|
||||
final AssetStudioGlyphMaterialSchema next = buildSchema(schemaId, existing, assignedTiles, orderedColors);
|
||||
final List<AssetStudioGlyphMaterialSchema> schemas = new ArrayList<>();
|
||||
boolean replaced = false;
|
||||
for (AssetStudioGlyphMaterialSchema schema : current.schemas()) {
|
||||
if (schema.schemaId().equals(schemaId)) {
|
||||
schemas.add(next);
|
||||
replaced = true;
|
||||
} else {
|
||||
schemas.add(schema);
|
||||
}
|
||||
}
|
||||
if (!replaced) {
|
||||
schemas.add(next);
|
||||
}
|
||||
schemas.sort(Comparator.comparing(AssetStudioGlyphMaterialSchema::schemaId, String.CASE_INSENSITIVE_ORDER));
|
||||
return new AssetStudioGlyphMaterialMetadata(schemas, current.palettes(), current.supportFile());
|
||||
}
|
||||
|
||||
public AssetStudioGlyphMaterialMetadata removeSchema(String schemaId) {
|
||||
if (!canRemove(schemaId)) {
|
||||
throw new IllegalStateException("Schema is still referenced by one or more palettes.");
|
||||
}
|
||||
final AssetStudioGlyphMaterialMetadata current = metadata();
|
||||
final List<AssetStudioGlyphMaterialSchema> schemas = current.schemas().stream()
|
||||
.filter(schema -> !schema.schemaId().equals(schemaId))
|
||||
.toList();
|
||||
return new AssetStudioGlyphMaterialMetadata(schemas, current.palettes(), current.supportFile());
|
||||
}
|
||||
|
||||
public String nextSchemaId() {
|
||||
int next = 1;
|
||||
final Set<String> ids = schemas().stream().map(AssetStudioGlyphMaterialSchema::schemaId).collect(java.util.stream.Collectors.toSet());
|
||||
while (ids.contains("schema-" + next)) {
|
||||
next += 1;
|
||||
}
|
||||
return "schema-" + next;
|
||||
}
|
||||
|
||||
public int unassignedTileCount() {
|
||||
return availableTilesForCreate().size();
|
||||
}
|
||||
|
||||
private AssetColorSchemaDraft sourceDraft(String schemaId) {
|
||||
final AssetStudioGlyphMaterialSchema schema = findSchema(schemaId).orElse(null);
|
||||
final List<AssetWorkspaceBankCompositionFile> selectableTiles = schema == null
|
||||
? availableTilesForCreate()
|
||||
: availableTilesForEdit(schema.schemaId());
|
||||
final Set<String> assignedArtifactIds = schema == null
|
||||
? Set.of()
|
||||
: schema.artifactBindings().stream()
|
||||
.map(AssetStudioGlyphMaterialArtifactBinding::artifactId)
|
||||
.collect(java.util.stream.Collectors.toCollection(LinkedHashSet::new));
|
||||
final List<AssetWorkspaceBankCompositionFile> assignedTiles = selectableTiles.stream()
|
||||
.filter(file -> assignedArtifactIds.contains(rules.artifactId(file)))
|
||||
.toList();
|
||||
final List<AssetWorkspaceBankCompositionFile> availableTiles = selectableTiles.stream()
|
||||
.filter(file -> !assignedArtifactIds.contains(rules.artifactId(file)))
|
||||
.toList();
|
||||
final List<String> preferredColors = schema == null
|
||||
? List.of()
|
||||
: schema.materialIndices().entrySet().stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
.map(Map.Entry::getValue)
|
||||
.toList();
|
||||
return new AssetColorSchemaDraft(schemaId, schema != null, false, availableTiles, assignedTiles,
|
||||
preferredColors, schema == null);
|
||||
}
|
||||
|
||||
private String defaultSchemaId() {
|
||||
return schemas().stream().map(AssetStudioGlyphMaterialSchema::schemaId).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
private AssetStudioGlyphMaterialSchema buildSchema(
|
||||
String schemaId,
|
||||
AssetStudioGlyphMaterialSchema existing,
|
||||
List<AssetWorkspaceBankCompositionFile> assignedTiles,
|
||||
List<String> orderedColors) {
|
||||
final Map<Integer, String> materialIndices = new LinkedHashMap<>();
|
||||
for (int index = 0; index < orderedColors.size(); index += 1) {
|
||||
materialIndices.put(index, normalizeHtmlColor(orderedColors.get(index)));
|
||||
}
|
||||
final List<AssetStudioGlyphMaterialArtifactBinding> bindings = assignedTiles.stream()
|
||||
.map(file -> new AssetStudioGlyphMaterialArtifactBinding(rules.artifactId(file), rules.fingerprint(file)))
|
||||
.toList();
|
||||
final boolean unchanged = existing != null
|
||||
&& existing.materialIndices().equals(materialIndices)
|
||||
&& existing.artifactBindings().equals(bindings);
|
||||
final int version = existing == null
|
||||
? 1
|
||||
: unchanged ? existing.version() : existing.version() + 1;
|
||||
final AssetStudioGlyphMaterialSchemaStatus status = existing == null || !unchanged
|
||||
? AssetStudioGlyphMaterialSchemaStatus.OK
|
||||
: existing.status();
|
||||
return new AssetStudioGlyphMaterialSchema(schemaId, status, version, materialIndices, bindings);
|
||||
}
|
||||
|
||||
private static String normalizeHtmlColor(String color) {
|
||||
return Objects.requireNonNull(color, "color").trim().toUpperCase();
|
||||
}
|
||||
}
|
||||
+493
@@ -0,0 +1,493 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
import p.studio.api.assets.AssetConfigurationField;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphSpecialization;
|
||||
import p.studio.api.assets.metadata.AssetMetadataService;
|
||||
import p.studio.api.assets.metadata.AssetStudioSceneBankMetadata;
|
||||
import p.studio.api.assets.metadata.AssetStudioSceneLayerBinding;
|
||||
import p.studio.api.assets.metadata.AssetStudioSceneTile;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceAssetDetails;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceBankCompositionFile;
|
||||
import p.studio.api.assets.tiled.SceneTmxExportDisposition;
|
||||
import p.studio.api.assets.tiled.TiledAssetGenerationResult;
|
||||
import p.studio.api.assets.tiled.TiledAssetService;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class TiledAssetGenerationService implements TiledAssetService {
|
||||
public static final String GENERATED_TSX_FILE = "tileset.tsx";
|
||||
|
||||
private static final long FLIP_HORIZONTAL_FLAG = 0x80000000L;
|
||||
private static final long FLIP_VERTICAL_FLAG = 0x40000000L;
|
||||
private static final long FLIP_DIAGONAL_FLAG = 0x20000000L;
|
||||
private static final long GID_MASK = ~(FLIP_HORIZONTAL_FLAG | FLIP_VERTICAL_FLAG | FLIP_DIAGONAL_FLAG);
|
||||
|
||||
private final TiledXmlCodec codec = new TiledXmlCodec();
|
||||
private final AssetMetadataService metadataService;
|
||||
|
||||
public TiledAssetGenerationService(AssetMetadataService metadataService) {
|
||||
this.metadataService = Objects.requireNonNull(metadataService, "metadataService");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean sceneTmxExists(AssetWorkspaceAssetDetails details) {
|
||||
if (details == null || details.sceneBankMetadata() == null) {
|
||||
return false;
|
||||
}
|
||||
final String sceneTilemap = resolveSceneTilemap(details.sceneBankMetadata());
|
||||
return sceneTilemap != null && Files.isRegularFile(details.summary().assetRoot().resolve(sceneTilemap));
|
||||
}
|
||||
|
||||
public TiledAssetGenerationResult generateTilesetTsx(AssetWorkspaceAssetDetails details) {
|
||||
return exportTilesetTsx(details);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TiledAssetGenerationResult exportTilesetTsx(AssetWorkspaceAssetDetails details) {
|
||||
if (details == null
|
||||
|| details.summary().assetFamily() != AssetFamily.GLYPH_BANK
|
||||
|| details.summary().glyphSpecialization() != AssetStudioGlyphSpecialization.TILESET) {
|
||||
return new TiledAssetGenerationResult(false, "TSX export is available only for Tileset-specialized glyph banks.", List.of(), List.of());
|
||||
}
|
||||
final List<AssetWorkspaceBankCompositionFile> selectedFiles = details.bankComposition().selectedFiles();
|
||||
if (selectedFiles.isEmpty()) {
|
||||
return new TiledAssetGenerationResult(false, "The selected tileset bank has no included glyph artifacts.", List.of(), List.of());
|
||||
}
|
||||
final int tileSize = parseTileSize(details.metadataFields());
|
||||
final List<TiledTilesetTile> tiles = new ArrayList<>();
|
||||
for (int index = 0; index < selectedFiles.size(); index += 1) {
|
||||
final AssetWorkspaceBankCompositionFile file = selectedFiles.get(index);
|
||||
tiles.add(new TiledTilesetTile(
|
||||
index,
|
||||
file.path(),
|
||||
tileSize,
|
||||
tileSize,
|
||||
List.of(new TiledProperty("glyph_id", "int", Integer.toString(index))),
|
||||
null));
|
||||
}
|
||||
final TiledTilesetDocument document = new TiledTilesetDocument(
|
||||
"1.10",
|
||||
"1.12.1",
|
||||
details.summary().assetName(),
|
||||
tileSize,
|
||||
tileSize,
|
||||
tiles.size(),
|
||||
0,
|
||||
List.of(),
|
||||
tiles);
|
||||
final Path outputPath = details.summary().assetRoot().resolve(GENERATED_TSX_FILE);
|
||||
try {
|
||||
codec.writeTileset(outputPath, document);
|
||||
return new TiledAssetGenerationResult(true, "Exported TSX successfully.", List.of(), List.of(outputPath));
|
||||
} catch (IOException exception) {
|
||||
return new TiledAssetGenerationResult(false, "Unable to export TSX: " + exception.getMessage(), List.of(), List.of());
|
||||
}
|
||||
}
|
||||
|
||||
public TiledAssetGenerationResult generateSceneBankTilemaps(ProjectReference projectReference, AssetWorkspaceAssetDetails details) {
|
||||
return exportSceneBankTmx(projectReference, details);
|
||||
}
|
||||
|
||||
public TiledAssetGenerationResult generateSceneBankTilemap(ProjectReference projectReference, AssetWorkspaceAssetDetails details, int layerIndex) {
|
||||
return exportSceneBankTmx(projectReference, details);
|
||||
}
|
||||
|
||||
public TiledAssetGenerationResult exportSceneBankTmx(ProjectReference projectReference, AssetWorkspaceAssetDetails details) {
|
||||
return exportSceneBankTmx(projectReference, details, SceneTmxExportDisposition.OVERWRITE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TiledAssetGenerationResult exportSceneBankTmx(
|
||||
ProjectReference projectReference,
|
||||
AssetWorkspaceAssetDetails details,
|
||||
SceneTmxExportDisposition disposition) {
|
||||
if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) {
|
||||
return new TiledAssetGenerationResult(false, "TMX export is available only for Scene Bank assets.", List.of(), List.of());
|
||||
}
|
||||
final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata();
|
||||
if (metadata == null) {
|
||||
return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of());
|
||||
}
|
||||
final List<AssetStudioSceneLayerBinding> enabledLayers = metadata.layerBindings().stream()
|
||||
.filter(AssetStudioSceneLayerBinding::enabled)
|
||||
.toList();
|
||||
if (enabledLayers.isEmpty()) {
|
||||
return new TiledAssetGenerationResult(false, "Enable at least one layer before exporting TMX.", List.of(), List.of());
|
||||
}
|
||||
final String sceneTilemap = resolveSceneTilemap(metadata);
|
||||
if (sceneTilemap == null) {
|
||||
return new TiledAssetGenerationResult(false, "Scene TMX export requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of());
|
||||
}
|
||||
try {
|
||||
final ExportContext context = buildExportContext(projectReference, details, enabledLayers);
|
||||
final List<TiledTileLayer> tileLayers = new ArrayList<>();
|
||||
int nextLayerId = 1;
|
||||
for (AssetStudioSceneLayerBinding binding : enabledLayers) {
|
||||
final TilesetRef ref = context.tilesetByAssetRoot().get(binding.tilesetAssetRoot());
|
||||
final List<Long> gids = new ArrayList<>(binding.tiles().size());
|
||||
for (AssetStudioSceneTile tile : binding.tiles()) {
|
||||
if (!tile.active()) {
|
||||
gids.add(0L);
|
||||
continue;
|
||||
}
|
||||
if (tile.glyphId() >= ref.tileCount()) {
|
||||
return new TiledAssetGenerationResult(
|
||||
false,
|
||||
"Layer " + binding.index() + " references glyph_id outside the exported TSX range.",
|
||||
List.of(),
|
||||
List.of());
|
||||
}
|
||||
long gid = ref.firstGid() + tile.glyphId();
|
||||
if (tile.flipX()) {
|
||||
gid |= FLIP_HORIZONTAL_FLAG;
|
||||
}
|
||||
if (tile.flipY()) {
|
||||
gid |= FLIP_VERTICAL_FLAG;
|
||||
}
|
||||
gids.add(gid);
|
||||
}
|
||||
tileLayers.add(new TiledTileLayer(
|
||||
nextLayerId,
|
||||
binding.layerName(),
|
||||
binding.width(),
|
||||
binding.height(),
|
||||
gids,
|
||||
List.of()));
|
||||
nextLayerId += 1;
|
||||
}
|
||||
final TiledMapDocument document = new TiledMapDocument(
|
||||
"1.10",
|
||||
"1.12.1",
|
||||
"orthogonal",
|
||||
"right-down",
|
||||
enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::width).max().orElse(1),
|
||||
enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::height).max().orElse(1),
|
||||
context.tileSize(),
|
||||
context.tileSize(),
|
||||
nextLayerId,
|
||||
1,
|
||||
List.of(),
|
||||
context.tilesetRefs(),
|
||||
tileLayers,
|
||||
List.of());
|
||||
final Path outputPath = details.summary().assetRoot().resolve(sceneTilemap);
|
||||
final ArrayList<Path> writtenFiles = new ArrayList<>();
|
||||
if (disposition == SceneTmxExportDisposition.KEEP_BOTH && Files.isRegularFile(outputPath)) {
|
||||
final Path backupPath = nextSceneTmxBackupPath(outputPath);
|
||||
Files.copy(outputPath, backupPath);
|
||||
writtenFiles.add(backupPath);
|
||||
}
|
||||
codec.writeMap(outputPath, document);
|
||||
writtenFiles.add(outputPath);
|
||||
return new TiledAssetGenerationResult(true, "Exported TMX successfully.", enabledLayers, List.copyOf(writtenFiles));
|
||||
} catch (IOException | TiledUnsupportedFeatureException exception) {
|
||||
return new TiledAssetGenerationResult(false, "Unable to export TMX: " + exception.getMessage(), List.of(), List.of());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TiledAssetGenerationResult importSceneBankTmx(ProjectReference projectReference, AssetWorkspaceAssetDetails details) {
|
||||
if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import is available only for Scene Bank assets.", List.of(), List.of());
|
||||
}
|
||||
final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata();
|
||||
if (metadata == null) {
|
||||
return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of());
|
||||
}
|
||||
final String sceneTilemap = resolveSceneTilemap(metadata);
|
||||
if (sceneTilemap == null) {
|
||||
return new TiledAssetGenerationResult(false, "Scene TMX import requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of());
|
||||
}
|
||||
final Path inputPath = details.summary().assetRoot().resolve(sceneTilemap);
|
||||
if (!Files.isRegularFile(inputPath)) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import source is missing: " + sceneTilemap, List.of(), List.of());
|
||||
}
|
||||
try {
|
||||
final List<AssetStudioSceneLayerBinding> enabledLayers = metadata.layerBindings().stream()
|
||||
.filter(AssetStudioSceneLayerBinding::enabled)
|
||||
.toList();
|
||||
final ExportContext context = buildExportContext(projectReference, details, enabledLayers);
|
||||
final TiledMapDocument map = codec.readMap(inputPath);
|
||||
if (map.tileLayers().isEmpty()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: at least one tile layer is required.", List.of(), List.of());
|
||||
}
|
||||
if (map.tileLayers().size() > metadata.layerCount()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: more than four tile layers are not supported.", List.of(), List.of());
|
||||
}
|
||||
if (map.tilesets().size() != context.tilesetRefs().size()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset count.", List.of(), List.of());
|
||||
}
|
||||
for (int index = 0; index < context.tilesetRefs().size(); index += 1) {
|
||||
if (!context.tilesetRefs().get(index).source().equals(map.tilesets().get(index).source())) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset reference.", List.of(), List.of());
|
||||
}
|
||||
}
|
||||
|
||||
final List<AssetStudioSceneLayerBinding> updatedBindings = new ArrayList<>();
|
||||
for (int bindingIndex = 0; bindingIndex < metadata.layerBindings().size(); bindingIndex += 1) {
|
||||
final AssetStudioSceneLayerBinding binding = metadata.layerBindings().get(bindingIndex);
|
||||
if (bindingIndex >= map.tileLayers().size()) {
|
||||
updatedBindings.add(new AssetStudioSceneLayerBinding(
|
||||
false,
|
||||
binding.index(),
|
||||
binding.layerName(),
|
||||
binding.width(),
|
||||
binding.height(),
|
||||
binding.tilemap(),
|
||||
binding.tilesetAssetRoot(),
|
||||
binding.parallaxFactorX(),
|
||||
binding.parallaxFactorY(),
|
||||
binding.defaultPaletteId(),
|
||||
binding.tiles()));
|
||||
continue;
|
||||
}
|
||||
final TiledTileLayer importedLayer = map.tileLayers().get(bindingIndex);
|
||||
if (importedLayer.gids().size() != importedLayer.width() * importedLayer.height()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: layer tile data does not match layer dimensions.", List.of(), List.of());
|
||||
}
|
||||
final TilesetRef ref = resolveImportedLayerTilesetRef(importedLayer, binding, context);
|
||||
if (ref == null) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: layer uses an unexpected tileset.", List.of(), List.of());
|
||||
}
|
||||
final List<AssetStudioSceneTile> importedTiles = new ArrayList<>(importedLayer.width() * importedLayer.height());
|
||||
for (long rawGid : importedLayer.gids()) {
|
||||
if ((rawGid & FLIP_DIAGONAL_FLAG) != 0L) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: diagonal flips are not supported.", List.of(), List.of());
|
||||
}
|
||||
final boolean flipX = (rawGid & FLIP_HORIZONTAL_FLAG) != 0L;
|
||||
final boolean flipY = (rawGid & FLIP_VERTICAL_FLAG) != 0L;
|
||||
final long gid = rawGid & GID_MASK;
|
||||
if (gid == 0L) {
|
||||
importedTiles.add(AssetStudioSceneTile.inactive(binding.defaultPaletteId()));
|
||||
continue;
|
||||
}
|
||||
if (gid < ref.firstGid() || gid >= ref.firstGid() + ref.tileCount()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: tile uses an unexpected tileset.", List.of(), List.of());
|
||||
}
|
||||
final int tilesetTileId = (int) (gid - ref.firstGid());
|
||||
final Integer glyphId = ref.glyphIdByTileId().get(tilesetTileId);
|
||||
if (glyphId == null) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: tileset tile is missing glyph_id mapping.", List.of(), List.of());
|
||||
}
|
||||
importedTiles.add(new AssetStudioSceneTile(
|
||||
true,
|
||||
glyphId,
|
||||
binding.defaultPaletteId(),
|
||||
flipX,
|
||||
flipY));
|
||||
}
|
||||
updatedBindings.add(new AssetStudioSceneLayerBinding(
|
||||
true,
|
||||
binding.index(),
|
||||
binding.layerName(),
|
||||
importedLayer.width(),
|
||||
importedLayer.height(),
|
||||
binding.tilemap(),
|
||||
ref.assetRoot(),
|
||||
binding.parallaxFactorX(),
|
||||
binding.parallaxFactorY(),
|
||||
binding.defaultPaletteId(),
|
||||
importedTiles));
|
||||
}
|
||||
final int mapWidth = Math.max(map.width(), updatedBindings.stream()
|
||||
.filter(AssetStudioSceneLayerBinding::enabled)
|
||||
.mapToInt(AssetStudioSceneLayerBinding::width)
|
||||
.max()
|
||||
.orElse(metadata.mapWidth()));
|
||||
final int mapHeight = Math.max(map.height(), updatedBindings.stream()
|
||||
.filter(AssetStudioSceneLayerBinding::enabled)
|
||||
.mapToInt(AssetStudioSceneLayerBinding::height)
|
||||
.max()
|
||||
.orElse(metadata.mapHeight()));
|
||||
final var metadataWrite = metadataService.writeSceneBankMetadata(
|
||||
details.summary().assetRoot(), new AssetStudioSceneBankMetadata(
|
||||
mapWidth,
|
||||
mapHeight,
|
||||
metadata.layerCount(),
|
||||
updatedBindings,
|
||||
metadata.supportFile()));
|
||||
if (!metadataWrite.successful()) {
|
||||
return new TiledAssetGenerationResult(
|
||||
false,
|
||||
"Unable to import TMX: " + metadataWrite.message(),
|
||||
List.of(),
|
||||
List.of());
|
||||
}
|
||||
return new TiledAssetGenerationResult(true, "Imported TMX successfully.", updatedBindings, List.of(inputPath, metadata.supportFile()));
|
||||
} catch (IOException | TiledUnsupportedFeatureException exception) {
|
||||
return new TiledAssetGenerationResult(false, "Unable to import TMX: " + exception.getMessage(), List.of(), List.of());
|
||||
}
|
||||
}
|
||||
|
||||
private TilesetRef resolveImportedLayerTilesetRef(
|
||||
TiledTileLayer importedLayer,
|
||||
AssetStudioSceneLayerBinding binding,
|
||||
ExportContext context) {
|
||||
TilesetRef resolved = null;
|
||||
for (long rawGid : importedLayer.gids()) {
|
||||
final long gid = rawGid & GID_MASK;
|
||||
if (gid == 0L) {
|
||||
continue;
|
||||
}
|
||||
final TilesetRef ref = context.tilesetByAssetRoot().values().stream()
|
||||
.filter(candidate -> gid >= candidate.firstGid() && gid < candidate.firstGid() + candidate.tileCount())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (ref == null) {
|
||||
return null;
|
||||
}
|
||||
if (resolved != null && !resolved.assetRoot().equals(ref.assetRoot())) {
|
||||
return null;
|
||||
}
|
||||
resolved = ref;
|
||||
}
|
||||
if (resolved != null) {
|
||||
return resolved;
|
||||
}
|
||||
final String declaredAssetRoot = Objects.requireNonNullElse(binding.tilesetAssetRoot(), "").trim();
|
||||
if (!declaredAssetRoot.isBlank()) {
|
||||
return context.tilesetByAssetRoot().get(declaredAssetRoot);
|
||||
}
|
||||
if (context.tilesetByAssetRoot().size() == 1) {
|
||||
return context.tilesetByAssetRoot().values().iterator().next();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private ExportContext buildExportContext(
|
||||
ProjectReference projectReference,
|
||||
AssetWorkspaceAssetDetails details,
|
||||
List<AssetStudioSceneLayerBinding> enabledLayers) throws IOException {
|
||||
final LinkedHashMap<String, TilesetRef> refs = new LinkedHashMap<>();
|
||||
final List<TiledTilesetReference> tilesetRefs = new ArrayList<>();
|
||||
int tileSize = -1;
|
||||
int nextFirstGid = 1;
|
||||
for (AssetStudioSceneLayerBinding binding : enabledLayers) {
|
||||
if (refs.containsKey(binding.tilesetAssetRoot())) {
|
||||
continue;
|
||||
}
|
||||
final Path tilesetPath = projectReference.rootPath()
|
||||
.resolve("assets")
|
||||
.resolve(binding.tilesetAssetRoot())
|
||||
.resolve(GENERATED_TSX_FILE)
|
||||
.toAbsolutePath()
|
||||
.normalize();
|
||||
if (!Files.isRegularFile(tilesetPath)) {
|
||||
throw new IOException("Referenced TSX was not found for layer " + binding.index() + ": " + binding.tilesetAssetRoot());
|
||||
}
|
||||
final TiledTilesetDocument tileset = codec.readTileset(tilesetPath);
|
||||
if (tileSize < 0) {
|
||||
tileSize = tileset.tileWidth();
|
||||
} else if (tileSize != tileset.tileWidth() || tileSize != tileset.tileHeight()) {
|
||||
throw new IOException("All exported Scene Bank tilesets must share the same tile size.");
|
||||
}
|
||||
final String relativeTilesetPath = details.summary().assetRoot()
|
||||
.toAbsolutePath()
|
||||
.normalize()
|
||||
.relativize(tilesetPath)
|
||||
.toString()
|
||||
.replace('\\', '/');
|
||||
refs.put(binding.tilesetAssetRoot(), new TilesetRef(
|
||||
nextFirstGid,
|
||||
binding.tilesetAssetRoot(),
|
||||
relativeTilesetPath,
|
||||
tileset.tileCount(),
|
||||
glyphIdByTileId(tileset)));
|
||||
tilesetRefs.add(new TiledTilesetReference(nextFirstGid, relativeTilesetPath));
|
||||
nextFirstGid += tileset.tileCount();
|
||||
}
|
||||
if (tileSize <= 0) {
|
||||
throw new IOException("Unable to resolve tile size for Scene Bank export.");
|
||||
}
|
||||
return new ExportContext(tileSize, List.copyOf(tilesetRefs), Map.copyOf(refs));
|
||||
}
|
||||
|
||||
private String resolveSceneTilemap(AssetStudioSceneBankMetadata metadata) {
|
||||
final LinkedHashSet<String> tilemaps = new LinkedHashSet<>();
|
||||
for (AssetStudioSceneLayerBinding binding : metadata.layerBindings()) {
|
||||
final String tilemap = Objects.requireNonNullElse(binding.tilemap(), "").trim();
|
||||
if (!tilemap.isBlank()) {
|
||||
tilemaps.add(tilemap);
|
||||
}
|
||||
}
|
||||
return tilemaps.size() == 1 ? tilemaps.iterator().next() : null;
|
||||
}
|
||||
|
||||
private int parseTileSize(List<AssetConfigurationField> metadataFields) {
|
||||
final String value = metadataFields.stream()
|
||||
.filter(field -> "tile_size".equals(field.key()))
|
||||
.map(AssetConfigurationField::value)
|
||||
.findFirst()
|
||||
.orElse("16x16");
|
||||
final String normalized = value.trim().toLowerCase();
|
||||
if (normalized.startsWith("8x8")) {
|
||||
return 8;
|
||||
}
|
||||
if (normalized.startsWith("32x32")) {
|
||||
return 32;
|
||||
}
|
||||
return 16;
|
||||
}
|
||||
|
||||
private Path nextSceneTmxBackupPath(Path outputPath) {
|
||||
final String filename = outputPath.getFileName().toString();
|
||||
final int extensionOffset = filename.lastIndexOf('.');
|
||||
final String stem = extensionOffset >= 0 ? filename.substring(0, extensionOffset) : filename;
|
||||
final String extension = extensionOffset >= 0 ? filename.substring(extensionOffset) : "";
|
||||
final Path parent = outputPath.getParent();
|
||||
int sequence = 1;
|
||||
while (true) {
|
||||
final Path candidate = parent.resolve(stem + ".bkp-" + sequence + extension);
|
||||
if (!Files.exists(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
sequence += 1;
|
||||
}
|
||||
}
|
||||
|
||||
private Map<Integer, Integer> glyphIdByTileId(TiledTilesetDocument tileset) throws IOException {
|
||||
final LinkedHashMap<Integer, Integer> glyphs = new LinkedHashMap<>();
|
||||
for (TiledTilesetTile tile : tileset.tiles()) {
|
||||
final Integer glyphId = tile.properties().stream()
|
||||
.filter(property -> "glyph_id".equals(property.name()))
|
||||
.findFirst()
|
||||
.map(TiledProperty::value)
|
||||
.map(String::trim)
|
||||
.filter(value -> !value.isBlank())
|
||||
.map(Integer::parseInt)
|
||||
.orElse(null);
|
||||
if (glyphId == null || glyphId < 0) {
|
||||
throw new IOException("TSX tile " + tile.id() + " is missing a valid glyph_id property.");
|
||||
}
|
||||
glyphs.put(tile.id(), glyphId);
|
||||
}
|
||||
if (glyphs.size() != tileset.tileCount()) {
|
||||
throw new IOException("TSX tile count does not match declared tile_count.");
|
||||
}
|
||||
return Map.copyOf(glyphs);
|
||||
}
|
||||
|
||||
private record ExportContext(
|
||||
int tileSize,
|
||||
List<TiledTilesetReference> tilesetRefs,
|
||||
Map<String, TilesetRef> tilesetByAssetRoot) {
|
||||
}
|
||||
|
||||
private record TilesetRef(
|
||||
int firstGid,
|
||||
String assetRoot,
|
||||
String source,
|
||||
int tileCount,
|
||||
Map<Integer, Integer> glyphIdByTileId) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record TiledMapDocument(
|
||||
String version,
|
||||
String tiledVersion,
|
||||
String orientation,
|
||||
String renderOrder,
|
||||
int width,
|
||||
int height,
|
||||
int tileWidth,
|
||||
int tileHeight,
|
||||
int nextLayerId,
|
||||
int nextObjectId,
|
||||
List<TiledProperty> properties,
|
||||
List<TiledTilesetReference> tilesets,
|
||||
List<TiledTileLayer> tileLayers,
|
||||
List<TiledObjectLayer> objectLayers) {
|
||||
|
||||
public TiledMapDocument {
|
||||
version = Objects.requireNonNullElse(version, "1.10");
|
||||
tiledVersion = Objects.requireNonNullElse(tiledVersion, "1.12.1");
|
||||
orientation = Objects.requireNonNullElse(orientation, "orthogonal");
|
||||
renderOrder = Objects.requireNonNullElse(renderOrder, "right-down");
|
||||
properties = List.copyOf(Objects.requireNonNull(properties, "properties"));
|
||||
tilesets = List.copyOf(Objects.requireNonNull(tilesets, "tilesets"));
|
||||
tileLayers = List.copyOf(Objects.requireNonNull(tileLayers, "tileLayers"));
|
||||
objectLayers = List.copyOf(Objects.requireNonNull(objectLayers, "objectLayers"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record TiledObjectData(
|
||||
int id,
|
||||
String name,
|
||||
double x,
|
||||
double y,
|
||||
double width,
|
||||
double height,
|
||||
List<TiledPoint> polygonPoints,
|
||||
List<TiledProperty> properties) {
|
||||
|
||||
public TiledObjectData {
|
||||
name = Objects.requireNonNullElse(name, "").trim();
|
||||
polygonPoints = List.copyOf(Objects.requireNonNull(polygonPoints, "polygonPoints"));
|
||||
properties = List.copyOf(Objects.requireNonNull(properties, "properties"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record TiledObjectLayer(
|
||||
int id,
|
||||
String name,
|
||||
List<TiledObjectData> objects,
|
||||
List<TiledProperty> properties) {
|
||||
|
||||
public TiledObjectLayer {
|
||||
name = Objects.requireNonNullElse(name, "").trim();
|
||||
objects = List.copyOf(Objects.requireNonNull(objects, "objects"));
|
||||
properties = List.copyOf(Objects.requireNonNull(properties, "properties"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
public record TiledPoint(double x, double y) {
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public record TiledProperty(String name, String type, String value) {
|
||||
public TiledProperty {
|
||||
name = Objects.requireNonNull(name, "name").trim();
|
||||
type = Objects.requireNonNullElse(type, "string").trim();
|
||||
value = Objects.requireNonNullElse(value, "").trim();
|
||||
if (name.isBlank()) {
|
||||
throw new IllegalArgumentException("name must not be blank");
|
||||
}
|
||||
if (type.isBlank()) {
|
||||
type = "string";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record TiledTileLayer(
|
||||
int id,
|
||||
String name,
|
||||
int width,
|
||||
int height,
|
||||
List<Long> gids,
|
||||
List<TiledProperty> properties) {
|
||||
|
||||
public TiledTileLayer {
|
||||
name = Objects.requireNonNullElse(name, "").trim();
|
||||
gids = List.copyOf(Objects.requireNonNull(gids, "gids"));
|
||||
properties = List.copyOf(Objects.requireNonNull(properties, "properties"));
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record TiledTilesetDocument(
|
||||
String version,
|
||||
String tiledVersion,
|
||||
String name,
|
||||
int tileWidth,
|
||||
int tileHeight,
|
||||
int tileCount,
|
||||
int columns,
|
||||
List<TiledProperty> properties,
|
||||
List<TiledTilesetTile> tiles) {
|
||||
|
||||
public TiledTilesetDocument {
|
||||
version = Objects.requireNonNullElse(version, "1.10");
|
||||
tiledVersion = Objects.requireNonNullElse(tiledVersion, "1.12.1");
|
||||
name = Objects.requireNonNull(name, "name").trim();
|
||||
properties = List.copyOf(Objects.requireNonNull(properties, "properties"));
|
||||
tiles = List.copyOf(Objects.requireNonNull(tiles, "tiles"));
|
||||
if (name.isBlank()) {
|
||||
throw new IllegalArgumentException("name must not be blank");
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public record TiledTilesetReference(int firstGid, String source) {
|
||||
public TiledTilesetReference {
|
||||
source = Objects.requireNonNull(source, "source").trim();
|
||||
if (firstGid <= 0) {
|
||||
throw new IllegalArgumentException("firstGid must be positive");
|
||||
}
|
||||
if (source.isBlank()) {
|
||||
throw new IllegalArgumentException("source must not be blank");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record TiledTilesetTile(
|
||||
int id,
|
||||
String imageSource,
|
||||
int imageWidth,
|
||||
int imageHeight,
|
||||
List<TiledProperty> properties,
|
||||
TiledObjectLayer collisionLayer) {
|
||||
|
||||
public TiledTilesetTile {
|
||||
imageSource = Objects.requireNonNull(imageSource, "imageSource").trim();
|
||||
properties = List.copyOf(Objects.requireNonNull(properties, "properties"));
|
||||
if (imageSource.isBlank()) {
|
||||
throw new IllegalArgumentException("imageSource must not be blank");
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
public final class TiledUnsupportedFeatureException extends RuntimeException {
|
||||
public TiledUnsupportedFeatureException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.transform.OutputKeys;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class TiledXmlCodec {
|
||||
public TiledMapDocument readMap(Path path) throws IOException {
|
||||
final Document document = parseDocument(path);
|
||||
final Element root = document.getDocumentElement();
|
||||
if (!"map".equals(root.getTagName())) {
|
||||
throw new IOException("TMX root element must be <map>.");
|
||||
}
|
||||
if (!"0".equals(root.getAttribute("infinite")) && !root.getAttribute("infinite").isBlank()) {
|
||||
throw new TiledUnsupportedFeatureException("Infinite maps are not supported in wave 1.");
|
||||
}
|
||||
rejectMapUnsupportedChildren(root);
|
||||
return new TiledMapDocument(
|
||||
root.getAttribute("version"),
|
||||
root.getAttribute("tiledversion"),
|
||||
root.getAttribute("orientation"),
|
||||
root.getAttribute("renderorder"),
|
||||
intAttribute(root, "width", 0),
|
||||
intAttribute(root, "height", 0),
|
||||
intAttribute(root, "tilewidth", 0),
|
||||
intAttribute(root, "tileheight", 0),
|
||||
intAttribute(root, "nextlayerid", 0),
|
||||
intAttribute(root, "nextobjectid", 0),
|
||||
readProperties(child(root, "properties")),
|
||||
readTilesets(root),
|
||||
readTileLayers(root),
|
||||
readObjectLayers(root));
|
||||
}
|
||||
|
||||
public void writeMap(Path path, TiledMapDocument map) throws IOException {
|
||||
final Document document = newDocument();
|
||||
final Element root = document.createElement("map");
|
||||
document.appendChild(root);
|
||||
root.setAttribute("version", map.version());
|
||||
root.setAttribute("tiledversion", map.tiledVersion());
|
||||
root.setAttribute("orientation", map.orientation());
|
||||
root.setAttribute("renderorder", map.renderOrder());
|
||||
root.setAttribute("width", Integer.toString(map.width()));
|
||||
root.setAttribute("height", Integer.toString(map.height()));
|
||||
root.setAttribute("tilewidth", Integer.toString(map.tileWidth()));
|
||||
root.setAttribute("tileheight", Integer.toString(map.tileHeight()));
|
||||
root.setAttribute("infinite", "0");
|
||||
root.setAttribute("nextlayerid", Integer.toString(map.nextLayerId()));
|
||||
root.setAttribute("nextobjectid", Integer.toString(map.nextObjectId()));
|
||||
appendProperties(document, root, map.properties());
|
||||
for (TiledTilesetReference tileset : map.tilesets()) {
|
||||
final Element tilesetElement = document.createElement("tileset");
|
||||
tilesetElement.setAttribute("firstgid", Integer.toString(tileset.firstGid()));
|
||||
tilesetElement.setAttribute("source", tileset.source());
|
||||
root.appendChild(tilesetElement);
|
||||
}
|
||||
for (TiledTileLayer layer : map.tileLayers()) {
|
||||
final Element layerElement = document.createElement("layer");
|
||||
layerElement.setAttribute("id", Integer.toString(layer.id()));
|
||||
layerElement.setAttribute("name", layer.name());
|
||||
layerElement.setAttribute("width", Integer.toString(layer.width()));
|
||||
layerElement.setAttribute("height", Integer.toString(layer.height()));
|
||||
appendProperties(document, layerElement, layer.properties());
|
||||
final Element dataElement = document.createElement("data");
|
||||
dataElement.setAttribute("encoding", "csv");
|
||||
dataElement.setTextContent(csv(layer.gids(), layer.width()));
|
||||
layerElement.appendChild(dataElement);
|
||||
root.appendChild(layerElement);
|
||||
}
|
||||
for (TiledObjectLayer layer : map.objectLayers()) {
|
||||
root.appendChild(writeObjectLayer(document, layer, false));
|
||||
}
|
||||
writeDocument(path, document);
|
||||
}
|
||||
|
||||
public TiledTilesetDocument readTileset(Path path) throws IOException {
|
||||
final Document document = parseDocument(path);
|
||||
final Element root = document.getDocumentElement();
|
||||
if (!"tileset".equals(root.getTagName())) {
|
||||
throw new IOException("TSX root element must be <tileset>.");
|
||||
}
|
||||
rejectTilesetUnsupportedChildren(root);
|
||||
final List<TiledTilesetTile> tiles = new ArrayList<>();
|
||||
for (Element tileElement : children(root, "tile")) {
|
||||
if (child(tileElement, "animation") != null) {
|
||||
throw new TiledUnsupportedFeatureException("Tiled animations are not supported in wave 1.");
|
||||
}
|
||||
final Element imageElement = child(tileElement, "image");
|
||||
if (imageElement == null) {
|
||||
throw new IOException("TSX tile must contain an <image> element.");
|
||||
}
|
||||
tiles.add(new TiledTilesetTile(
|
||||
intAttribute(tileElement, "id", 0),
|
||||
imageElement.getAttribute("source"),
|
||||
intAttribute(imageElement, "width", 0),
|
||||
intAttribute(imageElement, "height", 0),
|
||||
readProperties(child(tileElement, "properties")),
|
||||
readEmbeddedObjectLayer(tileElement)));
|
||||
}
|
||||
tiles.sort(Comparator.comparingInt(TiledTilesetTile::id));
|
||||
return new TiledTilesetDocument(
|
||||
root.getAttribute("version"),
|
||||
root.getAttribute("tiledversion"),
|
||||
root.getAttribute("name"),
|
||||
intAttribute(root, "tilewidth", 0),
|
||||
intAttribute(root, "tileheight", 0),
|
||||
intAttribute(root, "tilecount", tiles.size()),
|
||||
intAttribute(root, "columns", 0),
|
||||
readProperties(child(root, "properties")),
|
||||
tiles);
|
||||
}
|
||||
|
||||
public void writeTileset(Path path, TiledTilesetDocument tileset) throws IOException {
|
||||
final Document document = newDocument();
|
||||
final Element root = document.createElement("tileset");
|
||||
document.appendChild(root);
|
||||
root.setAttribute("version", tileset.version());
|
||||
root.setAttribute("tiledversion", tileset.tiledVersion());
|
||||
root.setAttribute("name", tileset.name());
|
||||
root.setAttribute("tilewidth", Integer.toString(tileset.tileWidth()));
|
||||
root.setAttribute("tileheight", Integer.toString(tileset.tileHeight()));
|
||||
root.setAttribute("tilecount", Integer.toString(tileset.tileCount()));
|
||||
root.setAttribute("columns", Integer.toString(tileset.columns()));
|
||||
final Element grid = document.createElement("grid");
|
||||
grid.setAttribute("orientation", "orthogonal");
|
||||
grid.setAttribute("width", "1");
|
||||
grid.setAttribute("height", "1");
|
||||
root.appendChild(grid);
|
||||
appendProperties(document, root, tileset.properties());
|
||||
for (TiledTilesetTile tile : tileset.tiles()) {
|
||||
final Element tileElement = document.createElement("tile");
|
||||
tileElement.setAttribute("id", Integer.toString(tile.id()));
|
||||
appendProperties(document, tileElement, tile.properties());
|
||||
final Element imageElement = document.createElement("image");
|
||||
imageElement.setAttribute("source", tile.imageSource());
|
||||
imageElement.setAttribute("width", Integer.toString(tile.imageWidth()));
|
||||
imageElement.setAttribute("height", Integer.toString(tile.imageHeight()));
|
||||
tileElement.appendChild(imageElement);
|
||||
if (tile.collisionLayer() != null) {
|
||||
tileElement.appendChild(writeObjectLayer(document, tile.collisionLayer(), true));
|
||||
}
|
||||
root.appendChild(tileElement);
|
||||
}
|
||||
writeDocument(path, document);
|
||||
}
|
||||
|
||||
private Document parseDocument(Path path) throws IOException {
|
||||
try {
|
||||
final var factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(false);
|
||||
return factory.newDocumentBuilder().parse(path.toFile());
|
||||
} catch (TiledUnsupportedFeatureException exception) {
|
||||
throw exception;
|
||||
} catch (Exception exception) {
|
||||
throw new IOException("Unable to parse Tiled XML: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
private Document newDocument() throws IOException {
|
||||
try {
|
||||
return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
|
||||
} catch (Exception exception) {
|
||||
throw new IOException("Unable to create XML document: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
private void writeDocument(Path path, Document document) throws IOException {
|
||||
try {
|
||||
Files.createDirectories(Objects.requireNonNull(path, "path").toAbsolutePath().normalize().getParent());
|
||||
final var transformer = TransformerFactory.newInstance().newTransformer();
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
||||
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
|
||||
transformer.transform(new DOMSource(document), new StreamResult(path.toFile()));
|
||||
} catch (Exception exception) {
|
||||
throw new IOException("Unable to write Tiled XML: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
private void rejectMapUnsupportedChildren(Element root) {
|
||||
for (Element child : childElements(root)) {
|
||||
final String tag = child.getTagName();
|
||||
if ("imagelayer".equals(tag) || "group".equals(tag) || "template".equals(tag)) {
|
||||
throw new TiledUnsupportedFeatureException("Unsupported TMX feature in wave 1: " + tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void rejectTilesetUnsupportedChildren(Element root) {
|
||||
for (Element child : childElements(root)) {
|
||||
final String tag = child.getTagName();
|
||||
if ("wangsets".equals(tag) || "tileoffset".equals(tag) || "transformations".equals(tag)) {
|
||||
throw new TiledUnsupportedFeatureException("Unsupported TSX feature in wave 1: " + tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<TiledTilesetReference> readTilesets(Element root) {
|
||||
final List<TiledTilesetReference> tilesets = new ArrayList<>();
|
||||
for (Element tilesetElement : children(root, "tileset")) {
|
||||
if (!tilesetElement.hasAttribute("source")) {
|
||||
throw new TiledUnsupportedFeatureException("Inline tilesets are not supported in wave 1.");
|
||||
}
|
||||
tilesets.add(new TiledTilesetReference(
|
||||
intAttribute(tilesetElement, "firstgid", 1),
|
||||
tilesetElement.getAttribute("source")));
|
||||
}
|
||||
return List.copyOf(tilesets);
|
||||
}
|
||||
|
||||
private List<TiledTileLayer> readTileLayers(Element root) {
|
||||
final List<TiledTileLayer> layers = new ArrayList<>();
|
||||
for (Element layerElement : children(root, "layer")) {
|
||||
final Element dataElement = child(layerElement, "data");
|
||||
if (dataElement == null || !"csv".equalsIgnoreCase(dataElement.getAttribute("encoding"))) {
|
||||
throw new TiledUnsupportedFeatureException("Wave 1 supports only CSV tile layer encoding.");
|
||||
}
|
||||
layers.add(new TiledTileLayer(
|
||||
intAttribute(layerElement, "id", 0),
|
||||
layerElement.getAttribute("name"),
|
||||
intAttribute(layerElement, "width", 0),
|
||||
intAttribute(layerElement, "height", 0),
|
||||
parseCsvData(dataElement.getTextContent()),
|
||||
readProperties(child(layerElement, "properties"))));
|
||||
}
|
||||
return List.copyOf(layers);
|
||||
}
|
||||
|
||||
private List<TiledObjectLayer> readObjectLayers(Element root) {
|
||||
final List<TiledObjectLayer> layers = new ArrayList<>();
|
||||
for (Element objectGroup : children(root, "objectgroup")) {
|
||||
layers.add(readObjectLayer(objectGroup));
|
||||
}
|
||||
return List.copyOf(layers);
|
||||
}
|
||||
|
||||
private TiledObjectLayer readEmbeddedObjectLayer(Element parent) {
|
||||
final Element objectGroup = child(parent, "objectgroup");
|
||||
return objectGroup == null ? null : readObjectLayer(objectGroup);
|
||||
}
|
||||
|
||||
private TiledObjectLayer readObjectLayer(Element objectGroup) {
|
||||
final List<TiledObjectData> objects = new ArrayList<>();
|
||||
for (Element objectElement : children(objectGroup, "object")) {
|
||||
final Element polygon = child(objectElement, "polygon");
|
||||
if (child(objectElement, "ellipse") != null || child(objectElement, "point") != null || child(objectElement, "polyline") != null) {
|
||||
throw new TiledUnsupportedFeatureException("Unsupported object-layer geometry in wave 1.");
|
||||
}
|
||||
objects.add(new TiledObjectData(
|
||||
intAttribute(objectElement, "id", 0),
|
||||
objectElement.getAttribute("name"),
|
||||
doubleAttribute(objectElement, "x", 0.0d),
|
||||
doubleAttribute(objectElement, "y", 0.0d),
|
||||
doubleAttribute(objectElement, "width", 0.0d),
|
||||
doubleAttribute(objectElement, "height", 0.0d),
|
||||
polygon == null ? List.of() : parsePolygon(polygon.getAttribute("points")),
|
||||
readProperties(child(objectElement, "properties"))));
|
||||
}
|
||||
return new TiledObjectLayer(
|
||||
intAttribute(objectGroup, "id", 0),
|
||||
objectGroup.getAttribute("name"),
|
||||
objects,
|
||||
readProperties(child(objectGroup, "properties")));
|
||||
}
|
||||
|
||||
private Element writeObjectLayer(Document document, TiledObjectLayer layer, boolean embedded) {
|
||||
final Element objectGroup = document.createElement("objectgroup");
|
||||
if (layer.id() > 0) {
|
||||
objectGroup.setAttribute("id", Integer.toString(layer.id()));
|
||||
}
|
||||
if (!layer.name().isBlank()) {
|
||||
objectGroup.setAttribute("name", layer.name());
|
||||
}
|
||||
if (embedded) {
|
||||
objectGroup.setAttribute("draworder", "index");
|
||||
}
|
||||
appendProperties(document, objectGroup, layer.properties());
|
||||
for (TiledObjectData object : layer.objects()) {
|
||||
final Element objectElement = document.createElement("object");
|
||||
if (object.id() > 0) {
|
||||
objectElement.setAttribute("id", Integer.toString(object.id()));
|
||||
}
|
||||
if (!object.name().isBlank()) {
|
||||
objectElement.setAttribute("name", object.name());
|
||||
}
|
||||
objectElement.setAttribute("x", formatDecimal(object.x()));
|
||||
objectElement.setAttribute("y", formatDecimal(object.y()));
|
||||
if (object.width() > 0.0d) {
|
||||
objectElement.setAttribute("width", formatDecimal(object.width()));
|
||||
}
|
||||
if (object.height() > 0.0d) {
|
||||
objectElement.setAttribute("height", formatDecimal(object.height()));
|
||||
}
|
||||
appendProperties(document, objectElement, object.properties());
|
||||
if (!object.polygonPoints().isEmpty()) {
|
||||
final Element polygon = document.createElement("polygon");
|
||||
polygon.setAttribute("points", polygonPoints(object.polygonPoints()));
|
||||
objectElement.appendChild(polygon);
|
||||
}
|
||||
objectGroup.appendChild(objectElement);
|
||||
}
|
||||
return objectGroup;
|
||||
}
|
||||
|
||||
private void appendProperties(Document document, Element parent, List<TiledProperty> properties) {
|
||||
if (properties.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
final Element propertiesElement = document.createElement("properties");
|
||||
for (TiledProperty property : properties) {
|
||||
final Element propertyElement = document.createElement("property");
|
||||
propertyElement.setAttribute("name", property.name());
|
||||
if (!"string".equals(property.type())) {
|
||||
propertyElement.setAttribute("type", property.type());
|
||||
}
|
||||
propertyElement.setAttribute("value", property.value());
|
||||
propertiesElement.appendChild(propertyElement);
|
||||
}
|
||||
parent.appendChild(propertiesElement);
|
||||
}
|
||||
|
||||
private List<TiledProperty> readProperties(Element propertiesElement) {
|
||||
if (propertiesElement == null) {
|
||||
return List.of();
|
||||
}
|
||||
final List<TiledProperty> properties = new ArrayList<>();
|
||||
for (Element propertyElement : children(propertiesElement, "property")) {
|
||||
properties.add(new TiledProperty(
|
||||
propertyElement.getAttribute("name"),
|
||||
propertyElement.getAttribute("type"),
|
||||
propertyElement.hasAttribute("value")
|
||||
? propertyElement.getAttribute("value")
|
||||
: propertyElement.getTextContent()));
|
||||
}
|
||||
return List.copyOf(properties);
|
||||
}
|
||||
|
||||
private List<Long> parseCsvData(String text) {
|
||||
final List<Long> gids = new ArrayList<>();
|
||||
for (String token : Objects.requireNonNullElse(text, "").split(",")) {
|
||||
final String normalized = token.trim();
|
||||
if (normalized.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
gids.add(Long.parseLong(normalized));
|
||||
}
|
||||
return List.copyOf(gids);
|
||||
}
|
||||
|
||||
private List<TiledPoint> parsePolygon(String points) {
|
||||
final List<TiledPoint> parsed = new ArrayList<>();
|
||||
for (String segment : Objects.requireNonNullElse(points, "").trim().split(" ")) {
|
||||
final String normalized = segment.trim();
|
||||
if (normalized.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
final String[] pair = normalized.split(",");
|
||||
if (pair.length != 2) {
|
||||
throw new TiledUnsupportedFeatureException("Invalid polygon point format in Tiled XML.");
|
||||
}
|
||||
parsed.add(new TiledPoint(Double.parseDouble(pair[0]), Double.parseDouble(pair[1])));
|
||||
}
|
||||
return List.copyOf(parsed);
|
||||
}
|
||||
|
||||
private String csv(List<Long> gids, int width) {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
for (int index = 0; index < gids.size(); index += 1) {
|
||||
if (index > 0) {
|
||||
builder.append(index % Math.max(width, 1) == 0 ? ",\n" : ",");
|
||||
}
|
||||
builder.append(Long.toUnsignedString(gids.get(index)));
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private String polygonPoints(List<TiledPoint> points) {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
for (int index = 0; index < points.size(); index += 1) {
|
||||
if (index > 0) {
|
||||
builder.append(' ');
|
||||
}
|
||||
builder.append(formatDecimal(points.get(index).x()))
|
||||
.append(',')
|
||||
.append(formatDecimal(points.get(index).y()));
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private int intAttribute(Element element, String attribute, int fallback) {
|
||||
final String value = element.getAttribute(attribute);
|
||||
if (value == null || value.isBlank()) {
|
||||
return fallback;
|
||||
}
|
||||
return Integer.parseInt(value.trim());
|
||||
}
|
||||
|
||||
private double doubleAttribute(Element element, String attribute, double fallback) {
|
||||
final String value = element.getAttribute(attribute);
|
||||
if (value == null || value.isBlank()) {
|
||||
return fallback;
|
||||
}
|
||||
return Double.parseDouble(value.trim());
|
||||
}
|
||||
|
||||
private String formatDecimal(double value) {
|
||||
if (Math.rint(value) == value) {
|
||||
return Long.toString(Math.round(value));
|
||||
}
|
||||
return String.format(Locale.ROOT, "%.6f", value)
|
||||
.replaceAll("0+$", "")
|
||||
.replaceAll("\\.$", "");
|
||||
}
|
||||
|
||||
private Element child(Element parent, String name) {
|
||||
for (Element child : childElements(parent)) {
|
||||
if (name.equals(child.getTagName())) {
|
||||
return child;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private List<Element> children(Element parent, String name) {
|
||||
final List<Element> elements = new ArrayList<>();
|
||||
for (Element child : childElements(parent)) {
|
||||
if (name.equals(child.getTagName())) {
|
||||
elements.add(child);
|
||||
}
|
||||
}
|
||||
return List.copyOf(elements);
|
||||
}
|
||||
|
||||
private List<Element> childElements(Element parent) {
|
||||
final NodeList children = parent.getChildNodes();
|
||||
final List<Element> elements = new ArrayList<>();
|
||||
for (int index = 0; index < children.getLength(); index += 1) {
|
||||
final Node node = children.item(index);
|
||||
if (node instanceof Element element) {
|
||||
elements.add(element);
|
||||
}
|
||||
}
|
||||
return List.copyOf(elements);
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package p.studio.core.execution;
|
||||
|
||||
import p.studio.api.execution.ExecutionController;
|
||||
import p.studio.api.execution.ExecutionControllerFactory;
|
||||
import p.studio.api.execution.ExecutionSession;
|
||||
import p.studio.api.project.ProjectLocalStudioSetup;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.shipper.Shipper;
|
||||
import p.studio.core.runtime.RuntimeGateway;
|
||||
import p.studio.api.operation.OperationExecutor;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public final class DefaultExecutionControllerFactory implements ExecutionControllerFactory {
|
||||
private final Shipper shipper;
|
||||
private final RuntimeGateway runtime;
|
||||
private final OperationExecutor operations;
|
||||
|
||||
public DefaultExecutionControllerFactory(Shipper shipper, RuntimeGateway runtime, OperationExecutor operations) {
|
||||
this.shipper = Objects.requireNonNull(shipper, "shipper");
|
||||
this.runtime = Objects.requireNonNull(runtime, "runtime");
|
||||
this.operations = Objects.requireNonNull(operations, "operations");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ExecutionController create(ProjectReference project, ProjectLocalStudioSetup setup, ExecutionSession session) {
|
||||
return new PlayStopExecutionController(project, setup, session, shipper, runtime, operations);
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
package p.studio.core.execution;
|
||||
|
||||
import p.studio.api.execution.ExecutionLogEntry;
|
||||
import p.studio.api.execution.ExecutionLogSeverity;
|
||||
import p.studio.api.execution.ExecutionLogSource;
|
||||
import p.studio.api.execution.ExecutionSession;
|
||||
import p.studio.api.execution.ExecutionSnapshot;
|
||||
import p.studio.api.execution.ExecutionState;
|
||||
import p.studio.api.operation.OperationSubscription;
|
||||
import p.studio.api.shipper.ShipperLogEntry;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class DefaultExecutionSession implements ExecutionSession {
|
||||
private final Object monitor = new Object();
|
||||
private final ArrayList<ExecutionLogEntry> logs = new ArrayList<>();
|
||||
private final CopyOnWriteArrayList<Consumer<ExecutionSnapshot>> listeners = new CopyOnWriteArrayList<>();
|
||||
private ExecutionState state = ExecutionState.IDLE;
|
||||
private long nextSequence = 1L;
|
||||
|
||||
@Override
|
||||
public ExecutionSnapshot snapshot() {
|
||||
synchronized (monitor) {
|
||||
return snapshotLocked();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OperationSubscription subscribe(Consumer<ExecutionSnapshot> listener) {
|
||||
final Consumer<ExecutionSnapshot> safeListener = Objects.requireNonNull(listener, "listener");
|
||||
listeners.add(safeListener);
|
||||
safeListener.accept(snapshot());
|
||||
return () -> listeners.remove(safeListener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beginPreparationCycle() { publish(transitionLocked(ExecutionState.PREPARING, true)); }
|
||||
|
||||
@Override
|
||||
public void transitionToPrepareFailed() { publish(transitionLocked(ExecutionState.PREPARE_FAILED, false)); }
|
||||
|
||||
@Override
|
||||
public void transitionToConnecting() { publish(transitionLocked(ExecutionState.CONNECTING, false)); }
|
||||
|
||||
@Override
|
||||
public void transitionToRunning() { publish(transitionLocked(ExecutionState.RUNNING, false)); }
|
||||
|
||||
@Override
|
||||
public void transitionToRuntimeFailed() { publish(transitionLocked(ExecutionState.RUNTIME_FAILED, false)); }
|
||||
|
||||
@Override
|
||||
public void transitionToStopped() { publish(transitionLocked(ExecutionState.STOPPED, false)); }
|
||||
|
||||
@Override
|
||||
public void resetToIdle() { publish(transitionLocked(ExecutionState.IDLE, false)); }
|
||||
|
||||
@Override
|
||||
public void appendShipperLog(ShipperLogEntry entry) {
|
||||
final ShipperLogEntry safeEntry = Objects.requireNonNull(entry, "entry");
|
||||
appendLog(
|
||||
switch (safeEntry.source()) {
|
||||
case BUILD -> ExecutionLogSource.BUILD;
|
||||
case PACK_VALIDATION -> ExecutionLogSource.PACK_VALIDATION;
|
||||
case PACK -> ExecutionLogSource.PACK;
|
||||
case MANIFEST -> ExecutionLogSource.MANIFEST;
|
||||
},
|
||||
switch (safeEntry.severity()) {
|
||||
case INFO -> ExecutionLogSeverity.INFO;
|
||||
case ERROR -> ExecutionLogSeverity.ERROR;
|
||||
},
|
||||
safeEntry.message(),
|
||||
safeEntry.timestamp());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void appendRuntimeLog(ExecutionLogSeverity severity, String message) {
|
||||
appendRuntimeLog(severity, message, Instant.now());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void appendRuntimeLog(ExecutionLogSeverity severity, String message, Instant timestamp) {
|
||||
appendLog(ExecutionLogSource.RUNTIME, severity, message, timestamp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
final ExecutionState current = snapshot().state();
|
||||
if (current == ExecutionState.PREPARING
|
||||
|| current == ExecutionState.CONNECTING
|
||||
|| current == ExecutionState.RUNNING) {
|
||||
transitionToStopped();
|
||||
}
|
||||
listeners.clear();
|
||||
}
|
||||
|
||||
private void appendLog(ExecutionLogSource source, ExecutionLogSeverity severity, String message, Instant timestamp) {
|
||||
final ExecutionSnapshot snapshot;
|
||||
synchronized (monitor) {
|
||||
logs.add(new ExecutionLogEntry(nextSequence++, timestamp, source, severity, message));
|
||||
snapshot = snapshotLocked();
|
||||
}
|
||||
publish(snapshot);
|
||||
}
|
||||
|
||||
private ExecutionSnapshot transitionLocked(ExecutionState target, boolean clearLogs) {
|
||||
final ExecutionSnapshot snapshot;
|
||||
synchronized (monitor) {
|
||||
ensureTransitionAllowed(state, Objects.requireNonNull(target, "target"));
|
||||
state = target;
|
||||
if (clearLogs) {
|
||||
logs.clear();
|
||||
nextSequence = 1L;
|
||||
}
|
||||
snapshot = snapshotLocked();
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
private ExecutionSnapshot snapshotLocked() {
|
||||
return new ExecutionSnapshot(state, List.copyOf(logs));
|
||||
}
|
||||
|
||||
private static void ensureTransitionAllowed(ExecutionState current, ExecutionState next) {
|
||||
if (current == next) return;
|
||||
final boolean allowed = switch (current) {
|
||||
case IDLE -> next == ExecutionState.PREPARING;
|
||||
case PREPARING -> next == ExecutionState.PREPARE_FAILED
|
||||
|| next == ExecutionState.CONNECTING
|
||||
|| next == ExecutionState.STOPPED;
|
||||
case PREPARE_FAILED -> next == ExecutionState.IDLE || next == ExecutionState.PREPARING;
|
||||
case CONNECTING -> next == ExecutionState.RUNNING || next == ExecutionState.RUNTIME_FAILED || next == ExecutionState.STOPPED;
|
||||
case RUNNING -> next == ExecutionState.STOPPED || next == ExecutionState.RUNTIME_FAILED;
|
||||
case RUNTIME_FAILED, STOPPED -> next == ExecutionState.IDLE || next == ExecutionState.PREPARING;
|
||||
};
|
||||
if (!allowed) throw new IllegalStateException("illegal execution transition: " + current + " -> " + next);
|
||||
}
|
||||
|
||||
private void publish(ExecutionSnapshot snapshot) {
|
||||
listeners.forEach(listener -> listener.accept(snapshot));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package p.studio.core.execution;
|
||||
|
||||
final class ExecutionModule {
|
||||
private ExecutionModule() {
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
package p.studio.core.execution;
|
||||
|
||||
import p.studio.api.execution.ExecutionController;
|
||||
import p.studio.api.execution.ExecutionLogSeverity;
|
||||
import p.studio.api.execution.ExecutionSession;
|
||||
import p.studio.api.execution.ExecutionSnapshot;
|
||||
import p.studio.api.execution.ExecutionState;
|
||||
import p.studio.api.project.ProjectLocalStudioSetup;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.shipper.Shipper;
|
||||
import p.studio.api.shipper.ShipperPrepareResult;
|
||||
import p.studio.api.operation.OperationExecutor;
|
||||
import p.studio.api.operation.OperationHandle;
|
||||
import p.studio.core.runtime.RuntimeConnection;
|
||||
import p.studio.core.runtime.RuntimeGateway;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletionException;
|
||||
|
||||
final class PlayStopExecutionController implements ExecutionController {
|
||||
private final Object monitor = new Object();
|
||||
private final ProjectReference project;
|
||||
private final ProjectLocalStudioSetup setup;
|
||||
private final ExecutionSession session;
|
||||
private final Shipper shipper;
|
||||
private final RuntimeGateway runtime;
|
||||
private final OperationExecutor operations;
|
||||
private RuntimeConnection connection;
|
||||
private OperationHandle<ExecutionSnapshot> activeOperation;
|
||||
private OperationHandle<ShipperPrepareResult> preparationOperation;
|
||||
private boolean stopRequested;
|
||||
|
||||
PlayStopExecutionController(ProjectReference project, ProjectLocalStudioSetup setup,
|
||||
ExecutionSession session, Shipper shipper, RuntimeGateway runtime, OperationExecutor operations) {
|
||||
this.project = Objects.requireNonNull(project, "project");
|
||||
this.setup = Objects.requireNonNull(setup, "setup");
|
||||
this.session = Objects.requireNonNull(session, "session");
|
||||
this.shipper = Objects.requireNonNull(shipper, "shipper");
|
||||
this.runtime = Objects.requireNonNull(runtime, "runtime");
|
||||
this.operations = Objects.requireNonNull(operations, "operations");
|
||||
}
|
||||
|
||||
@Override
|
||||
public OperationHandle<ExecutionSnapshot> play() {
|
||||
synchronized (monitor) {
|
||||
if (isBusy(session.snapshot().state()) && activeOperation != null) {
|
||||
return activeOperation;
|
||||
}
|
||||
stopRequested = false;
|
||||
session.beginPreparationCycle();
|
||||
activeOperation = operations.submit("Run " + project.name(), this::runPlay);
|
||||
return activeOperation;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
final ExecutionState state = session.snapshot().state();
|
||||
final RuntimeConnection active;
|
||||
final OperationHandle<ShipperPrepareResult> preparation;
|
||||
final OperationHandle<ExecutionSnapshot> execution;
|
||||
synchronized (monitor) {
|
||||
stopRequested = true;
|
||||
active = connection;
|
||||
connection = null;
|
||||
preparation = preparationOperation;
|
||||
preparationOperation = null;
|
||||
execution = activeOperation;
|
||||
}
|
||||
if (execution != null) execution.cancel();
|
||||
if (preparation != null) preparation.cancel();
|
||||
if (active != null) active.close();
|
||||
if (state == ExecutionState.PREPARING || state == ExecutionState.CONNECTING || state == ExecutionState.RUNNING) {
|
||||
session.transitionToStopped();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
stop();
|
||||
}
|
||||
|
||||
private ExecutionSnapshot runPlay() {
|
||||
final OperationHandle<ShipperPrepareResult> preparation = shipper.prepare(project, session::appendShipperLog);
|
||||
synchronized (monitor) {
|
||||
preparationOperation = preparation;
|
||||
if (stopRequested) {
|
||||
preparation.cancel();
|
||||
return session.snapshot();
|
||||
}
|
||||
}
|
||||
final ShipperPrepareResult prepared;
|
||||
try {
|
||||
prepared = preparation.completion().toCompletableFuture().join();
|
||||
} catch (CancellationException failure) {
|
||||
return session.snapshot();
|
||||
} catch (CompletionException failure) {
|
||||
if (stopRequested) {
|
||||
return session.snapshot();
|
||||
}
|
||||
session.appendRuntimeLog(ExecutionLogSeverity.ERROR,
|
||||
"Preparation failed: " + message(failure.getCause() == null ? failure : failure.getCause()));
|
||||
session.transitionToPrepareFailed();
|
||||
return session.snapshot();
|
||||
} finally {
|
||||
synchronized (monitor) {
|
||||
if (preparationOperation == preparation) {
|
||||
preparationOperation = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!prepared.success()) {
|
||||
session.transitionToPrepareFailed();
|
||||
return session.snapshot();
|
||||
}
|
||||
synchronized (monitor) {
|
||||
if (stopRequested) return session.snapshot();
|
||||
}
|
||||
session.transitionToConnecting();
|
||||
try {
|
||||
final RuntimeConnection started = runtime.start(project, setup,
|
||||
log -> session.appendRuntimeLog(log.severity(), log.message(), log.timestamp()));
|
||||
synchronized (monitor) {
|
||||
if (stopRequested) {
|
||||
started.close();
|
||||
session.transitionToStopped();
|
||||
return session.snapshot();
|
||||
}
|
||||
connection = started;
|
||||
}
|
||||
session.transitionToRunning();
|
||||
started.completion().whenComplete((exitCode, failure) -> handleExit(started, exitCode, failure));
|
||||
} catch (Exception failure) {
|
||||
session.appendRuntimeLog(ExecutionLogSeverity.ERROR, "Runtime startup failed: " + message(failure));
|
||||
session.transitionToRuntimeFailed();
|
||||
}
|
||||
return session.snapshot();
|
||||
}
|
||||
|
||||
private void handleExit(RuntimeConnection started, Integer exitCode, Throwable failure) {
|
||||
final boolean stopped;
|
||||
synchronized (monitor) {
|
||||
if (connection == started) connection = null;
|
||||
stopped = stopRequested;
|
||||
}
|
||||
if (stopped || session.snapshot().state() == ExecutionState.STOPPED) return;
|
||||
if (failure == null && exitCode != null && exitCode == 0) {
|
||||
session.appendRuntimeLog(ExecutionLogSeverity.INFO, "Runtime process exited successfully.");
|
||||
session.transitionToStopped();
|
||||
} else {
|
||||
session.appendRuntimeLog(ExecutionLogSeverity.ERROR,
|
||||
failure == null ? "Runtime process exited with code " + exitCode + "." : "Runtime process failed: " + message(failure));
|
||||
session.transitionToRuntimeFailed();
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isBusy(ExecutionState state) {
|
||||
return state == ExecutionState.PREPARING || state == ExecutionState.CONNECTING || state == ExecutionState.RUNNING;
|
||||
}
|
||||
|
||||
private static String message(Throwable failure) {
|
||||
return failure.getMessage() == null || failure.getMessage().isBlank()
|
||||
? failure.getClass().getSimpleName() : failure.getMessage();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package p.studio.core.project;
|
||||
|
||||
import p.studio.api.project.KnownProjects;
|
||||
import p.studio.api.project.ProjectCatalog;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
public final class KnownProjectsService implements KnownProjects {
|
||||
private final Path storageFile;
|
||||
private final ProjectCatalog catalog;
|
||||
|
||||
public KnownProjectsService(Path storageFile, ProjectCatalog catalog) {
|
||||
this.storageFile = Objects.requireNonNull(storageFile, "storageFile").toAbsolutePath().normalize();
|
||||
this.catalog = Objects.requireNonNull(catalog, "catalog");
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ProjectReference> listKnownProjects() {
|
||||
final boolean exists = Files.isRegularFile(storageFile);
|
||||
final Set<Path> paths = readStoredPaths();
|
||||
if (!exists && paths.isEmpty()) {
|
||||
final List<ProjectReference> discovered = catalog.listProjects();
|
||||
writeStoredPaths(discovered.stream().map(ProjectReference::rootPath).toList());
|
||||
return discovered;
|
||||
}
|
||||
final List<ProjectReference> projects = new ArrayList<>();
|
||||
boolean mutated = false;
|
||||
for (Path path : paths) {
|
||||
if (!Files.isDirectory(path)) {
|
||||
mutated = true;
|
||||
} else {
|
||||
projects.add(catalog.openProject(path));
|
||||
}
|
||||
}
|
||||
projects.sort(Comparator.comparing(ProjectReference::name, String.CASE_INSENSITIVE_ORDER));
|
||||
if (mutated) {
|
||||
writeStoredPaths(projects.stream().map(ProjectReference::rootPath).toList());
|
||||
}
|
||||
return List.copyOf(projects);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remember(ProjectReference project) {
|
||||
final Set<Path> paths = readStoredPaths();
|
||||
paths.add(normalize(project.rootPath()));
|
||||
writeStoredPaths(paths);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forget(ProjectReference project) {
|
||||
final Set<Path> paths = readStoredPaths();
|
||||
paths.remove(normalize(project.rootPath()));
|
||||
writeStoredPaths(paths);
|
||||
}
|
||||
|
||||
private Set<Path> readStoredPaths() {
|
||||
if (!Files.isRegularFile(storageFile)) {
|
||||
return new LinkedHashSet<>();
|
||||
}
|
||||
try {
|
||||
final Set<Path> paths = new LinkedHashSet<>();
|
||||
for (String line : Files.readAllLines(storageFile, StandardCharsets.UTF_8)) {
|
||||
if (!line.isBlank()) {
|
||||
paths.add(normalize(Path.of(line.trim())));
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private void writeStoredPaths(Iterable<Path> paths) {
|
||||
try {
|
||||
Files.createDirectories(storageFile.getParent());
|
||||
final List<String> lines = new ArrayList<>();
|
||||
paths.forEach(path -> lines.add(normalize(path).toString()));
|
||||
Files.write(storageFile, lines, StandardCharsets.UTF_8);
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private Path normalize(Path path) {
|
||||
return Objects.requireNonNull(path, "path").toAbsolutePath().normalize();
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package p.studio.core.project;
|
||||
|
||||
import p.packer.PackerWorkspaceService;
|
||||
import p.packer.messages.InitWorkspaceRequest;
|
||||
import p.packer.messages.PackerProjectContext;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.project.ProjectWorkspaceInitializer;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public final class PackerProjectWorkspaceInitializer implements ProjectWorkspaceInitializer {
|
||||
private final PackerWorkspaceService packer;
|
||||
|
||||
public PackerProjectWorkspaceInitializer(PackerWorkspaceService packer) {
|
||||
this.packer = Objects.requireNonNull(packer, "packer");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize(ProjectReference project) {
|
||||
final ProjectReference safeProject = Objects.requireNonNull(project, "project");
|
||||
packer.initWorkspace(new InitWorkspaceRequest(new PackerProjectContext(
|
||||
safeProject.name(), safeProject.rootPath())));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package p.studio.core.project;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.project.ProjectCatalog;
|
||||
import p.studio.api.project.ProjectCreationRequest;
|
||||
import p.studio.api.project.ProjectLocalStudioSetup;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.project.ProjectTarget;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public final class ProjectCatalogService implements ProjectCatalog {
|
||||
private static final String MANIFEST_FILE_NAME = "prometeu.json";
|
||||
private final Path projectsRoot;
|
||||
private final ObjectMapper mapper;
|
||||
private final ProjectLocalStudioSetupStore setupStore;
|
||||
|
||||
public ProjectCatalogService(Path projectsRoot, ObjectMapper mapper, ProjectLocalStudioSetupStore setupStore) {
|
||||
this.projectsRoot = Objects.requireNonNull(projectsRoot, "projectsRoot").toAbsolutePath().normalize();
|
||||
this.mapper = Objects.requireNonNull(mapper, "mapper").copy()
|
||||
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||
this.setupStore = Objects.requireNonNull(setupStore, "setupStore");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Path projectsRoot() {
|
||||
return projectsRoot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ProjectReference> listProjects() {
|
||||
if (!Files.isDirectory(projectsRoot)) {
|
||||
return List.of();
|
||||
}
|
||||
try (Stream<Path> children = Files.list(projectsRoot)) {
|
||||
return children.filter(this::isValidProjectRoot)
|
||||
.map(this::buildReference)
|
||||
.sorted(Comparator.comparing(ProjectReference::name, String.CASE_INSENSITIVE_ORDER))
|
||||
.toList();
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProjectReference openProject(Path projectPath) {
|
||||
return openProjectManifest(manifestPath(Objects.requireNonNull(projectPath, "projectPath").toAbsolutePath().normalize()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProjectReference openProjectManifest(Path manifestPath) {
|
||||
final Path normalized = Objects.requireNonNull(manifestPath, "manifestPath").toAbsolutePath().normalize();
|
||||
if (!normalized.getFileName().toString().equals(MANIFEST_FILE_NAME) || !Files.isRegularFile(normalized)) {
|
||||
throw new IllegalArgumentException("project manifest not found: expected " + normalized);
|
||||
}
|
||||
final Path root = normalized.getParent();
|
||||
if (root == null || !Files.isDirectory(root)) {
|
||||
throw new IllegalArgumentException("project root does not exist: " + normalized);
|
||||
}
|
||||
return buildReference(root);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProjectReference createProject(ProjectCreationRequest request) {
|
||||
Objects.requireNonNull(request, "request");
|
||||
final String displayName = requireText(request.projectName(), "project name");
|
||||
final String directoryName = sanitizeProjectName(displayName);
|
||||
final String languageId = requireText(request.languageId(), "project language");
|
||||
if (request.stdlib() <= 0 || request.indentationWidth() <= 0 || request.target() == null) {
|
||||
throw new IllegalArgumentException("invalid project configuration");
|
||||
}
|
||||
final Path sourceRoot = normalizeSourceRoot(request.sourceRoot());
|
||||
final Path parent = Objects.requireNonNull(request.parentLocation(), "parentLocation").toAbsolutePath().normalize();
|
||||
if (Files.exists(parent) && !Files.isDirectory(parent)) {
|
||||
throw new IllegalArgumentException("project location is not a directory: " + parent);
|
||||
}
|
||||
final Path root = parent.resolve(directoryName).normalize();
|
||||
if (Files.exists(root)) {
|
||||
throw new IllegalArgumentException("project already exists: " + directoryName);
|
||||
}
|
||||
final ProjectReference project = new ProjectReference(displayName, "1.0.0", languageId,
|
||||
request.stdlib(), request.target(), root);
|
||||
try {
|
||||
Files.createDirectories(ProjectStudioPaths.studioRoot(project));
|
||||
Files.createDirectories(root.resolve(".workspace"));
|
||||
Files.createDirectories(root.resolve(sourceRoot));
|
||||
Files.createDirectories(root.resolve("assets"));
|
||||
Files.createDirectories(root.resolve("build"));
|
||||
Files.createDirectories(root.resolve("cartridge"));
|
||||
Files.writeString(manifestPath(root), defaultManifest(project));
|
||||
Files.writeString(root.resolve(".gitignore"), defaultGitIgnore());
|
||||
setupStore.save(project, new ProjectLocalStudioSetup(request.runtimePath(),
|
||||
new ProjectLocalStudioSetup.EditorIndentationSetup("spaces", request.indentationWidth())));
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
return openProject(root);
|
||||
}
|
||||
|
||||
private ProjectReference buildReference(Path root) {
|
||||
final Path normalized = root.toAbsolutePath().normalize();
|
||||
final ProjectManifestSummary manifest;
|
||||
try {
|
||||
manifest = mapper.readValue(manifestPath(normalized).toFile(), ProjectManifestSummary.class);
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
final String name = requireText(manifest.name(), "manifest name");
|
||||
final String version = requireText(manifest.version(), "manifest version");
|
||||
final String language = requireText(manifest.language(), "manifest language");
|
||||
final int stdlib;
|
||||
try {
|
||||
stdlib = Integer.parseInt(requireText(manifest.stdlib(), "manifest stdlib"));
|
||||
} catch (NumberFormatException exception) {
|
||||
throw new IllegalArgumentException("project manifest invalid stdlib: " + manifestPath(normalized), exception);
|
||||
}
|
||||
final ProjectTarget target;
|
||||
try {
|
||||
target = ProjectTarget.valueOf(requireText(manifest.target(), "manifest target"));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new IllegalArgumentException("project manifest invalid target: " + manifestPath(normalized), exception);
|
||||
}
|
||||
return new ProjectReference(name, version, language, stdlib, target, normalized);
|
||||
}
|
||||
|
||||
private boolean isValidProjectRoot(Path path) {
|
||||
return Files.isDirectory(path) && Files.isRegularFile(manifestPath(path));
|
||||
}
|
||||
|
||||
private Path manifestPath(Path root) {
|
||||
return root.resolve(MANIFEST_FILE_NAME);
|
||||
}
|
||||
|
||||
private Path normalizeSourceRoot(String value) {
|
||||
final Path path = Path.of(requireText(value, "project source root")).normalize();
|
||||
if (path.isAbsolute() || path.startsWith("..")) {
|
||||
throw new IllegalArgumentException("project source root must be a relative project path");
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private String defaultManifest(ProjectReference project) {
|
||||
return """
|
||||
{
|
||||
"name": "%s",
|
||||
"version": "%s",
|
||||
"language": "%s",
|
||||
"stdlib": "%d",
|
||||
"target": "%s",
|
||||
"dependencies": []
|
||||
}
|
||||
""".formatted(project.name(), project.version(), project.languageId(),
|
||||
project.stdlibVersion(), project.target().exportReferenceName());
|
||||
}
|
||||
|
||||
private String defaultGitIgnore() {
|
||||
return ".studio/\n.workspace/\nbuild/\n\n.DS_Store\n.AppleDouble\n.LSOverride\nThumbs.db\nDesktop.ini\n.directory\n*~\n";
|
||||
}
|
||||
|
||||
private String sanitizeProjectName(String value) {
|
||||
final String result = requireText(value, "project name").toLowerCase(Locale.ROOT)
|
||||
.replaceAll("[^a-z0-9]+", "-").replaceAll("^-+", "").replaceAll("-+$", "");
|
||||
if (result.isEmpty()) {
|
||||
throw new IllegalArgumentException("project name must contain a letter or number");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String requireText(String value, String label) {
|
||||
final String result = Objects.requireNonNull(value, label).trim();
|
||||
if (result.isEmpty()) {
|
||||
throw new IllegalArgumentException(label + " must not be blank");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private record ProjectManifestSummary(String name, String version, String language, String stdlib, String target) {
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package p.studio.core.project;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.project.ProjectLocalStudioSetup;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class ProjectLocalStudioSetupStore {
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public ProjectLocalStudioSetupStore(ObjectMapper mapper) {
|
||||
this.mapper = Objects.requireNonNull(mapper, "mapper").copy()
|
||||
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||
}
|
||||
|
||||
public ProjectLocalStudioSetup load(ProjectReference project) {
|
||||
final Path path = ProjectStudioPaths.setupPath(project);
|
||||
if (!Files.isRegularFile(path)) {
|
||||
return ProjectLocalStudioSetup.defaults();
|
||||
}
|
||||
try {
|
||||
final ProjectLocalStudioSetup loaded = mapper.readValue(path.toFile(), ProjectLocalStudioSetup.class);
|
||||
return loaded == null ? ProjectLocalStudioSetup.defaults() : loaded;
|
||||
} catch (IOException | RuntimeException ignored) {
|
||||
return ProjectLocalStudioSetup.defaults();
|
||||
}
|
||||
}
|
||||
|
||||
public void save(ProjectReference project, ProjectLocalStudioSetup setup) {
|
||||
final Path path = ProjectStudioPaths.setupPath(project);
|
||||
try {
|
||||
Files.createDirectories(path.getParent());
|
||||
mapper.writerWithDefaultPrettyPrinter().writeValue(path.toFile(), Objects.requireNonNull(setup, "setup"));
|
||||
} catch (IOException exception) {
|
||||
throw new IllegalStateException("unable to save project setup: " + path, exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package p.studio.core.project;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import p.studio.api.project.ProjectLocalStudioState;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class ProjectLocalStudioStateStore {
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public ProjectLocalStudioStateStore(ObjectMapper mapper) {
|
||||
this.mapper = Objects.requireNonNull(mapper, "mapper").copy()
|
||||
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
|
||||
.enable(SerializationFeature.INDENT_OUTPUT);
|
||||
}
|
||||
|
||||
public ProjectLocalStudioState load(ProjectReference project) {
|
||||
final Path path = ProjectStudioPaths.statePath(project);
|
||||
if (!Files.isRegularFile(path)) {
|
||||
return ProjectLocalStudioState.defaults();
|
||||
}
|
||||
try {
|
||||
final ProjectLocalStudioState loaded = mapper.readValue(path.toFile(), ProjectLocalStudioState.class);
|
||||
return loaded == null || loaded.version() != ProjectLocalStudioState.CURRENT_VERSION
|
||||
? ProjectLocalStudioState.defaults()
|
||||
: loaded;
|
||||
} catch (IOException | RuntimeException ignored) {
|
||||
return ProjectLocalStudioState.defaults();
|
||||
}
|
||||
}
|
||||
|
||||
public void save(ProjectReference project, ProjectLocalStudioState state) {
|
||||
final Path path = ProjectStudioPaths.statePath(project);
|
||||
try {
|
||||
Files.createDirectories(path.getParent());
|
||||
mapper.writeValue(path.toFile(), Objects.requireNonNull(state, "state"));
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package p.studio.core.project;
|
||||
|
||||
final class ProjectModule {
|
||||
private ProjectModule() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package p.studio.core.project;
|
||||
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class ProjectStudioPaths {
|
||||
private ProjectStudioPaths() {
|
||||
}
|
||||
|
||||
public static Path studioRoot(ProjectReference project) {
|
||||
return Objects.requireNonNull(project, "project").rootPath().resolve(".studio").toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
public static Path activitiesPath(ProjectReference project) {
|
||||
return studioRoot(project).resolve("activities.json");
|
||||
}
|
||||
|
||||
public static Path setupPath(ProjectReference project) {
|
||||
return studioRoot(project).resolve("setup.json");
|
||||
}
|
||||
|
||||
public static Path statePath(ProjectReference project) {
|
||||
return studioRoot(project).resolve("state.json");
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package p.studio.core.project.preferences;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.preferences.ProjectActivityHistoryStore;
|
||||
import p.studio.api.preferences.ProjectActivityRecord;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class JsonProjectActivityHistoryStore implements ProjectActivityHistoryStore {
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public JsonProjectActivityHistoryStore(ObjectMapper mapper) {
|
||||
this.mapper = Objects.requireNonNull(mapper, "mapper").copy();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ProjectActivityRecord> load(ProjectReference projectReference) {
|
||||
final Path path = activitiesPath(projectReference);
|
||||
if (!Files.isRegularFile(path)) {
|
||||
return List.of();
|
||||
}
|
||||
try {
|
||||
final ProjectActivityRecord[] entries = mapper.readValue(path.toFile(), ProjectActivityRecord[].class);
|
||||
return entries == null ? List.of() : List.copyOf(Arrays.asList(entries));
|
||||
} catch (IOException | RuntimeException ignored) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(ProjectReference projectReference, List<ProjectActivityRecord> entries) {
|
||||
final Path path = activitiesPath(projectReference);
|
||||
try {
|
||||
Files.createDirectories(path.getParent());
|
||||
mapper.writerWithDefaultPrettyPrinter().writeValue(path.toFile(), List.copyOf(entries));
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private Path activitiesPath(ProjectReference projectReference) {
|
||||
return Objects.requireNonNull(projectReference, "projectReference")
|
||||
.rootPath()
|
||||
.resolve(".studio")
|
||||
.resolve("activities.json")
|
||||
.toAbsolutePath()
|
||||
.normalize();
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package p.studio.core.project.preferences;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.preferences.WindowGeometry;
|
||||
import p.studio.api.preferences.WindowStateStore;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
public final class JsonWindowStateStore implements WindowStateStore {
|
||||
private final Path storageFile;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public JsonWindowStateStore(Path storageFile, ObjectMapper mapper) {
|
||||
this.storageFile = Objects.requireNonNull(storageFile, "storageFile").toAbsolutePath().normalize();
|
||||
this.mapper = Objects.requireNonNull(mapper, "mapper").copy();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<WindowGeometry> load(ProjectReference projectReference) {
|
||||
return Optional.ofNullable(loadFile().projects().get(projectKey(projectReference)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(ProjectReference projectReference, WindowGeometry geometry) {
|
||||
final WindowStateFile current = loadFile();
|
||||
current.projects().put(projectKey(projectReference), Objects.requireNonNull(geometry, "geometry"));
|
||||
try {
|
||||
Files.createDirectories(storageFile.getParent());
|
||||
mapper.writerWithDefaultPrettyPrinter().writeValue(storageFile.toFile(), current.normalize());
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private WindowStateFile loadFile() {
|
||||
if (!Files.isRegularFile(storageFile)) {
|
||||
return WindowStateFile.empty();
|
||||
}
|
||||
try {
|
||||
final WindowStateFile loaded = mapper.readValue(storageFile.toFile(), WindowStateFile.class);
|
||||
return loaded == null ? WindowStateFile.empty() : loaded.normalize();
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String projectKey(ProjectReference projectReference) {
|
||||
return Objects.requireNonNull(projectReference, "projectReference").rootPath().toAbsolutePath().normalize().toString();
|
||||
}
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
private record WindowStateFile(Object launcher, Map<String, WindowGeometry> projects) {
|
||||
private static WindowStateFile empty() {
|
||||
return new WindowStateFile(null, new LinkedHashMap<>());
|
||||
}
|
||||
|
||||
private WindowStateFile normalize() {
|
||||
return new WindowStateFile(launcher, projects == null ? new LinkedHashMap<>() : new LinkedHashMap<>(projects));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package p.studio.core.runtime;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public interface RuntimeConnection extends AutoCloseable {
|
||||
CompletableFuture<Integer> completion();
|
||||
|
||||
@Override
|
||||
void close();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package p.studio.core.runtime;
|
||||
|
||||
import p.studio.api.project.ProjectLocalStudioSetup;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.runtime.RuntimeLogEntry;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface RuntimeGateway {
|
||||
RuntimeConnection start(ProjectReference project, ProjectLocalStudioSetup setup,
|
||||
Consumer<RuntimeLogEntry> logs) throws Exception;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package p.studio.core.runtime;
|
||||
|
||||
final class RuntimeModule {
|
||||
private RuntimeModule() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package p.studio.core.session;
|
||||
|
||||
import p.studio.api.execution.ExecutionSession;
|
||||
import p.studio.api.project.ProjectLocalStudioSetup;
|
||||
import p.studio.api.project.ProjectLocalStudioState;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.session.ProjectSession;
|
||||
import p.studio.core.project.ProjectLocalStudioStateStore;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public final class DefaultProjectSession implements ProjectSession {
|
||||
private final ProjectReference project;
|
||||
private final ProjectLocalStudioStateStore stateStore;
|
||||
private final ProjectLocalStudioSetup setup;
|
||||
private final ExecutionSession execution;
|
||||
private final LspLifecyclePort lsp;
|
||||
private ProjectLocalStudioState state;
|
||||
private boolean closed;
|
||||
|
||||
DefaultProjectSession(ProjectReference project, ProjectLocalStudioStateStore stateStore,
|
||||
ProjectLocalStudioSetup setup, ExecutionSession execution, LspLifecyclePort lsp,
|
||||
ProjectLocalStudioState state) {
|
||||
this.project = Objects.requireNonNull(project, "project");
|
||||
this.stateStore = Objects.requireNonNull(stateStore, "stateStore");
|
||||
this.setup = Objects.requireNonNull(setup, "setup");
|
||||
this.execution = Objects.requireNonNull(execution, "execution");
|
||||
this.lsp = Objects.requireNonNull(lsp, "lsp");
|
||||
this.state = Objects.requireNonNull(state, "state");
|
||||
}
|
||||
|
||||
@Override public ProjectReference projectReference() { return project; }
|
||||
@Override public ProjectLocalStudioState projectLocalStudioState() { return state; }
|
||||
@Override public ProjectLocalStudioSetup projectLocalStudioSetup() { return setup; }
|
||||
@Override public ExecutionSession executionSession() { return execution; }
|
||||
@Override public void replaceProjectLocalStudioState(ProjectLocalStudioState next) { state = Objects.requireNonNull(next, "state"); }
|
||||
@Override public void saveProjectLocalStudioState() { stateStore.save(project, state); }
|
||||
|
||||
@Override
|
||||
public synchronized void close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
RuntimeException failure = attempt(this::saveProjectLocalStudioState, null);
|
||||
failure = attempt(execution::close, failure);
|
||||
failure = attempt(() -> lsp.shutdown(project), failure);
|
||||
if (failure != null) throw failure;
|
||||
}
|
||||
|
||||
private static RuntimeException attempt(Runnable action, RuntimeException prior) {
|
||||
try {
|
||||
action.run();
|
||||
return prior;
|
||||
} catch (RuntimeException failure) {
|
||||
if (prior == null) return failure;
|
||||
prior.addSuppressed(failure);
|
||||
return prior;
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package p.studio.core.session;
|
||||
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.session.ProjectSession;
|
||||
import p.studio.api.session.ProjectSessionFactory;
|
||||
import p.studio.core.execution.DefaultExecutionSession;
|
||||
import p.studio.core.project.ProjectLocalStudioSetupStore;
|
||||
import p.studio.core.project.ProjectLocalStudioStateStore;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public final class DefaultProjectSessionFactory implements ProjectSessionFactory {
|
||||
private final ProjectLocalStudioStateStore stateStore;
|
||||
private final ProjectLocalStudioSetupStore setupStore;
|
||||
private final LspLifecyclePort lsp;
|
||||
|
||||
public DefaultProjectSessionFactory(ProjectLocalStudioStateStore stateStore,
|
||||
ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp) {
|
||||
this.stateStore = Objects.requireNonNull(stateStore, "stateStore");
|
||||
this.setupStore = Objects.requireNonNull(setupStore, "setupStore");
|
||||
this.lsp = Objects.requireNonNull(lsp, "lsp");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProjectSession open(ProjectReference projectReference) {
|
||||
final ProjectReference project = Objects.requireNonNull(projectReference, "projectReference");
|
||||
final var setup = setupStore.load(project);
|
||||
final var state = stateStore.load(project);
|
||||
lsp.boot(project);
|
||||
return new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lsp, state);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package p.studio.core.session;
|
||||
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
public interface LspLifecyclePort {
|
||||
void boot(ProjectReference project);
|
||||
|
||||
void shutdown(ProjectReference project);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package p.studio.core.session;
|
||||
|
||||
final class SessionModule {
|
||||
private SessionModule() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package p.studio.core.shipper;
|
||||
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface CompilerBuildGateway {
|
||||
CompilerBuildOutput compile(ProjectReference project, Consumer<String> logSink);
|
||||
|
||||
record CompilerBuildOutput(Path bytecodeArtifact, List<String> requiredCapabilities) {
|
||||
public CompilerBuildOutput {
|
||||
bytecodeArtifact = bytecodeArtifact == null ? null : bytecodeArtifact.toAbsolutePath().normalize();
|
||||
requiredCapabilities = List.copyOf(requiredCapabilities);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package p.studio.core.shipper;
|
||||
|
||||
final class ShipperModule {
|
||||
private ShipperModule() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package p.studio.core.shipper;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import p.packer.PackerWorkspaceService;
|
||||
import p.packer.messages.PackWorkspaceRequest;
|
||||
import p.packer.messages.PackerOperationStatus;
|
||||
import p.packer.messages.PackerProjectContext;
|
||||
import p.packer.messages.ValidatePackWorkspaceRequest;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.shipper.Shipper;
|
||||
import p.studio.api.shipper.ShipperLogEntry;
|
||||
import p.studio.api.shipper.ShipperLogSource;
|
||||
import p.studio.api.shipper.ShipperPrepareResult;
|
||||
import p.studio.api.shipper.ShipperPreparationStatus;
|
||||
import p.studio.api.operation.OperationExecutor;
|
||||
import p.studio.api.operation.OperationHandle;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class StudioShipperService implements Shipper {
|
||||
private final CompilerBuildGateway compiler;
|
||||
private final PackerWorkspaceService packer;
|
||||
private final ObjectMapper mapper;
|
||||
private final OperationExecutor operations;
|
||||
|
||||
public StudioShipperService(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper,
|
||||
OperationExecutor operations) {
|
||||
this.compiler = Objects.requireNonNull(compiler, "compiler");
|
||||
this.packer = Objects.requireNonNull(packer, "packer");
|
||||
this.mapper = Objects.requireNonNull(mapper, "mapper");
|
||||
this.operations = Objects.requireNonNull(operations, "operations");
|
||||
}
|
||||
|
||||
@Override
|
||||
public OperationHandle<ShipperPrepareResult> prepare(ProjectReference project, Consumer<ShipperLogEntry> sink) {
|
||||
Objects.requireNonNull(project, "project");
|
||||
Objects.requireNonNull(sink, "sink");
|
||||
return operations.submit("Build and pack " + project.name(), () -> prepareNow(project, sink));
|
||||
}
|
||||
|
||||
private ShipperPrepareResult prepareNow(ProjectReference project, Consumer<ShipperLogEntry> sink) {
|
||||
Objects.requireNonNull(project, "project");
|
||||
Objects.requireNonNull(sink, "sink");
|
||||
final List<ShipperLogEntry> logs = new ArrayList<>();
|
||||
final List<String> diagnostics = new ArrayList<>();
|
||||
try {
|
||||
final CompilerBuildGateway.CompilerBuildOutput build = compiler.compile(project,
|
||||
message -> emit(logs, sink, ShipperLogEntry.info(ShipperLogSource.BUILD, normalize(message))));
|
||||
if (build.bytecodeArtifact() != null) {
|
||||
emit(logs, sink, ShipperLogEntry.info(ShipperLogSource.BUILD,
|
||||
"Prepared program bytecode at " + build.bytecodeArtifact()));
|
||||
}
|
||||
final PackerProjectContext context = new PackerProjectContext(project.name(), project.rootPath());
|
||||
final var validation = packer.validatePackWorkspace(new ValidatePackWorkspaceRequest(context));
|
||||
emit(logs, sink, logFor(validation.status(), ShipperLogSource.PACK_VALIDATION, validation.summary()));
|
||||
validation.assets().forEach(asset -> asset.diagnostics().forEach(value -> diagnostics.add(value.message())));
|
||||
if (!validation.canPack()) {
|
||||
return ShipperPrepareResult.failed(logs, diagnostics);
|
||||
}
|
||||
final var packed = packer.packWorkspace(new PackWorkspaceRequest(context));
|
||||
emit(logs, sink, logFor(packed.status(), ShipperLogSource.PACK, packed.summary()));
|
||||
if (packed.status() != PackerOperationStatus.SUCCESS) {
|
||||
diagnostics.add(packed.summary());
|
||||
return ShipperPrepareResult.failed(logs, diagnostics);
|
||||
}
|
||||
final List<Path> artifacts = packed.result().emittedArtifacts().stream()
|
||||
.map(value -> value.path().toAbsolutePath().normalize()).toList();
|
||||
artifacts.forEach(path -> emit(logs, sink, ShipperLogEntry.info(ShipperLogSource.PACK, "Emitted " + path)));
|
||||
final Path manifest = writeManifest(project, build, logs, sink);
|
||||
return new ShipperPrepareResult(ShipperPreparationStatus.SUCCESS, logs, manifest, artifacts, diagnostics);
|
||||
} catch (RuntimeException exception) {
|
||||
final String message = exception.getMessage() == null ? exception.getClass().getSimpleName() : exception.getMessage();
|
||||
diagnostics.add(message);
|
||||
emit(logs, sink, ShipperLogEntry.error(ShipperLogSource.BUILD, message));
|
||||
return ShipperPrepareResult.failed(logs, diagnostics);
|
||||
}
|
||||
}
|
||||
|
||||
private Path writeManifest(ProjectReference project, CompilerBuildGateway.CompilerBuildOutput build,
|
||||
List<ShipperLogEntry> logs, Consumer<ShipperLogEntry> sink) {
|
||||
final Path buildRoot = project.rootPath().resolve("build").toAbsolutePath().normalize();
|
||||
final Path manifestPath = buildRoot.resolve("manifest.json");
|
||||
try {
|
||||
Files.createDirectories(buildRoot);
|
||||
final ObjectNode manifest = mapper.createObjectNode();
|
||||
manifest.put("magic", "PMTU");
|
||||
manifest.put("cartridge_version", 1);
|
||||
manifest.put("app_id", stableAppId(project));
|
||||
manifest.put("title", project.name());
|
||||
manifest.put("app_version", project.version());
|
||||
manifest.put("app_mode", project.target().exportReferenceName());
|
||||
final ArrayNode capabilities = mapper.createArrayNode();
|
||||
new LinkedHashSet<>(build.requiredCapabilities()).forEach(capabilities::add);
|
||||
manifest.set("capabilities", capabilities);
|
||||
manifest.set("asset_table", readArrayOrEmpty(buildRoot.resolve("asset_table.json")));
|
||||
manifest.set("preload", readArrayOrEmpty(buildRoot.resolve("preload.json")));
|
||||
mapper.writerWithDefaultPrettyPrinter().writeValue(manifestPath.toFile(), manifest);
|
||||
emit(logs, sink, ShipperLogEntry.info(ShipperLogSource.MANIFEST, "Generated manifest at " + manifestPath));
|
||||
return manifestPath;
|
||||
} catch (IOException exception) {
|
||||
throw new IllegalStateException("failed to write build manifest: " + manifestPath, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode readArrayOrEmpty(Path path) throws IOException {
|
||||
if (!Files.isRegularFile(path)) {
|
||||
return mapper.createArrayNode();
|
||||
}
|
||||
final JsonNode loaded = mapper.readTree(path.toFile());
|
||||
return loaded != null && loaded.isArray() ? loaded : mapper.createArrayNode();
|
||||
}
|
||||
|
||||
private int stableAppId(ProjectReference project) {
|
||||
final int hash = Objects.hash(project.name(), project.version(), project.languageId(), project.stdlibVersion());
|
||||
return hash == Integer.MIN_VALUE ? 1 : Math.max(1, Math.abs(hash));
|
||||
}
|
||||
|
||||
private ShipperLogEntry logFor(PackerOperationStatus status, ShipperLogSource source, String message) {
|
||||
return status == PackerOperationStatus.SUCCESS
|
||||
? ShipperLogEntry.info(source, message)
|
||||
: ShipperLogEntry.error(source, message);
|
||||
}
|
||||
|
||||
private void emit(List<ShipperLogEntry> logs, Consumer<ShipperLogEntry> sink, ShipperLogEntry entry) {
|
||||
logs.add(entry);
|
||||
sink.accept(entry);
|
||||
}
|
||||
|
||||
private String normalize(String message) {
|
||||
return message == null || message.isBlank() ? "(empty build log entry)" : message.strip();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package p.studio.core;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.modulith.core.ApplicationModules;
|
||||
import org.springframework.modulith.docs.Documenter;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class StudioModularityTest {
|
||||
private final ApplicationModules modules = ApplicationModules.of(StudioCore.class.getPackageName());
|
||||
|
||||
@Test
|
||||
void verifiesStudioCoreApplicationModules() {
|
||||
modules.verify();
|
||||
assertEquals(
|
||||
Set.of("project", "session", "assets", "shipper", "runtime", "execution"),
|
||||
modules.stream().map(module -> module.getIdentifier().toString()).collect(java.util.stream.Collectors.toSet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void documentsStudioCoreApplicationModules() {
|
||||
new Documenter(modules).writeDocumentation();
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package p.studio.core.assets;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.api.assets.AssetCapacityLevel;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
final class DefaultAssetCapacityPolicyTest {
|
||||
private final DefaultAssetCapacityPolicy policy = new DefaultAssetCapacityPolicy();
|
||||
|
||||
@Test
|
||||
void derivesGlyphCapacityFromTileSize() {
|
||||
assertEquals(1024, policy.maxArtifactsForGlyphBank(Map.of("tile_size", "8x8")));
|
||||
assertEquals(256, policy.maxArtifactsForGlyphBank(Map.of("tile_size", "16x16")));
|
||||
assertEquals(64, policy.maxArtifactsForGlyphBank(Map.of("tile_size", "32x32")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsExhaustedGlyphAndSoundBanks() {
|
||||
final var glyph = policy.evaluate(AssetFamily.GLYPH_BANK, 64, Map.of("tile_size", "32x32"), Map.of(), 0);
|
||||
final var sound = policy.evaluate(AssetFamily.SOUND_BANK, 2, Map.of(), Map.of("samples", Map.of(
|
||||
"1", Map.of("offset", 0, "length", 600_000),
|
||||
"2", Map.of("offset", 600_000, "length", 600_000))), 0);
|
||||
|
||||
assertTrue(glyph.blocked());
|
||||
assertEquals(AssetCapacityLevel.EXHAUSTED, glyph.level());
|
||||
assertTrue(sound.blocked());
|
||||
assertEquals("1200000 / 1048576 bytes", sound.labelText());
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package p.studio.core.assets;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.project.ProjectTarget;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
final class FileSystemAssetWorkspaceStorageTest {
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void preparesAssetsRootAndDetectsOnlyContainedAssetManifests() throws Exception {
|
||||
final var storage = new FileSystemAssetWorkspaceStorage();
|
||||
final var project = new ProjectReference("main", "1", "pbs", 1, ProjectTarget.Game, tempDir.resolve("project"));
|
||||
|
||||
assertTrue(storage.prepare(project).success());
|
||||
Files.createDirectories(storage.assetsRoot(project).resolve("scenes/main"));
|
||||
Files.writeString(storage.assetsRoot(project).resolve("scenes/main/asset.json"), "{}");
|
||||
|
||||
assertTrue(storage.assetManifestExists(project, "scenes/main"));
|
||||
assertFalse(storage.assetManifestExists(project, "../outside"));
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package p.studio.core.assets;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
final class PackerAssetCreationCatalogTest {
|
||||
private final PackerAssetCreationCatalog catalog = new PackerAssetCreationCatalog();
|
||||
|
||||
@Test
|
||||
void exposesProviderCreationChoicesWithoutLeakingProviderTypes() {
|
||||
assertTrue(catalog.supportedFamilies().contains(AssetFamily.GLYPH_BANK));
|
||||
assertFalse(catalog.supportedFamilies().contains(AssetFamily.UNKNOWN));
|
||||
assertTrue(catalog.supportedFormats(AssetFamily.GLYPH_BANK).contains("GLYPH_INDEXED_V1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatesFormatAndCodecCombinations() {
|
||||
final String format = catalog.supportedFormats(AssetFamily.GLYPH_BANK).getFirst();
|
||||
final String codec = catalog.availableCodecs(format).getFirst();
|
||||
|
||||
assertTrue(catalog.supports(format, codec));
|
||||
assertFalse(catalog.supports(format, "NOT_A_CODEC"));
|
||||
assertFalse(catalog.supports("NOT_A_FORMAT", codec));
|
||||
}
|
||||
}
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
package p.studio.core.assets.bank;
|
||||
|
||||
import p.studio.api.assets.workspace.*;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.api.assets.AssetConfigurationField;
|
||||
import p.studio.api.assets.AssetReference;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import p.studio.api.assets.AssetCapacityLevel;
|
||||
import p.studio.api.assets.AssetCapacityPolicy;
|
||||
import p.studio.api.assets.AssetCapacityState;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphSpecialization;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
final class DefaultAssetBankCompositionSessionTest {
|
||||
private DefaultAssetBankCompositionSession coordinator() {
|
||||
return new DefaultAssetBankCompositionSession(new TestCapacityPolicy());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tileFamilyBlocksSelectionAfterSlotCapacity() {
|
||||
final DefaultAssetBankCompositionSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(tileDetails("32x32", 65));
|
||||
coordinator.beginEdit();
|
||||
|
||||
coordinator.moveToSelected(coordinator.state().availableFiles());
|
||||
|
||||
assertEquals(64, coordinator.state().selectedFiles().size());
|
||||
assertTrue(coordinator.state().capacityState().blocked());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tileFamilyUsesAtlasCapacityFor8x8Tiles() {
|
||||
final DefaultAssetBankCompositionSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(tileDetails("8x8", 1_100));
|
||||
coordinator.beginEdit();
|
||||
|
||||
coordinator.moveToSelected(coordinator.state().availableFiles());
|
||||
|
||||
assertEquals(1_024, coordinator.state().selectedFiles().size());
|
||||
assertEquals("1024 / 1024", coordinator.state().capacityState().labelText());
|
||||
assertTrue(coordinator.state().capacityState().blocked());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tileFamilyUsesAtlasCapacityFor16x16Tiles() {
|
||||
final DefaultAssetBankCompositionSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(tileDetails("16x16", 300));
|
||||
coordinator.beginEdit();
|
||||
|
||||
coordinator.moveToSelected(coordinator.state().availableFiles());
|
||||
|
||||
assertEquals(256, coordinator.state().selectedFiles().size());
|
||||
assertEquals("256 / 256", coordinator.state().capacityState().labelText());
|
||||
assertTrue(coordinator.state().capacityState().blocked());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tileFamilyUsesAtlasCapacityFor32x32Tiles() {
|
||||
final DefaultAssetBankCompositionSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(tileDetails("32x32", 100));
|
||||
coordinator.beginEdit();
|
||||
|
||||
coordinator.moveToSelected(coordinator.state().availableFiles());
|
||||
|
||||
assertEquals(64, coordinator.state().selectedFiles().size());
|
||||
assertEquals("64 / 64", coordinator.state().capacityState().labelText());
|
||||
assertTrue(coordinator.state().capacityState().blocked());
|
||||
}
|
||||
|
||||
@Test
|
||||
void soundFamilyBlocksSelectionAfterByteCapacity() {
|
||||
final DefaultAssetBankCompositionSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(soundDetails(600_000L, 600_000L));
|
||||
coordinator.beginEdit();
|
||||
|
||||
coordinator.moveToSelected(coordinator.state().availableFiles());
|
||||
|
||||
assertEquals(1, coordinator.state().selectedFiles().size());
|
||||
assertTrue(coordinator.state().capacityState().progress() > 0.5d);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAndCancelFollowStudioFormSessionLifecycle() {
|
||||
final DefaultAssetBankCompositionSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(tileDetails("16x16", 2));
|
||||
coordinator.beginEdit();
|
||||
|
||||
final var firstFile = coordinator.state().availableFiles().subList(0, 1);
|
||||
coordinator.moveToSelected(firstFile);
|
||||
assertTrue(coordinator.state().dirty());
|
||||
|
||||
coordinator.reset();
|
||||
assertFalse(coordinator.state().dirty());
|
||||
|
||||
coordinator.moveToSelected(firstFile);
|
||||
assertTrue(coordinator.state().dirty());
|
||||
coordinator.cancel();
|
||||
assertFalse(coordinator.state().editing());
|
||||
assertFalse(coordinator.state().dirty());
|
||||
}
|
||||
|
||||
private AssetWorkspaceAssetDetails tileDetails(String tileSize, int fileCount) {
|
||||
return new AssetWorkspaceAssetDetails(
|
||||
summary(AssetFamily.GLYPH_BANK),
|
||||
List.of(),
|
||||
"GLYPH_INDEXED_V1",
|
||||
"NONE",
|
||||
List.of("NONE"),
|
||||
Map.of("NONE", List.of()),
|
||||
List.of(new AssetConfigurationField("tile_size", "Tile Size", "TEXT", tileSize, true, List.of())),
|
||||
Map.of(),
|
||||
new AssetWorkspaceBankCompositionDetails(
|
||||
files("tile", fileCount, 1024L),
|
||||
List.of(),
|
||||
0L),
|
||||
List.of(),
|
||||
null,
|
||||
null,
|
||||
AssetWorkspaceSceneBankValidation.NOT_APPLICABLE,
|
||||
List.of());
|
||||
}
|
||||
|
||||
private AssetWorkspaceAssetDetails soundDetails(long firstSize, long secondSize) {
|
||||
return new AssetWorkspaceAssetDetails(
|
||||
summary(AssetFamily.SOUND_BANK),
|
||||
List.of(),
|
||||
"SOUND_V1",
|
||||
"NONE",
|
||||
List.of("NONE"),
|
||||
Map.of("NONE", List.of()),
|
||||
List.of(),
|
||||
Map.of("samples", Map.of(
|
||||
"1", Map.of("offset", 0L, "length", firstSize),
|
||||
"2", Map.of("offset", firstSize, "length", secondSize))),
|
||||
new AssetWorkspaceBankCompositionDetails(
|
||||
List.of(
|
||||
new AssetWorkspaceBankCompositionFile("a.wav", "a.wav", firstSize, 1L, null, Map.of()),
|
||||
new AssetWorkspaceBankCompositionFile("b.wav", "b.wav", secondSize, 1L, null, Map.of())),
|
||||
List.of(),
|
||||
0L),
|
||||
List.of(),
|
||||
null,
|
||||
null,
|
||||
AssetWorkspaceSceneBankValidation.NOT_APPLICABLE,
|
||||
List.of());
|
||||
}
|
||||
|
||||
private List<AssetWorkspaceBankCompositionFile> files(String prefix, int count, long size) {
|
||||
return java.util.stream.IntStream.range(0, count)
|
||||
.mapToObj(index -> new AssetWorkspaceBankCompositionFile(
|
||||
prefix + "-" + index + ".png",
|
||||
prefix + "-" + index + ".png",
|
||||
size,
|
||||
1L,
|
||||
null,
|
||||
Map.of()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private AssetWorkspaceAssetSummary summary(AssetFamily family) {
|
||||
return new AssetWorkspaceAssetSummary(
|
||||
AssetReference.forAssetId(1),
|
||||
"bank",
|
||||
AssetWorkspaceAssetState.REGISTERED,
|
||||
AssetWorkspaceBuildParticipation.INCLUDED,
|
||||
1,
|
||||
family,
|
||||
AssetStudioGlyphSpecialization.NONE,
|
||||
Path.of("/tmp/bank"),
|
||||
false,
|
||||
false);
|
||||
}
|
||||
|
||||
private static final class TestCapacityPolicy implements AssetCapacityPolicy {
|
||||
@Override
|
||||
public AssetCapacityState evaluate(AssetFamily family, int count, Map<String, String> metadata,
|
||||
Map<String, Object> pipeline, long usedBytes) {
|
||||
if (family == AssetFamily.GLYPH_BANK) {
|
||||
final int maximum = maxArtifactsForGlyphBank(metadata);
|
||||
return new AssetCapacityState((double) count / maximum, AssetCapacityLevel.SAFE,
|
||||
count >= maximum, count + " / " + maximum, "");
|
||||
}
|
||||
final long maximum = 1024L * 1024L;
|
||||
return new AssetCapacityState((double) usedBytes / maximum, AssetCapacityLevel.SAFE,
|
||||
usedBytes >= maximum, usedBytes + " / " + maximum + " bytes", "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public int maxArtifactsForGlyphBank(Map<String, String> metadata) {
|
||||
return switch (metadata.getOrDefault("tile_size", "16x16")) {
|
||||
case "8x8" -> 1024;
|
||||
case "32x32" -> 64;
|
||||
default -> 256;
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
package p.studio.core.assets.metadata;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import p.studio.api.assets.metadata.*;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
final class AssetStudioMetadataServiceTest {
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private final AssetStudioMetadataService service = new AssetStudioMetadataService();
|
||||
|
||||
@Test
|
||||
void readsGlyphSpecializationFromStudioMetadataFile() throws Exception {
|
||||
final Path assetRoot = tempDir.resolve("tileset");
|
||||
Files.createDirectories(assetRoot);
|
||||
assertTrue(service.writeGlyphSpecialization(assetRoot, AssetStudioGlyphSpecialization.TILESET).successful());
|
||||
|
||||
final AssetStudioMetadataSnapshot snapshot = service.read(assetRoot, AssetFamily.GLYPH_BANK);
|
||||
|
||||
assertEquals(AssetStudioGlyphSpecialization.TILESET, snapshot.glyphSpecialization());
|
||||
assertNull(snapshot.sceneBankMetadata());
|
||||
assertNull(snapshot.glyphMaterialMetadata());
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsGlyphBankWithoutStudioMetadataAsNone() throws Exception {
|
||||
final Path assetRoot = tempDir.resolve("legacy-glyph");
|
||||
Files.createDirectories(assetRoot);
|
||||
|
||||
final AssetStudioMetadataSnapshot snapshot = service.read(assetRoot, AssetFamily.GLYPH_BANK);
|
||||
|
||||
assertEquals(AssetStudioGlyphSpecialization.NONE, snapshot.glyphSpecialization());
|
||||
assertNull(snapshot.sceneBankMetadata());
|
||||
assertNull(snapshot.glyphMaterialMetadata());
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsAndWritesGlyphMaterialSupportMetadata() throws Exception {
|
||||
final Path assetRoot = tempDir.resolve("glyph");
|
||||
Files.createDirectories(assetRoot);
|
||||
final AssetStudioGlyphMaterialMetadata metadata = new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
2,
|
||||
Map.of(0, "#8B4513", 1, "#00AA0000"),
|
||||
List.of(
|
||||
new AssetStudioGlyphMaterialArtifactBinding("artifact-1", "fp-1"),
|
||||
new AssetStudioGlyphMaterialArtifactBinding("artifact-2", "fp-2")))),
|
||||
List.of(new AssetStudioGlyphMaterialPalette(
|
||||
"palette-1",
|
||||
"Forest",
|
||||
"schema-1",
|
||||
2,
|
||||
List.of("#8B4513", "#00AA0000"))),
|
||||
null);
|
||||
assertTrue(service.writeGlyphMaterialMetadata(assetRoot, metadata).successful());
|
||||
|
||||
final AssetStudioMetadataSnapshot snapshot = service.read(assetRoot, AssetFamily.GLYPH_BANK);
|
||||
|
||||
assertNotNull(snapshot.glyphMaterialMetadata());
|
||||
assertEquals(1, snapshot.glyphMaterialMetadata().schemas().size());
|
||||
assertEquals("schema-1", snapshot.glyphMaterialMetadata().schemas().getFirst().schemaId());
|
||||
assertEquals("#8B4513", snapshot.glyphMaterialMetadata().schemas().getFirst().materialIndices().get(0));
|
||||
assertEquals(1, snapshot.glyphMaterialMetadata().palettes().size());
|
||||
assertEquals("Forest", snapshot.glyphMaterialMetadata().palettes().getFirst().displayName());
|
||||
assertEquals(List.of("#8B4513", "#00AA0000"), snapshot.glyphMaterialMetadata().palettes().getFirst().colors());
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsHtmlRgbAsCanonicalGlyphMaterialColorAndDerivesRgba8888() {
|
||||
final AssetStudioGlyphMaterialPalette palette = new AssetStudioGlyphMaterialPalette(
|
||||
"palette-1",
|
||||
"schema-1",
|
||||
1,
|
||||
List.of("#FF0000", "#00FF00", "#0000FF", "#00000000"));
|
||||
|
||||
assertEquals(List.of("#FF0000", "#00FF00", "#0000FF", "#00000000"), palette.colors());
|
||||
assertEquals(List.of(0xFF0000FF, 0x00FF00FF, 0x0000FFFF, 0x00000000), palette.convertedRgba8888Colors());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void readsSceneBankSupportMetadataWhenContractIsValid() throws Exception {
|
||||
final Path assetRoot = tempDir.resolve("scene");
|
||||
Files.createDirectories(assetRoot);
|
||||
Files.writeString(assetRoot.resolve(AssetStudioMetadataService.SCENE_BANK_SUPPORT_FILE), """
|
||||
{
|
||||
"schema_version": 1,
|
||||
"map_width": 20,
|
||||
"map_height": 12,
|
||||
"layer_count": 4,
|
||||
"layers": [
|
||||
{ "index": 1, "enabled": true, "name": "Ground", "width": 20, "height": 12, "tilemap": "ground.tmx", "tileset_asset_root": "tilesets/ground", "parallax_factor_x": 1.0, "parallax_factor_y": 1.0, "default_palette_id": 2 },
|
||||
{ "index": 2, "enabled": true, "name": "Collision", "width": 10, "height": 8, "tilemap": "collision.tmx", "tileset_asset_root": "tilesets/ground", "parallax_factor_x": 0.5, "parallax_factor_y": 0.75, "default_palette_id": 3 },
|
||||
{ "index": 3, "enabled": false, "name": "Layer 3", "width": 20, "height": 12, "tilemap": "layer-3.tmx", "tileset_asset_root": "", "default_palette_id": 0 },
|
||||
{ "index": 4, "enabled": false, "name": "Layer 4", "width": 20, "height": 12, "tilemap": "layer-4.tmx", "tileset_asset_root": "", "default_palette_id": 0 }
|
||||
]
|
||||
}
|
||||
""");
|
||||
|
||||
final AssetStudioMetadataSnapshot snapshot = service.read(assetRoot, AssetFamily.SCENE_BANK);
|
||||
|
||||
assertNotNull(snapshot.sceneBankMetadata());
|
||||
assertEquals(20, snapshot.sceneBankMetadata().mapWidth());
|
||||
assertEquals(12, snapshot.sceneBankMetadata().mapHeight());
|
||||
assertEquals(4, snapshot.sceneBankMetadata().layerCount());
|
||||
assertEquals(10, snapshot.sceneBankMetadata().layerBindings().get(1).width());
|
||||
assertEquals(8, snapshot.sceneBankMetadata().layerBindings().get(1).height());
|
||||
assertEquals(0.5f, snapshot.sceneBankMetadata().layerBindings().get(1).parallaxFactorX());
|
||||
assertEquals(0.75f, snapshot.sceneBankMetadata().layerBindings().get(1).parallaxFactorY());
|
||||
assertEquals(3, snapshot.sceneBankMetadata().layerBindings().get(1).defaultPaletteId());
|
||||
assertEquals(20 * 12, snapshot.sceneBankMetadata().layerBindings().getFirst().tiles().size());
|
||||
assertFalse(snapshot.sceneBankMetadata().layerBindings().getFirst().tiles().getFirst().active());
|
||||
assertEquals(
|
||||
java.util.List.of("ground.tmx", "collision.tmx"),
|
||||
snapshot.sceneBankMetadata().layerBindings().stream()
|
||||
.filter(AssetStudioSceneLayerBinding::enabled)
|
||||
.map(AssetStudioSceneLayerBinding::tilemap)
|
||||
.toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsSceneBankSupportMetadataWhenLayerCountIsNotFixedAtFour() throws Exception {
|
||||
final Path assetRoot = tempDir.resolve("scene-invalid");
|
||||
Files.createDirectories(assetRoot);
|
||||
Files.writeString(assetRoot.resolve(AssetStudioMetadataService.SCENE_BANK_SUPPORT_FILE), """
|
||||
{
|
||||
"schema_version": 1,
|
||||
"map_width": 16,
|
||||
"map_height": 16,
|
||||
"layer_count": 3,
|
||||
"layers": [
|
||||
{ "index": 1, "enabled": true, "name": "A", "width": 16, "height": 16, "tilemap": "a.tmx", "tileset_asset_root": "", "default_palette_id": 0 },
|
||||
{ "index": 2, "enabled": false, "name": "B", "width": 16, "height": 16, "tilemap": "b.tmx", "tileset_asset_root": "", "default_palette_id": 0 },
|
||||
{ "index": 3, "enabled": false, "name": "C", "width": 16, "height": 16, "tilemap": "c.tmx", "tileset_asset_root": "", "default_palette_id": 0 }
|
||||
]
|
||||
}
|
||||
""");
|
||||
|
||||
final AssetStudioMetadataSnapshot snapshot = service.read(assetRoot, AssetFamily.SCENE_BANK);
|
||||
|
||||
assertNull(snapshot.sceneBankMetadata());
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesSceneBankSupportMetadataWithCanonicalLayerFields() throws Exception {
|
||||
final Path assetRoot = tempDir.resolve("scene-written");
|
||||
Files.createDirectories(assetRoot);
|
||||
final AssetStudioSceneBankMetadata metadata = new AssetStudioSceneBankMetadata(
|
||||
16,
|
||||
12,
|
||||
4,
|
||||
List.of(
|
||||
new AssetStudioSceneLayerBinding(true, 1, "Ground", 16, 12, "ground.tmx", "tilesets/ground", 1.0f, 1.0f, 2),
|
||||
new AssetStudioSceneLayerBinding(false, 2, "Layer 2", 16, 12, "layer-2.tmx", "", 1.0f, 1.0f, 0),
|
||||
new AssetStudioSceneLayerBinding(false, 3, "Layer 3", 16, 12, "layer-3.tmx", "", 1.0f, 1.0f, 0),
|
||||
new AssetStudioSceneLayerBinding(false, 4, "Layer 4", 16, 12, "layer-4.tmx", "", 1.0f, 1.0f, 0)),
|
||||
assetRoot.resolve(AssetStudioMetadataService.SCENE_BANK_SUPPORT_FILE));
|
||||
|
||||
assertTrue(service.writeSceneBankMetadata(assetRoot, metadata).successful());
|
||||
|
||||
final String json = Files.readString(assetRoot.resolve(AssetStudioMetadataService.SCENE_BANK_SUPPORT_FILE));
|
||||
assertTrue(json.contains("\"parallax_factor_x\""));
|
||||
assertTrue(json.contains("\"parallax_factor_y\""));
|
||||
assertTrue(json.contains("\"default_palette_id\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesSceneBankSupportMetadataWithCanonicalTilesWhenPresent() throws Exception {
|
||||
final Path assetRoot = tempDir.resolve("scene-tiles");
|
||||
Files.createDirectories(assetRoot);
|
||||
final AssetStudioSceneBankMetadata metadata = new AssetStudioSceneBankMetadata(
|
||||
2,
|
||||
2,
|
||||
4,
|
||||
List.of(
|
||||
new AssetStudioSceneLayerBinding(
|
||||
true,
|
||||
1,
|
||||
"Ground",
|
||||
2,
|
||||
2,
|
||||
"ground.tmx",
|
||||
"tilesets/ground",
|
||||
1.0f,
|
||||
1.0f,
|
||||
2,
|
||||
List.of(
|
||||
new AssetStudioSceneTile(true, 7, 2, false, false),
|
||||
AssetStudioSceneTile.inactive(2),
|
||||
AssetStudioSceneTile.inactive(2),
|
||||
AssetStudioSceneTile.inactive(2))),
|
||||
new AssetStudioSceneLayerBinding(false, 2, "Layer 2", 2, 2, "layer-2.tmx", "", 1.0f, 1.0f, 0),
|
||||
new AssetStudioSceneLayerBinding(false, 3, "Layer 3", 2, 2, "layer-3.tmx", "", 1.0f, 1.0f, 0),
|
||||
new AssetStudioSceneLayerBinding(false, 4, "Layer 4", 2, 2, "layer-4.tmx", "", 1.0f, 1.0f, 0)),
|
||||
assetRoot.resolve(AssetStudioMetadataService.SCENE_BANK_SUPPORT_FILE));
|
||||
|
||||
assertTrue(service.writeSceneBankMetadata(assetRoot, metadata).successful());
|
||||
|
||||
final String json = Files.readString(assetRoot.resolve(AssetStudioMetadataService.SCENE_BANK_SUPPORT_FILE));
|
||||
assertTrue(json.contains("\"tiles\""));
|
||||
assertTrue(json.contains("\"glyph_id\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void providesDefaultSceneBankMetadataWhenSupportFileIsMissing() throws Exception {
|
||||
final Path assetRoot = tempDir.resolve("scene-missing");
|
||||
Files.createDirectories(assetRoot);
|
||||
|
||||
final AssetStudioMetadataSnapshot snapshot = service.read(assetRoot, AssetFamily.SCENE_BANK);
|
||||
|
||||
assertNotNull(snapshot.sceneBankMetadata());
|
||||
assertEquals(16, snapshot.sceneBankMetadata().mapWidth());
|
||||
assertEquals("scene.tmx", snapshot.sceneBankMetadata().layerBindings().getFirst().tilemap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertsMetadataIoFailureToTypedResult() throws Exception {
|
||||
final Path assetRoot = tempDir.resolve("not-a-directory");
|
||||
Files.writeString(assetRoot, "occupied");
|
||||
|
||||
final AssetMetadataWriteResult result = service.writeGlyphSpecialization(
|
||||
assetRoot,
|
||||
AssetStudioGlyphSpecialization.TILESET);
|
||||
|
||||
assertFalse(result.successful());
|
||||
assertFalse(result.message().isBlank());
|
||||
}
|
||||
}
|
||||
+448
@@ -0,0 +1,448 @@
|
||||
package p.studio.core.assets.palette;
|
||||
|
||||
import p.studio.api.assets.workspace.*;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.api.assets.AssetReference;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import p.studio.api.assets.metadata.*;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
final class DefaultAssetPaletteSessionTest {
|
||||
private DefaultAssetPaletteSession coordinator() {
|
||||
return new DefaultAssetPaletteSession(new TestAssetColorSchemaRules());
|
||||
}
|
||||
|
||||
@Test
|
||||
void derivesOriginalPaletteFromReadySchemaWhenNoPaletteRecordExists() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000", 2, "#00FF00"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(),
|
||||
null),
|
||||
List.of()));
|
||||
|
||||
assertTrue(coordinator.ready());
|
||||
assertEquals(1, coordinator.state().allFiles().size());
|
||||
assertEquals("schema-1 / original", coordinator.state().allFiles().getFirst().displayName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void initialSelectionMatchesPersistedPackerPipelinePalettePayload() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
final AssetStudioGlyphMaterialPalette persisted = new AssetStudioGlyphMaterialPalette(
|
||||
"palette-1",
|
||||
"schema-1",
|
||||
1,
|
||||
List.of("#FF0000", "#00FF00"));
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000", 2, "#00FF00"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(persisted),
|
||||
null),
|
||||
List.of(Map.of(
|
||||
"index", 0,
|
||||
"rgba8888", List.of(0xFF0000FF, 0x00FF00FF)))));
|
||||
|
||||
assertEquals(1, coordinator.state().selectedFiles().size());
|
||||
assertEquals("palette-1", coordinator.state().selectedFiles().getFirst().metadata().get("paletteId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void previewPaletteDefaultsToAvailablePaletteWhenBuildSelectionIsEmpty() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000", 2, "#00FF00"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(new AssetStudioGlyphMaterialPalette(
|
||||
"palette-1",
|
||||
"schema-1",
|
||||
1,
|
||||
List.of("#112233", "#445566"))),
|
||||
null),
|
||||
List.of()));
|
||||
|
||||
assertNotNull(coordinator.state().previewPaletteFile());
|
||||
assertTrue(coordinator.state().availableFiles().contains(coordinator.state().previewPaletteFile()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void originalPaletteRemainsSyntheticEvenWhenUserPaletteHasSameColors() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000", 2, "#00FF00"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(new AssetStudioGlyphMaterialPalette(
|
||||
"palette-1",
|
||||
"schema-1",
|
||||
1,
|
||||
List.of("#FF0000", "#00FF00"))),
|
||||
null),
|
||||
List.of()));
|
||||
|
||||
assertEquals(2, coordinator.state().allFiles().size());
|
||||
final AssetWorkspaceBankCompositionFile original = coordinator.state().allFiles().stream()
|
||||
.filter(coordinator::paletteIsOriginal)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
final AssetWorkspaceBankCompositionFile userPalette = coordinator.state().allFiles().stream()
|
||||
.filter(file -> "palette-1".equals(file.metadata().get("paletteId")))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
|
||||
assertEquals("schema-schema-1-original", original.metadata().get("paletteId"));
|
||||
assertFalse(coordinator.paletteIsOriginal(userPalette));
|
||||
}
|
||||
|
||||
@Test
|
||||
void originalPaletteTracksSchemaMaterialColorsAfterMetadataUpdate() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000", 2, "#00FF00"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(),
|
||||
null),
|
||||
List.of()));
|
||||
|
||||
coordinator.replaceMaterialMetadata(new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
2,
|
||||
Map.of(1, "#112233", 2, "#445566"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(),
|
||||
null));
|
||||
|
||||
final AssetWorkspaceBankCompositionFile original = coordinator.state().allFiles().stream()
|
||||
.filter(coordinator::paletteIsOriginal)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
final Map<String, Object> palette = (Map<String, Object>) original.metadata().get("palette");
|
||||
assertEquals(List.of(0xFF112233, 0xFF445566), palette.get("originalArgb8888"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateDetectionUsesSameSchemaColorsAndOrder() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000", 2, "#00FF00"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(new AssetStudioGlyphMaterialPalette(
|
||||
"palette-1",
|
||||
"schema-1",
|
||||
1,
|
||||
List.of("#FF0000", "#00FF00"))),
|
||||
null),
|
||||
List.of()));
|
||||
|
||||
assertTrue(coordinator.duplicatePaletteExists(null, "schema-1", List.of("#FF0000", "#00FF00")));
|
||||
assertFalse(coordinator.duplicatePaletteExists(null, "schema-1", List.of("#00FF00", "#FF0000")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void paletteDisplayNameUsesExplicitNameWhenPresent() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000", 2, "#00FF00"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(new AssetStudioGlyphMaterialPalette(
|
||||
"palette-1",
|
||||
"Forest",
|
||||
"schema-1",
|
||||
1,
|
||||
List.of("#FF0000", "#00FF00"))),
|
||||
null),
|
||||
List.of()));
|
||||
|
||||
final AssetWorkspaceBankCompositionFile palette = coordinator.state().allFiles().getFirst();
|
||||
assertEquals("Forest", palette.displayName());
|
||||
assertEquals("Forest", palette.metadata().get("explicitPaletteDisplayName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void paletteDisplayNameFallsBackToColorsWhenNameIsBlank() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000", 2, "#00FF00"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(new AssetStudioGlyphMaterialPalette(
|
||||
"palette-1",
|
||||
"schema-1",
|
||||
1,
|
||||
List.of("#FF0000", "#00FF00"))),
|
||||
null),
|
||||
List.of()));
|
||||
|
||||
final AssetWorkspaceBankCompositionFile palette = coordinator.state().allFiles().getFirst();
|
||||
assertEquals("ember bloom", palette.displayName());
|
||||
assertFalse(palette.metadata().containsKey("explicitPaletteDisplayName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatedPaletteDisplayNameUsesPoeticColorWords() {
|
||||
assertEquals("snow white", coordinator().generatedDisplayName(List.of("#FFFFFF")));
|
||||
assertEquals("fog twist", coordinator().generatedDisplayName(List.of("#F2F4F4", "#707878")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void upsertPalettePersistsGeneratedDisplayNameWhenNameIsBlank() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#F2F4F4", 2, "#707878"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(),
|
||||
null),
|
||||
List.of()));
|
||||
|
||||
final AssetStudioGlyphMaterialMetadata metadata = coordinator.upsertPalette(
|
||||
"palette-1",
|
||||
" ",
|
||||
"schema-1",
|
||||
List.of("#F2F4F4", "#707878"));
|
||||
|
||||
assertEquals("fog twist", metadata.palettes().getFirst().displayName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void removePaletteDeletesUserPaletteEvenWhenSelectedForBuild() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000", 2, "#00FF00"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(new AssetStudioGlyphMaterialPalette(
|
||||
"palette-1",
|
||||
"schema-1",
|
||||
1,
|
||||
List.of("#112233", "#445566"))),
|
||||
null),
|
||||
List.of(Map.of(
|
||||
"originalArgb8888", List.of(0xFF112233, 0xFF445566),
|
||||
"rgba8888", List.of(0x112233FF, 0x445566FF)))));
|
||||
|
||||
final AssetStudioGlyphMaterialMetadata metadata = coordinator.removePalette("palette-1");
|
||||
|
||||
assertTrue(metadata.palettes().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void removePaletteRejectsSyntheticOriginalPalette() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000", 2, "#00FF00"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(),
|
||||
null),
|
||||
List.of()));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> coordinator.removePalette("schema-schema-1-original"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stalePaletteIsProjectedAsInvalid() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
2,
|
||||
Map.of(1, "#FF0000"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(new AssetStudioGlyphMaterialPalette(
|
||||
"palette-1",
|
||||
"schema-1",
|
||||
1,
|
||||
List.of("#FF0000"))),
|
||||
null),
|
||||
List.of()));
|
||||
|
||||
final AssetWorkspaceBankCompositionFile palette = coordinator.state().allFiles().getFirst();
|
||||
assertEquals(Boolean.FALSE, palette.metadata().get("valid"));
|
||||
assertTrue(((String) palette.metadata().get("invalidReason")).contains("stale"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void paletteIsInvalidWhenSchemaArtifactFingerprintDrifts() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-old")))),
|
||||
List.of(new AssetStudioGlyphMaterialPalette(
|
||||
"palette-1",
|
||||
"schema-1",
|
||||
1,
|
||||
List.of("#FF0000"))),
|
||||
null),
|
||||
List.of()));
|
||||
|
||||
final AssetWorkspaceBankCompositionFile palette = coordinator.state().allFiles().getFirst();
|
||||
assertEquals(Boolean.FALSE, palette.metadata().get("valid"));
|
||||
assertTrue(((String) palette.metadata().get("invalidReason")).contains("inconsistent"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void previewTilesAreScopedToSelectedPaletteSchema() {
|
||||
final DefaultAssetPaletteSession coordinator = coordinator();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("tile-a.png", "artifact-a"), tile("tile-b.png", "artifact-b")),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(
|
||||
new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000", 2, "#00FF00"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a"))),
|
||||
new AssetStudioGlyphMaterialSchema(
|
||||
"schema-2",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#0000FF"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-b", "fp-b")))),
|
||||
List.of(),
|
||||
null),
|
||||
List.of()));
|
||||
|
||||
final AssetWorkspaceBankCompositionFile schema2Palette = coordinator.state().allFiles().stream()
|
||||
.filter(file -> "schema-2".equals(file.metadata().get("schemaId")))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
coordinator.selectPreviewPalette(schema2Palette);
|
||||
|
||||
assertEquals(List.of("tile-b.png"), coordinator.state().previewTileFiles().stream().map(AssetWorkspaceBankCompositionFile::path).toList());
|
||||
assertEquals("schema-2", coordinator.state().previewPaletteFile().metadata().get("schemaId"));
|
||||
assertEquals(Map.of(1, "#0000FF"), coordinator.state().previewPaletteFile().metadata().get("schemaMaterialIndices"));
|
||||
}
|
||||
|
||||
private AssetWorkspaceAssetDetails details(
|
||||
List<AssetWorkspaceBankCompositionFile> selectedFiles,
|
||||
AssetStudioGlyphMaterialMetadata metadata,
|
||||
List<Map<String, Object>> pipelinePalettes) {
|
||||
return new AssetWorkspaceAssetDetails(
|
||||
new AssetWorkspaceAssetSummary(
|
||||
AssetReference.forAssetId(1),
|
||||
"bank",
|
||||
AssetWorkspaceAssetState.REGISTERED,
|
||||
AssetWorkspaceBuildParticipation.INCLUDED,
|
||||
1,
|
||||
AssetFamily.GLYPH_BANK,
|
||||
AssetStudioGlyphSpecialization.SPRITES,
|
||||
Path.of("/tmp/bank"),
|
||||
false,
|
||||
false),
|
||||
List.of(),
|
||||
"GLYPH_INDEXED_V1",
|
||||
"NONE",
|
||||
List.of("NONE"),
|
||||
Map.of("NONE", List.of()),
|
||||
List.of(),
|
||||
Map.of(),
|
||||
new AssetWorkspaceBankCompositionDetails(List.of(), selectedFiles, 0L),
|
||||
pipelinePalettes,
|
||||
metadata,
|
||||
null,
|
||||
AssetWorkspaceSceneBankValidation.NOT_APPLICABLE,
|
||||
List.of());
|
||||
}
|
||||
|
||||
private AssetWorkspaceBankCompositionFile tile(String path, String artifactId) {
|
||||
return new AssetWorkspaceBankCompositionFile(
|
||||
path,
|
||||
path,
|
||||
256L,
|
||||
1L,
|
||||
"artifact-a".equals(artifactId) ? "fp-a" : "fp-b",
|
||||
Map.of(
|
||||
"artifactId", artifactId,
|
||||
"tile", Map.of(
|
||||
"width", 2,
|
||||
"height", 2,
|
||||
"paletteIndices", List.of(0, 1, 2, 0)),
|
||||
"palette", Map.of(
|
||||
"originalArgb8888", List.of(0xFFFF0000, 0xFF00FF00),
|
||||
"rgba8888", List.of(0xFF0000FF, 0x00FF00FF))));
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package p.studio.core.assets.palette;
|
||||
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialArtifactBinding;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialSchema;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphMaterialSchemaStatus;
|
||||
import p.studio.api.assets.schema.AssetColorSchemaRules;
|
||||
import p.studio.api.assets.workspace.AssetWorkspaceBankCompositionFile;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
final class TestAssetColorSchemaRules implements AssetColorSchemaRules {
|
||||
@Override
|
||||
public AssetStudioGlyphMaterialSchemaStatus effectiveStatus(
|
||||
AssetStudioGlyphMaterialSchema schema,
|
||||
List<AssetWorkspaceBankCompositionFile> selectedTiles) {
|
||||
if (schema.status() == AssetStudioGlyphMaterialSchemaStatus.INCONSISTENT) {
|
||||
return AssetStudioGlyphMaterialSchemaStatus.INCONSISTENT;
|
||||
}
|
||||
final Map<String, AssetWorkspaceBankCompositionFile> selectedByArtifactId = new HashMap<>();
|
||||
for (AssetWorkspaceBankCompositionFile tile : selectedTiles) {
|
||||
if (artifactId(tile) != null) {
|
||||
selectedByArtifactId.put(artifactId(tile), tile);
|
||||
}
|
||||
}
|
||||
for (AssetStudioGlyphMaterialArtifactBinding binding : schema.artifactBindings()) {
|
||||
final AssetWorkspaceBankCompositionFile tile = selectedByArtifactId.get(binding.artifactId());
|
||||
if (tile == null || !Objects.equals(binding.fingerprint(), fingerprint(tile))) {
|
||||
return AssetStudioGlyphMaterialSchemaStatus.INCONSISTENT;
|
||||
}
|
||||
}
|
||||
return AssetStudioGlyphMaterialSchemaStatus.OK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsSchemaAuthoring(AssetWorkspaceBankCompositionFile file) {
|
||||
return artifactId(file) != null && fingerprint(file) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String artifactId(AssetWorkspaceBankCompositionFile file) {
|
||||
if (file == null || !(file.metadata().get("artifactId") instanceof String value) || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String fingerprint(AssetWorkspaceBankCompositionFile file) {
|
||||
if (file == null) {
|
||||
return null;
|
||||
}
|
||||
return file.fingerprint() == null || file.fingerprint().isBlank() ? null : file.fingerprint().trim();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> tileColors(AssetWorkspaceBankCompositionFile file) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
package p.studio.core.assets.scene;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.assets.AssetConfigurationField;
|
||||
import p.studio.api.assets.AssetReference;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import p.studio.api.project.ProjectTarget;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphSpecialization;
|
||||
import p.studio.api.assets.metadata.AssetStudioSceneBankMetadata;
|
||||
import p.studio.api.assets.metadata.AssetStudioSceneLayerBinding;
|
||||
import p.studio.api.assets.metadata.AssetStudioSceneTile;
|
||||
import p.studio.api.assets.scene.SceneBankWorkflowResult;
|
||||
import p.studio.api.assets.workspace.*;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
final class SceneBankWorkflowServiceTest {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final SceneBankWorkflowService workflowService = new SceneBankWorkflowService((projectReference, tilesetAssetRoot) ->
|
||||
"tilesets/overworld".equals(tilesetAssetRoot) ? 1 : -1);
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void inspectProjectsCanonicalSceneStateIntoReadyRequest() throws Exception {
|
||||
final ProjectReference project = projectReference();
|
||||
final AssetWorkspaceAssetDetails sceneDetails = createValidScene(project);
|
||||
|
||||
final SceneBankWorkflowResult result = workflowService.inspect(project, sceneDetails);
|
||||
|
||||
assertEquals(AssetWorkspaceSceneBankStatus.READY, result.validation().status());
|
||||
assertFalse(result.validation().pendingExternalChanges());
|
||||
assertFalse(result.validation().canAccept());
|
||||
assertTrue(Files.isRegularFile(sceneDetails.summary().assetRoot().resolve(SceneBankWorkflowService.ACCEPTED_REQUEST_FILE)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validationFailsWhenReferencedGlyphAssetCannotResolveTileSize() throws Exception {
|
||||
final ProjectReference project = projectReference();
|
||||
final Path sceneRoot = project.rootPath().resolve("assets/scenes/broken");
|
||||
Files.createDirectories(sceneRoot);
|
||||
final AssetWorkspaceAssetDetails brokenScene = new AssetWorkspaceAssetDetails(
|
||||
new AssetWorkspaceAssetSummary(
|
||||
AssetReference.forAssetId(2),
|
||||
"broken_scene",
|
||||
AssetWorkspaceAssetState.REGISTERED,
|
||||
AssetWorkspaceBuildParticipation.EXCLUDED,
|
||||
2,
|
||||
AssetFamily.SCENE_BANK,
|
||||
AssetStudioGlyphSpecialization.NONE,
|
||||
sceneRoot,
|
||||
false,
|
||||
false),
|
||||
List.of(),
|
||||
"SCENE_TILED_V1",
|
||||
"NONE",
|
||||
List.of("NONE"),
|
||||
Map.of("NONE", List.of()),
|
||||
List.of(),
|
||||
Map.of(),
|
||||
new AssetWorkspaceBankCompositionDetails(List.of(), List.of(), 0L),
|
||||
List.of(),
|
||||
null,
|
||||
new AssetStudioSceneBankMetadata(
|
||||
8,
|
||||
8,
|
||||
4,
|
||||
List.of(
|
||||
new AssetStudioSceneLayerBinding(true, 1, "Ground", 8, 8, "ground.tmx", "tilesets/missing", 1.0f, 1.0f, 0),
|
||||
new AssetStudioSceneLayerBinding(false, 2, "Layer 2", 8, 8, "layer-2.tmx", "", 1.0f, 1.0f, 0),
|
||||
new AssetStudioSceneLayerBinding(false, 3, "Layer 3", 8, 8, "layer-3.tmx", "", 1.0f, 1.0f, 0),
|
||||
new AssetStudioSceneLayerBinding(false, 4, "Layer 4", 8, 8, "layer-4.tmx", "", 1.0f, 1.0f, 0)),
|
||||
sceneRoot.resolve("scene-bank.studio.json")),
|
||||
AssetWorkspaceSceneBankValidation.NOT_APPLICABLE,
|
||||
List.of());
|
||||
|
||||
final SceneBankWorkflowResult result = workflowService.inspect(project, brokenScene);
|
||||
|
||||
assertEquals(AssetWorkspaceSceneBankStatus.VALIDATION_FAILED, result.validation().status());
|
||||
assertTrue(result.diagnostics().stream().anyMatch(diagnostic -> diagnostic.message().contains("tile_size")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inspectPersistsCanonicalScenePackRequestUsingCanonicalTiles() throws Exception {
|
||||
final ProjectReference project = projectReference();
|
||||
final AssetWorkspaceAssetDetails sceneDetails = createValidScene(project);
|
||||
|
||||
final SceneBankWorkflowResult result = workflowService.inspect(project, sceneDetails);
|
||||
assertEquals(AssetWorkspaceSceneBankStatus.READY, result.validation().status());
|
||||
|
||||
final JsonNode request = mapper.readTree(sceneDetails.summary().assetRoot().resolve(SceneBankWorkflowService.ACCEPTED_REQUEST_FILE).toFile());
|
||||
assertEquals("SCENE/tilemap_v1", request.path("format").asText());
|
||||
assertEquals(1, request.path("version").asInt());
|
||||
final JsonNode firstLayer = request.path("layers").get(0);
|
||||
assertTrue(firstLayer.path("active").asBoolean());
|
||||
assertEquals(1, firstLayer.path("glyph_asset_id").asInt());
|
||||
assertEquals(2, firstLayer.path("tiles").get(0).path("palette_id").asInt());
|
||||
assertEquals(7, firstLayer.path("tiles").get(0).path("glyph_id").asInt());
|
||||
assertEquals(3, firstLayer.path("tiles").get(1).path("palette_id").asInt());
|
||||
assertEquals(9, firstLayer.path("tiles").get(1).path("glyph_id").asInt());
|
||||
assertTrue(firstLayer.path("tiles").get(1).path("flip_x").asBoolean());
|
||||
final JsonNode secondLayer = request.path("layers").get(1);
|
||||
assertFalse(secondLayer.path("active").asBoolean());
|
||||
assertEquals(1, secondLayer.path("glyph_asset_id").asInt());
|
||||
assertEquals(16, secondLayer.path("tile_size").asInt());
|
||||
}
|
||||
|
||||
private ProjectReference projectReference() {
|
||||
return new ProjectReference("main", "1", "pbs", 1, ProjectTarget.Game, tempDir.resolve("project"));
|
||||
}
|
||||
|
||||
private AssetWorkspaceAssetDetails createValidScene(ProjectReference project) throws Exception {
|
||||
final Path tilesetRoot = project.rootPath().resolve("assets/tilesets/overworld");
|
||||
Files.createDirectories(tilesetRoot);
|
||||
Files.writeString(tilesetRoot.resolve("a.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("asset.json"), """
|
||||
{
|
||||
"output": {
|
||||
"metadata": {
|
||||
"tile_size": "16x16"
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
final Path sceneRoot = project.rootPath().resolve("assets/scenes/overworld");
|
||||
Files.createDirectories(sceneRoot);
|
||||
return sceneDetails(sceneRoot);
|
||||
}
|
||||
|
||||
private AssetWorkspaceAssetDetails sceneDetails(Path assetRoot) {
|
||||
return new AssetWorkspaceAssetDetails(
|
||||
new AssetWorkspaceAssetSummary(
|
||||
AssetReference.forAssetId(2),
|
||||
"overworld_scene",
|
||||
AssetWorkspaceAssetState.REGISTERED,
|
||||
AssetWorkspaceBuildParticipation.EXCLUDED,
|
||||
2,
|
||||
AssetFamily.SCENE_BANK,
|
||||
AssetStudioGlyphSpecialization.NONE,
|
||||
assetRoot,
|
||||
false,
|
||||
false),
|
||||
List.of(),
|
||||
"SCENE_TILED_V1",
|
||||
"NONE",
|
||||
List.of("NONE"),
|
||||
Map.of("NONE", List.of()),
|
||||
List.of(new AssetConfigurationField(
|
||||
"tile_size",
|
||||
"Tile Size",
|
||||
"ENUM",
|
||||
"16x16",
|
||||
true,
|
||||
List.of("8x8", "16x16", "32x32"))),
|
||||
Map.of(),
|
||||
new AssetWorkspaceBankCompositionDetails(List.of(), List.of(), 0L),
|
||||
List.of(),
|
||||
null,
|
||||
new AssetStudioSceneBankMetadata(
|
||||
16,
|
||||
12,
|
||||
4,
|
||||
List.of(
|
||||
new AssetStudioSceneLayerBinding(
|
||||
true,
|
||||
1,
|
||||
"Ground",
|
||||
16,
|
||||
12,
|
||||
"ground.tmx",
|
||||
"tilesets/overworld",
|
||||
1.0f,
|
||||
1.0f,
|
||||
2,
|
||||
canonicalTiles(16, 12)),
|
||||
new AssetStudioSceneLayerBinding(false, 2, "Layer 2", 16, 12, "layer-2.tmx", "", 1.0f, 1.0f, 0),
|
||||
new AssetStudioSceneLayerBinding(false, 3, "Layer 3", 16, 12, "layer-3.tmx", "", 1.0f, 1.0f, 0),
|
||||
new AssetStudioSceneLayerBinding(false, 4, "Layer 4", 16, 12, "layer-4.tmx", "", 1.0f, 1.0f, 0)),
|
||||
assetRoot.resolve("scene-bank.studio.json")),
|
||||
AssetWorkspaceSceneBankValidation.NOT_APPLICABLE,
|
||||
List.of());
|
||||
}
|
||||
|
||||
private List<AssetStudioSceneTile> canonicalTiles(int width, int height) {
|
||||
final ArrayList<AssetStudioSceneTile> tiles = new ArrayList<>(width * height);
|
||||
tiles.add(new AssetStudioSceneTile(true, 7, 2, false, false));
|
||||
tiles.add(new AssetStudioSceneTile(true, 9, 3, true, false));
|
||||
while (tiles.size() < width * height) {
|
||||
tiles.add(AssetStudioSceneTile.inactive(2));
|
||||
}
|
||||
return List.copyOf(tiles);
|
||||
}
|
||||
}
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
package p.studio.core.assets.schema;
|
||||
|
||||
import p.studio.api.assets.workspace.*;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.api.assets.AssetReference;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import p.studio.api.assets.metadata.*;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
final class DefaultAssetColorSchemaSessionTest {
|
||||
private final DefaultAssetColorSchemaRules rules = new DefaultAssetColorSchemaRules();
|
||||
|
||||
@Test
|
||||
void createFlowExcludesTilesAlreadyBoundToAnotherSchema() {
|
||||
final DefaultAssetColorSchemaSession coordinator = session();
|
||||
final AssetWorkspaceBankCompositionFile tileA = tile("a.png", "artifact-a", "fp-a", List.of("#FF0000"));
|
||||
final AssetWorkspaceBankCompositionFile tileB = tile("b.png", "artifact-b", "fp-b", List.of("#00FF00"));
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tileA, tileB),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(),
|
||||
null)));
|
||||
|
||||
assertEquals(List.of(tileB), coordinator.availableTilesForCreate());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createFlowListsSelectedTilesBeforePaletteMetadataExists() {
|
||||
final DefaultAssetColorSchemaSession coordinator = session();
|
||||
final AssetWorkspaceBankCompositionFile tile = selectedArtifactOnly("a.png", "artifact-a", "fp-a");
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile),
|
||||
new AssetStudioGlyphMaterialMetadata(List.of(), List.of(), null)));
|
||||
|
||||
assertEquals(List.of(tile), coordinator.availableTilesForCreate());
|
||||
assertEquals(List.of(), rules.tileColors(tile));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tileColorsPreserveRgbaAlphaWhenAvailable() {
|
||||
final AssetWorkspaceBankCompositionFile tile = new AssetWorkspaceBankCompositionFile(
|
||||
"a.png",
|
||||
"a.png",
|
||||
64L,
|
||||
1L,
|
||||
"fp-a",
|
||||
Map.of(
|
||||
"artifactId", "artifact-a",
|
||||
"tile", Map.of("width", 8, "height", 8, "paletteIndices", List.of(0, 1)),
|
||||
"palette", Map.of("rgba8888", List.of(0x00000000, 0xFF0000FF))));
|
||||
|
||||
assertEquals(List.of("#00000000", "#FF0000"), rules.tileColors(tile));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createFlowUsesSelectedFingerprintWhenCurrentFileFingerprintIsMissing() {
|
||||
final DefaultAssetColorSchemaSession coordinator = session();
|
||||
final AssetWorkspaceBankCompositionFile tile = new AssetWorkspaceBankCompositionFile(
|
||||
"a.png",
|
||||
"a.png",
|
||||
64L,
|
||||
1L,
|
||||
null,
|
||||
Map.of(
|
||||
"artifactId", "artifact-a",
|
||||
"selectedFingerprint", "fp-a"));
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile),
|
||||
new AssetStudioGlyphMaterialMetadata(List.of(), List.of(), null)));
|
||||
|
||||
assertEquals(List.of(tile), coordinator.availableTilesForCreate());
|
||||
final AssetStudioGlyphMaterialMetadata metadata = coordinator.upsertSchema(
|
||||
"schema-1",
|
||||
List.of(tile),
|
||||
List.of("#FF0000"));
|
||||
assertEquals("fp-a", metadata.schemas().getFirst().artifactBindings().getFirst().fingerprint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateFlowKeepsCurrentTilesAndIncrementsVersionWhenSchemaChanges() {
|
||||
final DefaultAssetColorSchemaSession coordinator = session();
|
||||
final AssetWorkspaceBankCompositionFile tileA = tile("a.png", "artifact-a", "fp-a", List.of("#FF0000"));
|
||||
final AssetWorkspaceBankCompositionFile tileB = tile("b.png", "artifact-b", "fp-b", List.of("#00FF00"));
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tileA, tileB),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(),
|
||||
null)));
|
||||
|
||||
final AssetStudioGlyphMaterialMetadata updated = coordinator.upsertSchema(
|
||||
"schema-1",
|
||||
List.of(tileA, tileB),
|
||||
List.of("#FF0000", "#00FF00"));
|
||||
|
||||
final AssetStudioGlyphMaterialSchema schema = updated.schemas().getFirst();
|
||||
assertEquals(2, schema.version());
|
||||
assertEquals(Map.of(0, "#FF0000", 1, "#00FF00"), schema.materialIndices());
|
||||
assertEquals(List.of("artifact-a", "artifact-b"), schema.artifactBindings().stream().map(AssetStudioGlyphMaterialArtifactBinding::artifactId).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeIsBlockedWhenPalettesStillReferenceSchema() {
|
||||
final DefaultAssetColorSchemaSession coordinator = session();
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile("a.png", "artifact-a", "fp-a", List.of("#FF0000"))),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(new AssetStudioGlyphMaterialPalette("palette-1", "schema-1", 1, List.of("#FF0000"))),
|
||||
null)));
|
||||
|
||||
assertFalse(coordinator.canRemove("schema-1"));
|
||||
assertThrows(IllegalStateException.class, () -> coordinator.removeSchema("schema-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void effectiveStatusBecomesInconsistentWhenArtifactFingerprintDrifts() {
|
||||
final AssetStudioGlyphMaterialSchema schema = new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-old")));
|
||||
|
||||
assertEquals(
|
||||
AssetStudioGlyphMaterialSchemaStatus.INCONSISTENT,
|
||||
rules.effectiveStatus(
|
||||
schema,
|
||||
List.of(tile("a.png", "artifact-a", "fp-new", List.of("#FF0000", "#FF0001")))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void schemaUpdateCanRefreshOnlyFingerprintAndIncrementVersion() {
|
||||
final DefaultAssetColorSchemaSession coordinator = session();
|
||||
final AssetWorkspaceBankCompositionFile changedTile = tile("a.png", "artifact-a", "fp-new", List.of("#FF0000"));
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(changedTile),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(1, "#FF0000"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-old")))),
|
||||
List.of(),
|
||||
null)));
|
||||
|
||||
final AssetStudioGlyphMaterialSchema updated = coordinator.upsertSchema(
|
||||
"schema-1",
|
||||
List.of(changedTile),
|
||||
List.of("#FF0000")).schemas().getFirst();
|
||||
|
||||
assertEquals(2, updated.version());
|
||||
assertEquals(AssetStudioGlyphMaterialSchemaStatus.OK, updated.status());
|
||||
assertEquals("fp-new", updated.artifactBindings().getFirst().fingerprint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void editSessionOwnsDraftMovementColorDerivationAndReset() {
|
||||
final DefaultAssetColorSchemaSession coordinator = session();
|
||||
final AssetWorkspaceBankCompositionFile tileA = tile("a.png", "artifact-a", "fp-a", List.of("#FF0000"));
|
||||
final AssetWorkspaceBankCompositionFile tileB = tile("b.png", "artifact-b", "fp-b", List.of("#00FF00"));
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tileA, tileB),
|
||||
new AssetStudioGlyphMaterialMetadata(List.of(), List.of(), null)));
|
||||
|
||||
coordinator.beginEdit();
|
||||
coordinator.createSchema();
|
||||
assertEquals("schema-1", coordinator.state().schemaId());
|
||||
assertEquals(List.of(tileA, tileB), coordinator.state().availableTiles());
|
||||
|
||||
coordinator.moveToAssigned(List.of(tileA, tileB));
|
||||
assertEquals(List.of(tileA, tileB), coordinator.state().assignedTiles());
|
||||
assertEquals(List.of("#FF0000", "#00FF00"), coordinator.state().orderedColors());
|
||||
assertTrue(coordinator.state().dirty());
|
||||
|
||||
coordinator.reset();
|
||||
assertFalse(coordinator.state().selected());
|
||||
assertFalse(coordinator.state().dirty());
|
||||
assertTrue(coordinator.state().editing());
|
||||
|
||||
coordinator.cancel();
|
||||
assertFalse(coordinator.state().editing());
|
||||
}
|
||||
|
||||
@Test
|
||||
void editSessionOwnsExistingSchemaRemovalState() {
|
||||
final DefaultAssetColorSchemaSession coordinator = session();
|
||||
final AssetWorkspaceBankCompositionFile tile = tile("a.png", "artifact-a", "fp-a", List.of("#FF0000"));
|
||||
coordinator.replaceDetails(details(
|
||||
List.of(tile),
|
||||
new AssetStudioGlyphMaterialMetadata(
|
||||
List.of(new AssetStudioGlyphMaterialSchema(
|
||||
"schema-1",
|
||||
AssetStudioGlyphMaterialSchemaStatus.OK,
|
||||
1,
|
||||
Map.of(0, "#FF0000"),
|
||||
List.of(new AssetStudioGlyphMaterialArtifactBinding("artifact-a", "fp-a")))),
|
||||
List.of(),
|
||||
null)));
|
||||
|
||||
coordinator.beginEdit();
|
||||
coordinator.selectSchema("schema-1");
|
||||
assertTrue(coordinator.state().existingSchema());
|
||||
assertEquals(List.of(tile), coordinator.state().assignedTiles());
|
||||
|
||||
coordinator.markSelectedSchemaForRemoval();
|
||||
assertTrue(coordinator.state().removeRequested());
|
||||
assertTrue(coordinator.state().dirty());
|
||||
}
|
||||
|
||||
private AssetWorkspaceAssetDetails details(
|
||||
List<AssetWorkspaceBankCompositionFile> selectedTiles,
|
||||
AssetStudioGlyphMaterialMetadata metadata) {
|
||||
return new AssetWorkspaceAssetDetails(
|
||||
new AssetWorkspaceAssetSummary(
|
||||
AssetReference.forAssetId(1),
|
||||
"glyph_bank",
|
||||
AssetWorkspaceAssetState.REGISTERED,
|
||||
AssetWorkspaceBuildParticipation.INCLUDED,
|
||||
1,
|
||||
AssetFamily.GLYPH_BANK,
|
||||
AssetStudioGlyphSpecialization.SPRITES,
|
||||
Path.of("/tmp/glyph"),
|
||||
false,
|
||||
false),
|
||||
List.of(),
|
||||
"GLYPH_INDEXED_V1",
|
||||
"NONE",
|
||||
List.of("NONE"),
|
||||
Map.of("NONE", List.of()),
|
||||
List.of(),
|
||||
Map.of(),
|
||||
new AssetWorkspaceBankCompositionDetails(List.of(), selectedTiles, 0L),
|
||||
List.of(),
|
||||
metadata,
|
||||
null,
|
||||
AssetWorkspaceSceneBankValidation.NOT_APPLICABLE,
|
||||
List.of());
|
||||
}
|
||||
|
||||
private DefaultAssetColorSchemaSession session() {
|
||||
return new DefaultAssetColorSchemaSession(rules);
|
||||
}
|
||||
|
||||
private AssetWorkspaceBankCompositionFile tile(String path, String artifactId, String fingerprint, List<String> colors) {
|
||||
final List<Integer> argb = colors.stream()
|
||||
.map(color -> Integer.parseUnsignedInt("FF" + color.substring(1), 16))
|
||||
.map(Integer::valueOf)
|
||||
.toList();
|
||||
return new AssetWorkspaceBankCompositionFile(
|
||||
path,
|
||||
path,
|
||||
64L,
|
||||
1L,
|
||||
fingerprint,
|
||||
Map.of(
|
||||
"artifactId", artifactId,
|
||||
"tile", Map.of("width", 8, "height", 8, "paletteIndices", List.of(1, 1, 1)),
|
||||
"palette", Map.of("originalArgb8888", argb, "rgba8888", List.of())));
|
||||
}
|
||||
|
||||
private AssetWorkspaceBankCompositionFile selectedArtifactOnly(String path, String artifactId, String fingerprint) {
|
||||
return new AssetWorkspaceBankCompositionFile(
|
||||
path,
|
||||
path,
|
||||
64L,
|
||||
1L,
|
||||
fingerprint,
|
||||
Map.of("artifactId", artifactId));
|
||||
}
|
||||
}
|
||||
+505
@@ -0,0 +1,505 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
import p.studio.api.assets.tiled.SceneTmxExportDisposition;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.assets.AssetConfigurationField;
|
||||
import p.studio.api.assets.AssetReference;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import p.studio.api.project.ProjectTarget;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.assets.workspace.*;
|
||||
import p.studio.api.assets.metadata.*;
|
||||
import p.studio.api.assets.tiled.TiledAssetGenerationResult;
|
||||
import p.studio.core.assets.metadata.AssetStudioMetadataService;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
final class TiledAssetGenerationServiceTest {
|
||||
private final AssetStudioMetadataService metadataService = new AssetStudioMetadataService();
|
||||
private final TiledAssetGenerationService service = new TiledAssetGenerationService(metadataService);
|
||||
private final TiledXmlCodec codec = new TiledXmlCodec();
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void exportsTsxForTilesetSpecializedGlyphBank() throws Exception {
|
||||
final Path assetRoot = tempDir.resolve("assets/tilesets/overworld");
|
||||
Files.createDirectories(assetRoot);
|
||||
Files.writeString(assetRoot.resolve("a.png"), "fixture");
|
||||
Files.writeString(assetRoot.resolve("b.png"), "fixture");
|
||||
|
||||
final TiledAssetGenerationResult result = service.exportTilesetTsx(tilesetDetails(assetRoot));
|
||||
|
||||
assertTrue(result.success());
|
||||
final Path tsxPath = assetRoot.resolve(TiledAssetGenerationService.GENERATED_TSX_FILE);
|
||||
assertTrue(Files.isRegularFile(tsxPath));
|
||||
final TiledTilesetDocument tileset = codec.readTileset(tsxPath);
|
||||
assertEquals(2, tileset.tiles().size());
|
||||
assertEquals("a.png", tileset.tiles().getFirst().imageSource());
|
||||
assertEquals("glyph_id", tileset.tiles().getFirst().properties().getFirst().name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void exportsSingleSceneTmxFromCanonicalState() throws Exception {
|
||||
final Path projectRoot = tempDir.resolve("project");
|
||||
final Path tilesetRoot = projectRoot.resolve("assets/tilesets/overworld");
|
||||
Files.createDirectories(tilesetRoot);
|
||||
Files.writeString(tilesetRoot.resolve("a.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("b.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("asset.json"), """
|
||||
{
|
||||
"output": {
|
||||
"metadata": {
|
||||
"tile_size": "16x16"
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
assertTrue(service.exportTilesetTsx(tilesetDetails(tilesetRoot)).success());
|
||||
|
||||
final Path sceneRoot = projectRoot.resolve("assets/scenes/overworld");
|
||||
Files.createDirectories(sceneRoot);
|
||||
final AssetWorkspaceAssetDetails details = sceneDetails(sceneRoot);
|
||||
final ProjectReference projectReference = new ProjectReference("main", "1", "pbs", 1, ProjectTarget.Game, projectRoot);
|
||||
|
||||
final TiledAssetGenerationResult result = service.exportSceneBankTmx(projectReference, details);
|
||||
|
||||
assertTrue(result.success());
|
||||
final Path tmxPath = sceneRoot.resolve("scene.tmx");
|
||||
assertTrue(Files.isRegularFile(tmxPath));
|
||||
final TiledMapDocument map = codec.readMap(tmxPath);
|
||||
assertEquals("../../tilesets/overworld/tileset.tsx", map.tilesets().getFirst().source());
|
||||
assertEquals(2, map.tileLayers().size());
|
||||
assertEquals("Ground", map.tileLayers().getFirst().name());
|
||||
assertEquals(1L, map.tileLayers().getFirst().gids().getFirst());
|
||||
}
|
||||
|
||||
@Test
|
||||
void exportsSceneTmxKeepingExistingFileAsBackup() throws Exception {
|
||||
final Path projectRoot = tempDir.resolve("project-export-backup");
|
||||
final Path tilesetRoot = projectRoot.resolve("assets/tilesets/overworld");
|
||||
Files.createDirectories(tilesetRoot);
|
||||
Files.writeString(tilesetRoot.resolve("a.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("b.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("asset.json"), """
|
||||
{
|
||||
"output": {
|
||||
"metadata": {
|
||||
"tile_size": "16x16"
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
assertTrue(service.exportTilesetTsx(tilesetDetails(tilesetRoot)).success());
|
||||
|
||||
final Path sceneRoot = projectRoot.resolve("assets/scenes/overworld");
|
||||
Files.createDirectories(sceneRoot);
|
||||
final AssetWorkspaceAssetDetails details = sceneDetails(sceneRoot);
|
||||
final ProjectReference projectReference = new ProjectReference("main", "1", "pbs", 1, ProjectTarget.Game, projectRoot);
|
||||
|
||||
final Path tmxPath = sceneRoot.resolve("scene.tmx");
|
||||
Files.writeString(tmxPath, "legacy");
|
||||
|
||||
final TiledAssetGenerationResult result = service.exportSceneBankTmx(
|
||||
projectReference,
|
||||
details,
|
||||
SceneTmxExportDisposition.KEEP_BOTH);
|
||||
|
||||
assertTrue(result.success());
|
||||
final Path backupPath = sceneRoot.resolve("scene.bkp-1.tmx");
|
||||
assertTrue(Files.isRegularFile(backupPath));
|
||||
assertEquals("legacy", Files.readString(backupPath));
|
||||
assertNotEquals("legacy", Files.readString(tmxPath));
|
||||
assertTrue(result.writtenFiles().contains(backupPath));
|
||||
assertTrue(result.writtenFiles().contains(tmxPath));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importsSceneTmxIntoCanonicalTiles() throws Exception {
|
||||
final Path projectRoot = tempDir.resolve("project-import");
|
||||
final Path tilesetRoot = projectRoot.resolve("assets/tilesets/overworld");
|
||||
Files.createDirectories(tilesetRoot);
|
||||
Files.writeString(tilesetRoot.resolve("a.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("b.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("asset.json"), """
|
||||
{
|
||||
"output": {
|
||||
"metadata": {
|
||||
"tile_size": "16x16"
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
assertTrue(service.exportTilesetTsx(tilesetDetails(tilesetRoot)).success());
|
||||
|
||||
final Path sceneRoot = projectRoot.resolve("assets/scenes/overworld");
|
||||
Files.createDirectories(sceneRoot);
|
||||
final AssetWorkspaceAssetDetails details = sceneDetails(sceneRoot);
|
||||
final ProjectReference projectReference = new ProjectReference("main", "1", "pbs", 1, ProjectTarget.Game, projectRoot);
|
||||
assertTrue(service.exportSceneBankTmx(projectReference, details).success());
|
||||
|
||||
final Path tmxPath = sceneRoot.resolve("scene.tmx");
|
||||
Files.writeString(tmxPath, Files.readString(tmxPath).replaceFirst("1,0,0,0", "2147483650,0,0,0"));
|
||||
|
||||
final TiledAssetGenerationResult result = service.importSceneBankTmx(projectReference, details);
|
||||
|
||||
assertTrue(result.success());
|
||||
final AssetStudioMetadataService metadataService = new AssetStudioMetadataService();
|
||||
final var snapshot = metadataService.read(sceneRoot, AssetFamily.SCENE_BANK);
|
||||
assertNotNull(snapshot.sceneBankMetadata());
|
||||
assertTrue(snapshot.sceneBankMetadata().layerBindings().getFirst().tiles().getFirst().active());
|
||||
assertEquals(1, snapshot.sceneBankMetadata().layerBindings().getFirst().tiles().getFirst().glyphId());
|
||||
assertTrue(snapshot.sceneBankMetadata().layerBindings().getFirst().tiles().getFirst().flipX());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importsSceneTmxUsingGlyphIdPropertyFromTsx() throws Exception {
|
||||
final Path projectRoot = tempDir.resolve("project-import-glyph-property");
|
||||
final Path tilesetRoot = projectRoot.resolve("assets/tilesets/overworld");
|
||||
Files.createDirectories(tilesetRoot);
|
||||
Files.writeString(tilesetRoot.resolve("a.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("b.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("asset.json"), """
|
||||
{
|
||||
"output": {
|
||||
"metadata": {
|
||||
"tile_size": "16x16"
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
assertTrue(service.exportTilesetTsx(tilesetDetails(tilesetRoot)).success());
|
||||
|
||||
final Path sceneRoot = projectRoot.resolve("assets/scenes/overworld");
|
||||
Files.createDirectories(sceneRoot);
|
||||
final AssetWorkspaceAssetDetails details = sceneDetails(sceneRoot);
|
||||
final ProjectReference projectReference = new ProjectReference("main", "1", "pbs", 1, ProjectTarget.Game, projectRoot);
|
||||
assertTrue(service.exportSceneBankTmx(projectReference, details).success());
|
||||
|
||||
final Path tsxPath = tilesetRoot.resolve(TiledAssetGenerationService.GENERATED_TSX_FILE);
|
||||
Files.writeString(tsxPath, Files.readString(tsxPath)
|
||||
.replace("value=\"0\"", "value=\"7\"")
|
||||
.replace("value=\"1\"", "value=\"3\""));
|
||||
|
||||
final Path tmxPath = sceneRoot.resolve("scene.tmx");
|
||||
Files.writeString(tmxPath, Files.readString(tmxPath).replaceFirst("1,0,0,0", "2,0,0,0"));
|
||||
|
||||
final TiledAssetGenerationResult result = service.importSceneBankTmx(projectReference, details);
|
||||
|
||||
assertTrue(result.success());
|
||||
final AssetStudioMetadataService metadataService = new AssetStudioMetadataService();
|
||||
final var snapshot = metadataService.read(sceneRoot, AssetFamily.SCENE_BANK);
|
||||
assertNotNull(snapshot.sceneBankMetadata());
|
||||
assertEquals(3, snapshot.sceneBankMetadata().layerBindings().getFirst().tiles().getFirst().glyphId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importsSceneTmxAndPropagatesLayerDimensionsFromTmx() throws Exception {
|
||||
final Path projectRoot = tempDir.resolve("project-import-resize");
|
||||
final Path tilesetRoot = projectRoot.resolve("assets/tilesets/overworld");
|
||||
Files.createDirectories(tilesetRoot);
|
||||
Files.writeString(tilesetRoot.resolve("a.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("b.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("asset.json"), """
|
||||
{
|
||||
"output": {
|
||||
"metadata": {
|
||||
"tile_size": "16x16"
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
assertTrue(service.exportTilesetTsx(tilesetDetails(tilesetRoot)).success());
|
||||
|
||||
final Path sceneRoot = projectRoot.resolve("assets/scenes/overworld");
|
||||
Files.createDirectories(sceneRoot);
|
||||
final AssetWorkspaceAssetDetails details = sceneDetails(sceneRoot);
|
||||
final ProjectReference projectReference = new ProjectReference("main", "1", "pbs", 1, ProjectTarget.Game, projectRoot);
|
||||
assertTrue(service.exportSceneBankTmx(projectReference, details).success());
|
||||
|
||||
final Path tmxPath = sceneRoot.resolve("scene.tmx");
|
||||
final String resizedTmx = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<map version="1.10" tiledversion="1.12.1" orientation="orthogonal" renderorder="right-down" width="6" height="5" tilewidth="16" tileheight="16" infinite="0" nextlayerid="3" nextobjectid="1">
|
||||
<tileset firstgid="1" source="../../tilesets/overworld/tileset.tsx"/>
|
||||
<layer id="1" name="Ground" width="6" height="5">
|
||||
<data encoding="csv">
|
||||
1,0,0,0,0,0,
|
||||
0,0,0,0,0,0,
|
||||
0,0,0,0,0,0,
|
||||
0,0,0,0,0,0,
|
||||
0,0,0,0,0,0
|
||||
</data>
|
||||
</layer>
|
||||
<layer id="2" name="Decor" width="3" height="2">
|
||||
<data encoding="csv">
|
||||
2,0,0,
|
||||
0,0,0
|
||||
</data>
|
||||
</layer>
|
||||
</map>
|
||||
""";
|
||||
Files.writeString(tmxPath, resizedTmx);
|
||||
|
||||
final TiledAssetGenerationResult result = service.importSceneBankTmx(projectReference, details);
|
||||
|
||||
assertTrue(result.success());
|
||||
final AssetStudioMetadataService metadataService = new AssetStudioMetadataService();
|
||||
final var snapshot = metadataService.read(sceneRoot, AssetFamily.SCENE_BANK);
|
||||
assertNotNull(snapshot.sceneBankMetadata());
|
||||
assertEquals(6, snapshot.sceneBankMetadata().mapWidth());
|
||||
assertEquals(5, snapshot.sceneBankMetadata().mapHeight());
|
||||
assertEquals(6, snapshot.sceneBankMetadata().layerBindings().get(0).width());
|
||||
assertEquals(5, snapshot.sceneBankMetadata().layerBindings().get(0).height());
|
||||
assertEquals(3, snapshot.sceneBankMetadata().layerBindings().get(1).width());
|
||||
assertEquals(2, snapshot.sceneBankMetadata().layerBindings().get(1).height());
|
||||
assertEquals(30, snapshot.sceneBankMetadata().layerBindings().get(0).tiles().size());
|
||||
assertEquals(6, snapshot.sceneBankMetadata().layerBindings().get(1).tiles().size());
|
||||
assertEquals("Ground", snapshot.sceneBankMetadata().layerBindings().get(0).layerName());
|
||||
assertEquals("Decor", snapshot.sceneBankMetadata().layerBindings().get(1).layerName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importsSceneTmxAndPromotesNewLayerIntoDisabledStudioSlot() throws Exception {
|
||||
final Path projectRoot = tempDir.resolve("project-import-new-layer");
|
||||
final Path tilesetRoot = projectRoot.resolve("assets/tilesets/overworld");
|
||||
Files.createDirectories(tilesetRoot);
|
||||
Files.writeString(tilesetRoot.resolve("a.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("b.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("asset.json"), """
|
||||
{
|
||||
"output": {
|
||||
"metadata": {
|
||||
"tile_size": "16x16"
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
assertTrue(service.exportTilesetTsx(tilesetDetails(tilesetRoot)).success());
|
||||
|
||||
final Path sceneRoot = projectRoot.resolve("assets/scenes/overworld");
|
||||
Files.createDirectories(sceneRoot);
|
||||
final AssetWorkspaceAssetDetails details = sceneDetails(sceneRoot);
|
||||
final ProjectReference projectReference = new ProjectReference("main", "1", "pbs", 1, ProjectTarget.Game, projectRoot);
|
||||
assertTrue(service.exportSceneBankTmx(projectReference, details).success());
|
||||
|
||||
final Path tmxPath = sceneRoot.resolve("scene.tmx");
|
||||
final String expandedTmx = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<map version="1.10" tiledversion="1.12.1" orientation="orthogonal" renderorder="right-down" width="4" height="4" tilewidth="16" tileheight="16" infinite="0" nextlayerid="4" nextobjectid="1">
|
||||
<tileset firstgid="1" source="../../tilesets/overworld/tileset.tsx"/>
|
||||
<layer id="1" name="Ground" width="4" height="4">
|
||||
<data encoding="csv">
|
||||
1,0,0,0,
|
||||
0,0,0,0,
|
||||
0,0,0,0,
|
||||
0,0,0,0
|
||||
</data>
|
||||
</layer>
|
||||
<layer id="2" name="Decor" width="4" height="4">
|
||||
<data encoding="csv">
|
||||
2,0,0,0,
|
||||
0,0,0,0,
|
||||
0,0,0,0,
|
||||
0,0,0,0
|
||||
</data>
|
||||
</layer>
|
||||
<layer id="3" name="Collision" width="2" height="2">
|
||||
<data encoding="csv">
|
||||
1,0,
|
||||
0,0
|
||||
</data>
|
||||
</layer>
|
||||
</map>
|
||||
""";
|
||||
Files.writeString(tmxPath, expandedTmx);
|
||||
|
||||
final TiledAssetGenerationResult result = service.importSceneBankTmx(projectReference, details);
|
||||
|
||||
assertTrue(result.success());
|
||||
final AssetStudioMetadataService metadataService = new AssetStudioMetadataService();
|
||||
final var snapshot = metadataService.read(sceneRoot, AssetFamily.SCENE_BANK);
|
||||
assertNotNull(snapshot.sceneBankMetadata());
|
||||
assertEquals(3, snapshot.sceneBankMetadata().enabledLayerCount());
|
||||
assertTrue(snapshot.sceneBankMetadata().layerBindings().get(2).enabled());
|
||||
assertEquals("Layer 3", snapshot.sceneBankMetadata().layerBindings().get(2).layerName());
|
||||
assertEquals("tilesets/overworld", snapshot.sceneBankMetadata().layerBindings().get(2).tilesetAssetRoot());
|
||||
assertEquals(2, snapshot.sceneBankMetadata().layerBindings().get(2).width());
|
||||
assertEquals(2, snapshot.sceneBankMetadata().layerBindings().get(2).height());
|
||||
assertEquals(0, snapshot.sceneBankMetadata().layerBindings().get(2).tiles().getFirst().glyphId());
|
||||
assertFalse(snapshot.sceneBankMetadata().layerBindings().get(3).enabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsSceneTmxImportWithoutTileLayers() throws Exception {
|
||||
final Path projectRoot = tempDir.resolve("project-import-no-layers");
|
||||
final Path tilesetRoot = projectRoot.resolve("assets/tilesets/overworld");
|
||||
Files.createDirectories(tilesetRoot);
|
||||
Files.writeString(tilesetRoot.resolve("a.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("b.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("asset.json"), """
|
||||
{
|
||||
"output": {
|
||||
"metadata": {
|
||||
"tile_size": "16x16"
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
assertTrue(service.exportTilesetTsx(tilesetDetails(tilesetRoot)).success());
|
||||
|
||||
final Path sceneRoot = projectRoot.resolve("assets/scenes/overworld");
|
||||
Files.createDirectories(sceneRoot);
|
||||
final AssetWorkspaceAssetDetails details = sceneDetails(sceneRoot);
|
||||
final ProjectReference projectReference = new ProjectReference("main", "1", "pbs", 1, ProjectTarget.Game, projectRoot);
|
||||
|
||||
final Path tmxPath = sceneRoot.resolve("scene.tmx");
|
||||
Files.writeString(tmxPath, """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<map version="1.10" tiledversion="1.12.1" orientation="orthogonal" renderorder="right-down" width="4" height="4" tilewidth="16" tileheight="16" infinite="0" nextlayerid="1" nextobjectid="1">
|
||||
<tileset firstgid="1" source="../../tilesets/overworld/tileset.tsx"/>
|
||||
</map>
|
||||
""");
|
||||
|
||||
final TiledAssetGenerationResult result = service.importSceneBankTmx(projectReference, details);
|
||||
|
||||
assertFalse(result.success());
|
||||
assertEquals("TMX import rejected: at least one tile layer is required.", result.message());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsSceneTmxImportWithMoreThanFourTileLayers() throws Exception {
|
||||
final Path projectRoot = tempDir.resolve("project-import-too-many-layers");
|
||||
final Path tilesetRoot = projectRoot.resolve("assets/tilesets/overworld");
|
||||
Files.createDirectories(tilesetRoot);
|
||||
Files.writeString(tilesetRoot.resolve("a.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("b.png"), "fixture");
|
||||
Files.writeString(tilesetRoot.resolve("asset.json"), """
|
||||
{
|
||||
"output": {
|
||||
"metadata": {
|
||||
"tile_size": "16x16"
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
assertTrue(service.exportTilesetTsx(tilesetDetails(tilesetRoot)).success());
|
||||
|
||||
final Path sceneRoot = projectRoot.resolve("assets/scenes/overworld");
|
||||
Files.createDirectories(sceneRoot);
|
||||
final AssetWorkspaceAssetDetails details = sceneDetails(sceneRoot);
|
||||
final ProjectReference projectReference = new ProjectReference("main", "1", "pbs", 1, ProjectTarget.Game, projectRoot);
|
||||
|
||||
final Path tmxPath = sceneRoot.resolve("scene.tmx");
|
||||
Files.writeString(tmxPath, """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<map version="1.10" tiledversion="1.12.1" orientation="orthogonal" renderorder="right-down" width="4" height="4" tilewidth="16" tileheight="16" infinite="0" nextlayerid="6" nextobjectid="1">
|
||||
<tileset firstgid="1" source="../../tilesets/overworld/tileset.tsx"/>
|
||||
<layer id="1" name="A" width="4" height="4"><data encoding="csv">1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</data></layer>
|
||||
<layer id="2" name="B" width="4" height="4"><data encoding="csv">1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</data></layer>
|
||||
<layer id="3" name="C" width="4" height="4"><data encoding="csv">1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</data></layer>
|
||||
<layer id="4" name="D" width="4" height="4"><data encoding="csv">1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</data></layer>
|
||||
<layer id="5" name="E" width="4" height="4"><data encoding="csv">1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</data></layer>
|
||||
</map>
|
||||
""");
|
||||
|
||||
final TiledAssetGenerationResult result = service.importSceneBankTmx(projectReference, details);
|
||||
|
||||
assertFalse(result.success());
|
||||
assertEquals("TMX import rejected: more than four tile layers are not supported.", result.message());
|
||||
}
|
||||
|
||||
private AssetWorkspaceAssetDetails tilesetDetails(Path assetRoot) {
|
||||
return new AssetWorkspaceAssetDetails(
|
||||
new AssetWorkspaceAssetSummary(
|
||||
AssetReference.forAssetId(1),
|
||||
"overworld_tileset",
|
||||
AssetWorkspaceAssetState.REGISTERED,
|
||||
AssetWorkspaceBuildParticipation.INCLUDED,
|
||||
1,
|
||||
AssetFamily.GLYPH_BANK,
|
||||
AssetStudioGlyphSpecialization.TILESET,
|
||||
assetRoot,
|
||||
false,
|
||||
false),
|
||||
List.of(),
|
||||
"GLYPH_INDEXED_V1",
|
||||
"NONE",
|
||||
List.of("NONE"),
|
||||
Map.of("NONE", List.of()),
|
||||
List.of(new AssetConfigurationField(
|
||||
"tile_size",
|
||||
"Tile Size",
|
||||
"ENUM",
|
||||
"16x16",
|
||||
true,
|
||||
List.of("8x8", "16x16", "32x32"))),
|
||||
Map.of(),
|
||||
new AssetWorkspaceBankCompositionDetails(
|
||||
List.of(),
|
||||
List.of(
|
||||
new AssetWorkspaceBankCompositionFile("a.png", "a.png", 1L, 1L, null, Map.of()),
|
||||
new AssetWorkspaceBankCompositionFile("b.png", "b.png", 1L, 1L, null, Map.of())),
|
||||
0L),
|
||||
List.of(),
|
||||
null,
|
||||
null,
|
||||
AssetWorkspaceSceneBankValidation.NOT_APPLICABLE,
|
||||
List.of());
|
||||
}
|
||||
|
||||
private AssetWorkspaceAssetDetails sceneDetails(Path assetRoot) {
|
||||
return new AssetWorkspaceAssetDetails(
|
||||
new AssetWorkspaceAssetSummary(
|
||||
AssetReference.forAssetId(2),
|
||||
"overworld_scene",
|
||||
AssetWorkspaceAssetState.REGISTERED,
|
||||
AssetWorkspaceBuildParticipation.EXCLUDED,
|
||||
2,
|
||||
AssetFamily.SCENE_BANK,
|
||||
AssetStudioGlyphSpecialization.NONE,
|
||||
assetRoot,
|
||||
false,
|
||||
false),
|
||||
List.of(),
|
||||
"SCENE_TILED_V1",
|
||||
"NONE",
|
||||
List.of("NONE"),
|
||||
Map.of("NONE", List.of()),
|
||||
List.of(),
|
||||
Map.of(),
|
||||
new AssetWorkspaceBankCompositionDetails(List.of(), List.of(), 0L),
|
||||
List.of(),
|
||||
null,
|
||||
new AssetStudioSceneBankMetadata(
|
||||
4,
|
||||
4,
|
||||
4,
|
||||
List.of(
|
||||
new AssetStudioSceneLayerBinding(true, 1, "Ground", 4, 4, "scene.tmx", "tilesets/overworld", 1.0f, 1.0f, 0, canonicalTiles(4, 4, 0)),
|
||||
new AssetStudioSceneLayerBinding(true, 2, "Decor", 4, 4, "scene.tmx", "tilesets/overworld", 1.0f, 1.0f, 0, canonicalTiles(4, 4, 1)),
|
||||
new AssetStudioSceneLayerBinding(false, 3, "Layer 3", 4, 4, "scene.tmx", "", 1.0f, 1.0f, 0),
|
||||
new AssetStudioSceneLayerBinding(false, 4, "Layer 4", 4, 4, "scene.tmx", "", 1.0f, 1.0f, 0)),
|
||||
assetRoot.resolve("scene-bank.studio.json")),
|
||||
AssetWorkspaceSceneBankValidation.NOT_APPLICABLE,
|
||||
List.of());
|
||||
}
|
||||
|
||||
private List<AssetStudioSceneTile> canonicalTiles(int width, int height, int glyphId) {
|
||||
final ArrayList<AssetStudioSceneTile> tiles = new ArrayList<>(width * height);
|
||||
tiles.add(new AssetStudioSceneTile(true, glyphId, 0, false, false));
|
||||
while (tiles.size() < width * height) {
|
||||
tiles.add(AssetStudioSceneTile.inactive(0));
|
||||
}
|
||||
return List.copyOf(tiles);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package p.studio.core.assets.tiled;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
final class TiledXmlCodecTest {
|
||||
private final TiledXmlCodec codec = new TiledXmlCodec();
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void readsFixtureTmxAndPreservesWaveOneSurfaces() throws Exception {
|
||||
final TiledMapDocument map = codec.readMap(Path.of("..", "test-projects", "main", "assets", "scenes", "primeiro mapa.tmx").toAbsolutePath().normalize());
|
||||
|
||||
assertEquals(25, map.width());
|
||||
assertEquals(25, map.height());
|
||||
assertEquals(1, map.tilesets().size());
|
||||
assertEquals("../Zelda3/primeiro tileset.tsx", map.tilesets().getFirst().source());
|
||||
assertEquals(1, map.tileLayers().size());
|
||||
assertEquals(625, map.tileLayers().getFirst().gids().size());
|
||||
assertEquals(1, map.objectLayers().size());
|
||||
assertEquals(9, map.objectLayers().getFirst().objects().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsFixtureTsxWithPropertiesAndCollisionObjects() throws Exception {
|
||||
final TiledTilesetDocument tileset = codec.readTileset(Path.of("..", "test-projects", "main", "assets", "Zelda3", "primeiro tileset.tsx").toAbsolutePath().normalize());
|
||||
|
||||
assertEquals(32, tileset.tileWidth());
|
||||
assertEquals(32, tileset.tileHeight());
|
||||
assertEquals(13, tileset.tileCount());
|
||||
assertEquals(13, tileset.tiles().size());
|
||||
assertEquals("glyph_id", tileset.tiles().getFirst().properties().getFirst().name());
|
||||
assertNotNull(tileset.tiles().getFirst().collisionLayer());
|
||||
assertEquals(2, tileset.tiles().getFirst().collisionLayer().objects().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUnsupportedInfiniteMaps() throws Exception {
|
||||
final Path path = tempDir.resolve("infinite.tmx");
|
||||
Files.writeString(path, """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<map version="1.10" tiledversion="1.12.1" orientation="orthogonal" renderorder="right-down"
|
||||
width="10" height="10" tilewidth="16" tileheight="16" infinite="1"/>
|
||||
""");
|
||||
|
||||
assertThrows(TiledUnsupportedFeatureException.class, () -> codec.readMap(path));
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package p.studio.core.execution;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.api.execution.ExecutionLogSeverity;
|
||||
import p.studio.api.execution.ExecutionLogSource;
|
||||
import p.studio.api.execution.ExecutionSnapshot;
|
||||
import p.studio.api.execution.ExecutionState;
|
||||
import p.studio.api.shipper.ShipperLogEntry;
|
||||
import p.studio.api.shipper.ShipperLogSeverity;
|
||||
import p.studio.api.shipper.ShipperLogSource;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
final class DefaultExecutionSessionTest {
|
||||
@Test
|
||||
void enforcesStateMachineAndPreservesLogIdentity() {
|
||||
final var session = new DefaultExecutionSession();
|
||||
final Instant now = Instant.parse("2026-04-06T10:15:30Z");
|
||||
assertEquals(ExecutionState.IDLE, session.snapshot().state());
|
||||
assertThrows(IllegalStateException.class, session::transitionToRunning);
|
||||
|
||||
session.beginPreparationCycle();
|
||||
session.appendShipperLog(new ShipperLogEntry(ShipperLogSource.BUILD, ShipperLogSeverity.INFO, "Compiler started", now));
|
||||
session.appendRuntimeLog(ExecutionLogSeverity.ERROR, "Runtime failed", now.plusSeconds(1));
|
||||
session.transitionToPrepareFailed();
|
||||
|
||||
assertEquals(ExecutionState.PREPARE_FAILED, session.snapshot().state());
|
||||
assertEquals(ExecutionLogSource.BUILD, session.snapshot().logs().get(0).source());
|
||||
assertEquals(ExecutionLogSource.RUNTIME, session.snapshot().logs().get(1).source());
|
||||
assertEquals(2L, session.snapshot().logs().get(1).sequence());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishesImmutableSnapshotsAndCanUnsubscribe() {
|
||||
final var session = new DefaultExecutionSession();
|
||||
final ArrayList<ExecutionSnapshot> snapshots = new ArrayList<>();
|
||||
final var subscription = session.subscribe(snapshots::add);
|
||||
session.beginPreparationCycle();
|
||||
subscription.close();
|
||||
session.transitionToPrepareFailed();
|
||||
assertEquals(2, snapshots.size());
|
||||
assertEquals(ExecutionState.IDLE, snapshots.getFirst().state());
|
||||
assertEquals(ExecutionState.PREPARING, snapshots.getLast().state());
|
||||
}
|
||||
}
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
package p.studio.core.execution;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.api.execution.ExecutionState;
|
||||
import p.studio.api.project.ProjectLocalStudioSetup;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.project.ProjectTarget;
|
||||
import p.studio.api.runtime.RuntimeLogEntry;
|
||||
import p.studio.api.shipper.Shipper;
|
||||
import p.studio.api.shipper.ShipperPreparationStatus;
|
||||
import p.studio.api.shipper.ShipperPrepareResult;
|
||||
import p.studio.core.runtime.RuntimeConnection;
|
||||
import p.studio.core.runtime.RuntimeGateway;
|
||||
import p.studio.api.operation.OperationExecutor;
|
||||
import p.studio.api.operation.OperationHandle;
|
||||
import p.studio.api.operation.OperationId;
|
||||
import p.studio.api.operation.OperationSnapshot;
|
||||
import p.studio.api.operation.OperationState;
|
||||
import p.studio.api.operation.OperationSubscription;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
final class PlayStopExecutionControllerTest {
|
||||
private static final OperationExecutor OPERATIONS = new ImmediateOperationExecutor();
|
||||
|
||||
@Test
|
||||
void successfulPreparationStartsRuntimeAndProjectsExit() {
|
||||
final var session = new DefaultExecutionSession();
|
||||
final var completion = new CompletableFuture<Integer>();
|
||||
final RuntimeGateway runtime = (project, setup, logs) -> {
|
||||
logs.accept(RuntimeLogEntry.info("connected"));
|
||||
return connection(completion);
|
||||
};
|
||||
final var controller = new PlayStopExecutionController(project(), ProjectLocalStudioSetup.defaults(),
|
||||
session, successfulShipper(), runtime, OPERATIONS);
|
||||
|
||||
controller.play();
|
||||
assertEquals(ExecutionState.RUNNING, session.snapshot().state());
|
||||
completion.complete(0);
|
||||
assertEquals(ExecutionState.STOPPED, session.snapshot().state());
|
||||
}
|
||||
|
||||
@Test
|
||||
void preparationFailureDoesNotStartRuntime() {
|
||||
final var session = new DefaultExecutionSession();
|
||||
final RuntimeGateway runtime = (project, setup, logs) -> { throw new AssertionError("must not start"); };
|
||||
final Shipper shipper = (project, logs) -> OPERATIONS.submit("prepare", () -> new ShipperPrepareResult(
|
||||
ShipperPreparationStatus.FAILED, List.of(), null, List.of(), List.of()));
|
||||
final var controller = new PlayStopExecutionController(project(), ProjectLocalStudioSetup.defaults(),
|
||||
session, shipper, runtime, OPERATIONS);
|
||||
|
||||
controller.play();
|
||||
assertEquals(ExecutionState.PREPARE_FAILED, session.snapshot().state());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopCancelsPreparationAndExecutionOperations() throws Exception {
|
||||
final var session = new DefaultExecutionSession();
|
||||
final var preparationStarted = new CountDownLatch(1);
|
||||
final var releasePreparation = new CountDownLatch(1);
|
||||
final RuntimeGateway runtime = (project, setup, logs) -> {
|
||||
throw new AssertionError("runtime must not start after cancellation");
|
||||
};
|
||||
try (var operations = new AsyncOperationExecutor()) {
|
||||
final Shipper shipper = (project, logs) -> operations.submit("prepare", () -> {
|
||||
preparationStarted.countDown();
|
||||
releasePreparation.await();
|
||||
return new ShipperPrepareResult(
|
||||
ShipperPreparationStatus.SUCCESS, List.of(), Path.of("manifest.json"), List.of(), List.of());
|
||||
});
|
||||
final var controller = new PlayStopExecutionController(project(), ProjectLocalStudioSetup.defaults(),
|
||||
session, shipper, runtime, operations);
|
||||
|
||||
final OperationHandle<?> execution = controller.play();
|
||||
assertTrue(preparationStarted.await(2, TimeUnit.SECONDS));
|
||||
controller.stop();
|
||||
|
||||
assertEquals(ExecutionState.STOPPED, session.snapshot().state());
|
||||
assertEquals(OperationState.CANCELLED, execution.snapshot().state());
|
||||
releasePreparation.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
private static Shipper successfulShipper() {
|
||||
return (project, logs) -> OPERATIONS.submit("prepare", () -> new ShipperPrepareResult(
|
||||
ShipperPreparationStatus.SUCCESS, List.of(), Path.of("manifest.json"), List.of(), List.of()));
|
||||
}
|
||||
|
||||
private static RuntimeConnection connection(CompletableFuture<Integer> completion) {
|
||||
return new RuntimeConnection() {
|
||||
@Override public CompletableFuture<Integer> completion() { return completion; }
|
||||
@Override public void close() { completion.complete(-1); }
|
||||
};
|
||||
}
|
||||
|
||||
private static ProjectReference project() {
|
||||
return new ProjectReference("Example", "1", "pbs", 1, ProjectTarget.Game, Path.of("."));
|
||||
}
|
||||
|
||||
private static final class ImmediateOperationExecutor implements OperationExecutor {
|
||||
@Override
|
||||
public <R> OperationHandle<R> submit(String summary, Callable<R> operation) {
|
||||
try {
|
||||
return new CompletedOperationHandle<>(summary, operation.call());
|
||||
} catch (Exception failure) {
|
||||
throw new RuntimeException(failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class CompletedOperationHandle<R> implements OperationHandle<R> {
|
||||
private final OperationSnapshot snapshot;
|
||||
private final CompletableFuture<R> completion;
|
||||
|
||||
private CompletedOperationHandle(String summary, R result) {
|
||||
final OperationId id = new OperationId(UUID.randomUUID().toString());
|
||||
snapshot = new OperationSnapshot(id, OperationState.SUCCEEDED, Instant.now(), summary);
|
||||
completion = CompletableFuture.completedFuture(result);
|
||||
}
|
||||
|
||||
@Override public OperationId id() { return snapshot.id(); }
|
||||
@Override public OperationSnapshot snapshot() { return snapshot; }
|
||||
@Override public CompletionStage<R> completion() { return completion; }
|
||||
@Override public boolean cancel() { return false; }
|
||||
@Override public OperationSubscription subscribe(Consumer<OperationSnapshot> subscriber) {
|
||||
subscriber.accept(snapshot);
|
||||
return () -> { };
|
||||
}
|
||||
}
|
||||
|
||||
private static final class AsyncOperationExecutor implements OperationExecutor, AutoCloseable {
|
||||
private final ExecutorService executor = Executors.newFixedThreadPool(4);
|
||||
|
||||
@Override
|
||||
public <R> OperationHandle<R> submit(String summary, Callable<R> operation) {
|
||||
final AsyncOperationHandle<R> handle = new AsyncOperationHandle<>(summary);
|
||||
handle.start(executor, operation);
|
||||
return handle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class AsyncOperationHandle<R> implements OperationHandle<R> {
|
||||
private final OperationId id = new OperationId(UUID.randomUUID().toString());
|
||||
private final CompletableFuture<R> completion = new CompletableFuture<>();
|
||||
private final AtomicReference<OperationSnapshot> snapshot;
|
||||
private volatile Future<?> task;
|
||||
|
||||
private AsyncOperationHandle(String summary) {
|
||||
snapshot = new AtomicReference<>(new OperationSnapshot(id, OperationState.PENDING, Instant.now(), summary));
|
||||
}
|
||||
|
||||
private void start(ExecutorService executor, Callable<R> operation) {
|
||||
snapshot.set(new OperationSnapshot(id, OperationState.RUNNING, Instant.now(), snapshot.get().summary()));
|
||||
task = executor.submit(() -> {
|
||||
try {
|
||||
final R result = operation.call();
|
||||
if (!completion.isCancelled()) {
|
||||
snapshot.set(new OperationSnapshot(id, OperationState.SUCCEEDED, Instant.now(), snapshot.get().summary()));
|
||||
completion.complete(result);
|
||||
}
|
||||
} catch (Throwable failure) {
|
||||
if (!completion.isCancelled()) {
|
||||
snapshot.set(new OperationSnapshot(id, OperationState.FAILED, Instant.now(), snapshot.get().summary()));
|
||||
completion.completeExceptionally(failure);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override public OperationId id() { return id; }
|
||||
@Override public OperationSnapshot snapshot() { return snapshot.get(); }
|
||||
@Override public CompletionStage<R> completion() { return completion; }
|
||||
|
||||
@Override
|
||||
public boolean cancel() {
|
||||
if (!completion.cancel(false)) {
|
||||
return false;
|
||||
}
|
||||
snapshot.set(new OperationSnapshot(id, OperationState.CANCELLED, Instant.now(), snapshot.get().summary()));
|
||||
final Future<?> submitted = task;
|
||||
if (submitted != null) {
|
||||
submitted.cancel(true);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OperationSubscription subscribe(Consumer<OperationSnapshot> subscriber) {
|
||||
subscriber.accept(snapshot.get());
|
||||
return () -> { };
|
||||
}
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package p.studio.core.project;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class KnownProjectsServiceTest {
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void seedsRemembersAndForgetsWithoutDeletingProjects() throws Exception {
|
||||
final Path root = tempDir.resolve("projects");
|
||||
Files.createDirectories(root.resolve("alpha"));
|
||||
Files.writeString(root.resolve("alpha/prometeu.json"), """
|
||||
{"name":"Alpha","version":"1","language":"pbs","stdlib":"1","target":"Game"}
|
||||
""");
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final var catalog = new ProjectCatalogService(root, mapper, new ProjectLocalStudioSetupStore(mapper));
|
||||
final var known = new KnownProjectsService(tempDir.resolve("known.txt"), catalog);
|
||||
|
||||
final ProjectReference alpha = known.listKnownProjects().getFirst();
|
||||
known.forget(alpha);
|
||||
assertEquals(java.util.List.of(), known.listKnownProjects());
|
||||
known.remember(alpha);
|
||||
assertEquals(java.util.List.of("Alpha"), known.listKnownProjects().stream().map(ProjectReference::name).toList());
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package p.studio.core.project;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.project.ProjectCreationRequest;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.project.ProjectTarget;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ProjectCatalogServiceTest {
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void createsAndReopensAProjectWithLocalSetup() throws Exception {
|
||||
final ProjectCatalogService service = service(tempDir);
|
||||
final ProjectReference project = service.createProject(new ProjectCreationRequest(
|
||||
"Core Project", tempDir, "pbs", 7, ProjectTarget.Game, "code", 8, "/runtime"));
|
||||
|
||||
assertEquals("Core Project", project.name());
|
||||
assertEquals(ProjectTarget.Game, project.target());
|
||||
assertTrue(Files.isDirectory(project.rootPath().resolve("code")));
|
||||
assertTrue(Files.isRegularFile(project.rootPath().resolve(".studio/setup.json")));
|
||||
assertEquals(project, service.openProject(project.rootPath()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listsOnlyDirectoriesWithValidProjectManifests() throws Exception {
|
||||
Files.createDirectories(tempDir.resolve("alpha"));
|
||||
Files.createDirectories(tempDir.resolve("scratch"));
|
||||
Files.writeString(tempDir.resolve("alpha/prometeu.json"), """
|
||||
{"name":"Alpha","version":"1","language":"pbs","stdlib":"1","target":"Game"}
|
||||
""");
|
||||
|
||||
assertEquals(java.util.List.of("Alpha"),
|
||||
service(tempDir).listProjects().stream().map(ProjectReference::name).toList());
|
||||
}
|
||||
|
||||
private ProjectCatalogService service(Path root) {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
return new ProjectCatalogService(root, mapper, new ProjectLocalStudioSetupStore(mapper));
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package p.studio.core.project;
|
||||
|
||||
import p.studio.api.project.ProjectLocalStudioSetup;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.project.ProjectTarget;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
final class ProjectLocalStudioSetupStoreTest {
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void loadsDedicatedProjectSetupFile() throws Exception {
|
||||
final ProjectLocalStudioSetupStore service = new ProjectLocalStudioSetupStore(new com.fasterxml.jackson.databind.ObjectMapper());
|
||||
final ProjectReference project = project("main");
|
||||
Files.createDirectories(ProjectStudioPaths.studioRoot(project));
|
||||
Files.writeString(
|
||||
ProjectStudioPaths.setupPath(project),
|
||||
"""
|
||||
{
|
||||
"prometeuRuntimePath": "/opt/prometeu/runtime",
|
||||
"editorIndentation": {
|
||||
"mode": "spaces",
|
||||
"width": 2
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
assertEquals(
|
||||
new ProjectLocalStudioSetup(
|
||||
"/opt/prometeu/runtime",
|
||||
new ProjectLocalStudioSetup.EditorIndentationSetup("spaces", 2)),
|
||||
service.load(project));
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingDedicatedProjectSetupFileFallsBackToDefaults() {
|
||||
final ProjectLocalStudioSetupStore service = new ProjectLocalStudioSetupStore(new com.fasterxml.jackson.databind.ObjectMapper());
|
||||
|
||||
assertEquals(ProjectLocalStudioSetup.defaults(), service.load(project("main")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedDedicatedProjectSetupFileFallsBackToDefaults() throws Exception {
|
||||
final ProjectLocalStudioSetupStore service = new ProjectLocalStudioSetupStore(new com.fasterxml.jackson.databind.ObjectMapper());
|
||||
final ProjectReference project = project("main");
|
||||
Files.createDirectories(ProjectStudioPaths.studioRoot(project));
|
||||
Files.writeString(ProjectStudioPaths.setupPath(project), "{ not valid json");
|
||||
|
||||
assertEquals(ProjectLocalStudioSetup.defaults(), service.load(project));
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveWritesNormalizedDedicatedProjectSetupFile() throws Exception {
|
||||
final ProjectLocalStudioSetupStore service = new ProjectLocalStudioSetupStore(new com.fasterxml.jackson.databind.ObjectMapper());
|
||||
final ProjectReference project = project("main");
|
||||
|
||||
service.save(
|
||||
project,
|
||||
new ProjectLocalStudioSetup(
|
||||
" /opt/prometeu/runtime ",
|
||||
new ProjectLocalStudioSetup.EditorIndentationSetup("spaces", 8)));
|
||||
|
||||
assertEquals(
|
||||
new ProjectLocalStudioSetup(
|
||||
"/opt/prometeu/runtime",
|
||||
new ProjectLocalStudioSetup.EditorIndentationSetup("spaces", 8)),
|
||||
service.load(project));
|
||||
}
|
||||
|
||||
private ProjectReference project(final String name) {
|
||||
final Path projectRoot = tempDir.resolve(name);
|
||||
return new ProjectReference("Main", "1.0.0", "pbs", 1, ProjectTarget.Game, projectRoot);
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package p.studio.core.project;
|
||||
|
||||
import p.studio.api.project.ProjectLocalStudioState;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.project.ProjectTarget;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
final class ProjectLocalStudioStateStoreTest {
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void savesAndLoadsSingleFileProjectLocalStudioState() {
|
||||
final ProjectLocalStudioStateStore service = new ProjectLocalStudioStateStore(new com.fasterxml.jackson.databind.ObjectMapper());
|
||||
final ProjectReference project = project("main");
|
||||
final ProjectLocalStudioState state = new ProjectLocalStudioState(
|
||||
ProjectLocalStudioState.CURRENT_VERSION,
|
||||
new ProjectLocalStudioState.ShellLayout(
|
||||
new ProjectLocalStudioState.AssetsLayoutState(List.of(0.42d))),
|
||||
new ProjectLocalStudioState.OpenShellState("ASSETS"));
|
||||
|
||||
service.save(project, state);
|
||||
|
||||
assertTrue(Files.isRegularFile(ProjectStudioPaths.statePath(project)));
|
||||
assertEquals(state, service.load(project));
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedStateFallsBackToDefaults() throws Exception {
|
||||
final ProjectLocalStudioStateStore service = new ProjectLocalStudioStateStore(new com.fasterxml.jackson.databind.ObjectMapper());
|
||||
final ProjectReference project = project("main");
|
||||
Files.createDirectories(ProjectStudioPaths.studioRoot(project));
|
||||
Files.writeString(ProjectStudioPaths.statePath(project), "{ not valid json");
|
||||
|
||||
assertEquals(ProjectLocalStudioState.defaults(), service.load(project));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedVersionFallsBackToDefaults() throws Exception {
|
||||
final ProjectLocalStudioStateStore service = new ProjectLocalStudioStateStore(new com.fasterxml.jackson.databind.ObjectMapper());
|
||||
final ProjectReference project = project("main");
|
||||
Files.createDirectories(ProjectStudioPaths.studioRoot(project));
|
||||
Files.writeString(
|
||||
ProjectStudioPaths.statePath(project),
|
||||
"""
|
||||
{
|
||||
"version": 99
|
||||
}
|
||||
""");
|
||||
|
||||
assertEquals(ProjectLocalStudioState.defaults(), service.load(project));
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyEditorStateLoadsWithAssetsFallbackAndIgnoresEditorFields() throws Exception {
|
||||
final ProjectLocalStudioStateStore service = new ProjectLocalStudioStateStore(new com.fasterxml.jackson.databind.ObjectMapper());
|
||||
final ProjectReference project = project("main");
|
||||
Files.createDirectories(ProjectStudioPaths.studioRoot(project));
|
||||
Files.writeString(
|
||||
ProjectStudioPaths.statePath(project),
|
||||
"""
|
||||
{
|
||||
"version": 1,
|
||||
"shellLayout": {
|
||||
"editorLayout": {
|
||||
"contentSplitDividers": [0.2, 0.8]
|
||||
},
|
||||
"assetsLayout": {
|
||||
"contentSplitDividers": [0.42]
|
||||
}
|
||||
},
|
||||
"openShellState": {
|
||||
"selectedWorkspaceId": "EDITOR"
|
||||
},
|
||||
"editorRestoration": {
|
||||
"openTabPaths": ["src/main.pbs"],
|
||||
"activeTabPath": "src/main.pbs"
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
assertEquals(
|
||||
new ProjectLocalStudioState(
|
||||
ProjectLocalStudioState.CURRENT_VERSION,
|
||||
new ProjectLocalStudioState.ShellLayout(
|
||||
new ProjectLocalStudioState.AssetsLayoutState(List.of(0.42d))),
|
||||
new ProjectLocalStudioState.OpenShellState("ASSETS")),
|
||||
service.load(project));
|
||||
}
|
||||
|
||||
private ProjectReference project(final String name) {
|
||||
final Path projectRoot = tempDir.resolve(name);
|
||||
return new ProjectReference("Main", "1.0.0", "pbs", 1, ProjectTarget.Game, projectRoot);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package p.studio.core.project.preferences;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.preferences.ProjectActivityRecord;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.project.ProjectTarget;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
final class JsonProjectActivityHistoryStoreTest {
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void persistsProjectScopedHistoryAndToleratesMalformedStorage() throws Exception {
|
||||
final var store = new JsonProjectActivityHistoryStore(new ObjectMapper());
|
||||
final var project = new ProjectReference("main", "1", "pbs", 1, ProjectTarget.Game, tempDir.resolve("project"));
|
||||
final var history = List.of(new ProjectActivityRecord("Studio", "Opened", "SUCCESS", false));
|
||||
|
||||
store.save(project, history);
|
||||
assertEquals(history, store.load(project));
|
||||
|
||||
Files.writeString(project.rootPath().resolve(".studio/activities.json"), "{ invalid");
|
||||
assertEquals(List.of(), store.load(project));
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package p.studio.core.project.preferences;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.preferences.WindowGeometry;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.project.ProjectTarget;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
final class JsonWindowStateStoreTest {
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void persistsGeometryByNormalizedProjectRoot() {
|
||||
final Path storage = tempDir.resolve("window-state.json");
|
||||
final var project = new ProjectReference("main", "1", "pbs", 1, ProjectTarget.Game, tempDir.resolve("project"));
|
||||
final var geometry = new WindowGeometry(12, 34, 1280, 840, true);
|
||||
|
||||
new JsonWindowStateStore(storage, new ObjectMapper()).save(project, geometry);
|
||||
|
||||
assertEquals(geometry, new JsonWindowStateStore(storage, new ObjectMapper()).load(project).orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsExistingFileWhileIgnoringLegacyLauncherState() throws Exception {
|
||||
final Path projectRoot = tempDir.resolve("project").toAbsolutePath().normalize();
|
||||
final Path storage = tempDir.resolve("window-state.json");
|
||||
Files.writeString(storage, """
|
||||
{
|
||||
"launcher": {"x": 1, "y": 2, "width": 3, "height": 4, "maximized": false},
|
||||
"projects": {
|
||||
"%s": {"x": 10, "y": 20, "width": 900, "height": 700, "maximized": false}
|
||||
}
|
||||
}
|
||||
""".formatted(projectRoot.toString().replace("\\", "\\\\")));
|
||||
final var project = new ProjectReference("main", "1", "pbs", 1, ProjectTarget.Game, projectRoot);
|
||||
|
||||
assertEquals(new WindowGeometry(10, 20, 900, 700, false),
|
||||
new JsonWindowStateStore(storage, new ObjectMapper()).load(project).orElseThrow());
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package p.studio.core.session;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.project.ProjectLocalStudioState;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.project.ProjectTarget;
|
||||
import p.studio.core.project.ProjectLocalStudioSetupStore;
|
||||
import p.studio.core.project.ProjectLocalStudioStateStore;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
final class DefaultProjectSessionTest {
|
||||
@TempDir Path temporaryDirectory;
|
||||
|
||||
@Test
|
||||
void factoryLoadsStateBootsLspAndCloseIsOrderedAndIdempotent() {
|
||||
final var mapper = new ObjectMapper();
|
||||
final var stateStore = new ProjectLocalStudioStateStore(mapper);
|
||||
final var setupStore = new ProjectLocalStudioSetupStore(mapper);
|
||||
final var lsp = new RecordingLsp();
|
||||
final var factory = new DefaultProjectSessionFactory(stateStore, setupStore, lsp);
|
||||
final var project = project();
|
||||
|
||||
final var session = factory.open(project);
|
||||
final var next = ProjectLocalStudioState.defaults()
|
||||
.withOpenShellState(new ProjectLocalStudioState.OpenShellState("DEBUG"));
|
||||
session.replaceProjectLocalStudioState(next);
|
||||
session.close();
|
||||
session.close();
|
||||
|
||||
assertEquals(1, lsp.boots);
|
||||
assertEquals(1, lsp.shutdowns);
|
||||
assertEquals(next, stateStore.load(project));
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeAggregatesCleanupFailures() {
|
||||
final var mapper = new ObjectMapper();
|
||||
final var lsp = new RecordingLsp();
|
||||
lsp.failShutdown = true;
|
||||
final var session = new DefaultProjectSessionFactory(
|
||||
new ProjectLocalStudioStateStore(mapper),
|
||||
new ProjectLocalStudioSetupStore(mapper), lsp).open(project());
|
||||
final var failure = assertThrows(IllegalStateException.class, session::close);
|
||||
assertEquals("lsp shutdown", failure.getMessage());
|
||||
}
|
||||
|
||||
private ProjectReference project() {
|
||||
return new ProjectReference("Example", "1.0.0", "pbs", 1, ProjectTarget.Game, temporaryDirectory);
|
||||
}
|
||||
|
||||
private static final class RecordingLsp implements LspLifecyclePort {
|
||||
int boots;
|
||||
int shutdowns;
|
||||
boolean failShutdown;
|
||||
@Override public void boot(ProjectReference project) { boots++; }
|
||||
@Override public void shutdown(ProjectReference project) {
|
||||
shutdowns++;
|
||||
if (failShutdown) throw new IllegalStateException("lsp shutdown");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user