Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add M26 STEP import/export API hooks and client panel

Yuechen Li42d01972f747
diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
index 54a7e7ab..53be7aea 100644
--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
@@ -341,6 +341,94 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
Assert.True(copiedMaxX > originalMaxX + 8d);
}
+
+ [Fact]
+ public async Task StepIo_ExportImportRoundTrip_TessellatesImportedOccurrence()
+ {
+ var document = await CreateDocumentAsync("/api/v1/documents");
+ var box = await CreateBoxAsync("/api/v1/documents", document.Data!.DocumentId, 2, 2, 2);
+
+ var exportResponse = await _client.GetAsync($"/api/v1/documents/{document.Data.DocumentId}/definitions/{box.Data!.DefinitionId}/export/step");
+ exportResponse.EnsureSuccessStatusCode();
+ var exported = await exportResponse.Content.ReadFromJsonAsync<ApiResponseDto<StepExportResponseDto>>();
+
+ Assert.NotNull(exported);
+ Assert.True(exported!.Success);
+ Assert.NotNull(exported.Data);
+ Assert.Contains("ISO-10303-21", exported.Data!.StepText);
+ Assert.Contains("MANIFOLD_SOLID_BREP", exported.Data.StepText);
+
+ var importResponse = await _client.PostAsJsonAsync(
+ $"/api/v1/documents/{document.Data.DocumentId}/import/step",
+ new StepImportRequestDto(exported.Data.StepText, "Imported Box"));
+ importResponse.EnsureSuccessStatusCode();
+
+ var imported = await importResponse.Content.ReadFromJsonAsync<ApiResponseDto<StepImportResponseDto>>();
+ Assert.NotNull(imported);
+ Assert.True(imported!.Success);
+ Assert.NotNull(imported.Data);
+ Assert.NotEqual(box.Data.DefinitionId, imported.Data!.DefinitionId);
+ Assert.NotEqual(box.Data.BodyId, imported.Data.OccurrenceId);
+
+ var tessellationResponse = await _client.PostAsJsonAsync(
+ $"/api/v1/documents/{document.Data.DocumentId}/bodies/{imported.Data.OccurrenceId}/tessellate",
+ new TessellateRequestDto(null));
+ tessellationResponse.EnsureSuccessStatusCode();
+
+ var tessellation = await tessellationResponse.Content.ReadFromJsonAsync<ApiResponseDto<TessellationResponseDto>>();
+ Assert.NotNull(tessellation);
+ Assert.True(tessellation!.Success);
+ Assert.NotEmpty(tessellation.Data!.FacePatches);
+ Assert.NotEmpty(tessellation.Data.EdgePolylines);
+ }
+
+ [Fact]
+ public async Task StepImport_EmptyText_ReturnsBadRequestEnvelope()
+ {
+ var document = await CreateDocumentAsync("/api/v1/documents");
+
+ var response = await _client.PostAsJsonAsync(
+ $"/api/v1/documents/{document.Data!.DocumentId}/import/step",
+ new StepImportRequestDto("", null));
+
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ var payload = await response.Content.ReadFromJsonAsync<ApiResponseDto<object>>();
+ Assert.NotNull(payload);
+ Assert.False(payload!.Success);
+ Assert.NotEmpty(payload.Diagnostics);
+ Assert.Contains(payload.Diagnostics, d => d.Code == "InvalidArgument");
+ }
+
+ [Fact]
+ public async Task StepExport_MissingDefinition_ReturnsNotFoundEnvelope()
+ {
+ var document = await CreateDocumentAsync("/api/v1/documents");
+
+ var response = await _client.GetAsync($"/api/v1/documents/{document.Data!.DocumentId}/definitions/{Guid.NewGuid()}/export/step");
+
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ var payload = await response.Content.ReadFromJsonAsync<ApiResponseDto<object>>();
+ Assert.NotNull(payload);
+ Assert.False(payload!.Success);
+ Assert.NotEmpty(payload.Diagnostics);
+ }
+
+ [Fact]
+ public async Task StepImport_MalformedPayload_ReturnsDiagnostics()
+ {
+ var document = await CreateDocumentAsync("/api/v1/documents");
+
+ var response = await _client.PostAsJsonAsync(
+ $"/api/v1/documents/{document.Data!.DocumentId}/import/step",
+ new StepImportRequestDto("NOT_A_STEP_FILE", null));
+
+ Assert.Contains(response.StatusCode, new[] { HttpStatusCode.BadRequest, HttpStatusCode.UnprocessableEntity });
+ var payload = await response.Content.ReadFromJsonAsync<ApiResponseDto<object>>();
+ Assert.NotNull(payload);
+ Assert.False(payload!.Success);
+ Assert.NotEmpty(payload.Diagnostics);
+ }
+
[Fact]
public async Task PickResponse_ContainsOccurrenceIdentity()
{
diff --git a/Aetheris.Server/Api/KernelEndpoints.cs b/Aetheris.Server/Api/KernelEndpoints.cs
index ff419bea..e3db050b 100644
--- a/Aetheris.Server/Api/KernelEndpoints.cs
+++ b/Aetheris.Server/Api/KernelEndpoints.cs
@@ -4,6 +4,7 @@ using Aetheris.Kernel.Core.Brep.Features;
using Aetheris.Kernel.Core.Brep.Picking;
using Aetheris.Kernel.Core.Brep.Tessellation;
using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Step242;
using Aetheris.Server.Contracts;
using Aetheris.Server.Documents;
@@ -215,6 +216,43 @@ public static class KernelEndpoints
return ApiMappings.Ok(new OccurrenceCreatedResponseDto(documentId, occurrence.OccurrenceId, occurrence.DefinitionId, occurrence.Name));
}));
+
+ documents.MapGet("/{documentId:guid}/definitions/{definitionId:guid}/export/step", (Guid documentId, Guid definitionId, KernelDocumentStore store) =>
+ WithDocument(store, documentId, document =>
+ {
+ if (!document.TryGetDefinition(definitionId, out var definitionBody))
+ {
+ return ApiMappings.NotFound($"Definition '{definitionId}' was not found.", "documents.definitions.export.step");
+ }
+
+ var exportResult = Step242Exporter.ExportBody(definitionBody);
+ if (!exportResult.IsSuccess)
+ {
+ return ApiMappings.KernelFailure(exportResult.Diagnostics);
+ }
+
+ return ApiMappings.Ok(new StepExportResponseDto(documentId, definitionId, exportResult.Value, []));
+ }));
+
+ documents.MapPost("/{documentId:guid}/import/step", (Guid documentId, StepImportRequestDto request, KernelDocumentStore store) =>
+ WithDocument(store, documentId, document =>
+ {
+ if (string.IsNullOrWhiteSpace(request.StepText))
+ {
+ return ApiMappings.BadRequestFromMessage("StepText must be provided.", "documents.import.step");
+ }
+
+ var importResult = Step242Importer.ImportBody(request.StepText);
+ if (!importResult.IsSuccess)
+ {
+ return ApiMappings.KernelFailure(importResult.Diagnostics);
+ }
+
+ var occurrenceName = string.IsNullOrWhiteSpace(request.Name) ? "Imported" : request.Name;
+ var imported = document.AddDefinitionAndOccurrence(importResult.Value, occurrenceName);
+ return ApiMappings.Ok(new StepImportResponseDto(documentId, imported.DefinitionId, imported.OccurrenceId, occurrenceName, []));
+ }));
+
documents.MapPost("/{documentId:guid}/bodies/{bodyId:guid}/transform", (Guid documentId, Guid bodyId, TranslateBodyRequestDto request, KernelDocumentStore store) =>
WithDocument(store, documentId, document =>
{
diff --git a/Aetheris.Server/Contracts/ApiContracts.cs b/Aetheris.Server/Contracts/ApiContracts.cs
index 5429b994..d970ffff 100644
--- a/Aetheris.Server/Contracts/ApiContracts.cs
+++ b/Aetheris.Server/Contracts/ApiContracts.cs
@@ -40,6 +40,12 @@ public sealed record CreateOccurrenceRequestDto(Guid? SourceOccurrenceId, Guid?
public sealed record OccurrenceCreatedResponseDto(Guid DocumentId, Guid BodyId, Guid DefinitionId, string? Name);
+public sealed record StepExportResponseDto(Guid DocumentId, Guid DefinitionId, string StepText, IReadOnlyList<DiagnosticDto> Diagnostics);
+
+public sealed record StepImportRequestDto(string? StepText, string? Name);
+
+public sealed record StepImportResponseDto(Guid DocumentId, Guid DefinitionId, Guid OccurrenceId, string? Name, IReadOnlyList<DiagnosticDto> Diagnostics);
+
public sealed record ExtrudeRequestDto(
IReadOnlyList<ProfilePoint2Dto> Profile,
Point3Dto Origin,
diff --git a/Aetheris.Server/Documents/DocumentSession.cs b/Aetheris.Server/Documents/DocumentSession.cs
index 4d67f78b..b6ef690a 100644
--- a/Aetheris.Server/Documents/DocumentSession.cs
+++ b/Aetheris.Server/Documents/DocumentSession.cs
@@ -69,6 +69,14 @@ public sealed class DocumentSession
}
}
+ public bool TryGetDefinition(Guid definitionId, out BrepBody body)
+ {
+ lock (_sync)
+ {
+ return _definitions.TryGetValue(definitionId, out body!);
+ }
+ }
+
public bool TryCreateOccurrence(Guid definitionId, out BodyOccurrence occurrence, string? name = null)
{
lock (_sync)
@@ -103,6 +111,9 @@ public sealed class DocumentSession
}
}
+ public (Guid OccurrenceId, Guid DefinitionId) AddDefinitionAndOccurrence(BrepBody body, string? occurrenceName = null)
+ => AddBody(body, occurrenceName);
+
public bool TryGetBodyTransform(Guid occurrenceId, out Transform3D transform)
{
lock (_sync)
diff --git a/aetheris.client/src/App.css b/aetheris.client/src/App.css
index 8bc5293b..6fdec5fc 100644
--- a/aetheris.client/src/App.css
+++ b/aetheris.client/src/App.css
@@ -118,3 +118,22 @@ button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
+
+.textarea-label {
+ display: flex;
+ flex-direction: column;
+ gap: 0.25rem;
+ margin-top: 0.5rem;
+ margin-bottom: 0.5rem;
+ font-size: 0.8rem;
+}
+
+textarea {
+ width: 100%;
+ border-radius: 4px;
+ border: 1px solid #334155;
+ padding: 0.4rem;
+ color: #e2e8f0;
+ background: #020617;
+ resize: vertical;
+}
diff --git a/aetheris.client/src/App.tsx b/aetheris.client/src/App.tsx
index 6101bcee..1911023b 100644
--- a/aetheris.client/src/App.tsx
+++ b/aetheris.client/src/App.tsx
@@ -5,7 +5,9 @@ import {
createBox,
createDocument,
executeBoolean,
+ exportDefinitionStep,
getDocumentSummary,
+ importStep,
pickBody,
tessellateBody,
translateBody,
@@ -49,6 +51,9 @@ function App() {
const [booleanTargetBodyId, setBooleanTargetBodyId] = useState<string>('');
const [booleanToolBodyId, setBooleanToolBodyId] = useState<string>('');
const [booleanOperation, setBooleanOperation] = useState<BooleanOperationUi>('Union');
+ const [stepExportText, setStepExportText] = useState('');
+ const [stepImportText, setStepImportText] = useState('');
+ const [stepImportName, setStepImportName] = useState('Imported');
const runAction = useCallback(async (actionName: string, action: () => Promise<void>) => {
setStatus('loading');
@@ -104,6 +109,9 @@ function App() {
setBooleanTargetBodyId('');
setBooleanToolBodyId('');
setBooleanOperation('Union');
+ setStepExportText('');
+ setStepImportText('');
+ setStepImportName('Imported');
});
}, [runAction]);
@@ -184,6 +192,43 @@ function App() {
});
}, [activeBodyId, documentId, runAction]);
+
+ const handleExportActiveStep = useCallback(async () => {
+ if (!documentId || !activeBodyId) {
+ return;
+ }
+
+ const activeOccurrence = occurrences.find((item) => item.occurrenceId === activeBodyId);
+ if (!activeOccurrence) {
+ setStatus('error');
+ setStatusMessage('Active occurrence metadata is unavailable for STEP export.');
+ setDiagnostics([]);
+ return;
+ }
+
+ await runAction('Export active STEP', async () => {
+ const text = await exportDefinitionStep(documentId, activeOccurrence.definitionId);
+ setStepExportText(text);
+ });
+ }, [activeBodyId, documentId, occurrences, runAction]);
+
+ const handleImportStep = useCallback(async () => {
+ if (!documentId) {
+ return;
+ }
+
+ await runAction('Import STEP', async () => {
+ const imported = await importStep(documentId, stepImportText, stepImportName.trim().length === 0 ? undefined : stepImportName.trim());
+ setStepExportText('');
+ await refreshSummaryAndActiveTessellation(imported.occurrenceId);
+ setStepImportName(imported.name ?? 'Imported');
+ setPickStatus('idle');
+ setPickMessage(`Imported occurrence ${imported.occurrenceId} is now active.`);
+ setPickDiagnostics([]);
+ setPickHits([]);
+ });
+ }, [documentId, refreshSummaryAndActiveTessellation, runAction, stepImportName, stepImportText]);
+
const handleUseActiveBodyAsTarget = useCallback(() => {
if (activeBodyId) {
setBooleanTargetBodyId(activeBodyId);
@@ -275,6 +320,7 @@ function App() {
const nearestHit = pickHits[0] ?? null;
const highlightedFaceId = nearestHit?.entityKind === 'Face' ? nearestHit.faceId : null;
const highlightedEdgeId = nearestHit?.entityKind === 'Edge' ? nearestHit.edgeId : null;
+ const canImportStep = Boolean(documentId && stepImportText.trim().length > 0 && status !== 'loading');
const canExecuteBoolean = Boolean(
documentId
&& bodyIds.length >= 2
@@ -387,6 +433,27 @@ function App() {
) : null}
</section>
+
+ <section>
+ <h3>STEP I/O</h3>
+ <button type="button" onClick={() => void handleExportActiveStep()} disabled={!activeBodyId || status === 'loading'}>
+ Export Active (STEP)
+ </button>
+ <label className="textarea-label">
+ Exported STEP
+ <textarea value={stepExportText} readOnly placeholder="Exported STEP text will appear here." rows={7} />
+ </label>
+ <label className="textarea-label">
+ Import STEP Text
+ <textarea value={stepImportText} onChange={(event) => setStepImportText(event.target.value)} placeholder="Paste STEP text here." rows={7} />
+ </label>
+ <label>
+ Imported Name
+ <input type="text" value={stepImportName} onChange={(event) => setStepImportName(event.target.value)} />
+ </label>
+ <button type="button" onClick={() => void handleImportStep()} disabled={!canImportStep}>Import STEP</button>
+ </section>
+
<h2>Debug / Status</h2>
<p><strong>Request status:</strong> {status}</p>
<p><strong>Message:</strong> {statusMessage}</p>
diff --git a/aetheris.client/src/__tests__/aetherisApi.test.ts b/aetheris.client/src/__tests__/aetherisApi.test.ts
index e4d9ac19..9cbfaac9 100644
--- a/aetheris.client/src/__tests__/aetherisApi.test.ts
+++ b/aetheris.client/src/__tests__/aetherisApi.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { ApiError, executeBoolean, parseEnvelope, pickBody, translateBody } from '../api/aetherisApi';
+import { ApiError, executeBoolean, exportDefinitionStep, importStep, parseEnvelope, pickBody, translateBody } from '../api/aetherisApi';
describe('parseEnvelope', () => {
it('returns data when envelope success is true', async () => {
@@ -154,3 +154,71 @@ describe('executeBoolean', () => {
}]));
});
});
+
+
+describe('STEP API', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('parses exportDefinitionStep success envelope', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ success: true,
+ data: {
+ documentId: 'doc-1',
+ definitionId: 'def-1',
+ stepText: 'ISO-10303-21;\nDATA;\n#1=MANIFOLD_SOLID_BREP();',
+ diagnostics: [],
+ },
+ diagnostics: [],
+ }), { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const stepText = await exportDefinitionStep('doc-1', 'def-1');
+
+ expect(fetchMock).toHaveBeenCalledWith('/api/v1/documents/doc-1/definitions/def-1/export/step', expect.objectContaining({ method: 'GET' }));
+ expect(stepText).toContain('ISO-10303-21');
+ });
+
+ it('parses importStep success envelope', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ success: true,
+ data: {
+ documentId: 'doc-1',
+ definitionId: 'def-2',
+ occurrenceId: 'occ-2',
+ name: 'Imported',
+ diagnostics: [],
+ },
+ diagnostics: [],
+ }), { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const response = await importStep('doc-1', 'ISO-10303-21;', 'Imported');
+
+ expect(fetchMock).toHaveBeenCalledWith('/api/v1/documents/doc-1/import/step', expect.objectContaining({ method: 'POST' }));
+ expect(response.definitionId).toBe('def-2');
+ expect(response.occurrenceId).toBe('occ-2');
+ });
+
+ it('propagates importStep diagnostics on envelope failure', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ success: false,
+ data: null,
+ diagnostics: [{
+ code: 'ValidationFailed',
+ severity: 'Error',
+ message: 'Malformed STEP payload.',
+ source: 'step242.import',
+ }],
+ }), { status: 422 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(importStep('doc-1', 'MALFORMED')).rejects.toEqual(new ApiError('Malformed STEP payload.', [{
+ code: 'ValidationFailed',
+ severity: 'Error',
+ message: 'Malformed STEP payload.',
+ source: 'step242.import',
+ }]));
+ });
+});
diff --git a/aetheris.client/src/api/aetherisApi.ts b/aetheris.client/src/api/aetherisApi.ts
index dc4bf40d..b1eea150 100644
--- a/aetheris.client/src/api/aetherisApi.ts
+++ b/aetheris.client/src/api/aetherisApi.ts
@@ -49,6 +49,21 @@ export interface BodyTransformedResponseDto {
appliedTranslation: Vector3Dto;
}
+export interface StepExportResponseDto {
+ documentId: string;
+ definitionId: string;
+ stepText: string;
+ diagnostics: DiagnosticDto[];
+}
+
+export interface StepImportResponseDto {
+ documentId: string;
+ definitionId: string;
+ occurrenceId: string;
+ name: string | null;
+ diagnostics: DiagnosticDto[];
+}
+
export type BooleanOperation = 'union' | 'subtract' | 'intersect';
export interface BooleanRequestDto {
@@ -207,4 +222,19 @@ export async function executeBoolean(documentId: string, requestDto: BooleanRequ
});
}
+export async function exportDefinitionStep(documentId: string, definitionId: string): Promise<string> {
+ const response = await request<StepExportResponseDto>(`/api/v1/documents/${documentId}/definitions/${definitionId}/export/step`, {
+ method: 'GET',
+ });
+
+ return response.stepText;
+}
+
+export async function importStep(documentId: string, stepText: string, name?: string): Promise<StepImportResponseDto> {
+ return request<StepImportResponseDto>(`/api/v1/documents/${documentId}/import/step`, {
+ method: 'POST',
+ body: JSON.stringify({ stepText, name: name ?? null }),
+ });
+}
+
export { parseEnvelope };
diff --git a/docs/milestones.md b/docs/milestones.md
index db9814bb..fa15ea36 100644
--- a/docs/milestones.md
+++ b/docs/milestones.md
@@ -235,3 +235,14 @@
- [x] Extend pick/document contracts minimally with occurrence identity and occurrence summaries while preserving M17 envelope behavior.
- [x] Keep React modeling UI compatible by listing/selecting occurrences and surfacing occurrence definition/translation context.
- [x] Add focused occurrence semantics + placement regression coverage; defer full assembly constraints, mates/kinematics, and broad AP242 assembly IO.
+
+
+## M26 — STEP Document I/O Hooks v1 (In-Memory, Subset Only)
+
+- [x] Add canonical backend STEP I/O endpoints for definition export and document import using the existing AP242 subset (`/api/v1/documents/{documentId}/definitions/{definitionId}/export/step`, `/api/v1/documents/{documentId}/import/step`).
+- [x] Add minimal DTO contracts for STEP import/export request/response payloads, preserving M17 envelope and diagnostic mapping behavior.
+- [x] Wire STEP import to create a new definition and a new identity-placed occurrence in in-memory document sessions (no DB/filesystem persistence).
+- [x] Extend server integration coverage for export→import→tessellate success and required negative paths (empty payload, missing definition, malformed STEP diagnostics).
+- [x] Add client API methods and explicit UI controls for button-driven STEP export/import text workflows, with imported occurrence auto-selection and tessellation refresh.
+- [x] Extend client envelope tests for STEP API success parsing and failure diagnostic propagation through `ApiError`.
+- [x] Defer AP242 assembly/product-structure mapping, multi-definition export, metadata completeness, and file-dialog UX to later milestones.