diff --git a/docs/DESIGN_VARIANTS_067G.md b/docs/DESIGN_VARIANTS_067G.md index 899558a..249cce9 100644 --- a/docs/DESIGN_VARIANTS_067G.md +++ b/docs/DESIGN_VARIANTS_067G.md @@ -64,7 +64,9 @@ retained failed trial. Results and saved variants store resolved values: `1`/`0` for a boolean and the listed text for a text choice. A saved text value requires semantic version 60; numeric-only variants keep version 56. Studio's **Edit value** and **Explore values** stage numbers only, so text choices are -compared and saved through the tool. +compared and saved through the tool. The +[Parametric HUD](PARAMETRIC_PROGRAMS.md#studio) configures a text choice on the +installed program. `ranked_indices` indexes `results` in objective order and includes only feasible rows with the requested metric available. `mass_kg` is absent and cannot be ranked diff --git a/docs/PARAMETRIC_HUD_048B.md b/docs/PARAMETRIC_HUD_048B.md index 6d29e80..c9063f2 100644 --- a/docs/PARAMETRIC_HUD_048B.md +++ b/docs/PARAMETRIC_HUD_048B.md @@ -129,10 +129,12 @@ choice. [parametric programs](PARAMETRIC_PROGRAMS.md#studio), a **Parameters / Programs** switch appears under the header. The HUD opens on Programs when no parameter is exposed. The Programs view uses the same rows, staging and -clamping for each program parameter. **Apply** publishes a revision-checked +clamping for each numeric program parameter; a boolean switches and a choice +moves through its declared list. **Apply** publishes a revision-checked `parametric_program` configure candidate instead of `param.set`. **Detach** and -**Remove** ask for confirmation first. A value typed, or a Detach or Remove -confirmed, while another writer changed the model is not used; the HUD reads +**Remove** ask for confirmation first. A value typed, a choice picked, or a +Detach or Remove confirmed, while another writer changed the model is not +used; the HUD reads the bindings again and asks for review. The Programs view has no Auto mode; each **Apply** prepares and publishes one candidate. diff --git a/docs/PARAMETRIC_PROGRAMS.md b/docs/PARAMETRIC_PROGRAMS.md index 27d0146..9e111a0 100644 --- a/docs/PARAMETRIC_PROGRAMS.md +++ b/docs/PARAMETRIC_PROGRAMS.md @@ -332,13 +332,19 @@ it on the same namespace. object, so the rows and `local_edits` are the same as the live inspect. The rest of the drawing, such as imported meshes, is not serialized on the UI thread. If that session cannot answer, the live session does. -- **Values.** Each declared parameter has a row with its value and `unit`, the - range, **-**/**+** and a value box for typed entry. Typed entry accepts a - number or an expression of document parameters, evaluated once. Integer - parameters step by 1 and are rounded. Other bounded parameters step by a power - of ten near a twentieth of the range. The HUD clamps to `min`/`max` and names - the limit; agents are rejected instead. Units are labels only. A value that is - not a number is shown read-only. +- **Values.** Each declared parameter has a row with its value and `unit`, + **-**/**+** and a value box. A number shows its range, and its value box + takes typed entry: a number or an expression of document parameters, + evaluated once. Integer parameters step by 1 and are rounded. Other bounded + parameters step by a power of ten near a twentieth of the range. The HUD + clamps to `min`/`max` and names the limit; agents are rejected instead. Units + are labels only. +- **Booleans and choices.** A boolean shows **On** or **Off**: the value box + switches it, **-** turns it off and **+** turns it on. A numeric or text + choice shows its position and the declared list. **-**/**+** move to the + previous or next declared value without wrapping, and the value box opens + the list. These rows take only declared values, so nothing is clamped. Text + wider than the value box ends in an ellipsis; the hint shows it whole. - **Apply.** Changes are staged in amber with `was `. **Apply (n)** sends `prepare{mode:"configure",namespace,values,expected_revision}`, then `doc_apply{candidate_id,expected_revision}` with @@ -346,9 +352,9 @@ it on the same namespace. path, so the viewport keeps painting. The result line shows the new revision and the measured prepare and publish times. - **Stale values.** Values belong to the revision of the rows they were staged - from. A value typed while another writer changed the model (for example from - the Design variants window) is not staged: the rows are read again and the - HUD asks for the value again. Values staged at an older revision are not + from. A value typed, or a choice picked from its list, while another writer + changed the model (for example from the Design variants window) is not + staged: the rows are read again and the HUD asks for the value again. Values staged at an older revision are not published. The first **Apply** reports the revision change, and whether the program source changed. A second **Apply** prepares them on the current model; **Reset** discards them. @@ -357,7 +363,8 @@ it on the same namespace. `PROGRAM_DEPENDANTS`, `PROGRAM_STALE_PROGRAM`, `PROGRAM_ASSERT` with the author's message, `PROGRAM_VALUES`, or the evaluator error of a failed candidate. A staged value outside a range that updated source narrowed is - marked `outside range`. + marked `outside range`, and a staged choice it no longer lists is marked + `not a declared choice`. - **Detach and Remove.** Both first show a confirmation with the binding, its owned objects and its local edits. **Cancel** changes nothing. If the model changes while the confirmation is open, nothing is sent. Otherwise the HUD @@ -505,11 +512,21 @@ the tool path and opens the HUD on Programs. It covers: - Detach cancelled and confirmed, Remove withheld after a commit during its confirmation, Remove and Undo, the Variants link, and viewport bounds; - the HUD's binding rows byte-identical to the live inspect after install, - after a local edit, and with four imported meshes in the drawing. + after a local edit, and with four imported meshes in the drawing; +- a second program with a text choice, a numeric choice and a boolean: **+** + and the choice list stage text, the boolean switches, and one **Apply** + publishes all three as one revision, with the generated objects and the + plate's native volume matching the chosen values; +- stepping past the last choice refused, the committed value unstaging its + row, a choice picked during a concurrent configure not staged, and a staged + choice dropped by an agent update rejected as `PROGRAM_VALUES` with the + document and revision unchanged. Captures are written next to `--shot` (`.program-hud-open.png`, `-staged`, `-applied`, `-rejected`, `-typed-race`, `-values`, `-local-edits`, -`-detach-dialog`, `-detached`, `-dependants`, `-remove-dialog` and `-narrow`). +`-detach-dialog`, `-detached`, `-dependants`, `-remove-dialog`, `-narrow`, +`-choices-staged`, `-choice-dialog`, `-choices-applied`, `-choice-dropped` and +`-choices-narrow`). In one local run with the four meshes (1.57 MB of authored source), the HUD's inspect took 2.6 ms and the live inspect 135 ms. This is a single measurement, not a benchmark. @@ -517,6 +534,7 @@ measurement, not a benchmark. Assertions and bounds encode the design rules stated by the author. They are not manufacturing, structural or fit qualification. No measured agent quality, time or token benefit is claimed. Editing program source in Studio is not -implemented. Studio's Design variants window stages numeric values only and the -Parametric HUD shows text values read-only, so text choices are configured -through the tools. Program assembly output is not implemented (see above). +implemented. Studio's Design variants window stages numeric values only, so a +text choice is compared and saved as a variant through the tool; the +Parametric HUD configures it on the installed program. Program assembly output +is not implemented (see above). diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 2088a82..9959b6a 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -491,7 +491,7 @@ Goal: create and revise a complete product with clear, reliable interactions. | ID | Milestone | Status | Acceptance still governing the work | |---|---|---|---| | B.01 | Readable navigation and editing | Parcial | Stable cube/axes, free orbit, selection/Spotlight, shortcuts and DPI; no clipped controls at supported resolutions. Measurement and display units have [013B evidence](iterations/013B.md); BOM layout has [015B evidence](iterations/015B.md). [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B native/mesh pointer selection, hover and visual authoring](iterations/019B.md). [020B exact extrusion gestures and source dimensions](iterations/020B.md). [021B direct handle and snapshot feedback](iterations/021B.md). [022B existing-solid resize, asynchronous previews, exact vertex tools and integrated sheets](iterations/022B.md). 029B adds accessible native fields, visible focus and dynamic DPI/work-area reflow; [sketch/accessibility evidence](SKETCH_ASSISTANCE_029B.md). [048B](iterations/048B.md) adds the Studio parametric HUD overlay with staged Rebuild/Auto. [053B native graph](PARAMETRIC_COMPONENTS_053B.md) connects authored relationships, geometry selection and local navigation. [065F](iterations/065F.md) unifies the Studio palette, ribbon grouping and one outline-icon family, with a floating sidebar on every tab. [072A storage visibility](GROWABLE_EDITING_072A.md) replaces discontinued quota percentages with actual retained counts/bytes and explicit resource errors; UI verification is pending. | -| B.02 | Everyday sketches and feature history | Parcial | Actionable constraint diagnostics, valid reorder, suppress/rollback and visible dependencies; rejection leaves the document intact. Arcs/snaps/expressions have scoped 005B/008D evidence. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B visual and parametric authoring](iterations/019B.md). [020B exact extrusion gestures and source dimensions](iterations/020B.md). [021B associative extrusion source](iterations/021B.md). [022B source-preserving edits, opaque validated preview handoff and version-37 journal checks](iterations/022B.md). 029B adds equilibrated QR solving and source/revision-bound reviewed conflict alternatives; [sketch assistance](SKETCH_ASSISTANCE_029B.md). [046B profile regions](PROFILE_REGIONS_046B.md) make multi-loop sketches with holes one extrude/revolve profile, with typed loop rejections and an optional region selection. [048B parametric HUD](PARAMETRIC_HUD_048B.md) exposes ranged named parameters and a sampled flex check. [051A scoped sketches](SCOPED_SKETCHES_051A.md) add definition ownership, explicit references and guarded per-scope capacity. [Parametric programs](PARAMETRIC_PROGRAMS.md) compile code-defined families into namespaced native features, with atomic re-runs that reject local edits and outside dependants (local CTest only). [072A growing history](GROWABLE_EDITING_072A.md) removes fixed history/node/replay ceilings without pruning or changing authoring semantics; local persistence and UI validation passed. [076A](iterations/076A.md) hardens program expressions and provenance, adds boolean/choice/text parameters (conditional format 60), `.arkprog` exchange and Studio HUD program controls; programs still emit no assembly. | +| B.02 | Everyday sketches and feature history | Parcial | Actionable constraint diagnostics, valid reorder, suppress/rollback and visible dependencies; rejection leaves the document intact. Arcs/snaps/expressions have scoped 005B/008D evidence. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B visual and parametric authoring](iterations/019B.md). [020B exact extrusion gestures and source dimensions](iterations/020B.md). [021B associative extrusion source](iterations/021B.md). [022B source-preserving edits, opaque validated preview handoff and version-37 journal checks](iterations/022B.md). 029B adds equilibrated QR solving and source/revision-bound reviewed conflict alternatives; [sketch assistance](SKETCH_ASSISTANCE_029B.md). [046B profile regions](PROFILE_REGIONS_046B.md) make multi-loop sketches with holes one extrude/revolve profile, with typed loop rejections and an optional region selection. [048B parametric HUD](PARAMETRIC_HUD_048B.md) exposes ranged named parameters and a sampled flex check. [051A scoped sketches](SCOPED_SKETCHES_051A.md) add definition ownership, explicit references and guarded per-scope capacity. [Parametric programs](PARAMETRIC_PROGRAMS.md) compile code-defined families into namespaced native features, with atomic re-runs that reject local edits and outside dependants (local CTest only). [072A growing history](GROWABLE_EDITING_072A.md) removes fixed history/node/replay ceilings without pruning or changing authoring semantics; local persistence and UI validation passed. [076A](iterations/076A.md) hardens program expressions and provenance, adds boolean/choice/text parameters (conditional format 60), `.arkprog` exchange and Studio HUD program controls; programs still emit no assembly. The HUD's Programs view has since gained controls for booleans and numeric or text choices (local `studio-program-hud-ui` only; not yet part of an identified iteration). | | B.03 | Advanced solids and surfaces | Parcial | Difficult loft/sweep/guide/patch/trim/thicken corpus, measured continuity and explicit repair; no mesh fallback concealing exact failures. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B visual and parametric authoring](iterations/019B.md). [020B exact sketch extrusion](iterations/020B.md). [021B bounded face/extrusion geometry](iterations/021B.md). [022B exact polyhedral vertex pull](NATIVE_VERTEX_PULL_022B.md) adds a bounded faceted-solid domain with input/output validity and selfinterference checks. 029B adds bounded exact orientation repair and a difficult geometry corpus; [repair evidence](SURFACE_REPAIR_029B.md). [046B hollow sweep sections](PROFILE_REGIONS_046B.md) sweep inner loops with one shared placement and a volume-conservation check. [051A native regression evidence](NATIVE_GEOMETRY_051A.md) covers shallow C0 offset classification and translated analytic C2 lofts with unchanged tolerances. | | B.04 | Large, configurable assemblies | Parcial | Subassemblies, reused instances, configurations, external references and selective loading; editing one definition updates all occurrences. Supported mechanisms are locally scoped. [022B source-linked component patterns](SPECIALIZED_PATTERNS_022B.md) cover inheritance, planar/spatial points, exact curve stations, chain alternation, skips and actual occurrence consumers; large configuration/loading qualification remains open. 029B adds semantic loading, measured derived-buffer/external-I/O reduction and scoped v2 configuration/pin ownership; [assembly evidence](ASSEMBLY_SCALING_029B.md). [048B exploded views](EXPLODED_VISUALIZE_048B.md) are display-only, revision-neutral and drivable by baked motions. [051A definition-owned sketches](SCOPED_SKETCHES_051A.md) are shared across occurrences and remapped with component checkout/merge. [053B reusable recipes](PARAMETRIC_COMPONENTS_053B.md) embed parts/assemblies with public overrides and explicit pinned revision updates. | | B.05 | Technical drawings and exchange | Parcial | Local 022B binds part definitions, exact occurrences and root/group assemblies to source-linked views, isometric projections, planar sections/hatches, semantic dimensions and declared tolerances in the same CAD viewport. Agents author drawings only on explicit user request. 029B adds bounded exact DXF export with local readback and source metadata. Broader drafting standards, GD&T qualification, independent recipient interoperability and physical qualification remain open. [067G](DRAWING_LIBRARY_067G.md) adds local multipage vector PDF presentation and caller-declared named geometric tolerance frames. [Drawing contract](DRAWINGS.md) [022B viewport evidence](DRAWING_VIEWPORT_022B.md) [029B evidence](VERIFICATION_029B.md). [048B Visualize](EXPLODED_VISUALIZE_048B.md) renders exploded assembly images with balloons and a BOM table on explicit request. | diff --git a/docs/THIRD_PARTY_NOTICES.md b/docs/THIRD_PARTY_NOTICES.md index b14ad15..35e3672 100644 --- a/docs/THIRD_PARTY_NOTICES.md +++ b/docs/THIRD_PARTY_NOTICES.md @@ -16,6 +16,10 @@ projection. Original model cards, attribution, runtime license and runtime third-party notices accompany the payload under `assets/memory` and `licenses`. `scripts/prepare-memory-embeddings.ps1` pins download bytes and source revisions; the asset manifest and package SBOM identify model/runtime files separately. +The runtime comes from the pinned official release archive or, when that is +unreachable, from the pinned official NuGet package. Both carry the same bytes +for the two runtime libraries, the license and the third-party notices, and +the script checks each of those four files against its own SHA-256. The runtime performs local inference without an external embedding service. These dependencies do not change the geometric authority of OCCT/B-rep. diff --git a/scripts/prepare-memory-embeddings.ps1 b/scripts/prepare-memory-embeddings.ps1 index 28f9353..2faffb9 100644 --- a/scripts/prepare-memory-embeddings.ps1 +++ b/scripts/prepare-memory-embeddings.ps1 @@ -26,19 +26,52 @@ Fetch-Pinned "$projectionUrl/README.md" 'MODEL-ORIGINAL-README.md' 'e5d0a1b73964 $runtimeVersion = '1.23.2' $cacheRoot = Join-Path (Split-Path $assetRoot -Parent) 'memory-downloads' New-Item -ItemType Directory -Force -Path $cacheRoot | Out-Null -$archive = Join-Path $cacheRoot "onnxruntime-win-x64-$runtimeVersion.zip" -if (-not (Test-Path -LiteralPath $archive)) { Invoke-WebRequest -UseBasicParsing "https://github.com/microsoft/onnxruntime/releases/download/v$runtimeVersion/onnxruntime-win-x64-$runtimeVersion.zip" -OutFile $archive } -Assert-Digest $archive '0b38df9af21834e41e73d602d90db5cb06dbd1ca618948b8f1d66d607ac9f3cd' +# Two official Microsoft packages carry byte-identical copies of the four files +# used here. Each package is pinned and the extracted files are pinned again +# below, so the result does not depend on which package was reachable. +$runtimePackages = @( + @{ Name="onnxruntime-win-x64-$runtimeVersion.zip" + Url="https://github.com/microsoft/onnxruntime/releases/download/v$runtimeVersion/onnxruntime-win-x64-$runtimeVersion.zip" + Digest='0b38df9af21834e41e73d602d90db5cb06dbd1ca618948b8f1d66d607ac9f3cd' + Root="onnxruntime-win-x64-$runtimeVersion/"; Libraries='lib/' }, + @{ Name="microsoft.ml.onnxruntime.$runtimeVersion.nupkg" + Url="https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime/$runtimeVersion/microsoft.ml.onnxruntime.$runtimeVersion.nupkg" + Digest='25fe172f7fcdf34f2b5b02c8b997f6b88abc282956849d4af4335af23d0c4e4a' + Root=''; Libraries='runtimes/win-x64/native/' } +) +$runtimePackage = $null +$unreachable = @() +foreach ($candidate in $runtimePackages) { + $archive = Join-Path $cacheRoot $candidate.Name + if (-not (Test-Path -LiteralPath $archive)) { + # Download beside the cache name so an interrupted transfer is never + # mistaken for the pinned package on the next run. + $partial = "$archive.partial" + try { + Invoke-WebRequest -UseBasicParsing $candidate.Url -OutFile $partial + Move-Item -LiteralPath $partial -Destination $archive -Force + } catch { + Remove-Item -LiteralPath $partial -Force -ErrorAction SilentlyContinue + $unreachable += "$($candidate.Url): $($_.Exception.Message)" + continue + } + } + Assert-Digest $archive $candidate.Digest + $runtimePackage = $candidate + break +} +if (-not $runtimePackage) { throw "No pinned ONNX Runtime $runtimeVersion package could be downloaded. $($unreachable -join ' | ')" } +foreach ($failure in $unreachable) { Write-Warning "ONNX Runtime source unavailable; using $($runtimePackage.Name). $failure" } Add-Type -AssemblyName System.IO.Compression.FileSystem $zip = [IO.Compression.ZipFile]::OpenRead($archive) try { foreach ($mapping in @{ - 'lib/onnxruntime.dll'='onnxruntime.dll'; - 'lib/onnxruntime_providers_shared.dll'='onnxruntime_providers_shared.dll'; + "$($runtimePackage.Libraries)onnxruntime.dll"='onnxruntime.dll'; + "$($runtimePackage.Libraries)onnxruntime_providers_shared.dll"='onnxruntime_providers_shared.dll'; 'LICENSE'='ONNXRUNTIME-LICENSE.txt'; 'ThirdPartyNotices.txt'='ONNXRUNTIME-ThirdPartyNotices.txt' }.GetEnumerator()) { - $entry = $zip.GetEntry("onnxruntime-win-x64-$runtimeVersion/$($mapping.Key)") + $entry = $zip.GetEntry("$($runtimePackage.Root)$($mapping.Key)") if (-not $entry) { throw "Missing pinned archive entry: $($mapping.Key)" } $stream = $entry.Open() $buffer = [IO.MemoryStream]::new() @@ -50,6 +83,8 @@ try { } finally { $zip.Dispose() } Assert-Digest (Join-Path $assetRoot 'onnxruntime.dll') 'dec964ab1ee36cc9b0ae247d13b376627992fc57dec0454354017ab8fd84f1ea' Assert-Digest (Join-Path $assetRoot 'onnxruntime_providers_shared.dll') 'a2b3a50956aa75a9879c8472bc7df4f7a8072bcd2db19a1b7d988e7688f293ef' +Assert-Digest (Join-Path $assetRoot 'ONNXRUNTIME-LICENSE.txt') 'c250d6278f0b47a6439fb7592b08b58a55eb9f535aa49a1db63211c3f982b674' +Assert-Digest (Join-Path $assetRoot 'ONNXRUNTIME-ThirdPartyNotices.txt') 'e00f828e0a33de591a355ae6606d2625f5758da7d2c844db7821c9dd3e3647b6' # The pinned original model card declares Apache-2.0. Preserve both model cards # alongside the standard Apache-2.0 license text and explicit attribution. Write-ArkBytesIfDifferent -Path (Join-Path $assetRoot 'MODEL-LICENSE.txt') -Bytes ([IO.File]::ReadAllBytes((Join-Path $repoRoot 'LICENSE'))) diff --git a/src/view/program_hud.inl b/src/view/program_hud.inl index 348d258..4b31485 100644 --- a/src/view/program_hud.inl +++ b/src/view/program_hud.inl @@ -1,13 +1,15 @@ // Program controls in the Parametric HUD. Installed parametric programs are read // with parametric_program{action:"inspect"} (namespace, name, values, local_edits). -// Public values are staged like HUD rows and publish as one human transaction: +// Public values (numbers, booleans and listed choices) are staged like HUD rows and +// publish as one human transaction: // prepare{mode:"configure"} evaluates an isolated exact candidate, then // doc_apply{candidate_id,expected_revision} commits it. Both calls use runTool's CAD // worker path, so the viewport keeps painting. A rejection keeps the document, the // revision and the staged values. Detach and Remove ask for confirmation first. struct ProgramHudState { bool view=false;arkjson::Value rows=arkjson::Value::makeArr();u64 revision=~u64(0),epoch=~u64(0),objectEpoch=~u64(0);double inspectMs=0;std::string inspectError,inspectScope,selected; - std::vector> staged;std::string stagedNamespace,stagedSha;u64 stagedRevision=~u64(0); + // Staged values as configure sends them: a number (1/0 for a boolean) or the text of a text choice. + std::vector> staged;std::string stagedNamespace,stagedSha;u64 stagedRevision=~u64(0); std::string result,code,codeNote;bool resultError=false;double prepareMs=0,applyMs=0;int scroll=0,visible=0,focus=-1;std::vector rowNames; }; static ProgramHudState g_programHud; @@ -25,11 +27,19 @@ static Spec spec(const V& s){Spec r;const auto& lo=field(s,"min");const auto& hi static std::string number(double x){if(x==0)x=0;char b[40];if(x==std::floor(x)&&std::fabs(x)<1e15){std::snprintf(b,sizeof b,"%lld",(long long)x);return b;}for(int p=1;p<=17;++p){std::snprintf(b,sizeof b,"%.*g",p,x);if(std::strtod(b,nullptr)==x)break;}return b;} static std::string format(double x,const Spec& s){return number(x)+(s.unit.empty()?"":" "+s.unit);} static std::string range(const Spec& s){std::string t=s.lo&&s.hi?number(s.min)+" .. "+format(s.max,s):s.lo?">= "+format(s.min,s):s.hi?"<= "+format(s.max,s):std::string("no limits");return t+(s.integer?" / integer":" / step "+number(s.step));} +// Parameter kinds come from inspect's parameter_kinds. A boolean stores 1/0 and switches Off/On; +// a choice stores one listed number or text and moves through the declared list. +enum class Kind {Number,Boolean,Choice,Text}; +static Kind kindOf(const V& r,const std::string& name){const std::string kind=field(field(r,"parameter_kinds"),name.c_str()).asStr();return kind=="boolean"?Kind::Boolean:kind=="choice"?Kind::Choice:kind=="text_choice"?Kind::Text:Kind::Number;} +static bool same(const V& a,const V& b){return a.t==b.t&&(a.t==V::Str?a.str==b.str:a.t==V::Num&&a.num==b.num);} +static std::vector options(Kind kind,const V& sp){if(kind==Kind::Boolean)return {V::makeNum(0),V::makeNum(1)};const auto& listed=field(sp,"choices");return kind==Kind::Number||listed.t!=V::Arr?std::vector{}:listed.arr;} +static int optionIndex(const std::vector& list,const V& value){for(size_t i=0;i(std::chrono::steady_clock::now()-started).count();p.revision=g_session.revision;p.epoch=g_documentEpoch;p.objectEpoch=g_objectDocumentEpoch; if(field(r,"isError").b){p.inspectError=field(field(r,"structuredContent"),"error").asStr();p.rows=V::makeArr();}else{p.inspectError.clear();p.rows=field(field(r,"structuredContent"),"programs");if(p.rows.t!=V::Arr)p.rows=V::makeArr();} if(!selected()){p.selected=p.rows.arr.empty()?std::string():field(p.rows.arr.front(),"namespace").asStr();p.scroll=0;p.focus=-1;} - // Staged values of a removed program or of a parameter it no longer declares cannot be applied. - if(!p.staged.empty()){const V* owner=row(p.stagedNamespace);if(!owner)clearStaged();else{const auto& values=field(*owner,"values");p.staged.erase(std::remove_if(p.staged.begin(),p.staged.end(),[&](const auto& e){return field(values,e.first.c_str()).t!=V::Num;}),p.staged.end());if(p.staged.empty())clearStaged();}} + // Staged values of a removed program, or of a parameter it no longer declares with that value type, cannot be applied. + if(!p.staged.empty()){const V* owner=row(p.stagedNamespace);if(!owner)clearStaged();else{const auto& values=field(*owner,"values");p.staged.erase(std::remove_if(p.staged.begin(),p.staged.end(),[&](const auto& e){const auto& stored=field(values,e.first.c_str());return stored.t!=e.second.t||(stored.t!=V::Num&&stored.t!=V::Str);}),p.staged.end());if(p.staged.empty())clearStaged();}} } static void poll(){if(!g_parametricHud.open||g_parametricHud.collapsed||!g_programHud.view||g_dialog||g_busy||g_preparingEdit)return;if(stale())refresh();} static void note(const std::string& text,bool error){auto& p=g_programHud;p.result=text;p.code.clear();p.resultError=error;g_status=text;} @@ -87,41 +97,76 @@ static bool publish(V args,u64 observed,const char* stage){ if(g_error){reject(applied,stage,observed);return false;} return true; } -// The UI clamps to the declared range and rounds integers, and says so; agents are rejected instead. +static bool blocked(){auto& p=g_programHud;if(p.staged.empty()||p.stagedNamespace==p.selected)return false;note("Apply or Reset the staged values of "+p.stagedNamespace+" first",true);return true;} // Staged values belong to the revision the shown rows were read at, not to a newer one. +// Returning to the committed value removes the row from the staged set. +static void stage(const std::string& name,const V& value,const std::string& shown,const char* how,const std::string& clamp={}){ + auto& p=g_programHud;const V* r=selected();if(!r)return;const auto& committed=field(field(*r,"values"),name.c_str()); + if(auto* staged=stagedValue(name)){if(same(value,committed))p.staged.erase(std::remove_if(p.staged.begin(),p.staged.end(),[&](const auto& e){return e.first==name;}),p.staged.end());else *staged=value;} + else if(!same(value,committed)){if(p.staged.empty()){p.stagedRevision=p.revision;p.stagedNamespace=p.selected;p.stagedSha=field(*r,"program_sha256").asStr();}p.staged.push_back({name,value});} + if(p.staged.empty())clearStaged();p.focus=(int)(std::find(p.rowNames.begin(),p.rowNames.end(),name)-p.rowNames.begin()); + note(clamp.empty()?std::to_string(p.staged.size())+" staged / "+how+" "+name+" = "+shown+" / Apply prepares and publishes":clamp+" / "+std::to_string(p.staged.size())+" staged",false); +} +// The UI clamps a number to the declared range and rounds integers, and says so; agents are rejected instead. static void set(const std::string& name,double value,const char* how){ - auto& p=g_programHud;const V* r=selected();if(!r)return;const auto& committed=field(field(*r,"values"),name.c_str());if(committed.t!=V::Num)return; - if(!p.staged.empty()&&p.stagedNamespace!=p.selected){note("Apply or Reset the staged values of "+p.stagedNamespace+" first",true);return;} + const V* r=selected();if(!r||kindOf(*r,name)!=Kind::Number||field(field(*r,"values"),name.c_str()).t!=V::Num||blocked())return; const Spec s=spec(field(field(*r,"parameters"),name.c_str()));std::string clamp; if(s.integer&&value!=std::round(value)){value=std::round(value);clamp="Rounded to the integer "+number(value);} if(s.lo&&values.max){value=s.integer?std::floor(s.max):s.max;clamp="Clamped to the program maximum "+format(value,s);} if(std::fabs(value)<1e-12)value=0; - if(auto* staged=stagedValue(name)){if(value==committed.num)p.staged.erase(std::remove_if(p.staged.begin(),p.staged.end(),[&](const auto& e){return e.first==name;}),p.staged.end());else *staged=value;} - else if(value!=committed.num){if(p.staged.empty()){p.stagedRevision=p.revision;p.stagedNamespace=p.selected;p.stagedSha=field(*r,"program_sha256").asStr();}p.staged.push_back({name,value});} - if(p.staged.empty())clearStaged();p.focus=(int)(std::find(p.rowNames.begin(),p.rowNames.end(),name)-p.rowNames.begin()); - note(clamp.empty()?std::to_string(p.staged.size())+" staged / "+how+" "+name+" = "+format(value,s)+" / Apply prepares and publishes":clamp+" / "+std::to_string(p.staged.size())+" staged",false); + stage(name,V::makeNum(value),format(value,s),how,clamp); +} +// A boolean or a choice takes only its listed values, so nothing is clamped or rounded. +static void choose(const std::string& name,const V& value,const char* how){ + const V* r=selected();if(!r||blocked())return;const Kind kind=kindOf(*r,name);const auto& sp=field(field(*r,"parameters"),name.c_str()); + if(optionIndex(options(kind,sp),value)<0)return;stage(name,value,show(kind,value,spec(sp)),how); } -static double current(const std::string& name){if(const auto* staged=stagedValue(name))return *staged;const V* r=selected();return r?field(field(*r,"values"),name.c_str()).num:0;} +static V currentValue(const std::string& name){if(const auto* staged=stagedValue(name))return *staged;const V* r=selected();return r?field(field(*r,"values"),name.c_str()):V{};} +static double current(const std::string& name){return currentValue(name).num;} static void step(const std::string& name,int direction){ - const V* r=selected();if(!r)return;const Spec s=spec(field(field(*r,"parameters"),name.c_str()));const double now=current(name); + const V* r=selected();if(!r)return;const auto& sp=field(field(*r,"parameters"),name.c_str());const Spec s=spec(sp);const Kind kind=kindOf(*r,name); + if(kind!=Kind::Number){ + // Declared order without wrapping; a staged value the source no longer lists restarts at an end. + const auto list=options(kind,sp);if(list.empty())return;const int at=optionIndex(list,currentValue(name)),next=at<0?(direction>0?0:(int)list.size()-1):at+direction; + if(next<0||next>=(int)list.size()){const std::string value=show(kind,list[(size_t)at],s);note(kind==Kind::Boolean?name+" is already "+value:std::string("Already at the ")+(direction>0?"last":"first")+" choice "+value,false);return;} + choose(name,list[(size_t)next],direction>0?"+":"-");return; + } + const double now=current(name); const bool atMax=s.hi&&direction>0&&now>=s.max-1e-12,atMin=s.lo&&direction<0&&now<=s.min+1e-12; if(atMax||atMin){note(std::string("Already at the program ")+(atMax?"maximum ":"minimum ")+format(atMax?s.max:s.min,s),false);return;} // Next point of the step grid anchored at min (or zero), even from an off-grid value. const double origin=s.lo?s.min:0,k=(now-origin)/s.step;set(name,origin+(direction>0?std::floor(k+1e-9)+1:std::ceil(k-1e-9)-1)*s.step,direction>0?"+":"-"); } +// The editor leaves other Studio windows (Design variants) usable: a value entered over +// an older model is not staged against the newer one; the rows are re-read for review. +static bool editedOverNewerModel(const std::string& ns,const std::string& name,u64 observed,u64 epoch,u64 objectEpoch,const char* again){ + auto& p=g_programHud; + if(g_session.revision!=observed||p.revision!=observed||g_documentEpoch!=epoch||g_objectDocumentEpoch!=objectEpoch){refresh();note("Model changed while editing "+name+" (revision "+std::to_string(observed)+" -> "+std::to_string(g_session.revision)+") / value not staged; review "+ns+" and "+again+" it again",true);return true;} + if(p.selected!=ns||!selected()){note("Program selection changed while editing / value not staged",true);return true;} + return false; +} static void type(const std::string& name){ auto& p=g_programHud;const V* r=selected();if(!r)return;const std::string ns=p.selected;const auto& sp=field(field(*r,"parameters"),name.c_str());const Spec s=spec(sp); const std::string description=field(sp,"description").asStr();std::string text=number(current(name));const u64 observed=p.revision,epoch=g_documentEpoch,objectEpoch=g_objectDocumentEpoch; if(!editText(("Program value: "+ns+" / "+name+" ("+range(s)+")"+(description.empty()?"":" / "+description)).c_str(),text))return; - // The editor leaves other Studio windows (Design variants) usable: a value typed over - // an older model is not staged against the newer one; the rows are re-read for review. - if(g_session.revision!=observed||p.revision!=observed||g_documentEpoch!=epoch||g_objectDocumentEpoch!=objectEpoch){refresh();note("Model changed while editing "+name+" (revision "+std::to_string(observed)+" -> "+std::to_string(g_session.revision)+") / value not staged; review "+ns+" and type it again",true);return;} - if(p.selected!=ns||!selected()){note("Program selection changed while editing / value not staged",true);return;} + if(editedOverNewerModel(ns,name,observed,epoch,objectEpoch,"type"))return; bool ok=false;const double value=evalExpr(trimField(text),g_doc.buildEnv(),&ok); if(!ok||!std::isfinite(value)){note("Enter a finite number (or an expression of document parameters) for "+name,true);return;} set(name,value,"typed"); } +// The value box: a number is typed, a boolean switches and a choice opens its declared list. +static void pick(const std::string& name){ + auto& p=g_programHud;const V* r=selected();if(!r)return;const Kind kind=kindOf(*r,name);if(kind==Kind::Number){type(name);return;} + const std::string ns=p.selected;const auto& sp=field(field(*r,"parameters"),name.c_str());const Spec s=spec(sp);const auto list=options(kind,sp);if(list.empty())return;const V now=currentValue(name); + if(kind==Kind::Boolean){choose(name,V::makeNum(now.num!=0?0:1),"switched");return;} + const std::string description=field(sp,"description").asStr();std::vector labels;for(const auto& option:list)labels.push_back(show(kind,option,s)); + std::vector fields{choiceField(name.c_str(),show(kind,now,s),labels)};const u64 observed=p.revision,epoch=g_documentEpoch,objectEpoch=g_objectDocumentEpoch; + if(!editFields(("Program choice: "+ns+" / "+name).c_str(),(std::to_string(list.size())+" declared choices"+(description.empty()?"":" / "+description)+". The choice is staged; Apply publishes it.").c_str(),fields,false,"Stage"))return; + if(editedOverNewerModel(ns,name,observed,epoch,objectEpoch,"choose"))return; + const auto found=std::find(labels.begin(),labels.end(),fields.front().value);if(found==labels.end()){note("Choose one of the declared values of "+name,true);return;} + choose(name,list[(size_t)(found-labels.begin())],"chose"); +} static void apply(){ auto& p=g_programHud;if(p.staged.empty()){note("Nothing staged / change a value first",false);return;} const V* r=row(p.stagedNamespace);if(!r){note("Program "+p.stagedNamespace+" is no longer installed / staged values discarded",true);clearStaged();return;} @@ -130,7 +175,7 @@ static void apply(){ note(std::string(source?"Program source of "+p.stagedNamespace+" changed":"Model changed")+" since these values were staged (revision "+std::to_string(p.stagedRevision)+" -> "+std::to_string(g_session.revision)+"). Review them: Apply again prepares them on the current model, Reset discards them.",true); p.stagedRevision=g_session.revision;p.stagedSha=field(*r,"program_sha256").asStr();return;} const u64 observed=p.stagedRevision;const std::string ns=p.stagedNamespace;const size_t count=p.staged.size(); - V a=V::makeObj(),values=V::makeObj();for(const auto& e:p.staged)values.set(e.first,V::makeNum(e.second));a.set("mode",V::makeStr("configure"));a.set("namespace",V::makeStr(ns));a.set("values",values); + V a=V::makeObj(),values=V::makeObj();for(const auto& e:p.staged)values.set(e.first,e.second);a.set("mode",V::makeStr("configure"));a.set("namespace",V::makeStr(ns));a.set("values",values); if(!publish(a,observed,"Apply"))return; clearStaged();refresh();char text[240];std::snprintf(text,sizeof text,"Applied %zu value%s to %s / revision %llu / exact candidate %.0f ms, publish %.0f ms",count,count==1?"":"s",ns.c_str(),(unsigned long long)g_session.revision,p.prepareMs,p.applyMs);note(text,false); } @@ -202,23 +247,30 @@ templatestatic void drawProgramHud(Rect rect,Mini& mini,c const auto& parameters=field(*r,"parameters");const auto& values=field(*r,"values");for(const auto& kv:parameters.obj)p.rowNames.push_back(kv.first);std::sort(p.rowNames.begin(),p.rowNames.end()); // stored key order is not stable float ry=y+l.headerH;const float listBottom=ry+l.rowsH-(l.overflow?22.f:0.f); for(int i=p.scroll;i<(int)p.rowNames.size()&&ilistBottom+1)break;const auto& name=p.rowNames[(size_t)i];const auto& sp=field(parameters,name.c_str());const auto& committed=field(values,name.c_str());const Spec s=spec(sp);const double* staged=stagedValue(name); - // Updated program source can narrow a range under a staged value; Apply then rejects with PROGRAM_VALUES. - const bool numeric=committed.t==V::Num;const double shownValue=staged?*staged:committed.num;const bool outside=numeric&&((s.lo&&shownValues.max)); + if(ry+rowH>listBottom+1)break;const auto& name=p.rowNames[(size_t)i];const auto& sp=field(parameters,name.c_str());const auto& committed=field(values,name.c_str());const Spec s=spec(sp);const V* staged=stagedValue(name); + // A row is editable when its stored value has the type its kind stores. Updated program source can + // narrow a range or drop a choice under a staged value; Apply then rejects with PROGRAM_VALUES. + const Kind kind=kindOf(*r,name);const auto list=options(kind,sp);const bool editable=committed.t==(kind==Kind::Text?V::Str:V::Num)&&(kind==Kind::Number||!list.empty()); + const V& shownValue=staged?*staged:committed;const int at=optionIndex(list,shownValue);const bool outside=editable&&(kind==Kind::Number?(s.lo&&shownValue.nums.max):at<0); if(staged){rect(x+6,ry+1,w-12,rowH-4,6,.30f,.20f,.04f,.55f,.98f,.70f,.26f,.55f,1);rect(x+6,ry+5,3,rowH-12,1,.99f,.72f,.27f,1,0,0,0,0,0);} - const float plusX=x+w-12-26,valueW=std::min(96.f,w*.32f),valueX=plusX-4-valueW,minusX=valueX-4-26,labelW=(numeric?minusX:x+w-12-valueW)-(x+14)-6; + const float plusX=x+w-12-26,valueW=std::min(96.f,w*.32f),valueX=plusX-4-valueW,minusX=valueX-4-26,labelW=(editable?minusX:x+w-12-valueW)-(x+14)-6; textOut(fitText(name,.62f,labelW),x+14,ry+5,.62f,.874f,.91f,.94f); - std::string second=numeric?range(s):"Not a number / configure it with an agent";if(staged)second="was "+format(committed.num,s)+" / "+second;if(outside)second="outside range / "+second; + std::string choices;for(const auto& option:list)choices+=(choices.empty()?"":", ")+show(kind,option,s); + std::string second=!editable?"Unsupported value / configure it with the tool":kind==Kind::Number?range(s):kind==Kind::Boolean?"Off or On":(at<0?std::to_string(list.size())+" choices":std::to_string(at+1)+" of "+std::to_string(list.size()))+" / "+choices; + if(staged)second="was "+show(kind,committed,s)+" / "+second;if(outside)second=std::string(kind==Kind::Number?"outside range":"not a declared choice")+" / "+second; textOut(fitText(second,.48f,w-28),x+14,ry+25,.48f,outside?.98f:staged?.99f:.53f,outside?.48f:staged?.78f:.65f,outside?.42f:staged?.44f:.73f); - const std::string shown=numeric?format(shownValue,s):committed.dump(); - if(!numeric){const float vx=x+w-12-valueW;textOut(fitText(shown,.60f,valueW),vx+valueW-std::min(valueW,textWidth(shown,.60f)),ry+6,.60f,.715f,.745f,.769f);} + const std::string shown=editable?show(kind,shownValue,s):committed.dump(); + if(!editable){const float vx=x+w-12-valueW;textOut(fitText(shown,.60f,valueW),vx+valueW-std::min(valueW,textWidth(shown,.60f)),ry+6,.60f,.715f,.745f,.769f);} else{ - const int base=rowBase+4*i;const bool enabled=!otherStaged;const bool hover=enabled&&pointer.x>=valueX&&pointer.x=ry+3&&pointer.y=valueX&&pointer.x=ry+3&&pointer.y=(int)p.rowNames.size())return true;const std::string name=p.rowNames[(size_t)index]; - if(part==0)step(name,-1);else if(part==2)step(name,1);else if(part==1)type(name);return true; + if(part==0)step(name,-1);else if(part==2)step(name,1);else if(part==1)pick(name);return true; } diff --git a/src/view/program_hud_selftest.inl b/src/view/program_hud_selftest.inl index ddf929b..a66bb0e 100644 --- a/src/view/program_hud_selftest.inl +++ b/src/view/program_hud_selftest.inl @@ -4,7 +4,8 @@ // above a narrowed max without changing the document, does not stage a value typed while // another writer configured the program, shows local edits, cancels and confirms Detach, // and removes a second program. Its binding rows must equal the live inspect, also with -// imported meshes in the drawing. Captures are written next to --shot. +// imported meshes in the drawing. A second program with a text choice, a numeric choice and a +// boolean is configured from their own controls. Captures are written next to --shot. static int testProgramHudUi(HWND hwnd,const std::string& shotPath){ using V=arkjson::Value;using namespace program_hud; auto check=[](bool ok,const std::string& why){if(!ok)throw std::runtime_error(why);}; @@ -21,7 +22,7 @@ static int testProgramHudUi(HWND hwnd,const std::string& shotPath){ auto value=[&](const char* ns,const char* name){const V* b=binding(ns);check(b!=nullptr,std::string("Binding missing: ")+ns);return field(field(*b,"values"),name).num;}; auto named=[&](const char* prefix){size_t n=0;for(const auto& f:g_doc.features)if(f.name.rfind(prefix,0)==0)++n;return n;}; auto bodies=[&](const char* prefix){size_t n=0;for(const auto& body:g_doc.evalBodies)if(const auto* f=g_doc.find(body.id);f&&f->name.rfind(prefix,0)==0)++n;return n;}; - auto staged=[&](const char* name)->double{for(const auto& e:g_programHud.staged)if(e.first==name)return e.second;throw std::runtime_error(std::string("Not staged: ")+name);}; + auto staged=[&](const char* name)->double{for(const auto& e:g_programHud.staged)if(e.first==name)return e.second.num;throw std::runtime_error(std::string("Not staged: ")+name);}; auto agent=[&](const char* commands){V a;check(arkjson::parse(commands,a),"Bad agent fixture");V actor=V::makeObj();actor.set("kind",V::makeStr("agent"));actor.set("id",V::makeStr("program-hud-selftest"));a.set("actor",actor);a.set("expected_revision",V::makeNum((double)g_session.revision));runTool("doc_apply",a);check(!g_error,g_status);}; auto install=[&](const char* example,const char* ns){V a=V::makeObj();a.set("action",V::makeStr("prepare"));a.set("mode",V::makeStr("install"));a.set("namespace",V::makeStr(ns));a.set("expected_revision",V::makeNum((double)g_session.revision)); for(const auto& row:parametricProgramExamples().arr)if(field(row,"id").asStr()==example)a.set("program",field(row,"program"));check(a.find("program")!=nullptr,std::string("Example missing: ")+example); @@ -120,8 +121,46 @@ static int testProgramHudUi(HWND hwnd,const std::string& shotPath){ for(int k=0;k<4;++k){V a=V::makeObj();a.set("path",V::makeStr(scan));a.set("name",V::makeStr("Scan "+std::to_string(k+1)));a.set("expected_revision",V::makeNum((double)g_session.revision));runTool("import_mesh",a);check(!g_error,g_status);} std::filesystem::remove(scan);draw();check(g_programHud.revision==g_session.revision,"Program rows were not re-read after the imports");sameAsLive("with imported meshes"); evidence<<"4 imported meshes, "<V{for(const auto& e:g_programHud.staged)if(e.first==name)return e.second;throw std::runtime_error(std::string("Not staged: ")+name);}; + auto stored=[&](const char* name)->V{const V* b=binding("plaque");check(b!=nullptr,"Binding missing: plaque");return field(field(*b,"values"),name);}; + const u64 plaqueRevision=g_session.revision;const auto plaqueJson=documentToJson(g_doc); + stage("choices-stage");press(rowId("finish",2));check(stagedValueOf("finish").t==V::Str&&stagedValueOf("finish").str=="gloss"&&g_programHud.result.find("+ finish = gloss")!=std::string::npos,"+ did not stage the next text choice: "+g_programHud.result); + g_dialogSmoke=3;g_dialogShot=shotPath+".program-hud-choice-dialog.png";g_dialogOverrideQueue.push_back({"matte"});press(rowId("finish",1));g_dialogSmoke=0;g_dialogShot.clear();check(stagedValueOf("finish").str=="matte"&&g_programHud.result.find("chose finish = matte")!=std::string::npos,"The choice list did not stage the picked text: "+g_programHud.result); + press(rowId("cap",1));check(stagedValueOf("cap").t==V::Num&&stagedValueOf("cap").num==1&&g_programHud.result.find("switched cap = On")!=std::string::npos,"The boolean did not switch on: "+g_programHud.result); + press(rowId("pegs",2));check(stagedValueOf("pegs").num==6,"+ did not stage the next numeric choice");press(rowId("pegs",2));check(stagedValueOf("pegs").num==6&&g_programHud.result.find("Already at the last choice 6")!=std::string::npos,"Stepping past the last choice was not refused: "+g_programHud.result); + check(g_programHud.staged.size()==3&&g_session.revision==plaqueRevision&&documentToJson(g_doc)==plaqueJson,"Staging typed parameters changed the document");inside("choices-staged");capture(".program-hud-choices-staged.png"); + stage("choices-apply");press(48015);check(!g_programHud.resultError&&g_session.revision==plaqueRevision+1&&g_programHud.staged.empty()&&g_programHud.result.find("Applied 3 values to plaque")!=std::string::npos,"Apply did not publish the typed parameters as one revision: "+g_programHud.code+" / "+g_programHud.result); + check(stored("finish").t==V::Str&&stored("finish").str=="matte"&&stored("cap").num==1&&stored("pegs").num==6&&named("plaque / Peg ")==6&&named("plaque / Cap")==1&&named("plaque / Plate matte")==1&&named("plaque / Plate satin")==0,"Configured values or generated objects differ from the staged choices"); + {V a=V::makeObj();a.set("id",V::makeStr("plaque / Plate matte"));a.set("detail",V::makeStr("properties"));const auto inspected=g_session.call("native_inspect",a);const auto& report=field(field(inspected,"structuredContent"),"report");const double volume=field(report,"volume_mm3").num,expected=80.*30*3; + check(field(report,"brep_valid").b&&std::fabs(volume-expected)<=expected*1e-6,"Plate is not the exact solid of the chosen finish: "+field(inspected,"structuredContent").dump().substr(0,400));evidence<<"typed parameters: finish matte, cap On and pegs 6 in one configure, Plate volume "<