@innovastudio/contentbuilder 1.5.217 → 1.5.218

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17428,8 +17428,16 @@ class CodeElement {
17428
17428
  if (doc.getElementById('css-cb-code-element')) return;
17429
17429
  const style = doc.createElement('style');
17430
17430
  style.id = 'css-cb-code-element';
17431
+ /*
17432
+ No 'position' here. The editor must lay a block out exactly as the
17433
+ published page does, and a block whose content is absolutely
17434
+ positioned (a full-bleed scene in an overlay, say) resolves against
17435
+ its nearest positioned ancestor: making the block itself one put
17436
+ that content inside a 30px-tall box in the editor while the same
17437
+ markup filled the section on the page.
17438
+ */
17431
17439
  style.textContent = `
17432
- [${ATTR}] { min-height: 30px; position: relative; -webkit-user-select: none; user-select: none; }
17440
+ [${ATTR}] { min-height: 30px; -webkit-user-select: none; user-select: none; }
17433
17441
  `;
17434
17442
  doc.head.appendChild(style);
17435
17443
  }
@@ -20970,7 +20978,7 @@ function getOffset(element) {
20970
20978
  top: box.top + (window.pageYOffset - document.documentElement.clientTop)
20971
20979
  };
20972
20980
  }
20973
- var location = WINDOW.location;
20981
+ var location$1 = WINDOW.location;
20974
20982
  var REGEXP_ORIGINS = /^(\w+:)\/\/([^:/?#]*):?(\d*)/i;
20975
20983
  /**
20976
20984
  * Check if the given URL is a cross origin URL.
@@ -20980,7 +20988,7 @@ var REGEXP_ORIGINS = /^(\w+:)\/\/([^:/?#]*):?(\d*)/i;
20980
20988
 
20981
20989
  function isCrossOriginURL(url) {
20982
20990
  var parts = url.match(REGEXP_ORIGINS);
20983
- return parts !== null && (parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port);
20991
+ return parts !== null && (parts[1] !== location$1.protocol || parts[2] !== location$1.hostname || parts[3] !== location$1.port);
20984
20992
  }
20985
20993
  /**
20986
20994
  * Add timestamp to the given URL.
@@ -82978,6 +82986,23 @@ ${this.buildHistoryContext()}`;
82978
82986
  * IMAGE PREVIEW HELPER
82979
82987
  * ============================================================================
82980
82988
  */
82989
+ /* Attachments shown under a user message, matching what the composer
82990
+ * renders when a file is attached for real. Demo playback only. */
82991
+ addUserAttachmentPreview(images) {
82992
+ const previewDiv = document.createElement('div');
82993
+ previewDiv.className = 'message user';
82994
+ let html = '<div class="message-content" style="display:flex;flex-wrap:wrap;gap:8px;padding:10px;">';
82995
+ images.forEach(img => {
82996
+ const url = this.escapeHtml(img.url || '');
82997
+ if (!url) return;
82998
+ const alt = this.escapeHtml(img.context || url.split('/').pop() || 'Attachment');
82999
+ html += `<img src="${url}" alt="${alt}" style="width:64px;height:64px;object-fit:cover;border-radius:6px;" />`;
83000
+ });
83001
+ html += '</div>';
83002
+ previewDiv.innerHTML = html;
83003
+ this.messagesContainer.appendChild(previewDiv);
83004
+ this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
83005
+ }
82981
83006
  addImagePreview(images) {
82982
83007
  const out = s => this.out(s);
82983
83008
  const previewDiv = document.createElement('div');
@@ -84528,9 +84553,12 @@ Return ONLY the edited section as a single <div class="is-section ...>. Do not o
84528
84553
  announcement.setAttribute('aria-live', 'polite');
84529
84554
  announcement.className = 'sr-only';
84530
84555
  announcement.textContent = message;
84531
- document.body.appendChild(announcement);
84556
+
84557
+ // Must live inside the builder container: the .sr-only rule is scoped
84558
+ // to [data-cb-ui], so elsewhere the text would be visible on screen.
84559
+ this.builderStuff.appendChild(announcement);
84532
84560
  setTimeout(() => {
84533
- document.body.removeChild(announcement);
84561
+ announcement.remove();
84534
84562
  }, 1000);
84535
84563
  }
84536
84564
 
@@ -84545,6 +84573,11 @@ Return ONLY the edited section as a single <div class="is-section ...>. Do not o
84545
84573
  this.demoConversations.forEach(msg => {
84546
84574
  if (msg.role === 'user') {
84547
84575
  this.addMessage('user', msg.content);
84576
+
84577
+ // Attachments the user sent with the message
84578
+ if (msg.imagePreview && msg.imagePreview.length > 0) {
84579
+ this.addUserAttachmentPreview(msg.imagePreview);
84580
+ }
84548
84581
  } else if (msg.role === 'assistant') {
84549
84582
  this.addMessage('assistant', msg.content, true);
84550
84583
 
@@ -84885,6 +84918,45 @@ Return ONLY the edited section as a single <div class="is-section ...>. Do not o
84885
84918
  }
84886
84919
  }
84887
84920
 
84921
+ /**
84922
+ * repair-markup.js
84923
+ * ----------------------------------------------------------------------------
84924
+ * Fixes applied to AI-written HTML on its way to the page, in the targets'
84925
+ * normalize() step.
84926
+ *
84927
+ * Only for defects that are unambiguous — a rule the framework states, where
84928
+ * the result is visibly broken and there is exactly one correct repair. Taste
84929
+ * belongs in the context documentation, not here: this must never turn one
84930
+ * valid design into another.
84931
+ * ----------------------------------------------------------------------------
84932
+ */
84933
+
84934
+ /*
84935
+ An outline button needs 'hover:border-transparent'.
84936
+
84937
+ 'border-current' makes the 2px border follow the text colour, hover colour
84938
+ included, so on hover the border becomes a visible ring and the hover fill
84939
+ stops inside it — the button appears to shrink. The class lets the border take
84940
+ the hover background instead.
84941
+
84942
+ Left alone: a button that sets its own hover border (any 'hover:border-*'
84943
+ class, or 'border' listed in data-cb-hover), which is a deliberate choice the
84944
+ class would override.
84945
+ */
84946
+ function repairButtons(root) {
84947
+ if (!root || !root.querySelectorAll) return 0;
84948
+ let fixed = 0;
84949
+ root.querySelectorAll('a[role="button"], button').forEach(el => {
84950
+ if (!el.classList.contains('border-current')) return;
84951
+ if ([...el.classList].some(c => c.startsWith('hover:border-'))) return;
84952
+ const hover = (el.getAttribute('data-cb-hover') || '').split(/\s+/);
84953
+ if (hover.includes('border')) return;
84954
+ el.classList.add('hover:border-transparent');
84955
+ fixed++;
84956
+ });
84957
+ return fixed;
84958
+ }
84959
+
84888
84960
  /**
84889
84961
  * target-section.js
84890
84962
  * ----------------------------------------------------------------------------
@@ -84899,7 +84971,6 @@ Return ONLY the edited section as a single <div class="is-section ...>. Do not o
84899
84971
  * products run the same engine instead of a copy of it.
84900
84972
  * ----------------------------------------------------------------------------
84901
84973
  */
84902
-
84903
84974
  function createSectionTarget(engine) {
84904
84975
  const b = () => engine.builder;
84905
84976
  const nodes = () => b().getSectionNodes();
@@ -84930,7 +85001,7 @@ function createSectionTarget(engine) {
84930
85001
 
84931
85002
  /* Reference the host actually supplied, in the order it is offered. */
84932
85003
  const docTopics = () => {
84933
- const t = ['box', 'animation'].filter(k => engine.contextParts[k]);
85004
+ const t = ['box', 'animation', '3d', 'games', 'code'].filter(k => engine.contextParts[k]);
84934
85005
  if (motionPathMode()) t.push('motionPath');
84935
85006
  return t;
84936
85007
  };
@@ -84948,6 +85019,7 @@ function createSectionTarget(engine) {
84948
85019
  const found = holder.querySelectorAll('.is-section');
84949
85020
  if (found.length !== 1) return null;
84950
85021
  const section = found[0];
85022
+ repairButtons(section);
84951
85023
  section.querySelectorAll('div.is-container').forEach(c => {
84952
85024
  if (![...c.classList].some(x => /^size-\d/.test(x))) c.classList.add('size-17');
84953
85025
  if (![...c.classList].some(x => /^leading-\d/.test(x))) c.classList.add('leading-17');
@@ -85074,7 +85146,7 @@ Sections are <div class="is-section ...">. Use ONLY documented classes — this
85074
85146
  ${onDemand.length ? `
85075
85147
  REFERENCE YOU MUST LOAD WHEN RELEVANT
85076
85148
  The documentation below covers grid, typography, spacing and colour. Further reference is available through get_framework_docs and is NOT included here:
85077
- ${onDemand.includes('box') ? '- "box": section and box structure — load before ADDING, REMOVING or RESTRUCTURING a section, or changing its layout, width or background.\n' : ''}${onDemand.includes('animation') ? '- "animation": the motion system — load before adding, changing or removing any animation.\n' : ''}${onDemand.includes('motionPath') ? `- "motionPath": moving an OBJECT along a route — a plane, rocket, car, dot or arrow flying, following or tracing a path, curve or journey across a scene. ${motionPathMode() === 'preserve' ? 'This effect is DISABLED for this site: load it only to preserve or adjust a path already in the markup, never to add one.' : 'Load it only for that; it is not needed for ordinary motion — entrances, fades, parallax, scroll reveals or hover effects.'} ALSO load it whenever markup you are about to edit contains a "data-fx-path" attribute, whatever the request was — those attributes are undocumented anywhere else and you will corrupt them otherwise.\n` : ''}Load what a task needs BEFORE writing markup for it. Never guess at classes from those areas.` : ''}`;
85149
+ ${onDemand.includes('box') ? '- "box": section and box structure — load before ADDING, REMOVING or RESTRUCTURING a section, or changing its layout, width or background.\n' : ''}${onDemand.includes('animation') ? '- "animation": the motion system — load before adding, changing or removing any animation.\n' : ''}${onDemand.includes('3d') ? '- "3d": real-time 3D (three.js) — load before creating or editing a 3D scene, 3D object or WebGL content; for a 3D game load it TOGETHER with "games".\n' : ''}${onDemand.includes('games') ? '- "games": building any game, 2D or 3D — load before game work. A 2D/doodle/casual game uses Canvas 2D from this doc alone (no three.js); a 3D game also loads "3d".\n' : ''}${onDemand.includes('code') ? '- "code": the code block (data-cb-code) for elements that need JavaScript — load before writing or editing one. Not needed for 3D (the "3d" reference covers its own block).\n' : ''}${onDemand.includes('motionPath') ? `- "motionPath": moving an OBJECT along a route — a plane, rocket, car, dot or arrow flying, following or tracing a path, curve or journey across a scene. ${motionPathMode() === 'preserve' ? 'This effect is DISABLED for this site: load it only to preserve or adjust a path already in the markup, never to add one.' : 'Load it only for that; it is not needed for ordinary motion — entrances, fades, parallax, scroll reveals or hover effects.'} ALSO load it whenever markup you are about to edit contains a "data-fx-path" attribute, whatever the request was — those attributes are undocumented anywhere else and you will corrupt them otherwise.\n` : ''}Load what a task needs BEFORE writing markup for it. Never guess at classes from those areas.` : ''}`;
85078
85150
  },
85079
85151
  /* Structural tools. The engine adds the attachment and image tools. */
85080
85152
  tools() {
@@ -85146,7 +85218,7 @@ ${onDemand.includes('box') ? '- "box": section and box structure — load before
85146
85218
  }
85147
85219
  }, ...(topics.length ? [{
85148
85220
  name: 'get_framework_docs',
85149
- description: `Load reference not included in your instructions. "box" covers section and box structure — layout, width, background. "animation" covers the motion system.${topics.includes('motionPath') ? ' "motionPath" covers moving an object along a route (a plane/rocket/dot tracing a path across a scene) — load it for that, and whenever markup you are editing contains a "data-fx-path" attribute.' : ''} Load what you need before writing the markup that uses it.`,
85221
+ description: `Load reference not included in your instructions. "box" covers section and box structure — layout, width, background. "animation" covers the motion system.${topics.includes('3d') ? ' "3d" covers real-time 3D (three.js).' : ''}${topics.includes('games') ? ' "games" covers building games, 2D and 3D.' : ''}${topics.includes('code') ? ' "code" covers the JavaScript code block (data-cb-code).' : ''}${topics.includes('motionPath') ? ' "motionPath" covers moving an object along a route (a plane/rocket/dot tracing a path across a scene) — load it for that, and whenever markup you are editing contains a "data-fx-path" attribute.' : ''} Load what you need before writing the markup that uses it.`,
85150
85222
  parameters: {
85151
85223
  type: 'object',
85152
85224
  properties: {
@@ -85346,7 +85418,7 @@ function createRowTarget(engine) {
85346
85418
  const limit = () => engine.limits.toolResult;
85347
85419
 
85348
85420
  /* Reference the host actually supplied, in the order it is offered. */
85349
- const docTopics = () => ['buttons', 'animation'].filter(k => engine.contextParts[k]);
85421
+ const docTopics = () => ['buttons', 'animation', '3d', 'games', 'code'].filter(k => engine.contextParts[k]);
85350
85422
 
85351
85423
  /*
85352
85424
  Exactly one .row, or null. Markup arrives fenced as often as not, and a
@@ -85360,6 +85432,7 @@ function createRowTarget(engine) {
85360
85432
  holder.innerHTML = html.replace(/```html\n?/g, '').replace(/```\n?/g, '').trim();
85361
85433
  const found = Array.from(holder.children).filter(el => el.classList.contains('row'));
85362
85434
  if (found.length !== 1) return null;
85435
+ repairButtons(found[0]);
85363
85436
  return found[0].outerHTML;
85364
85437
  }
85365
85438
  return {
@@ -86018,6 +86091,78 @@ ${docs}`;
86018
86091
  }
86019
86092
  });
86020
86093
  }
86094
+
86095
+ /*
86096
+ 3D asset generation (image-to-3D). Offered only when the host lists
86097
+ models3D — the same opt-in convention as the image tools. One image in,
86098
+ one .glb URL out; the model then loads it with GLTFLoader per the "3d"
86099
+ reference doc.
86100
+ */
86101
+ if (this.threeDConfig()) {
86102
+ const threeDParams = {
86103
+ image_url: {
86104
+ type: 'string',
86105
+ description: 'URL of the source image: a photo on the page, or a generate_image result.'
86106
+ }
86107
+ };
86108
+ if ((this.currentAttachments || []).some(a => a && a.kind === 'image')) {
86109
+ threeDParams.attachment = {
86110
+ type: 'integer',
86111
+ description: 'Use an attached image as the source instead of image_url, numbered from 1.'
86112
+ };
86113
+ }
86114
+ t.push({
86115
+ name: 'generate_3d_model',
86116
+ description: 'Generate a 3D model (.glb file) from an image and return its URL, for use inside a 3D scene (load the "3d" reference doc first if you have not). The image must show ONE object, clearly and mostly front-facing — a product shot, an illustration, a generated image. For an object with no source image, call generate_image first and feed its result in. Generation is billed and takes 30-90 seconds, so one call per object the user asked for. Then load the returned URL with GLTFLoader and the normalize pattern from the "3d" reference — the URL goes inside the scene code, never in an <img>.',
86117
+ parameters: {
86118
+ type: 'object',
86119
+ properties: threeDParams,
86120
+ required: []
86121
+ }
86122
+ });
86123
+ }
86124
+
86125
+ /*
86126
+ The critic loop: the model can SEE what a code block's canvas actually
86127
+ renders and fix visual problems before answering — the difference
86128
+ between shipping a black scene and noticing it. Offered only while the
86129
+ page holds a canvas inside a code block, so ordinary requests never
86130
+ see it.
86131
+ */
86132
+ /* Gated on the block, not its canvas — right after an insert the
86133
+ scene is still importing modules and the canvas does not exist yet,
86134
+ which is exactly when the model needs the tool in its list.
86135
+ captureRender does the waiting. */
86136
+ /*
86137
+ Only a model that reads images can act on the screenshot — for a
86138
+ text-only model the injected image is a provider error, so the tool is
86139
+ simply not offered and the docs' "when a view_render tool is offered"
86140
+ phrasing degrades the whole flow gracefully. Same capability registry
86141
+ the attach button uses.
86142
+ */
86143
+ /*
86144
+ Off unless the host turns it on: the self-check costs an extra
86145
+ vision round-trip per scene, so it is opt-in per site.
86146
+ */
86147
+ const selfCheckOn = !!(this.builder && this.builder.renderSelfCheck);
86148
+ const seesImages = resolveFileCapability(this.model, this.v1 && this.v1.codeModels || this.builder && this.builder.codeModels || []).accepts.includes('image');
86149
+ if (selfCheckOn && seesImages && this.builder && this.builder.doc && this.builder.doc.querySelector('[data-cb-code]')) {
86150
+ t.push({
86151
+ name: 'view_render',
86152
+ description: 'Screenshot the live render of a code block\'s canvas (3D scene, game, visualization). ALWAYS call this after creating a scene or making a significant visual change, then LOOK at the image and fix what is wrong (all black = missing environment/lights; empty = camera not framing the content; clipped or tiny = wrong scale or camera position) before giving your final answer. The screenshot arrives as an image in the next message. HTML overlays are not included — only the canvas.',
86153
+ parameters: {
86154
+ type: 'object',
86155
+ properties: {
86156
+ block: {
86157
+ type: 'integer',
86158
+ description: '1-based index among the page\'s canvas-bearing code blocks; omit for the first',
86159
+ default: 1
86160
+ }
86161
+ },
86162
+ required: []
86163
+ }
86164
+ });
86165
+ }
86021
86166
  return t;
86022
86167
  }
86023
86168
 
@@ -86068,6 +86213,14 @@ ${docs}`;
86068
86213
  {
86069
86214
  return await this.editImage(args);
86070
86215
  }
86216
+ case 'generate_3d_model':
86217
+ {
86218
+ return await this.generate3DModel(args);
86219
+ }
86220
+ case 'view_render':
86221
+ {
86222
+ return await this.captureRender(args);
86223
+ }
86071
86224
  default:
86072
86225
  return {
86073
86226
  error: `unknown tool ${name}`
@@ -86087,6 +86240,12 @@ ${docs}`;
86087
86240
 
86088
86241
  async send(text, attachments = []) {
86089
86242
  this.abort = new AbortController();
86243
+ // Per-request ceilings on the expensive/loopable tools. MAX_STEPS
86244
+ // bounds the loop as a whole; these stop a model from burning paid
86245
+ // generations or endless self-checks chasing a critique it cannot
86246
+ // satisfy — past the cap the tool refuses and tells it to finish.
86247
+ this.spent3D = 0;
86248
+ this.spentShots = 0;
86090
86249
  this.beginBatch(); // one undo entry for the whole request
86091
86250
  this.currentAttachments = attachments || [];
86092
86251
  this.attachmentUrls = {};
@@ -86147,6 +86306,30 @@ ${docs}`;
86147
86306
  content: JSON.stringify(result)
86148
86307
  });
86149
86308
  }
86309
+
86310
+ /*
86311
+ view_render screenshots cannot ride in the tool message —
86312
+ tool results are text on every provider — so they follow as a
86313
+ user message. dropAttachmentPayloads compacts them on the next
86314
+ request like any other image, so they never accumulate.
86315
+ */
86316
+ if (this.pendingShots && this.pendingShots.length) {
86317
+ const parts = [{
86318
+ type: 'text',
86319
+ text: 'Screenshot of the current render:'
86320
+ }];
86321
+ this.pendingShots.forEach(u => parts.push({
86322
+ type: 'image_url',
86323
+ image_url: {
86324
+ url: u
86325
+ }
86326
+ }));
86327
+ messages.push({
86328
+ role: 'user',
86329
+ content: parts
86330
+ });
86331
+ this.pendingShots = [];
86332
+ }
86150
86333
  }
86151
86334
 
86152
86335
  // Ran out of steps. Not an error the user should see as a crash.
@@ -86582,6 +86765,267 @@ ${docs}`;
86582
86765
  freshOutline() {
86583
86766
  return this.target.outline();
86584
86767
  }
86768
+
86769
+ /*
86770
+ Screenshot a code block's canvas for the critic loop. Waits for the canvas
86771
+ to exist and paint (module imports take a moment after an insert), then
86772
+ downscales to keep the image cheap. Requires the scene's renderer to have
86773
+ preserveDrawingBuffer: true (the 3d reference's shell sets it) — without
86774
+ it a WebGL canvas reads back blank between frames.
86775
+ */
86776
+ async captureRender(args = {}) {
86777
+ const doc = this.builder && this.builder.doc;
86778
+ if (!doc) return {
86779
+ error: 'no page'
86780
+ };
86781
+ this.spentShots = (this.spentShots || 0) + 1;
86782
+ if (this.spentShots > 6) {
86783
+ return {
86784
+ error: 'limit reached: no more render checks in this request. Answer with the scene as it is, and be honest about anything still not right.'
86785
+ };
86786
+ }
86787
+ const n = Math.max(1, parseInt(args.block, 10) || 1);
86788
+ let canvas = null;
86789
+ for (let i = 0; i < 24; i++) {
86790
+ const canvases = doc.querySelectorAll('[data-cb-code] canvas');
86791
+ canvas = canvases[n - 1] || null;
86792
+ if (canvas && canvas.width > 2 && canvas.height > 2) break;
86793
+ await new Promise(r => setTimeout(r, 500));
86794
+ if (this.abort && this.abort.signal.aborted) throw Object.assign(new Error('aborted'), {
86795
+ name: 'AbortError'
86796
+ });
86797
+ }
86798
+ if (!canvas) return {
86799
+ error: 'no rendering canvas found in a code block (is the scene failing before it creates one?)'
86800
+ };
86801
+ await new Promise(r => setTimeout(r, 1500)); // let the first real frames draw
86802
+
86803
+ try {
86804
+ const scale = Math.min(1, 768 / canvas.width);
86805
+ const w = Math.max(1, Math.round(canvas.width * scale));
86806
+ const h = Math.max(1, Math.round(canvas.height * scale));
86807
+ const off = document.createElement('canvas');
86808
+ off.width = w;
86809
+ off.height = h;
86810
+ const ctx = off.getContext('2d');
86811
+ ctx.drawImage(canvas, 0, 0, w, h);
86812
+
86813
+ // A uniform image means nothing drew (or the renderer lacks
86814
+ // preserveDrawingBuffer) — say so instead of sending a blank.
86815
+ const d = ctx.getImageData(0, 0, w, h).data;
86816
+ let uniform = true;
86817
+ for (let i = 4; i < d.length; i += 997 * 4) {
86818
+ if (d[i] !== d[0] || d[i + 1] !== d[1] || d[i + 2] !== d[2]) {
86819
+ uniform = false;
86820
+ break;
86821
+ }
86822
+ }
86823
+ const dataUrl = off.toDataURL('image/jpeg', 0.8);
86824
+ this.pendingShots = this.pendingShots || [];
86825
+ this.pendingShots.push(dataUrl);
86826
+ if (uniform) {
86827
+ return {
86828
+ ok: true,
86829
+ warning: 'the canvas is a single flat color — either nothing rendered (check for errors: missing environment, objects outside the camera view) or the renderer lacks preserveDrawingBuffer: true, which this check requires. The (blank) screenshot follows as an image.'
86830
+ };
86831
+ }
86832
+ return {
86833
+ ok: true,
86834
+ note: 'screenshot captured — it follows as an image in the next message. Look at it before answering.'
86835
+ };
86836
+ } catch (e) {
86837
+ return {
86838
+ error: 'could not capture the canvas: ' + String(e && e.message || e)
86839
+ };
86840
+ }
86841
+ }
86842
+
86843
+ /*
86844
+ 3D generation configuration, resolved per call so a host can switch
86845
+ provider at runtime the same way image generation can. Mirrors v1's
86846
+ provider resolution: endpoint options are looked up as
86847
+ `<base>_<Provider>` in any casing, falling back to the _Fal names.
86848
+ Today every supported provider is queue-shaped (request/status/result);
86849
+ a future single-call 3D provider gets its own branch in generate3DModel,
86850
+ the way SINGLE_CALL_IMAGE_PROVIDERS did for images.
86851
+ */
86852
+ threeDConfig() {
86853
+ const b = this.builder;
86854
+ if (!b) return null;
86855
+ const models = Array.isArray(b.models3D) ? b.models3D.filter(m => m && m.id) : [];
86856
+ if (!models.length) return null;
86857
+ const provider = b.default3DGenerationProvider || 'fal';
86858
+ const val = base => {
86859
+ const wanted = `${base}_${provider}`.toLowerCase();
86860
+ const key = Object.keys(b).find(k => k.toLowerCase() === wanted && b[k]);
86861
+ return key ? b[key] : undefined;
86862
+ };
86863
+ const generateUrl = val('generateMediaUrl') || b.generateMediaUrl_Fal;
86864
+ const statusUrl = val('checkRequestStatusUrl') || b.checkRequestStatusUrl_Fal;
86865
+ const resultUrl = val('getResultUrl') || b.getResultUrl_Fal;
86866
+ if (!generateUrl || !statusUrl || !resultUrl) return null;
86867
+
86868
+ // The saved selection, snapping to the first entry when it is not listed
86869
+ const saved = this.v1 && this.v1.settings && this.v1.settings.model3D;
86870
+ const model = (models.find(m => m.id === saved) || models[0]).id;
86871
+ return {
86872
+ provider,
86873
+ models,
86874
+ model,
86875
+ generateUrl,
86876
+ statusUrl,
86877
+ resultUrl
86878
+ };
86879
+ }
86880
+
86881
+ /*
86882
+ Image-to-3D. The image reaches the provider the same way reference images
86883
+ do for image editing: data URLs go through as-is, same-origin files are
86884
+ read into a data URL (the provider cannot fetch a private host), and
86885
+ public URLs are passed for the provider to fetch itself.
86886
+ */
86887
+ async generate3DModel(args = {}) {
86888
+ const cfg = this.threeDConfig();
86889
+ if (!cfg) return {
86890
+ error: '3D generation is not configured'
86891
+ };
86892
+ this.spent3D = (this.spent3D || 0) + 1;
86893
+ if (this.spent3D > 4) {
86894
+ return {
86895
+ error: 'limit reached: no more 3D model generations in this request. Use the models you already have (or build the object from code), finish the scene, and tell the user a model did not come out right if that is the case.'
86896
+ };
86897
+ }
86898
+ const signal = this.abort ? this.abort.signal : null;
86899
+
86900
+ // Resolve the source image
86901
+ let src = null;
86902
+ if (args.attachment !== undefined && args.attachment !== null) {
86903
+ const list = (this.currentAttachments || []).filter(a => a && a.kind === 'image');
86904
+ const att = list[(parseInt(args.attachment, 10) || 1) - 1];
86905
+ if (!att) return {
86906
+ error: `there ${list.length === 1 ? 'is 1 attached image' : `are ${list.length} attached images`}`
86907
+ };
86908
+ src = att.dataUrl;
86909
+ } else if (args.image_url) {
86910
+ src = this.expandAttachmentUrls(String(args.image_url));
86911
+ if (!/^data:/i.test(src)) {
86912
+ let abs;
86913
+ try {
86914
+ abs = new URL(src, location.href);
86915
+ } catch (e) {
86916
+ return {
86917
+ error: 'image_url is not a valid URL'
86918
+ };
86919
+ }
86920
+ if (abs.origin === location.origin) {
86921
+ try {
86922
+ const blob = await (await fetch(abs.href, {
86923
+ signal
86924
+ })).blob();
86925
+ src = await new Promise((resolve, reject) => {
86926
+ const r = new FileReader();
86927
+ r.onload = () => resolve(r.result);
86928
+ r.onerror = reject;
86929
+ r.readAsDataURL(blob);
86930
+ });
86931
+ } catch (e) {
86932
+ return {
86933
+ error: 'could not read the image at image_url'
86934
+ };
86935
+ }
86936
+ } else {
86937
+ src = abs.href; // public URL — the provider fetches it
86938
+ }
86939
+ }
86940
+ } else {
86941
+ return {
86942
+ error: 'give image_url or attachment'
86943
+ };
86944
+ }
86945
+ const b = this.builder;
86946
+ const headers = {
86947
+ ...b.headers,
86948
+ ...b.defaultHeaders
86949
+ };
86950
+ const customData = b.editor && b.editor.customData || {};
86951
+ const post = async (url, body) => {
86952
+ const response = await fetch(url, {
86953
+ method: 'POST',
86954
+ headers,
86955
+ signal,
86956
+ body: JSON.stringify(body)
86957
+ });
86958
+ return await response.json();
86959
+ };
86960
+
86961
+ // Each model family names its input field differently
86962
+ const payload = /hunyuan/i.test(cfg.model) ? {
86963
+ input_image_url: src
86964
+ } : {
86965
+ image_urls: [src],
86966
+ geometry_file_format: 'glb'
86967
+ }; // Rodin-shaped default
86968
+
86969
+ const firstTwoParts = cfg.model.split('/').slice(0, 2).join('/');
86970
+ const req = await post(cfg.generateUrl, {
86971
+ model: cfg.model,
86972
+ customData,
86973
+ endpoint: `https://queue.fal.run/${cfg.model}`,
86974
+ payload
86975
+ });
86976
+ if (req.error || !req.request_id) {
86977
+ return {
86978
+ error: typeof req.error === 'string' ? req.error : '3D generation request failed'
86979
+ };
86980
+ }
86981
+ const request_id = req.request_id;
86982
+ const statusBody = {
86983
+ model: cfg.model,
86984
+ endpoint: `https://queue.fal.run/${firstTwoParts}/requests/${request_id}/status`,
86985
+ request_id,
86986
+ customData
86987
+ };
86988
+ let status = '';
86989
+ for (let i = 0; i < 150 && status !== 'COMPLETED'; i++) {
86990
+ const st = await post(cfg.statusUrl, statusBody);
86991
+ if (st.ok === false) return {
86992
+ error: st.error || '3D generation failed'
86993
+ };
86994
+ if (st.ok && st.status) {
86995
+ status = st.status;
86996
+ if (status === 'FAILED') return {
86997
+ error: '3D generation failed'
86998
+ };
86999
+ } else if (st.data) {
87000
+ // API-style status (mirrors the image flow's fallback)
87001
+ if (st.data.model_mesh || st.data.model_glb || st.data.model_urls) status = 'COMPLETED';else if (st.data.status && !st.data.error) status = st.data.status;
87002
+ }
87003
+ if (status !== 'COMPLETED') await new Promise(r => setTimeout(r, 2000));
87004
+ if (signal && signal.aborted) throw Object.assign(new Error('aborted'), {
87005
+ name: 'AbortError'
87006
+ });
87007
+ }
87008
+ if (status !== 'COMPLETED') return {
87009
+ error: '3D generation timed out'
87010
+ };
87011
+ const res = await post(cfg.resultUrl, {
87012
+ model: cfg.model,
87013
+ request_id,
87014
+ customData,
87015
+ endpoint: `https://queue.fal.run/${firstTwoParts}/requests/${request_id}`
87016
+ });
87017
+ if (res.error) return {
87018
+ error: typeof res.error === 'string' ? res.error : '3D result failed'
87019
+ };
87020
+ const entry = res.data && res.data.entries && res.data.entries[0];
87021
+ if (!entry || !entry.url) return {
87022
+ error: 'the generation returned no model file'
87023
+ };
87024
+ return {
87025
+ url: entry.url,
87026
+ format: 'glb'
87027
+ };
87028
+ }
86585
87029
  async generateImages(prompt, count = 1, size) {
86586
87030
  if (!this.v1) throw new Error('image generation is not configured');
86587
87031
  const signal = this.abort ? this.abort.signal : null;
@@ -86748,6 +87192,10 @@ function describeStep(tool, args, out, target) {
86748
87192
  return out('Reading the attachment') + '…';
86749
87193
  case 'generate_image':
86750
87194
  return out('Generating image') + '…';
87195
+ case 'generate_3d_model':
87196
+ return out('Generating 3D model') + '…';
87197
+ case 'view_render':
87198
+ return out('Checking the render') + '…';
86751
87199
  case 'edit_image':
86752
87200
  return out('Editing image') + '…';
86753
87201
  case '__waiting':
@@ -87009,6 +87457,55 @@ function attachCodeChatV2(codechat, builder, opts = {}) {
87009
87457
  v2.stop();
87010
87458
  if (origAbort) origAbort();
87011
87459
  };
87460
+
87461
+ /*
87462
+ Settings dialog: the 3D model picker. Injected here rather than written
87463
+ into the panel because the panel belongs to v1 and 3D generation is a v2
87464
+ feature — the same borrowing pattern as sendMessage above. The group
87465
+ exists only when the host configured models3D; with one entry it simply
87466
+ shows what is active.
87467
+ */
87468
+ const t3d = v2.threeDConfig && v2.threeDConfig();
87469
+ if (t3d && codechat.builderStuff && !codechat.builderStuff.querySelector('#model3DSelect')) {
87470
+ const anchor = codechat.builderStuff.querySelector('.div-image-generation-options');
87471
+ if (anchor) {
87472
+ const group = document.createElement('div');
87473
+ group.className = 'setting-group';
87474
+ group.innerHTML = `
87475
+ <label for="model3DSelect" class="setting-label">${out('3D Model')}</label>
87476
+ <p class="setting-description">${out('Select the AI model used for 3D model generation')}</p>
87477
+ <div class="cb-sel"><select id="model3DSelect"></select></div>`;
87478
+ const sel = group.querySelector('#model3DSelect');
87479
+ t3d.models.forEach(m => {
87480
+ const opt = document.createElement('option');
87481
+ opt.value = m.id;
87482
+ opt.textContent = m.label || m.id;
87483
+ sel.appendChild(opt);
87484
+ });
87485
+ anchor.parentNode.insertBefore(group, anchor.nextSibling);
87486
+
87487
+ // Current value on every open; snap to the first when stale
87488
+ const origOpen = codechat.openSettings ? codechat.openSettings.bind(codechat) : null;
87489
+ if (origOpen) {
87490
+ codechat.openSettings = function () {
87491
+ origOpen();
87492
+ const cfg = v2.threeDConfig();
87493
+ sel.value = cfg && cfg.model || '';
87494
+ if (sel.selectedIndex < 0 && sel.options.length) sel.selectedIndex = 0;
87495
+ };
87496
+ }
87497
+
87498
+ // Persist with the rest of the settings: set before the panel's
87499
+ // own save stringifies this.settings.
87500
+ const origSave = codechat.saveSettings ? codechat.saveSettings.bind(codechat) : null;
87501
+ if (origSave) {
87502
+ codechat.saveSettings = function () {
87503
+ codechat.settings.model3D = sel.value;
87504
+ origSave();
87505
+ };
87506
+ }
87507
+ }
87508
+ }
87012
87509
  return v2;
87013
87510
  }
87014
87511
 
@@ -87038,7 +87535,7 @@ All content lives in rows and columns — NEVER place content directly under a c
87038
87535
 
87039
87536
  - Size: 'size-<n>' (px). Available: 12,13,14,15,16,17,18,19,20,21,24,28,32,35,38,42,46,48,50,54,60,64,68,72,76,80,84,88,92,96,100 … up to 400. Anchors: labels 12-14, body 16-18, subheads 20-32, headings 42-60, hero/display 60-96.
87040
87537
  - Weight: font-light font-normal font-medium font-semibold font-bold
87041
- - Tracking: tracking-tight tracking-normal tracking-wide tracking-wider tracking-150 (ideal for uppercase labels)
87538
+ - Tracking: named steps tracking-tighter tracking-tight tracking-normal tracking-wide tracking-wider tracking-widest, then a numeric scale 'tracking-<n>' where n is a multiple of 25 from 0 to 500 (n/1000 em, so 'tracking-150' = 0.15em). Uppercase labels read best at 150-250; display headings often want tracking-tight.
87042
87539
  - Leading: leading-none leading-12 leading-13 leading-14 leading-15 leading-16 leading-17 leading-18 — body: leading-17/18, headings: leading-12/13
87043
87540
  - Text utils: uppercase lowercase capitalize text-center text-left text-right — put alignment classes ON the text elements (h/p), NOT on a wrapper div. Keep column content flat.
87044
87541
 
@@ -87176,184 +87673,591 @@ Icons: use Bootstrap Icons (NOT emojis), wrapped in a div: <div class="text-cent
87176
87673
  - Minimalist: generous whitespace; palette of black/white/grays; light heading weights; hierarchy through size and spacing, not color.
87177
87674
  `;
87178
87675
 
87179
- const contextCodeBlock = `
87180
- # Custom Code Block
87181
-
87182
- Use Code Block for creating interactive elements that need JavaScript.
87676
+ /*
87677
+ * context-code.js — the code element reference for Code Chat.
87678
+ *
87679
+ * Documents the RELEASED code element ([data-cb-code], see
87680
+ * contentbuilder/docs/code-element-guide.md and codeelement.js). The previous
87681
+ * version of this file described an old experimental contract
87682
+ * (data-cb-type="code" + container.mount) that never shipped.
87683
+ *
87684
+ * Sent on every v1 request and served as the on-demand 'code' topic in v2,
87685
+ * so it is kept short. No backticks or ${ } — template literal.
87686
+ *
87687
+ * Takes the host's options because where a block may sit differs by product:
87688
+ * ContentBox also has overlay layers, ContentBuilder does not. One file, one
87689
+ * wording, and neither product is told about markup it has no use for.
87690
+ */
87183
87691
 
87184
- Code Block can only be placed:
87692
+ function getContextCodeBlock(opts = {}) {
87693
+ // Where a block may sit. ContentBox also has overlay layers; ContentBuilder
87694
+ // has columns only, and must not be told about markup it does not have.
87695
+ const placement = opts.overlay ? `It sits inside a column,
87696
+ beside other content, or inside '.is-overlay > .is-overlay-content'. To fill
87697
+ that layer, give the block 'position:absolute;inset:0' — the overlay is
87698
+ full-screen, the block is not.` : `It sits
87699
+ inside a column, beside other content.`;
87700
+ return `
87701
+ # Code Block
87185
87702
 
87186
- - in content (inside div.column)
87187
- - in overlay (must be in div.is-overlay-content)
87703
+ For elements that need JavaScript, use a code block: <div data-cb-code>
87704
+ (that attribute alone marks it — no class, no other bookkeeping). ${placement} The code runs live while editing and
87705
+ runs again on the saved page.
87188
87706
 
87189
- **In Content**
87707
+ A simple block is complete as written — no wrapper, no ceremony:
87190
87708
 
87191
- <div class="row">
87192
- <div class="column">
87193
- <div data-cb-type="code">
87194
- <!-- Your Code -->
87195
- </div>
87196
- </div>
87709
+ <div data-cb-code>
87710
+ <h1 id="greet7x">Lorem ipsum</h1>
87711
+ <p>This is a code block.</p>
87712
+ <script>
87713
+ document.querySelector('#greet7x').innerHTML = '<b>Hello World..!</b>';
87714
+ </script>
87197
87715
  </div>
87198
87716
 
87199
- **In Overlay**
87717
+ Ids are safe: when a block is duplicated, the editor gives the copy fresh ids
87718
+ and updates the references inside its script to match.
87200
87719
 
87201
- <div class="is-section is-box is-section-100 type-system-ui">
87202
- <div class="is-overlay">
87203
- <div class="is-overlay-content">
87204
- <div data-cb-type="code" style="position: absolute; top:0, left:0; width: 100%; height: 100%">
87205
- <!-- Your Code -->
87206
- </div>
87207
- </div>
87208
- </div>
87209
-
87210
- <!-- ... -->
87211
- </div>
87720
+ For blocks that do more, these rules keep them working through editing:
87721
+
87722
+ - The editor re-renders the block on edit, undo and duplicate, and each
87723
+ render runs the code again on FRESH elements. Anything that keeps running
87724
+ — a timer, an interval, a window/document listener, an animation loop —
87725
+ must stop by itself when its elements leave the page. Check isConnected:
87212
87726
 
87213
- ### 1. Basic Example
87727
+ const display = document.querySelector('#clock9k');
87728
+ const iv = setInterval(() => {
87729
+ if (!display.isConnected) { clearInterval(iv); return; }
87730
+ display.textContent = new Date().toLocaleTimeString();
87731
+ }, 1000);
87214
87732
 
87215
- **Important**: Always Use 'data-cb-type="code"' and create 'mount' function.
87733
+ - Plain classic <script> tags only — never type="module". To load a library,
87734
+ use dynamic import() inside ONE async IIFE wrapping the whole script,
87735
+ closed with exactly one })(); at the end — never nest a second wrapper:
87216
87736
 
87217
- <div data-cb-type="code">
87218
- <h3 class="code-block__title font-normal size-24">Code Block</h3>
87219
- <p>This is a custom code block. Open HTML code editor to edit this block.</p>
87220
87737
  <script>
87221
- (function() {
87222
- // Get reference to this specific script element
87223
- const currentScript = document.currentScript;
87224
- // Navigate to the parent container
87225
- const container = currentScript.parentElement;
87226
-
87227
- const initialize = async () => {
87228
- // Find the title within THIS container only
87229
- const title = container.querySelector('.code-block__title');
87230
- if (title) {
87231
- title.textContent = 'Code Block';
87232
- }
87233
- };
87234
-
87235
- // Create mount function and store it on the container
87236
- // for the Runtime to render the plugin
87237
- container.mount = function() {
87238
- initialize(); // Start initialization
87239
- };
87240
- // If no runtime, just start initialization
87241
- if (!window.builderRuntime) {
87242
- initialize();
87243
- }
87738
+ (async () => {
87739
+ const confetti = (await import('https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/+esm')).default;
87740
+ // ... the rest of the block's code ...
87244
87741
  })();
87245
87742
  </script>
87246
- </div>
87247
87743
 
87248
- ### 2. Inline '<style>' and Dynamic External Script Loading
87249
- ` + `
87250
- <div data-cb-type="code">
87251
- <style>
87744
+ A classic library that defines a global loads with a created <script>
87745
+ element (check for an existing one first); CSS files the same way with a
87746
+ <link rel="stylesheet">. If you read document.currentScript, do it on the
87747
+ first line — it is null after the first await.
87252
87748
 
87253
- </style>
87749
+ - Self-contained only: styles inline or in a <style> tag inside the block;
87750
+ never touch document-level styles or elements outside the block.
87751
+ `;
87752
+ }
87254
87753
 
87255
- <div class="swiper swiper-initialized swiper-horizontal">
87256
-
87257
- </div>
87754
+ /*
87755
+ * context-3d.js — the "3d" on-demand doc topic for Code Chat v2.
87756
+ *
87757
+ * Loaded via get_framework_docs ONLY when a request involves real-time 3D:
87758
+ * a three.js scene, WebGL content, a 3D product view, or a browser game.
87759
+ * It is never part of the resident system prompt — 3D requests are rare and
87760
+ * this reference is long, so it rides the same on-demand rail as "animation".
87761
+ *
87762
+ * The recipes here were verified in the ContentBuilder public/test-3d
87763
+ * experiments (Sept 2026): the quality shell, sky-as-light, instanced grass,
87764
+ * and the glb normalize pattern are lifted from working pages, not invented.
87765
+ * Keep code samples free of backticks and ${ } — this is a template literal.
87766
+ */
87258
87767
 
87259
- <script>
87260
- (function() {
87261
- const currentScript = document.currentScript;
87262
- const container = currentScript.parentElement;
87263
-
87264
- // Dynamic loader for Swiper CSS
87265
- const loadSwiperCSS = () => {
87266
- return new Promise((resolve, reject) => {
87267
- // Check if CSS already loaded
87268
- const existingLink = document.querySelector('link[href*="swiper-bundle.min.css"]');
87269
- if (existingLink) {
87270
- resolve();
87271
- return;
87272
- }
87768
+ const context3D = `
87769
+ # Real-Time 3D & Games (three.js)
87273
87770
 
87274
- const link = document.createElement('link');
87275
- link.rel = 'stylesheet';
87276
- link.href = 'https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css';
87277
- link.onload = () => resolve();
87278
- link.onerror = reject;
87279
- document.head.appendChild(link);
87280
- });
87281
- };
87771
+ Use this whenever the user asks for a 3D scene, 3D object, WebGL, a 3D
87772
+ product/hero visual, or a playable browser game. Everything lives in a code
87773
+ element (data-cb-code), which runs live in the editor and as plain HTML on
87774
+ the published page.
87282
87775
 
87283
- // Dynamic loader for Swiper JS
87284
- const loadSwiper = () => {
87285
- return new Promise((resolve, reject) => {
87286
- if (window.Swiper) {
87287
- resolve(window.Swiper);
87288
- return;
87289
- }
87290
- const script = document.createElement('script');
87291
- script.src = 'https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js';
87292
- script.onload = () => resolve(window.Swiper);
87293
- script.onerror = reject;
87294
- document.head.appendChild(script);
87295
- });
87296
- };
87297
-
87298
- // Initialize plugin
87299
- const initializeSlider = async () => {
87300
- try {
87301
- // Load dependencies
87302
- await loadSwiperCSS();
87303
- const Swiper = await loadSwiper();
87776
+ A finished-looking scene is mostly LIGHTING, not geometry. Never ship the
87777
+ naive setup (ambient + directional light, no environment, no tone mapping) —
87778
+ it makes every material look like flat plastic. Always use the Scene Shell
87779
+ below.
87304
87780
 
87305
- // ...
87781
+ ## 1. The block
87306
87782
 
87307
- } catch (error) {
87308
- console.error('Failed to initialize slider:', error);
87309
- }
87310
- };
87783
+ 3D lives in a code element: <div data-cb-code> (that attribute alone marks
87784
+ it; no class, no other bookkeeping). It sits inside a normal column, beside
87785
+ other content. The code runs LIVE while editing and runs again on the saved
87786
+ page, so what the user sees in the editor is the real scene.
87311
87787
 
87312
- // Create mount function and store it on the container
87313
- // for the Runtime to render the plugin
87314
- container.mount = function() {
87315
- initializeSlider(); // Start initialization
87316
- };
87317
- // If no runtime, just start initialization
87318
- if (!window.builderRuntime) {
87319
- initializeSlider();
87320
- }
87788
+ <div data-cb-code>
87789
+ <div class="scene3d-stage" style="width:100%; aspect-ratio:16/9; position:relative; overflow:hidden; border-radius:8px; background:#101014;"></div>
87790
+ <script>
87791
+ (async () => {
87792
+ const container = document.currentScript.parentElement; // BEFORE any await
87793
+ const stage = container.querySelector('.scene3d-stage');
87794
+ // ... imports, then build the scene (see Scene Shell) ...
87321
87795
  })();
87322
87796
  </script>
87323
87797
  </div>
87324
87798
 
87325
- Remember: The goal is to create code blocks that are **self-contained**, **conflict-free**, and **easy to integrate** into any HTML environment. Follow these patterns for consistent, reliable code block development.
87326
-
87327
- ### Important:
87328
-
87329
- **Code Block can only be placed**:
87330
-
87331
- - in content (inside div.column)
87332
- - in overlay (must be in div.is-overlay-content)
87799
+ ONE async IIFE wraps the whole script — do not nest a second wrapper
87800
+ function, and close it with exactly one })(); at the end. Read
87801
+ document.currentScript on the first line: it is only set before the first
87802
+ await.
87803
+
87804
+ Rules that keep it healthy in the editor:
87805
+ - Plain classic <script> tags only — never type="module" (dynamic import()
87806
+ inside the classic script is the way to load modules).
87807
+ - Query elements from the container (document.currentScript.parentElement),
87808
+ not by id — the block can be duplicated, and container-scoped queries stay
87809
+ correct in every copy.
87810
+ - The editor re-renders the block on edit, undo and duplicate, and each
87811
+ render runs the code again on FRESH elements. Anything that keeps running
87812
+ — the render loop, timers, window/document listeners — must stop by itself
87813
+ when its elements leave the page. The shell's loop below does this with an
87814
+ isConnected check; apply the same rule to any setInterval or listener you
87815
+ add outside the loop.
87816
+ - The stage div is styled inline (width 100% + aspect-ratio); make it taller
87817
+ or full-bleed by changing that style, not by touching anything outside the
87818
+ block.
87819
+
87820
+ ## 2. Loading three.js
87821
+
87822
+ Load as ES modules with dynamic import inside the script. Use jsdelivr's
87823
+ +esm build and PIN the version — addons then resolve their internal 'three'
87824
+ import to the same module instance, so no import map is needed:
87825
+
87826
+ const THREE = await import('https://cdn.jsdelivr.net/npm/three@0.180.0/+esm');
87827
+ const { OrbitControls } = await import('https://cdn.jsdelivr.net/npm/three@0.180.0/examples/jsm/controls/OrbitControls.js/+esm');
87828
+ const { GLTFLoader } = await import('https://cdn.jsdelivr.net/npm/three@0.180.0/examples/jsm/loaders/GLTFLoader.js/+esm');
87829
+ const { MeshoptDecoder } = await import('https://cdn.jsdelivr.net/npm/three@0.180.0/examples/jsm/libs/meshopt_decoder.module.js/+esm');
87830
+ const { RoomEnvironment } = await import('https://cdn.jsdelivr.net/npm/three@0.180.0/examples/jsm/environments/RoomEnvironment.js/+esm');
87831
+ const { Sky } = await import('https://cdn.jsdelivr.net/npm/three@0.180.0/examples/jsm/objects/Sky.js/+esm');
87832
+
87833
+ Import only what the scene uses. Every addon lives under examples/jsm/ with
87834
+ the same /+esm suffix.
87835
+
87836
+ ## 3. The Scene Shell — always
87837
+
87838
+ const renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true }); // preserveDrawingBuffer: required by the view_render self-check
87839
+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
87840
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
87841
+ renderer.shadowMap.enabled = true;
87842
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
87843
+ stage.appendChild(renderer.domElement);
87844
+
87845
+ const scene = new THREE.Scene();
87846
+ const camera = new THREE.PerspectiveCamera(40, 1, 0.1, 200);
87847
+
87848
+ // ENVIRONMENT LIGHT — the single biggest quality lever. Pick one:
87849
+ // (a) Indoor / product / abstract: the built-in room, no files needed.
87850
+ const pmrem = new THREE.PMREMGenerator(renderer);
87851
+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
87852
+ // (b) Outdoor: a physical sky that also LIGHTS the scene — see Environments.
87853
+ // (c) A specific mood: an equirect .hdr URL via RGBELoader, same mapping.
87854
+
87855
+ // KEY LIGHT with soft shadows grounds the objects.
87856
+ const sun = new THREE.DirectionalLight(0xfff2e0, 2.2);
87857
+ sun.position.set(4, 6, 3);
87858
+ sun.castShadow = true;
87859
+ sun.shadow.mapSize.set(2048, 2048);
87860
+ sun.shadow.radius = 5;
87861
+ sun.shadow.bias = -0.0005;
87862
+ scene.add(sun);
87863
+
87864
+ // SIZE to the stage, not the window. Handles editor column resizes too.
87865
+ function resize() {
87866
+ const w = stage.clientWidth, h = stage.clientHeight;
87867
+ if (!w || !h) return;
87868
+ camera.aspect = w / h;
87869
+ camera.updateProjectionMatrix();
87870
+ renderer.setSize(w, h);
87871
+ }
87872
+ new ResizeObserver(resize).observe(stage);
87873
+ resize();
87874
+
87875
+ // LOOP — stops itself when this render is replaced (edit/undo/duplicate),
87876
+ // and pauses while the block is off-screen or the tab is hidden.
87877
+ let visible = true;
87878
+ new IntersectionObserver(function(e) { visible = e[0].isIntersecting; }).observe(stage);
87879
+ const clock = new THREE.Clock();
87880
+ renderer.setAnimationLoop(function() {
87881
+ if (!stage.isConnected) { // this render was discarded
87882
+ renderer.setAnimationLoop(null);
87883
+ renderer.dispose();
87884
+ return;
87885
+ }
87886
+ if (!visible || document.hidden) return;
87887
+ const dt = Math.min(clock.getDelta(), 0.05);
87888
+ // ... update(dt) ...
87889
+ renderer.render(scene, camera);
87890
+ });
87333
87891
 
87334
- **In Content**
87892
+ Materials: MeshStandardMaterial (metalness/roughness) or MeshPhysicalMaterial
87893
+ (clearcoat, transmission). With the environment set they pick up real
87894
+ reflections; without it, metals render black — that is the "flat plastic"
87895
+ failure. Shadows: castShadow/receiveShadow on meshes, receiveShadow on the
87896
+ ground. A ShadowMaterial plane (opacity ~0.35) gives a shadow-only floor for
87897
+ product shots.
87898
+
87899
+ ## 4. Objects: write code or load a .glb
87900
+
87901
+ - WRITE CODE for man-made, regular shapes: buildings, furniture, product
87902
+ mockups, abstract hero geometry. Compose primitives (Box, Cylinder,
87903
+ Extrude, Lathe, RoundedBoxGeometry addon), and add a subtle CanvasTexture
87904
+ for surface interest (wood planks, panel lines). Free, tiny, editable.
87905
+ - LOAD A .glb for organic or specific things: characters, animals, plants, a
87906
+ real product, anything that must match a reference image. Getting one:
87907
+ - When a generate_3d_model tool is offered, use it: give it ONE clear image
87908
+ of the object (a photo on the page, a generate_image result, or the
87909
+ user's attachment) and load the .glb URL it returns. For an object with
87910
+ no image yet, generate_image first, then feed that in — image quality
87911
+ decides model quality.
87912
+ - When no such tool is offered, build the object from primitives with
87913
+ real material craft instead — never fabricate a model URL.
87914
+
87915
+ Always set the meshopt decoder (generated models are usually
87916
+ meshopt-compressed; it is harmless for plain files), and normalize — glbs
87917
+ come in arbitrary scale:
87918
+
87919
+ const loader = new GLTFLoader();
87920
+ loader.setMeshoptDecoder(MeshoptDecoder);
87921
+ const gltf = await loader.loadAsync(url);
87922
+ const obj = gltf.scene;
87923
+ const box = new THREE.Box3().setFromObject(obj);
87924
+ const size = box.getSize(new THREE.Vector3());
87925
+ obj.scale.setScalar(TARGET_HEIGHT / Math.max(size.x, size.y, size.z));
87926
+ box.setFromObject(obj);
87927
+ const center = box.getCenter(new THREE.Vector3());
87928
+ obj.position.set(-center.x, -box.min.y, -center.z); // centered, on the floor
87929
+ obj.traverse(function(n) { if (n.isMesh) { n.castShadow = true; n.receiveShadow = true; } });
87930
+ scene.add(obj);
87931
+
87932
+ ## 5. Environments (outdoor scenes)
87933
+
87934
+ SKY THAT LIGHTS THE SCENE — golden hour in a few lines, no texture files:
87935
+
87936
+ const sky = new Sky();
87937
+ sky.scale.setScalar(4000);
87938
+ scene.add(sky);
87939
+ const sunDir = new THREE.Vector3().setFromSphericalCoords(1,
87940
+ THREE.MathUtils.degToRad(90 - 6), // elevation: 2-8 = sunset, 30+ = day
87941
+ THREE.MathUtils.degToRad(245)); // azimuth
87942
+ sky.material.uniforms.sunPosition.value.copy(sunDir);
87943
+ sky.material.uniforms.turbidity.value = 6;
87944
+ sky.material.uniforms.rayleigh.value = 2.2;
87945
+ scene.environment = pmrem.fromScene(sky, 0.02).texture; // the sky IS the light
87946
+ sun.position.copy(sunDir).multiplyScalar(120); // key light matches it
87947
+ renderer.toneMappingExposure = 0.55; // Sky is bright; tune 0.4-0.7
87948
+ scene.fog = new THREE.FogExp2(0xe8c8a0, 0.0035); // depth haze sells distance
87949
+
87950
+ TERRAIN — a displaced plane. Define ONE height function and reuse it for
87951
+ placing everything (grass, props) so nothing floats:
87952
+
87953
+ function ground(x, z) {
87954
+ return 1.1 * Math.sin(x * 0.045 + 1) * Math.cos(z * 0.05)
87955
+ + 0.5 * Math.sin(x * 0.11 + 2.3) * Math.sin(z * 0.13 + 1.1);
87956
+ }
87957
+ Build a PlaneGeometry(240, 240, 180, 180), rotateX(-PI/2), set each vertex y
87958
+ from ground(x, z), give vertices green colors varied by height, then
87959
+ computeVertexNormals() and a MeshStandardMaterial({ vertexColors: true,
87960
+ roughness: 1 }).
87961
+
87962
+ WATER — a large plane with a dark blue-grey MeshStandardMaterial and
87963
+ roughness around 0.15. With the sky environment set it reflects the sunset
87964
+ by itself. Place it below the terrain edge.
87965
+
87966
+ GRASS / vegetation — NEVER individual meshes, always ONE InstancedBufferGeometry
87967
+ draw call. One tapered blade (a 4-row triangle strip about 0.018 wide, 1 tall),
87968
+ instanced 50k-150k times with per-instance attributes: offset vec3 (position,
87969
+ y from ground()), data vec4 (rotation angle, height 0.35-0.9, wind phase,
87970
+ tint 0.8-1.2). A small ShaderMaterial does the rest:
87971
+ - vertex: scale by height, bend tip (p.z += t*t*0.1), rotate by angle, sway by
87972
+ sin(time * 1.5 + phase + offset.x * 0.15) * 0.14 * t * t, add offset.
87973
+ - fragment: mix a dark base green (0.07, 0.13, 0.03) to a light tip green
87974
+ (0.38, 0.46, 0.13) by the blade's v coordinate, times tint; optionally add a
87975
+ small warm term at the very tip for sunset scenes.
87976
+ Scatter on a disc around the focal point (radius * sqrt(random) keeps it
87977
+ even), skip blades under objects, set instanceCount, frustumCulled = false,
87978
+ side: THREE.DoubleSide. Update the time uniform in the loop. The same
87979
+ technique makes flowers, reeds and starfields — change the geometry and count.
87980
+
87981
+ ## 6. Interaction
87982
+
87983
+ HOVER + CLICK on 3D objects — a raycaster against the renderer bounds (never
87984
+ window coordinates; the canvas is inside a column):
87985
+
87986
+ const ray = new THREE.Raycaster();
87987
+ const pointer = new THREE.Vector2();
87988
+ function pick(e) {
87989
+ const r = renderer.domElement.getBoundingClientRect();
87990
+ pointer.set(((e.clientX - r.left) / r.width) * 2 - 1,
87991
+ -((e.clientY - r.top) / r.height) * 2 + 1);
87992
+ ray.setFromCamera(pointer, camera);
87993
+ const hit = ray.intersectObjects(pickables, true)[0];
87994
+ return hit ? hit.object : null;
87995
+ }
87996
+ renderer.domElement.addEventListener('pointermove', function(e) {
87997
+ const o = pick(e);
87998
+ renderer.domElement.style.cursor = o ? 'pointer' : '';
87999
+ // hover response: scale/emissive lerp in the loop, not a snap
88000
+ });
88001
+ renderer.domElement.addEventListener('click', function(e) {
88002
+ const o = pick(e); if (o) { /* select, open, score ... */ }
88003
+ });
87335
88004
 
87336
- <div class="row">
87337
- <div class="column">
87338
- <div data-cb-type="code">
87339
- <!-- Your Code -->
87340
- </div>
87341
- </div>
87342
- </div>
88005
+ Animate responses smoothly in the loop (lerp toward a target scale/rotation/
88006
+ color) instead of setting values on the event — that is what makes it feel
88007
+ polished. Camera orbit: OrbitControls with enableDamping = true; constrain
88008
+ (maxPolarAngle, min/maxDistance) so users cannot go under the floor.
88009
+
88010
+ REVEAL PATTERNS — a click should MEAN something, not just wobble. Four
88011
+ recurring shapes, all built from the same pieces (pick + lerp + HTML):
88012
+
88013
+ CAMERA FOCUS (product tour): click an object, fly the camera to frame it,
88014
+ and offer the way back.
88015
+
88016
+ let camTo = null, lookTo = null;
88017
+ function focus(obj) {
88018
+ const p = new THREE.Vector3();
88019
+ obj.getWorldPosition(p);
88020
+ camTo = p.clone().add(new THREE.Vector3(1.4, 0.8, 2.0)); // offset that frames it
88021
+ lookTo = p.clone();
88022
+ backBtn.style.display = 'block';
88023
+ }
88024
+ function overview() {
88025
+ camTo = HOME_POS.clone(); lookTo = HOME_TARGET.clone();
88026
+ backBtn.style.display = 'none'; card.style.display = 'none';
88027
+ }
88028
+ // in the loop:
88029
+ if (camTo) {
88030
+ const k = 1 - Math.exp(-dt * 4);
88031
+ camera.position.lerp(camTo, k);
88032
+ controls.target.lerp(lookTo, k);
88033
+ if (camera.position.distanceTo(camTo) < 0.01) { camTo = null; lookTo = null; }
88034
+ }
88035
+ controls.addEventListener('start', function() { camTo = null; lookTo = null; }); // user drag wins
88036
+
88037
+ INFO CARD: the revealed details are real HTML overlaid on the stage — never
88038
+ 3D text. A fixed-position card (absolute inside the stage, e.g. right side)
88039
+ reads better than one tracking the 3D point, and never clips. Fill it per
88040
+ object from a plain data object keyed by mesh name; give it a real <button>
88041
+ to close, and close on Escape too. Selectable, accessible, translatable.
88042
+
88043
+ STATE REVEAL: the click changes the scene itself — a lid opens, parts fan
88044
+ out into an exploded view, the chosen item stays lit while the rest dim.
88045
+ Record each part's home transform at build time, keep one 0..1 reveal value
88046
+ per group, and lerp every part between home and revealed each frame from
88047
+ that value. Dimming: lerp material color or opacity, never a CSS filter.
88048
+
88049
+ SCENE-TO-PAGE REVEAL: when the revealed content belongs in the page (specs,
88050
+ paragraphs, a price table), toggle a normal HTML element NEXT TO the stage
88051
+ instead of an overlay. The content stays selectable and readable without
88052
+ WebGL; the scene is the index, the page is the content.
88053
+
88054
+ Shared rules: one selection at a time; clicking empty space = Back; Back and
88055
+ close are real, keyboard-reachable buttons; everything moves through the
88056
+ loop's lerp, nothing snaps.
88057
+
88058
+ Touch: pointer events above already cover it; OrbitControls handles touch
88059
+ orbit. Do not call preventDefault on wheel/touch you do not use — the page
88060
+ must keep scrolling normally past the block.
88061
+
88062
+ SCROLL-DRIVEN scenes: read progress from the block's own position — works
88063
+ everywhere:
88064
+
88065
+ function scrollProgress() { // 0 when entering, 1 when leaving
88066
+ const r = stage.getBoundingClientRect();
88067
+ return THREE.MathUtils.clamp((innerHeight - r.top) / (innerHeight + r.height), 0, 1);
88068
+ }
88069
+ Call it in the loop and drive camera/objects from it (again through lerp for
88070
+ smoothness). On a ContentBox page whose section has data-fx-emit, prefer the
88071
+ host's event: container.closest('.is-section').addEventListener('fx:progress',
88072
+ function(e) { p = e.detail.progress; }).
88073
+
88074
+ ## 7. Games (3D)
88075
+
88076
+ Game craft — loop, input, state machine, HUD, sound, recycling, cleanup —
88077
+ lives in the "games" reference: load it for any game. This section is only
88078
+ what makes a THREE.JS game look and feel right:
88079
+
88080
+ - The Scene Shell applies to games in full. Environment lighting, real
88081
+ materials, fog and shadows are what separate a game from a tech demo —
88082
+ never fall back to flat MeshBasicMaterial arcade defaults. Emissive
88083
+ materials + bloom give the cheap "neon glow" so many game styles want.
88084
+ - HERO ASSETS: the 2-3 entities that carry the whole look — the player
88085
+ craft, the collectible, one signature obstacle — deserve generated models
88086
+ (generate_3d_model when offered). Load each .glb ONCE, then obj.clone()
88087
+ per spawn; cloning is as cheap as cloning boxes, so recycling pools work
88088
+ unchanged. This single choice is the difference between "colored cubes"
88089
+ and a game with an identity.
88090
+ - FILLER stays coded, but crafted: RoundedBoxGeometry over BoxGeometry,
88091
+ slight bevels, emissive rims, vertex-colored gradients — never bare
88092
+ saturated boxes.
88093
+ - Movement feel: lerp positions and tilt/bank the player toward its motion;
88094
+ camera follows with damping, never rigidly.
88095
+ - Update per frame from the update(dt) function; collisions at this scale
88096
+ are distance checks (player.position.distanceTo(e.position) < r1 + r2).
88097
+
88098
+ ## 8. Self-check — see your work
88099
+
88100
+ When a view_render tool is offered, ALWAYS call it after creating a scene or
88101
+ making a significant visual change, and LOOK at the screenshot before
88102
+ answering:
88103
+ - All black or flat: the environment/lighting is missing, or every object is
88104
+ outside the camera view.
88105
+ - Empty or nearly empty: camera position/target does not frame the content —
88106
+ check object positions and scale.
88107
+ - Clipped, tiny or washed out: adjust framing, scale or exposure.
88108
+ Fix what is wrong, re-check once, and only then answer. Do not describe a
88109
+ scene you have not seen. (The screenshot shows the canvas only — HTML
88110
+ overlays are not in it.)
88111
+
88112
+ Judge the render like an art director: the bar is FINISHED, not merely
88113
+ correct. A right-shaped scene rendered badly — glaring or flat light, dead
88114
+ materials, awkward framing, harsh exposure — is not done. Weigh the impact
88115
+ yourself, and reach for the cheap lever first:
88116
+ - Anything fixable in code — lighting, environment, exposure, camera,
88117
+ materials, scale — is FREE. If a change would noticeably improve the
88118
+ scene, make it.
88119
+ - Regenerating a model costs the user money. Do it only when the asset
88120
+ itself is the problem (mangled geometry, clearly the wrong object) and
88121
+ code cannot compensate — better light, exposure and framing rescue a
88122
+ mediocre asset more often than a re-roll does.
88123
+ When the scene genuinely reads well, it is done — stop; do not iterate on
88124
+ differences a viewer would not notice.
88125
+
88126
+ ## 9. Performance & hygiene
88127
+
88128
+ - One scene per block; reuse geometries/materials; instancing for anything
88129
+ repeated more than ~20 times.
88130
+ - Keep pixelRatio capped at 2 and shadow maps at 2048 or below.
88131
+ - The visibility pause in the shell is mandatory — a page can hold several
88132
+ blocks and background tabs must not burn CPU.
88133
+ - Respect prefers-reduced-motion: if it matches, skip autonomous camera
88134
+ motion and wind sway; render still frames on interaction only.
88135
+ - Do not touch document-level styles, and never assume the block is the only
88136
+ 3D on the page.
88137
+ `;
87343
88138
 
87344
- **In Overlay**
88139
+ /*
88140
+ * context-games.js — the "games" on-demand doc topic for Code Chat v2.
88141
+ *
88142
+ * Loaded via get_framework_docs for ANY game request, 2D or 3D. It owns the
88143
+ * craft every game shares (loop, input, state, HUD, sound, cleanup) plus the
88144
+ * 2D Canvas branch; a 3D game additionally loads the "3d" topic, whose games
88145
+ * section holds only the 3D-specific rendering rules.
88146
+ *
88147
+ * Asset reality check (user-verified, Sept 2026): most image models FAIL at
88148
+ * transparent PNGs — sprites are requested on solid backgrounds and handled
88149
+ * in code. Never instruct the model to ask for transparency.
88150
+ * Keep code samples free of backticks and ${ } — template literal.
88151
+ */
87345
88152
 
87346
- <div class="is-section is-box is-section-100 type-system-ui">
87347
- <div class="is-overlay">
87348
- <div class="is-overlay-content">
87349
- <div data-cb-type="code" style="position: absolute; top:0, left:0; width: 100%; height: 100%">
87350
- <!-- Your Code -->
87351
- </div>
87352
- </div>
88153
+ const contextGames = `
88154
+ # Building Games
88155
+
88156
+ Use this for any playable game. First decide the dimension — it changes the
88157
+ whole toolchain:
88158
+
88159
+ - 2D (doodle, flat, sprite, puzzle, casual, "simple game"): the Canvas 2D
88160
+ API in a code block. Do NOT use three.js for these — it is heavier, slower
88161
+ to write, and fights the flat aesthetic.
88162
+ - 3D (depth, camera, "3D"): three.js — ALSO load the "3d" reference and
88163
+ follow its games section for rendering and assets.
88164
+
88165
+ Target scale either way: an arcade mini-game — one scene, one core mechanic,
88166
+ polished. Refine with the user over turns.
88167
+
88168
+ ## The skeleton every game shares
88169
+
88170
+ Everything lives in one code block (see the "code" reference for the block
88171
+ contract). Inside it:
88172
+
88173
+ - LOOP: requestAnimationFrame with a clamped delta; stop yourself when the
88174
+ block is re-rendered:
88175
+
88176
+ let last = performance.now();
88177
+ function frame(now) {
88178
+ if (!stage.isConnected) return; // this render was replaced
88179
+ const dt = Math.min((now - last) / 1000, 0.05);
88180
+ last = now;
88181
+ update(dt); draw();
88182
+ requestAnimationFrame(frame);
88183
+ }
88184
+ requestAnimationFrame(frame);
88185
+
88186
+ - INPUT: one flags object; keyboard listeners attach on game start (the
88187
+ start click also gives focus), ignore keys while the user types elsewhere,
88188
+ and detach themselves via the isConnected check. Map pointerdown /
88189
+ pointermove on the stage to the same flags so touch works. Do not
88190
+ preventDefault on events you do not use — the page must keep scrolling.
88191
+ - STATE: a small machine — ready / playing / over — with restart resetting
88192
+ state, never reloading. Show "click or tap to start".
88193
+ - HUD: HTML positioned over the stage (score, lives, messages) — real text,
88194
+ updated via textContent, never drawn glyph-by-glyph into the canvas.
88195
+ - SOUND: only if asked; short WebAudio oscillator beeps, no external files.
88196
+ - ENTITIES: recycle, never allocate per frame — spawn from a pool, move
88197
+ off-screen items back in.
88198
+ - SELF-CHECK: when a view_render tool is offered, screenshot after building
88199
+ and after big visual changes, judge it, fix, re-check once.
88200
+
88201
+ ## 2D games (Canvas 2D)
88202
+
88203
+ Setup — crisp on every screen:
88204
+
88205
+ <div data-cb-code>
88206
+ <div class="game-stage" style="position:relative; width:100%; aspect-ratio:16/10; overflow:hidden; border-radius:8px; background:#fdfdf8;">
88207
+ <canvas style="position:absolute; inset:0; width:100%; height:100%;"></canvas>
88208
+ <!-- HUD elements here -->
87353
88209
  </div>
87354
-
87355
- <!-- ... -->
88210
+ <script>
88211
+ (async () => {
88212
+ const container = document.currentScript.parentElement;
88213
+ const stage = container.querySelector('.game-stage');
88214
+ const canvas = stage.querySelector('canvas');
88215
+ const ctx = canvas.getContext('2d');
88216
+ function fit() {
88217
+ const dpr = Math.min(devicePixelRatio, 2);
88218
+ canvas.width = stage.clientWidth * dpr;
88219
+ canvas.height = stage.clientHeight * dpr;
88220
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0); // draw in CSS pixels
88221
+ }
88222
+ new ResizeObserver(fit).observe(stage);
88223
+ fit();
88224
+ // ... game ...
88225
+ })();
88226
+ </script>
87356
88227
  </div>
88228
+
88229
+ Collision at this scale is rectangles and circle distances — no physics
88230
+ library unless the game truly is physics.
88231
+
88232
+ ART DIRECTION — a 2D game must look intentional, not like debug rectangles:
88233
+ pick a style (hand-drawn doodle, flat pastel, neon minimal) and carry it
88234
+ through background, entities, HUD typography and even the game-over screen.
88235
+
88236
+ - DOODLE STYLE, pure code: draw with strokes, not fills — rounded lineJoin,
88237
+ slightly thick lines, and a small random jitter added to each vertex,
88238
+ re-rolled only a few times per second (a wobble timer, not every frame) so
88239
+ shapes shiver like a flipbook. Paper background (#fdfdf8, faint grid),
88240
+ handwritten-feel HUD (a casual system font, slight rotation).
88241
+ - SPRITES from generate_image, when the style needs real drawings: request
88242
+ each sprite "on a plain solid white background, no shadow" in one
88243
+ consistent style. Do NOT request transparent backgrounds — image models
88244
+ usually fail at true transparency, delivering fake checkerboards or dirty
88245
+ edges. Then either:
88246
+ - design the game on the SAME background color, so the sprite's white
88247
+ simply disappears (the doodle-on-paper trick — zero code); or
88248
+ - key it out at load: draw to an offscreen canvas, getImageData, and set
88249
+ alpha 0 on pixels close to the corner color (tolerance ~28); cache the
88250
+ result and draw that.
88251
+ - Parallax sells motion cheaply: two or three background layers scrolling at
88252
+ different speeds.
88253
+
88254
+ ## 3D games
88255
+
88256
+ Load the "3d" reference and follow its games section. The short version:
88257
+ the scene shell (environment light, real materials, fog) applies to games
88258
+ exactly as to scenes — no flat-material arcade fallback — and the 2-3 hero
88259
+ entities that carry the look (player, collectible, signature obstacle)
88260
+ deserve generated models, loaded once and cloned per spawn.
87357
88261
  `;
87358
88262
 
87359
88263
  const contextDesignGuide = `
@@ -88961,7 +89865,7 @@ class ContentBuilder {
88961
89865
  this.ShortcutInfo = new ShortcutInfo(this);
88962
89866
  if (!this.opts.isContentBox) {
88963
89867
  this.codechat = new CodeChat({
88964
- context: contextContentFramework + contextCodeBlock + contextDesignGuide
89868
+ context: contextContentFramework + getContextCodeBlock() + contextDesignGuide
88965
89869
  }, this);
88966
89870
 
88967
89871
  /*
@@ -88976,10 +89880,16 @@ class ContentBuilder {
88976
89880
  attachCodeChatV2(this.codechat, this, {
88977
89881
  contextParts: {
88978
89882
  content: contextContentFramework,
88979
- designCore: contextDesignGuide
89883
+ designCore: contextDesignGuide,
89884
+ code: getContextCodeBlock(),
89885
+ // on-demand 'code' doc topic
89886
+ '3d': context3D,
89887
+ // on-demand '3d' doc topic
89888
+ games: contextGames // on-demand 'games' doc topic
88980
89889
  }
88981
89890
  });
88982
89891
  }
89892
+
88983
89893
  if (this.startAIAssistant) {
88984
89894
  this.openAIAssistant();
88985
89895
  }