@konfigure/sdk 0.2.1 → 0.3.0
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.
- package/README.md +54 -1
- package/dist/chunk-4KQN5AVT.js +782 -0
- package/dist/chunk-EBEY7ID3.js +1 -0
- package/dist/chunk-HFOEVYNK.js +4 -0
- package/dist/chunk-XR6EHOK2.js +482 -0
- package/dist/client-B2yVMro3.d.ts +80 -0
- package/dist/{configurator-6ISAZiAx.d.ts → configurator-CnGR3YDW.d.ts} +1 -1
- package/dist/index.d.ts +5 -57
- package/dist/index.js +1 -4
- package/dist/showroom.d.ts +145 -0
- package/dist/showroom.js +171 -0
- package/dist/{src-GJ5RXX7G.js → src-SHLZZCVA.js} +6 -6
- package/dist/view.d.ts +1 -1
- package/dist/view.js +3 -785
- package/package.json +5 -1
- package/dist/chunk-ARGXORCF.js +0 -1
- package/dist/chunk-OOVVLYAY.js +0 -482
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { P as ProductLine, L as LineCatalog, d as ConfigurationState, e as Configurator, S as SavedConfiguration, I as InquiryInput, i as SubmittedInquiry } from './configurator-CnGR3YDW.js';
|
|
2
|
+
|
|
3
|
+
type KonfigureClientOptions = {
|
|
4
|
+
/** The instance's origin, e.g. `https://example.konfigure.app`. */
|
|
5
|
+
instance: string;
|
|
6
|
+
/** Catalogue language and the language of enquiry e-mails (cs, en, de, fr). Default `cs`. */
|
|
7
|
+
locale?: string;
|
|
8
|
+
/** A fetch to use instead of the global one (SSR, tests). */
|
|
9
|
+
fetch?: typeof fetch;
|
|
10
|
+
};
|
|
11
|
+
/** One opening of the instance's show house, and the product standing in it. */
|
|
12
|
+
type ShowroomPlace = {
|
|
13
|
+
key: string;
|
|
14
|
+
/** The opening's name, in the instance's language (`Vchodové dveře`). */
|
|
15
|
+
name: string;
|
|
16
|
+
moduleCode: string;
|
|
17
|
+
/** Null when the instance's catalogue has no public module with that code. */
|
|
18
|
+
moduleId: number | null;
|
|
19
|
+
productLineId: number | null;
|
|
20
|
+
/** The opening, metres. */
|
|
21
|
+
width: number;
|
|
22
|
+
height: number;
|
|
23
|
+
/** A door the visitor walks through. */
|
|
24
|
+
passage: boolean;
|
|
25
|
+
};
|
|
26
|
+
/** The instance's showroom, as `mountShowroom` draws it (`client.showroom()`). */
|
|
27
|
+
type ShowroomManifest = {
|
|
28
|
+
venue: 'house';
|
|
29
|
+
/** Absolute base URL of the room's files. */
|
|
30
|
+
files: string;
|
|
31
|
+
places: ShowroomPlace[];
|
|
32
|
+
};
|
|
33
|
+
type SavedConfigurationRecord = {
|
|
34
|
+
id: string;
|
|
35
|
+
displayId: string | null;
|
|
36
|
+
name: string;
|
|
37
|
+
productLineId: number | null;
|
|
38
|
+
state: ConfigurationState;
|
|
39
|
+
shareUrl: string;
|
|
40
|
+
viewUrl: string;
|
|
41
|
+
};
|
|
42
|
+
type LeadInput = {
|
|
43
|
+
/** Field key → value, e.g. `{ name, email, phone, message }`. */
|
|
44
|
+
data: Record<string, string>;
|
|
45
|
+
/** Which gate or form captured it, for the dashboard. */
|
|
46
|
+
gateKey?: string;
|
|
47
|
+
/** A saved configuration it belongs to. */
|
|
48
|
+
configurationId?: string;
|
|
49
|
+
};
|
|
50
|
+
type ConfiguratorRequest = {
|
|
51
|
+
productLine: number | string;
|
|
52
|
+
module?: number | string;
|
|
53
|
+
state?: ConfigurationState;
|
|
54
|
+
} | {
|
|
55
|
+
configuration: string;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* A client for one Konfigure instance. Everything goes over the instance's
|
|
59
|
+
* public API with plain `fetch` — no cookies (requests are anonymous), so the
|
|
60
|
+
* site's origin has to be on the instance's embed allow-list for the browser
|
|
61
|
+
* to let the responses through (see the README).
|
|
62
|
+
*/
|
|
63
|
+
declare function createKonfigureClient(options: KonfigureClientOptions): {
|
|
64
|
+
instance: string;
|
|
65
|
+
locale: string;
|
|
66
|
+
productLines: () => Promise<ProductLine[]>;
|
|
67
|
+
productLine: (ref: number | string) => Promise<ProductLine>;
|
|
68
|
+
catalog: (ref: number | string) => Promise<LineCatalog>;
|
|
69
|
+
configurator: (request: ConfiguratorRequest) => Promise<Configurator>;
|
|
70
|
+
showroom: () => Promise<ShowroomManifest>;
|
|
71
|
+
getConfiguration: (id: string) => Promise<SavedConfigurationRecord>;
|
|
72
|
+
saveConfiguration: (state: ConfigurationState, name: string) => Promise<SavedConfiguration>;
|
|
73
|
+
submitInquiry: (state: ConfigurationState, inquiry: InquiryInput) => Promise<SubmittedInquiry>;
|
|
74
|
+
submitLead: (lead: LeadInput) => Promise<{
|
|
75
|
+
ok: boolean;
|
|
76
|
+
}>;
|
|
77
|
+
};
|
|
78
|
+
type KonfigureClient = ReturnType<typeof createKonfigureClient>;
|
|
79
|
+
|
|
80
|
+
export { type KonfigureClient as K, type LeadInput as L, type SavedConfigurationRecord as S, type KonfigureClientOptions as a, type ShowroomManifest as b, type ShowroomPlace as c, createKonfigureClient as d };
|
|
@@ -465,4 +465,4 @@ declare function createConfigurator(config: ConfiguratorOptions): {
|
|
|
465
465
|
};
|
|
466
466
|
type Configurator = ReturnType<typeof createConfigurator>;
|
|
467
467
|
|
|
468
|
-
export type { AnyOption as A,
|
|
468
|
+
export type { AnyOption as A, CatalogRule as C, Group as G, InquiryInput as I, LineCatalog as L, ModuleOption as M, Option as O, ProductLine as P, SavedConfiguration as S, ValidationIssue as V, ChangeEvent as a, ConfigModuleState as b, ConfigPartState as c, ConfigurationState as d, Configurator as e, GroupKind as f, Size as g, SizeLimits as h, SubmittedInquiry as i, SummaryRow as j, SurfaceOption as k };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,59 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
export { A as AnyOption,
|
|
3
|
-
|
|
4
|
-
type KonfigureClientOptions = {
|
|
5
|
-
/** The instance's origin, e.g. `https://example.konfigure.app`. */
|
|
6
|
-
instance: string;
|
|
7
|
-
/** Catalogue language and the language of enquiry e-mails (cs, en, de, fr). Default `cs`. */
|
|
8
|
-
locale?: string;
|
|
9
|
-
/** A fetch to use instead of the global one (SSR, tests). */
|
|
10
|
-
fetch?: typeof fetch;
|
|
11
|
-
};
|
|
12
|
-
type SavedConfigurationRecord = {
|
|
13
|
-
id: string;
|
|
14
|
-
displayId: string | null;
|
|
15
|
-
name: string;
|
|
16
|
-
productLineId: number | null;
|
|
17
|
-
state: ConfigurationState;
|
|
18
|
-
shareUrl: string;
|
|
19
|
-
viewUrl: string;
|
|
20
|
-
};
|
|
21
|
-
type LeadInput = {
|
|
22
|
-
/** Field key → value, e.g. `{ name, email, phone, message }`. */
|
|
23
|
-
data: Record<string, string>;
|
|
24
|
-
/** Which gate or form captured it, for the dashboard. */
|
|
25
|
-
gateKey?: string;
|
|
26
|
-
/** A saved configuration it belongs to. */
|
|
27
|
-
configurationId?: string;
|
|
28
|
-
};
|
|
29
|
-
type ConfiguratorRequest = {
|
|
30
|
-
productLine: number | string;
|
|
31
|
-
module?: number | string;
|
|
32
|
-
state?: ConfigurationState;
|
|
33
|
-
} | {
|
|
34
|
-
configuration: string;
|
|
35
|
-
};
|
|
36
|
-
/**
|
|
37
|
-
* A client for one Konfigure instance. Everything goes over the instance's
|
|
38
|
-
* public API with plain `fetch` — no cookies (requests are anonymous), so the
|
|
39
|
-
* site's origin has to be on the instance's embed allow-list for the browser
|
|
40
|
-
* to let the responses through (see the README).
|
|
41
|
-
*/
|
|
42
|
-
declare function createKonfigureClient(options: KonfigureClientOptions): {
|
|
43
|
-
instance: string;
|
|
44
|
-
locale: string;
|
|
45
|
-
productLines: () => Promise<ProductLine[]>;
|
|
46
|
-
productLine: (ref: number | string) => Promise<ProductLine>;
|
|
47
|
-
catalog: (ref: number | string) => Promise<LineCatalog>;
|
|
48
|
-
configurator: (request: ConfiguratorRequest) => Promise<Configurator>;
|
|
49
|
-
getConfiguration: (id: string) => Promise<SavedConfigurationRecord>;
|
|
50
|
-
saveConfiguration: (state: ConfigurationState, name: string) => Promise<SavedConfiguration>;
|
|
51
|
-
submitInquiry: (state: ConfigurationState, inquiry: InquiryInput) => Promise<SubmittedInquiry>;
|
|
52
|
-
submitLead: (lead: LeadInput) => Promise<{
|
|
53
|
-
ok: boolean;
|
|
54
|
-
}>;
|
|
55
|
-
};
|
|
56
|
-
type KonfigureClient = ReturnType<typeof createKonfigureClient>;
|
|
1
|
+
export { K as KonfigureClient, a as KonfigureClientOptions, L as LeadInput, S as SavedConfigurationRecord, b as ShowroomManifest, c as ShowroomPlace, d as createKonfigureClient } from './client-B2yVMro3.js';
|
|
2
|
+
export { A as AnyOption, C as CatalogRule, a as ChangeEvent, b as ConfigModuleState, c as ConfigPartState, d as ConfigurationState, e as Configurator, G as Group, f as GroupKind, I as InquiryInput, L as LineCatalog, M as ModuleOption, O as Option, P as ProductLine, S as SavedConfiguration, g as Size, h as SizeLimits, i as SubmittedInquiry, j as SummaryRow, k as SurfaceOption, V as ValidationIssue } from './configurator-CnGR3YDW.js';
|
|
57
3
|
|
|
58
4
|
type KonfigureErrorCode =
|
|
59
5
|
/** The instance answered with an error status (see `status`). */
|
|
@@ -72,6 +18,8 @@ type KonfigureErrorCode =
|
|
|
72
18
|
| 'option_disabled'
|
|
73
19
|
/** A configuration state that doesn't belong to this configurator. */
|
|
74
20
|
| 'invalid_state'
|
|
21
|
+
/** No showroom view of that name (`views()` lists them). */
|
|
22
|
+
| 'unknown_view'
|
|
75
23
|
/** The view has nothing drawn yet (await `whenReady()`), or was disposed. */
|
|
76
24
|
| 'not_ready'
|
|
77
25
|
/** A photo studio is open on the view: one at a time, and the scene is the studio's until it is disposed. */
|
|
@@ -94,4 +42,4 @@ declare class KonfigureError extends Error {
|
|
|
94
42
|
});
|
|
95
43
|
}
|
|
96
44
|
|
|
97
|
-
export {
|
|
45
|
+
export { KonfigureError, type KonfigureErrorCode };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1 @@
|
|
|
1
|
-
import {g,h,j as j$1,i,b,f,a as a$1}from'./chunk-ARGXORCF.js';export{a as KonfigureError}from'./chunk-ARGXORCF.js';import {a}from'./chunk-XUSV3KOD.js';function j(t,e){return e?/^(https?:|data:|blob:)/i.test(e)?e:new URL(e,`${t}/`).toString():null}a(j,"absoluteUrl");function W(t,e){if(!t||!e)return t;let o=Date.parse(e);return Number.isNaN(o)?t:`${t}${t.includes("?")?"&":"?"}v=${o}`}a(W,"versionedUrl");function G(t){return t.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}a(G,"slugify");function J(t){if(Array.isArray(t))return t;let e=t?.items;return Array.isArray(e)?e:[]}a(J,"listRows");function le(t){return t.status===void 0||t.status==="public"}a(le,"isPublished");function de(t,e){return {id:e.id,name:e.name,slug:e.slug||G(e.name),description:e.description??null,image:W(j(t,e.image),e.updatedAt),scenePreset:e.scenePreset??null}}a(de,"toProductLine");function Ae(t){let e=new Set;for(let o of t.basePartSlots??[]){o.defaultPartId&&e.add(o.defaultPartId);for(let a of o.compatibleParts??[])e.add(a.partId);}for(let o of t.moduleSlots??[])for(let a of o.accessoryPartIds??[])e.add(a);return e}a(Ae,"partIdsOfModule");function $e(t,e){let o=[...t];for(;o.length>0;){let a=e.get(o.pop());for(let m of a?.partSlots??[])for(let y of [m.defaultPartId,...(m.compatibleParts??[]).map(h=>h.partId)])y&&!t.has(y)&&(t.add(y),o.push(y));}return t}a($e,"closePartIds");var ke=["normalPath","roughnessPath","metalnessPath","aoPath","heightPath"];function Re(t,e){let o=a(m=>W(j(t,m),e.updatedAt),"asset"),a$1=null;try{a$1=typeof e.textureJson=="string"?JSON.parse(e.textureJson):e.textureJson??null;}catch{a$1=null;}if(a$1){a$1={...a$1};for(let m of ke){let y=a$1[m];typeof y=="string"&&(a$1[m]=o(y));}}return {...e,textureJson:a$1,texturePath:o(e.texturePath),thumbnailPath:o(e.thumbnailPath)}}a(Re,"absoluteSurface");function ze(t,e){return {...e,image:j(t,e.image),models:e.models.map(o=>o.model3d?{...o,model3d:{...o.model3d,filePath:W(j(t,o.model3d.filePath),o.model3d.updatedAt)??o.model3d.filePath}}:o)}}a(ze,"absolutePart");function ce(t,e,o){let a=J(o.modules).filter(le).map(p=>({...p,image:j(t,p.image)})).sort((p,C)=>(p.sortOrder??0)-(C.sortOrder??0)),m=J(o.parts),y=new Map(m.map(p=>[p.id,p])),h=new Set;for(let p of a)for(let C of Ae(p))h.add(C);$e(h,y);let b=J(o.rules).filter(p=>p.productLine?.id===e.id&&le(p)).sort((p,C)=>C.priority-p.priority);return {productLine:e,modules:a,parts:m.filter(p=>h.has(p.id)).map(p=>ze(t,p)),surfaces:J(o.surfaces).filter(p=>p.status!=="deleted").map(p=>Re(t,p)),surfaceGroups:J(o.surfaceGroups),rules:b}}a(ce,"buildLineCatalog");function fe(t){return {catalog:t,modules:new Map(t.modules.map(e=>[e.id,e])),parts:new Map(t.parts.map(e=>[e.id,e])),surfaces:new Map(t.surfaces.map(e=>[e.id,e])),surfaceGroups:new Map(t.surfaceGroups.map(e=>[e.id,e]))}}a(fe,"indexCatalog");function q(t,e,o){let a=t.surfaces.get(o);return a!==void 0&&g(e,o,a.groupId)}a(q,"isSurfaceAllowed");function U(t,e){return e.hasConfigurableSurface?t.catalog.surfaces.filter(o=>q(t,e,o.id)):[]}a(U,"surfacePalette");function B(t,e,o={}){let a=t.parts.get(e),m=a?h(a,{preferred:o.surfaceId,inherited:o.inheritedSurfaceId},b=>q(t,a,b)):void 0,y=a?.hasConfigurableSurface&&m!==void 0&&t.surfaces.has(m)?m:void 0,h$1={};for(let b of a?.partSlots??[]){let p=j$1(b);h$1[b.name]=p?B(t,p,{inheritedSurfaceId:m}):null;}return {apiPartId:e,...y!==void 0&&{surfaceId:y},nestedSlots:h$1}}a(B,"defaultPartState");function Ne(t,e){let o=(e.compatibleParts??[]).map(a=>a.partId).filter(a=>t.parts.has(a));return i(e,o)??null}a(Ne,"startingPartOf");function T(t){return [...t.basePartSlots??[]].sort((e,o)=>(e.order??0)-(o.order??0))}a(T,"sortedBaseSlots");function K(t){let e=Object.fromEntries(Object.entries(t.children).map(([o,a])=>[o,K(a)]));return {...t,children:e,hash:b({apiModuleId:t.apiModuleId,basePartSlots:t.basePartSlots,invertedSlots:t.invertedSlots,rotatedSlots:t.rotatedSlots,childrenHashes:Object.fromEntries(Object.entries(e).map(([o,a])=>[o,a.hash])),size:t.size})}}a(K,"withHash");function pe(t,e){let o={},a={};for(let m of T(e)){let y=Ne(t,m);y!=null&&(o[m.name]=B(t,y),m.defaultInverted&&(a[m.name]=true));}return K({apiModuleId:e.id,basePartSlots:o,invertedSlots:a,rotatedSlots:{},children:{},childSlotNames:{},position:{x:0,y:0,z:0},rotationY:0})}a(pe,"defaultModuleState");function _e(t,e){return !!t&&!!e&&t.trim().toLowerCase()===e.trim().toLowerCase()}a(_e,"sameName");function me(t,e,o){let a=pe(t,o);if(!e)return a;let m=t.modules.get(e.apiModuleId),y={...a.basePartSlots};for(let b of T(o)){let p=e.basePartSlots[b.name];if(!p)continue;let C=t.parts.get(p.apiPartId),x=(b.compatibleParts??[]).map(A=>A.partId),O=x.find(A=>_e(t.parts.get(A)?.name,C?.name));if(O===void 0){let k=(m?.basePartSlots?.find($=>$.name===b.name)?.compatibleParts??[]).findIndex($=>$.partId===p.apiPartId);k>=0&&k<x.length&&(O=x[k]);}O===void 0&&(O=y[b.name]?.apiPartId),O!==void 0&&(y[b.name]=B(t,O,{surfaceId:p.surfaceId}));}let h=e.size?je(o.sizing,e.size):null;return K({...a,basePartSlots:y,...h&&{size:h}})}a(me,"carryOverModuleState");function je(t,e){if(!t)return null;let o=a((a,m)=>Math.round(Math.min(m.max,Math.max(m.min,a))),"clamp");return {width:o(e.width,t.width),height:o(e.height,t.height)}}a(je,"fitSize");function Q(t,e){return {productLineId:t.catalog.productLine.id,rootModule:pe(t,e),modifiers:{},quantities:{modules:1,connectors:0},extraConnections:[],environment:"space"}}a(Q,"initialState");function Z(t){return t?1+Object.values(t.children).reduce((e,o)=>e+Z(o),0):0}a(Z,"countModules");function ge(t){return {apiPartId:t.apiPartId,partSlots:Object.fromEntries(Object.entries(t.nestedSlots).map(([e,o])=>[e,{part:o?ge(o):void 0}]))}}a(ge,"rulePart");function F(t,e,o="root"){let a=t.modules.get(e.apiModuleId),m={};for(let[h,b]of Object.entries(e.basePartSlots)){let p=a?.basePartSlots?.find(C=>C.name===h);m[h]={part:ge(b),compatibleParts:(p?.compatibleParts??[]).map(C=>({apiPartId:C.partId}))};}let y={};for(let h of a?.moduleSlots??[]){let b=e.children[h.name];y[h.name]={module:b?F(t,b,`${o}/${h.name}`):void 0,compatibleModules:(h.compatibleModuleIds??[]).map(p=>({id:p}))};}return {id:o,apiModuleId:e.apiModuleId,basePartSlots:m,moduleSlots:y}}a(F,"ruleModule");function H(t){let e=[t];for(let o of Object.values(t.moduleSlots))o.module&&e.push(...H(o.module));return e}a(H,"allRuleModules");var he={cs:{module:"Model",surface:"Povrch",size:"Rozm\u011Br"},en:{module:"Model",surface:"Finish",size:"Size"},de:{module:"Modell",surface:"Oberfl\xE4che",size:"Ma\xDF"},fr:{module:"Mod\xE8le",surface:"Finition",size:"Dimensions"}};function Se(t,e){if(typeof e=="number")return t.find(a=>a.id===e);let o=e.trim().toLowerCase();return t.find(a=>String(a.id)===o)??t.find(a=>a.code?.trim().toLowerCase()===o)??t.find(a=>a.name.trim().toLowerCase()===o)}a(Se,"findOption");function Te(t){let e=t.textureJson,o=e&&typeof e=="object"?e.color:void 0;return typeof o=="string"?o:null}a(Te,"colourOf");function be(t){let e=fe(t.catalog),{catalog:o}=t,a$2=he[t.locale]??he.en,m=f(o.rules),y=new Map;if(o.modules.length===0)throw new a$1("unknown_module",`Product line "${o.productLine.name}" has no published modules`);let h=t.state?p(t.state):Q(e,b(t.module));function b(n){if(n===void 0)return o.modules.find(s=>s.allowAsInitialModule!==false)??o.modules[0];let r=Se(o.modules,n);if(!r)throw new a$1("unknown_module",`No module "${n}" in product line "${o.productLine.name}"`);return r}a(b,"resolveModule");function p(n){if(n.productLineId!=null&&n.productLineId!==o.productLine.id)throw new a$1("invalid_state",`State is for product line ${n.productLineId}, this configurator is ${o.productLine.id}`);let r=n.rootModule?K(n.rootModule):null;if(r&&!e.modules.has(r.apiModuleId))throw new a$1("invalid_state",`Module ${r.apiModuleId} is not in this line`);return {productLineId:o.productLine.id,rootModule:r,modifiers:n.modifiers??{},quantities:{...n.quantities,modules:Z(r)},extraConnections:n.extraConnections??[],environment:n.environment??"space"}}a(p,"normalise");function C(){let n=h.rootModule;if(!n)throw new a$1("invalid_state","The configuration has no module");return n}a(C,"root");function x(){return e.modules.get(C().apiModuleId)}a(x,"currentModule");function O(n){return x().basePartSlots?.find(r=>r.name===n)}a(O,"slotOf");function A(){return T(x()).filter(n=>!n.syncWithSlotName)}a(A,"leaderSlots");function k(n){return T(x()).filter(r=>r.syncWithSlotName===n)}a(k,"followersOf");function $(n){return (n.compatibleParts??[]).map(r=>e.parts.get(r.partId)).filter(r=>!!r&&!r.hideFromConfigurator)}a($,"visibleParts");function N(n){let r=C().basePartSlots[n]?.apiPartId;return r===void 0?void 0:e.parts.get(r)}a(N,"partIn");function X(){return A().filter(n=>{let r=N(n.name);return r?U(e,r).length>0:false})}a(X,"surfaceSlots");function d(){let n=[];o.modules.length>1&&n.push({key:"module",kind:"module",label:a$2.module});for(let s of A())$(s).length>1&&n.push({key:s.name,kind:"part",label:s.label||s.name});let r=X();for(let s of r)U(e,N(s.name)).length>1&&n.push({key:`surface:${s.name}`,kind:"surface",label:s.label||s.name,slots:[s.name]});return r.length>0&&n.push({key:"surface",kind:"surface",label:a$2.surface,slots:r.map(s=>s.name)}),n}a(d,"groups");function l(n){let r=d().find(s=>s.key===n);if(!r){let s=d().map(f=>f.key).join(", ");throw new a$1("unknown_group",`No group "${n}" (this module has: ${s})`)}return r}a(l,"requireGroup");function I(){let n=C().apiModuleId;return o.modules.map(r=>({id:r.id,code:r.code??null,name:r.name,description:r.description??null,image:r.image??null,sizes:r.sizes??null,sizing:r.sizing??null,selected:r.id===n,disabled:false,reason:null}))}a(I,"moduleOptions");function w(n){let r=O(n),s=C(),f=s.basePartSlots[n]?.apiPartId,u=F(e,s),S=H(u);return $(r).map(c=>{let g=c.id===f?null:m.checkPart(c.id,n,u,S,n);return {id:c.id,code:c.code??null,name:c.name,description:c.description??null,image:c.image??null,selected:c.id===f,disabled:!!g,reason:g?.message??null}})}a(w,"partOptions");function P(n){let r=C(),s=new Map;for(let u of n){let S=N(u);if(S)for(let c of U(e,S)){let g=s.get(c.id)??{surface:c,slots:[]};g.slots.push(u),s.set(c.id,g);}}let f=n.map(u=>r.basePartSlots[u]?.surfaceId);return o.surfaces.filter(u=>s.has(u.id)).map(u=>{let{slots:S}=s.get(u.id),c=u.groupId!=null?e.surfaceGroups.get(u.groupId):void 0;return {id:u.id,code:null,name:u.name,description:u.description??null,image:u.thumbnailPath??u.texturePath??null,color:Te(u),groupId:u.groupId??null,groupName:c?.name??null,slots:S,selected:f.length>0&&f.every(g=>g===u.id),disabled:false,reason:null}})}a(P,"surfaceOptions");function L(n){let r=l(n);return r.kind==="module"?I():r.kind==="part"?w(r.key):P(r.slots??[])}a(L,"options");function R(n){return L(n).find(r=>r.selected)??null}a(R,"selected");function v(n,r){let s=K(n);h={...h,rootModule:s,quantities:{...h.quantities,modules:1}},Y("change",{state:_(),changed:r});}a(v,"commit");function V(n,r,s){let f={...n.basePartSlots};for(let u of [r,...k(r).map(S=>S.name)]){if(!O(u)?.compatibleParts?.some(g=>g.partId===s))continue;let c=f[u];c?.apiPartId!==s&&(f[u]=B(e,s,{surfaceId:c?.surfaceId}));}return {...n,basePartSlots:f}}a(V,"placePart");function ee(n,r,s){let f=e.parts.get(n.apiPartId),u=!!f?.hasConfigurableSurface&&q(e,f,r),S=Object.fromEntries(Object.entries(n.nestedSlots).map(([c,g])=>[c,g&&g.surfaceId===s?ee(g,r,s):g]));return {...n,...u&&{surfaceId:r},nestedSlots:S}}a(ee,"paint");function ye(n,r,s){let f={...n.basePartSlots};for(let u of r)for(let S of [u,...k(u).map(c=>c.name)]){let c=f[S];c&&(f[S]=ee(c,s,c.surfaceId));}return {...n,basePartSlots:f}}a(ye,"paintSlots");function Ie(n,r){let s=l(n),f=L(n),u=Se(f,r);if(!u){let g=f.map(z=>z.name).join(", ");throw new a$1("unknown_option",`No option "${r}" in "${n}" (${g})`)}if(u.disabled)throw new a$1("option_disabled",u.reason??`"${u.name}" is ruled out`);if(u.selected)return false;let S=C();if(s.kind==="module")return v(me(e,S,e.modules.get(u.id)),["*"]),true;if(s.kind==="part"){let g=V(S,n,u.id),z=[n],E=F(e,g);for(let D of m.partChangeSyncs(u.id,n,E,H(E)))D.moduleId===E.id&&(g=V(g,D.slotName,D.newPartId),z.push(D.slotName));return v(g,z),true}let c=u.slots;return v(ye(S,c,u.id),[n,...c.map(g=>`surface:${g}`)].filter((g,z,E)=>E.indexOf(g)===z)),true}a(Ie,"select");function te(){let n=x().sizing;return n?JSON.parse(JSON.stringify(n)):null}a(te,"sizeLimits");function Pe(){let n=C().size;return n?{...n}:null}a(Pe,"size");function Ce(n){let r=C();if(n===null){if(!r.size)return false;let{size:c,...g}=r;return v(g,["size"]),true}let s=te();if(!s)throw new a$1("size_not_available",`"${x().name}" comes in one size only`);let f=Math.round(n.width),u=Math.round(n.height),S=a((c,g)=>Number.isFinite(c)&&c>=g.min&&c<=g.max,"fits");if(!S(f,s.width)||!S(u,s.height))throw new a$1("size_out_of_range",`${f} \xD7 ${u} mm is outside ${s.width.min}\u2013${s.width.max} \xD7 ${s.height.min}\u2013${s.height.max} mm`,{details:s});return r.size?.width===f&&r.size?.height===u?false:(v({...r,size:{width:f,height:u}},["size"]),true)}a(Ce,"setSize");function we(){let n=C(),r=x(),s=[{group:"module",label:a$2.module,value:r.name,optionId:r.id}];n.size&&s.push({group:"size",label:a$2.size,value:`${n.size.width} \xD7 ${n.size.height} mm`,optionId:r.id});for(let f of A()){let u=N(f.name);if(!u)continue;$(f).length>1&&s.push({group:f.name,label:f.label||f.name,value:u.name,optionId:u.id});let S=n.basePartSlots[f.name]?.surfaceId,c=S!==void 0?e.surfaces.get(S):void 0;c&&U(e,u).length>0&&s.push({group:`surface:${f.name}`,label:f.label||f.name,value:c.name,optionId:c.id});}return s}a(we,"summary");function ne(){let n=[],r=h.rootModule;if(!r)return n.push({group:"module",code:"missing_module",message:"No module chosen"}),{valid:false,issues:n};let s=F(e,r),f=H(s);for(let u of T(x())){let S=r.basePartSlots[u.name];if(!S)continue;let c=e.parts.get(S.apiPartId);if(!c||!u.compatibleParts?.some(z=>z.partId===S.apiPartId)){n.push({group:u.name,code:"incompatible_part",message:`Part ${S.apiPartId} does not fit slot "${u.name}"`});continue}let g=m.checkPart(c.id,u.name,s,f,u.name);g&&n.push({group:u.name,code:"rule_violation",message:g.message}),S.surfaceId!==void 0&&!q(e,c,S.surfaceId)&&n.push({group:`surface:${u.name}`,code:"surface_not_allowed",message:`Finish ${S.surfaceId} is not offered for "${c.name}"`});}return {valid:n.length===0,issues:n}}a(ne,"validate");function _(){return JSON.parse(JSON.stringify(h))}a(_,"toJSON");function Me(n){h=p(n),Y("change",{state:_(),changed:["*"]});}a(Me,"load");function xe(n){h=Q(e,n===void 0?x():b(n)),Y("change",{state:_(),changed:["*"]});}a(xe,"reset");function Le(n,r){let s=y.get(n)??new Set;return s.add(r),y.set(n,s),()=>{s.delete(r);}}a(Le,"on");function Y(n,r){for(let s of y.get(n)??[])try{s(r);}catch(f){console.error("[konfigure] change listener failed",f);}}a(Y,"emit");function ve(n={}){let r=n.name??`${o.productLine.name} \xB7 ${x().name}`;return t.save(_(),r)}a(ve,"save");function Oe(n){let r=ne();if(!r.valid)throw new a$1("invalid_state",r.issues.map(s=>s.message).join("; "),{details:r.issues});return t.submitInquiry(_(),n)}return a(Oe,"submitInquiry"),{productLine:o.productLine,catalog:o,instance:t.instance,groups:d,options:L,selected:R,select:Ie,summary:we,validate:ne,price:a(()=>null,"price"),module:a(()=>x(),"module"),size:Pe,setSize:Ce,sizeLimits:te,toJSON:_,load:Me,reset:xe,on:Le,save:ve,submitInquiry:Oe}}a(be,"createConfigurator");function Ke(t){let e=t.instance.replace(/\/+$/,""),o=t.locale??"cs",a$2=t.fetch??globalThis.fetch.bind(globalThis),m=o==="cs"?"":`/${o}`,y=null,h=new Map;async function b(d,l){let I=`${e}${d}${d.includes("?")?"&":"?"}locale=${o}`,w;try{w=await a$2(I,{method:l?.method??"GET",headers:{Accept:"application/json",...l?.body!==void 0&&{"Content-Type":"application/json"}},body:l?.body!==void 0?JSON.stringify(l.body):void 0,credentials:"omit"});}catch(P){throw new a$1("network",`Could not reach ${e}${d} \u2014 is the instance running, and is this site's origin on its allowed origins?`,{cause:P})}if(!w.ok){let P;try{P=await w.json();}catch{P=void 0;}let L=P?.why??P?.message??w.statusText;throw new a$1("http",`${l?.method??"GET"} ${d}: ${L}`,{status:w.status,details:P})}return await w.json()}a(b,"request");function p(d){return {shareUrl:`${e}${m}/configuration/${d}`,viewUrl:`${e}${m}/configuration/${d}/view`}}a(p,"links");function C(){return y??=b("/api/product-lines/active").then(d=>d.map(l=>de(e,l))).catch(d=>{throw y=null,d}),y}a(C,"productLines");async function x(d){let l=await C(),I=typeof d=="string"?d.trim().toLowerCase():d,w=l.find(P=>P.id===I||String(P.id)===I)??l.find(P=>P.slug===I)??l.find(P=>typeof I=="string"&&G(P.name)===G(I));if(!w){let P=l.map(L=>L.slug).join(", ");throw new a$1("unknown_product_line",`No product line "${d}" (${P})`)}return w}a(x,"productLine");function O(d){return x(d).then(l=>{let I=h.get(l.id);return I||(I=Promise.all([b(`/api/product-lines/${l.id}/modules`),b("/api/parts"),b("/api/surfaces"),b("/api/surface-groups"),b("/api/rules").catch(()=>[])]).then(([w,P,L,R,v])=>ce(e,l,{modules:w,parts:P,surfaces:L,surfaceGroups:R,rules:v})),I.catch(()=>h.delete(l.id)),h.set(l.id,I)),I})}a(O,"catalog");async function A(d){let l=await b(`/api/saved-configurations/${encodeURIComponent(d)}`),I=[...l.versions??[]].sort((L,R)=>R.versionNumber-L.versionNumber),w=I.find(L=>L.versionNumber===l.currentVersionNumber)??I[0];if(!w)throw new a$1("invalid_state",`Configuration ${d} has no saved version`);let P=JSON.parse(w.configurationJson);return {id:l.id,displayId:l.displayId??null,name:l.name,productLineId:P.productLineId??l.productLineId??null,state:P,...p(l.id)}}a(A,"getConfiguration");async function k(d,l){let I=await b("/api/saved-configurations",{method:"POST",body:{name:l,status:"public",configurationJson:JSON.stringify(d),remoteProductLineId:d.productLineId}});return {id:I.id,displayId:I.displayId??null,...p(I.id)}}a(k,"saveConfiguration");async function $(d,l){let[I,...w]=(l.name??"").trim().split(/\s+/),P=Object.entries(l.extra??{}).filter(([,v])=>v!=null&&v!=="").map(([v,V])=>`${v}: ${V}`),L=[l.message?.trim(),P.join(`
|
|
2
|
-
`)].filter(Boolean).join(`
|
|
3
|
-
|
|
4
|
-
`),R=await b("/api/inquiries",{method:"POST",body:{projectJson:JSON.stringify(d),remoteProductLineId:d.productLineId,contactSnapshot:{email:l.email,...I&&{firstName:I},...w.length>0&&{lastName:w.join(" ")},...l.phone&&{phone:l.phone},...l.company&&{companyName:l.company}},note:L||void 0,state:"submitted"}});return {id:R.id,displayId:R.displayId??null}}a($,"submitInquiry");async function N(d){return b("/api/leads",{method:"POST",body:{data:d.data,gateKey:d.gateKey,configId:d.configurationId,locale:o}})}a(N,"submitLead");async function X(d){let l,I;if("configuration"in d){let w=await A(d.configuration);if(w.productLineId==null)throw new a$1("invalid_state",`Configuration ${w.id} has no product line`);l=w.state,I=w.productLineId;}else l=d.state,I=d.productLine;return be({catalog:await O(I),locale:o,instance:e,module:"module"in d?d.module:void 0,state:l,save:k,submitInquiry:$})}return a(X,"configurator"),{instance:e,locale:o,productLines:C,productLine:x,catalog:O,configurator:X,getConfiguration:A,saveConfiguration:k,submitInquiry:$,submitLead:N}}a(Ke,"createKonfigureClient");export{Ke as createKonfigureClient};
|
|
1
|
+
export{d as createKonfigureClient}from'./chunk-HFOEVYNK.js';export{a as KonfigureError}from'./chunk-EBEY7ID3.js';import'./chunk-XUSV3KOD.js';
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import * as three from 'three';
|
|
2
|
+
import { WebGLRenderer, Scene, PerspectiveCamera } from 'three';
|
|
3
|
+
import { K as KonfigureClient, c as ShowroomPlace } from './client-B2yVMro3.js';
|
|
4
|
+
export { b as ShowroomManifest } from './client-B2yVMro3.js';
|
|
5
|
+
import { e as Configurator } from './configurator-CnGR3YDW.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @konfigure/sdk/showroom — the instance's virtual showroom drawn on your own
|
|
9
|
+
* website: the show house with every opening holding the product the
|
|
10
|
+
* instance's catalogue has for it, built by the same engine and room kit as
|
|
11
|
+
* the instance's own `/showroom` page (@konfigure/three/showroom).
|
|
12
|
+
*
|
|
13
|
+
* Two ways to show it. `preview`: a picture of one view — no UI, no input, a
|
|
14
|
+
* slow drift if you like, drawn at most 30 times a second and not at all off
|
|
15
|
+
* screen — for a card on a home page. `walk`: the visitor walks and looks
|
|
16
|
+
* round (drag to look, click the floor to walk there, click a product to step
|
|
17
|
+
* up to it and get an `exhibit` event), for a showroom page of your own.
|
|
18
|
+
*
|
|
19
|
+
* Give it the visitor's configurator and the openings of that product line
|
|
20
|
+
* show what they configured, live.
|
|
21
|
+
*
|
|
22
|
+
* Browser only. Import it lazily (`await import('@konfigure/sdk/showroom')`).
|
|
23
|
+
*/
|
|
24
|
+
type ShowroomMode = 'preview' | 'walk';
|
|
25
|
+
/**
|
|
26
|
+
* How well the room is drawn. `preview` (the default for a preview): one
|
|
27
|
+
* sample pass, the room's light at half size, no area lights. `low` and
|
|
28
|
+
* `high` are the instance's own page's qualities; `auto` (the default for a
|
|
29
|
+
* walk) picks between them by what the device says about itself.
|
|
30
|
+
*/
|
|
31
|
+
type ShowroomQualityName = 'preview' | 'low' | 'high' | 'auto';
|
|
32
|
+
type ShowroomViewInfo = {
|
|
33
|
+
name: string;
|
|
34
|
+
label: string;
|
|
35
|
+
};
|
|
36
|
+
/** A product of the showroom, as the `exhibit` event gives it. */
|
|
37
|
+
type ShowroomExhibit = ShowroomPlace & {
|
|
38
|
+
/** It shows the configurator's state (see `configuratorPlaces`). */
|
|
39
|
+
configured: boolean;
|
|
40
|
+
};
|
|
41
|
+
type ShowroomEvents = {
|
|
42
|
+
/** The room is in and drawn (products may still be coming). */
|
|
43
|
+
room: void;
|
|
44
|
+
/** A product finished building (or rebuilding, after a configurator change). */
|
|
45
|
+
placed: ShowroomExhibit;
|
|
46
|
+
/** The visitor clicked a product (walk mode, input on). */
|
|
47
|
+
exhibit: ShowroomExhibit;
|
|
48
|
+
/** The camera arrived at a view (`setView`). */
|
|
49
|
+
view: string;
|
|
50
|
+
};
|
|
51
|
+
type MountShowroomOptions = {
|
|
52
|
+
/** The instance's origin. Or pass `client`. */
|
|
53
|
+
instance?: string;
|
|
54
|
+
/** A client you already have (shares its catalogue cache). */
|
|
55
|
+
client?: KonfigureClient;
|
|
56
|
+
/**
|
|
57
|
+
* The visitor's configurator. The openings holding its product line show
|
|
58
|
+
* its state, and follow every change: the same module where the opening
|
|
59
|
+
* holds that one, else its finishes and parts carried over slot by slot.
|
|
60
|
+
* A made-to-measure size is kept only where it is the opening's own.
|
|
61
|
+
*/
|
|
62
|
+
configurator?: Configurator;
|
|
63
|
+
/** Which openings (place keys) show the configurator. Default: every one of its product line. */
|
|
64
|
+
configuratorPlaces?: string[];
|
|
65
|
+
/** Default `preview`. */
|
|
66
|
+
mode?: ShowroomMode;
|
|
67
|
+
/** The view to start at (`views()`). Default `street`. */
|
|
68
|
+
view?: string;
|
|
69
|
+
/** Preview only: turn slowly to and fro. Default true. */
|
|
70
|
+
drift?: boolean;
|
|
71
|
+
/** Take the visitor's input (look, walk, click). Default: on in `walk`, off in `preview`. */
|
|
72
|
+
input?: boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Walk mode on a mouse: capture the pointer to look, the way a game does,
|
|
75
|
+
* and act on what the middle of the picture rests on (draw your own aim
|
|
76
|
+
* dot). Default false: drag to look, click where you mean.
|
|
77
|
+
*/
|
|
78
|
+
pointerLock?: boolean;
|
|
79
|
+
quality?: ShowroomQualityName;
|
|
80
|
+
/** The most device pixels drawn per CSS pixel. Default: the quality's (1 for a preview). */
|
|
81
|
+
pixelRatio?: number;
|
|
82
|
+
/** The most frames drawn a second. Default 30 in a preview, the display's rate in a walk. */
|
|
83
|
+
fps?: number;
|
|
84
|
+
/** Stop drawing while the element is off screen or the tab hidden. Default true. */
|
|
85
|
+
pauseOffscreen?: boolean;
|
|
86
|
+
/** Where the Draco decoder lives (only for Draco-compressed product GLBs). Default: three.js's CDN. */
|
|
87
|
+
dracoDecoderPath?: string;
|
|
88
|
+
/** Called when a product fails to build (a missing model, a network error). */
|
|
89
|
+
onError?: (error: unknown) => void;
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* Draw the instance's showroom into `container`. A `<canvas>` is drawn into
|
|
93
|
+
* directly; any other element gets a canvas filling it. Resolves once the
|
|
94
|
+
* room is drawn; the products follow (`whenReady`).
|
|
95
|
+
*/
|
|
96
|
+
declare function mountShowroom(container: HTMLElement, options?: MountShowroomOptions): Promise<{
|
|
97
|
+
/** Resolves once every product stands, and the latest configurator change is built. */
|
|
98
|
+
whenReady: () => Promise<void>;
|
|
99
|
+
/** The places to look from: `[{ name: 'street', label: 'Před domem' }, …]`. */
|
|
100
|
+
views: () => ShowroomViewInfo[];
|
|
101
|
+
/** The view the camera is at, or null once the visitor has walked off. */
|
|
102
|
+
view: () => string | null;
|
|
103
|
+
/**
|
|
104
|
+
* Go to a view. `seconds: 0` cuts; otherwise the camera walks there — the
|
|
105
|
+
* way a visitor would, through the doors — in `seconds`, or at walking
|
|
106
|
+
* pace. Default: a cut in a preview, a walk in walk mode.
|
|
107
|
+
*/
|
|
108
|
+
setView(name: string, { seconds }?: {
|
|
109
|
+
seconds?: number;
|
|
110
|
+
}): Promise<void>;
|
|
111
|
+
/** The products standing in the house, as the `exhibit` event gives them. */
|
|
112
|
+
exhibits: () => ShowroomExhibit[];
|
|
113
|
+
mode: () => ShowroomMode;
|
|
114
|
+
/** `walk` takes input and draws at the display's rate; `preview` neither. */
|
|
115
|
+
setMode: (next: ShowroomMode) => void;
|
|
116
|
+
/** Take the visitor's input or not, whatever the mode. */
|
|
117
|
+
setInput(on: boolean): void;
|
|
118
|
+
/** Preview: drift or hold still. */
|
|
119
|
+
setDrift(on: boolean): void;
|
|
120
|
+
/** Stop drawing (a hidden tab or an off-screen element already does). */
|
|
121
|
+
pause(): void;
|
|
122
|
+
resume(): void;
|
|
123
|
+
/** Listen to an event; returns the unsubscribe function. */
|
|
124
|
+
on<K extends keyof ShowroomEvents>(event: K, listener: (payload: ShowroomEvents[K]) => void): () => void;
|
|
125
|
+
/** The current frame as a PNG data URL. */
|
|
126
|
+
capture(): string;
|
|
127
|
+
/** What the room costs on this device, for whoever measures it. */
|
|
128
|
+
stats(): {
|
|
129
|
+
quality: string;
|
|
130
|
+
pixelRatio: number;
|
|
131
|
+
triangles: number;
|
|
132
|
+
calls: number;
|
|
133
|
+
textures: number;
|
|
134
|
+
geometries: number;
|
|
135
|
+
};
|
|
136
|
+
/** The renderer, scene and camera — an escape hatch; not a stable API. */
|
|
137
|
+
renderer: WebGLRenderer;
|
|
138
|
+
scene: Scene<three.Object3DEventMap>;
|
|
139
|
+
camera: PerspectiveCamera;
|
|
140
|
+
/** Stop drawing and free the GPU. */
|
|
141
|
+
dispose(): void;
|
|
142
|
+
}>;
|
|
143
|
+
type KonfigureShowroom = Awaited<ReturnType<typeof mountShowroom>>;
|
|
144
|
+
|
|
145
|
+
export { type KonfigureShowroom, type MountShowroomOptions, type ShowroomEvents, type ShowroomExhibit, type ShowroomMode, ShowroomPlace, type ShowroomQualityName, type ShowroomViewInfo, mountShowroom };
|
package/dist/showroom.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import {b,c,d,a as a$4}from'./chunk-HFOEVYNK.js';import {b as b$1,a as a$2,k,r,h,l,s}from'./chunk-4KQN5AVT.js';import {a as a$1}from'./chunk-EBEY7ID3.js';import {a as a$3,b as b$2}from'./chunk-XR6EHOK2.js';import {a}from'./chunk-XUSV3KOD.js';import {Color,CanvasTexture,Box3,Vector3,Group,RectAreaLight,MeshPhysicalMaterial,WebGLRenderTarget,LinearFilter,LinearMipmapLinearFilter,HalfFloatType,Matrix4,PerspectiveCamera,Vector2,MeshBasicMaterial,DoubleSide,EquirectangularReflectionMapping,SRGBColorSpace,ShaderChunk,BufferGeometry,Float32BufferAttribute,Vector4,InstancedMesh,Quaternion,MeshStandardMaterial,FrontSide,TextureLoader,BackSide,RepeatWrapping,Mesh,SphereGeometry,AmbientLight,DirectionalLight,PMREMGenerator,DepthTexture,WebGLRenderer,AgXToneMapping,Scene,Clock,HemisphereLight,Raycaster,BoxGeometry,PlaneGeometry,Plane}from'three';import {MeshoptDecoder}from'three/addons/libs/meshopt_decoder.module.js';import {RectAreaLightUniformsLib}from'three/addons/lights/RectAreaLightUniformsLib.js';import {GLTFLoader}from'three/addons/loaders/GLTFLoader.js';import {GTAOPass}from'three/addons/postprocessing/GTAOPass.js';import {OutputPass}from'three/addons/postprocessing/OutputPass.js';import {UnrealBloomPass}from'three/addons/postprocessing/UnrealBloomPass.js';function oo(t,e){return Math.abs(t.width-e.width*1e3)<=1&&Math.abs(t.height-e.height*1e3)<=1}a(oo,"fitsOpening");function gt(t,e,r){let s=e.moduleId==null?void 0:t.modules.get(e.moduleId);if(!s)throw new a$1("unknown_module",`No module ${e.moduleId} (${e.moduleCode}) in ${t.catalog.productLine.name}`);let u=r?.rootModule;if(!u)return b(t,s);let a=u.apiModuleId===s.id?u:c(t,u,s);if(!a.size||oo(a.size,e))return a;let{size:l,...d}=a;return d}a(gt,"placeState");var le=2,wt=1.2;function we(t,e){return t.level===void 0||e===void 0||Math.abs(t.level-e)<wt}a(we,"standsOn");function Ge(t,e,r){let[s,u]=[0,1];for(let[a,l,d,c]of [[t.x,e.x-t.x,r.x,r.halfX],[t.z,e.z-t.z,r.z,r.halfZ]]){if(Math.abs(l)<1e-9){if(Math.abs(a-d)>=c)return false;continue}let[f,S]=[(d-c-a)/l,(d+c-a)/l];s=Math.max(s,Math.min(f,S)),u=Math.min(u,Math.max(f,S));}return s<u}a(Ge,"walkCrosses");function lo(){let e=document.createElement("canvas");e.width=e.height=128;let r=e.getContext("2d"),s=r.createRadialGradient(128/2,128/2,0,128/2,128/2,128/2);return s.addColorStop(0,"rgba(0,0,0,1)"),s.addColorStop(.45,"rgba(0,0,0,1)"),s.addColorStop(1,"rgba(0,0,0,0)"),r.fillStyle=s,r.fillRect(0,0,128,128),new CanvasTexture(e)}a(lo,"edgeFadeTexture");function Be(t,e=512){let r=lo(),s=[];function u(a,l,d,c,f,S,w,_){let g=h({product:d,bounds:c,floorY:c.min.y,resolution:e});g.update(a,{light:f,blurWorld:S});let z=new Mesh(new PlaneGeometry(g.halfSize*2,g.halfSize*2),new MeshBasicMaterial({map:r,alphaMap:g.texture,transparent:true,depthWrite:false,opacity:w})),H=c.getCenter(new Vector3);z.rotation.x=-Math.PI/2,z.position.set(H.x,c.min.y+.002,H.z),z.renderOrder=1,z.layers.set(le),z.userData.shadowOf=l,_&&(z.material.clippingPlanes=[new Plane(new Vector3(1,0,0),-_.minX),new Plane(new Vector3(-1,0,0),_.maxX),new Plane(new Vector3(0,0,1),-_.minZ),new Plane(new Vector3(0,0,-1),_.maxZ)]),t.add(z),s.push({shadow:g,mesh:z});}return a(u,"cast"),{ground(a,l,d,c){let f=new Box3,S=[];if(l.updateMatrixWorld(true),l.traverseVisible(z=>{!z.isMesh||z.userData.isCollider||(f.expandByObject(z),S.push(z));}),f.isEmpty())return;let w=f.getCenter(new Vector3),_=f.getSize(new Vector3).y,g=w.clone().setY(f.min.y+8);if(u(a,l,S,f,g,.22*_,.4,c),d){let z=w.clone().add(d);u(a,l,S,f,z,.45*_,.16,c);}},dispose(){for(let{shadow:a,mesh:l}of s)a.dispose(),l.geometry.dispose(),l.material.dispose(),l.removeFromParent();r.dispose();}}}a(Be,"createProductShadows");var Ue=2,So=.7,Mo="#232325";function yt(t,e,r){return e>=t.minX&&e<=t.maxX&&r>=t.minZ&&r<=t.maxZ}a(yt,"inside");var xt=new WeakMap;function vo(t,e){let r=t.image;if(e>=1||!r)return t;let s=xt.get(r);if(s)return t.dispose(),s;let u=document.createElement("canvas");u.width=Math.max(1,Math.round(r.width*e)),u.height=Math.max(1,Math.round(r.height*e)),u.getContext("2d").drawImage(r,0,0,u.width,u.height);let a=new CanvasTexture(u);return a.flipY=t.flipY,a.colorSpace=t.colorSpace,a.channel=t.channel,t.dispose(),r.close?.(),xt.set(r,a),a}a(vo,"shrink");function Ro({levels:t,ramps:e},r,s,u){let a$1=a((d,c)=>!c||u!==void 0&&Math.abs(d-u)<So,"within"),l=0;for(let d of t)yt(d,r,s)&&a$1(d.y,d.stacked)&&(l=d.y);for(let d of e){if(!yt(d,r,s))continue;let[c,f,S]=d.axis==="x"?[d.minX,d.maxX,r]:[d.minZ,d.maxZ,s],w=d.from+(d.to-d.from)*(S-c)/(f-c);a$1(w,d.stacked)&&(l=w);}return l}a(Ro,"floorAt");function St(t,e,r,s){t.traverse(u=>{let a=u;if(!a.isMesh)return;if(r(a.geometry),a.name.startsWith("props")||a.parent?.name.startsWith("props")){let d=a.material;a.material=e.prop(d),a.material===d?r(d):d.dispose();return}let l=a.material;a.material=e.material(a.name,l.emissiveMap?vo(l.emissiveMap,s):null,r,l),l.dispose();});}a(St,"dressBakedModel");function vt(t,{name:e,model:r,layout:s,background:u,lightmaps:a$1=1,glass:l={color:"#e6ecee",opacity:.1},dress:d,loaded:c}){RectAreaLightUniformsLib.init();let f=new Group;f.name=e,t.add(f);let S=Be(f,256),w=[],_=a(b=>(w.push(b),b),"own");t.background=new Color(u);let g=null,z=null,H=null,R=[0];function h(b,y,x){return g?Ro(g,b,y,x):0}a(h,"floorHeight");function O(b,y){let x=h(b,y),L=0;return R.forEach((P,E)=>{Math.abs(P-x)<Math.abs(R[L]-x)&&(L=E);}),L}a(O,"levelOf");function v(b,y,x="flat",L=Mo){let P=b.split(`
|
|
2
|
+
`),E=180,p=`700 ${E}px "Helvetica Neue", Helvetica, Arial, sans-serif`,D=document.createElement("canvas"),U=D.getContext("2d");U.font=p;let K=x==="flat"?8:48;D.width=Math.ceil(Math.max(...P.map(C=>U.measureText(C).width)))+K*2,D.height=Math.ceil(E*(.94*(P.length-1)+1.2))+(x==="flat"?0:K),U.font=p,U.fillStyle=L;let q=a(()=>P.forEach((C,F)=>U.fillText(C,K,E*(.94*F+.92))),"draw");x!=="flat"&&(U.save(),x==="raised"?(U.shadowColor="rgba(52, 50, 48, 0.42)",U.shadowBlur=20,U.shadowOffsetX=4,U.shadowOffsetY=13):(U.shadowColor=L,U.shadowBlur=26),q(),U.restore()),q();let J=_(new CanvasTexture(D));J.colorSpace=SRGBColorSpace,J.anisotropy=8;let Y=y.height/E,A=D.width*Y,k=_(new MeshBasicMaterial({map:J,transparent:true,depthWrite:false}));x==="lit"&&k.color.setScalar(1.9);let B=new Mesh(_(new PlaneGeometry(A,D.height*Y)),k);B.rotation.y=y.rotationY;let i=new Vector3(Math.sin(y.rotationY),0,Math.cos(y.rotationY)),W=new Vector3(Math.cos(y.rotationY),0,-Math.sin(y.rotationY));B.position.set(...y.position).addScaledVector(i,.006).addScaledVector(W,y.align==="left"?A/2:y.align==="right"?-A/2:0),x!=="flat"&&(B.position.y-=K/2*Y),B.renderOrder=1,B.layers.set(le),f.add(B);}a(v,"lettering");let m={ready:Promise.resolve(),bounds:{minX:-16,maxX:16,minZ:-11,maxZ:8},start:{x:0,z:0,yaw:0},obstacles:[],floor:f,solid:f,place(b){return b.map(()=>null)},floorHeight:h,route(b,y){if(!g)return [];let[x,L]=[O(b.x,b.z),O(y.x,y.z)],P=[];for(let E=x;E<L;E++){let p=g.portals[E];p&&P.push({x:p.a[0],z:p.a[1]},{x:p.b[0],z:p.b[1]});}for(let E=x;E>L;E--){let p=g.portals[E-1];p&&P.push({x:p.b[0],z:p.b[1]},{x:p.a[0],z:p.a[1]});}return P},groundProduct(b,y,x){S.ground(b,y,void 0,x?.support);},dispose(){S.dispose();for(let b of w)b.dispose();t.remove(f);}};function I({position:b,size:y}){let x=new Mesh(_(new BoxGeometry(...y)),H);return x.position.set(...b),x.renderOrder=2,x.layers.set(le),x}return a(I,"pane"),m.ready=Promise.all([r?new GLTFLoader().setMeshoptDecoder(MeshoptDecoder).loadAsync(r):null,fetch(s).then(b=>b.json())]).then(([b,y])=>{g=y,R=[...new Set([0,...y.levels.map(x=>x.y)])].sort((x,L)=>x-L),z=d(y,_),b&&(St(b.scene,z,_,a$1),f.add(b.scene)),m.bounds=y.bounds,m.start=y.start,m.obstacles.push(...y.colliders);for(let x of y.lights){let L=new RectAreaLight(x.color,x.intensity,x.width,x.height);L.position.set(...x.position),L.lookAt(new Vector3(...x.target)),f.add(L);}H=_(new MeshPhysicalMaterial({color:l.color,roughness:.03,metalness:0,transparent:true,opacity:l.opacity,envMapIntensity:1.4,depthWrite:false}));for(let x of y.glass)f.add(I(x));for(let x of y.signs)v(x.text,x,x.lit?"lit":"raised",x.color);c?.(y);}),{room:m,group:f,own:_,lettering:v,layout:a(()=>g,"layout"),dressModel(b,y){z&&St(b,z,y,a$1);},pane:I}}a(vt,"createBakedRoom");function Lt({scale:t,strength:e=.85,height:r=0}){let s=new WebGLRenderTarget(1,1,{type:HalfFloatType,generateMipmaps:true,minFilter:LinearMipmapLinearFilter,magFilter:LinearFilter}),u={mirrorMap:{value:null},mirrorMatrix:{value:new Matrix4},mirrorStrength:{value:0},mirrorBlur:{value:Math.max(0,Math.log2(12*t))}},a=new PerspectiveCamera,l=new Vector2,[d,c,f]=[new Vector3,new Vector3,new Vector3],S=new Matrix4;return {uniforms:u,render(w,_,g){w.getDrawingBufferSize(l);let[z,H]=[Math.max(1,Math.round(l.x*t)),Math.max(1,Math.round(l.y*t))];if((s.width!==z||s.height!==H)&&s.setSize(z,H),g.updateMatrixWorld(),d.setFromMatrixPosition(g.matrixWorld),d.y<=r)return;S.extractRotation(g.matrixWorld),c.set(0,0,-1).applyMatrix4(S).add(d),f.set(0,1,0).applyMatrix4(S),a.position.set(d.x,2*r-d.y,d.z),a.up.set(f.x,-f.y,f.z),a.lookAt(c.x,2*r-c.y,c.z),a.projectionMatrix.copy(g.projectionMatrix),a.projectionMatrixInverse.copy(g.projectionMatrixInverse),a.updateMatrixWorld(),u.mirrorMatrix.value.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),u.mirrorMap.value=null;let R=w.getRenderTarget();w.setRenderTarget(s),w.render(_,a),w.setRenderTarget(R),u.mirrorMap.value=s.texture,u.mirrorStrength.value=e;},dispose(){s.dispose();}}}a(Lt,"createFloorMirror");var Ho="/models/showroom/house",Se={exposure:2,grade:{contrast:1.45,colour:1.1},productLight:.35},ae=a(t=>t*Math.PI/180,"degrees"),me=[{name:"facade",label:"Terasa",x:6.5,z:10.5,yaw:ae(-90),pitch:ae(-2)},{name:"interior",label:"Z chodby",x:12.3,z:12.2,yaw:ae(90),pitch:ae(-3)},{name:"street",label:"P\u0159ed domem",x:10.05,z:-7.4,yaw:ae(180),pitch:ae(-2)},{name:"living",label:"J\xEDdelna",x:4.2,z:3.4,yaw:ae(-45),pitch:ae(-3)}],Ct="#bcd3ea",xe={above:Math.PI/3,below:Math.PI/9},Oe=-2.51,Tt=118,Uo=new Color(.26,.29,.33),No=new Color(1.5,1.35,1.1),Yo=new Color(.8,.9,.4),Vo=.15;function Xo(t,e,r,s){let u=t.name.startsWith("plant-leaf"),a=new MeshBasicMaterial({map:t.map,vertexColors:true,side:DoubleSide,alphaTest:u?.3:0});return a.name=t.name,a.onBeforeCompile=l=>{l.uniforms.plantSun={value:e},l.uniforms.plantSunFront={value:r},l.uniforms.plantInside={value:s},l.uniforms.plantSkyLight={value:Uo},l.uniforms.plantSunLight={value:No},l.uniforms.plantThrough={value:Yo},l.vertexShader=l.vertexShader.replace("#include <common>",`#include <common>
|
|
3
|
+
uniform vec3 plantSun;
|
|
4
|
+
uniform vec3 plantSunFront;
|
|
5
|
+
varying float plantFacing;
|
|
6
|
+
varying float plantAgainst;
|
|
7
|
+
varying float plantOwn;
|
|
8
|
+
varying vec2 plantStands;`).replace("#include <begin_vertex>",`#include <begin_vertex>
|
|
9
|
+
vec3 outOfCrown = normal;
|
|
10
|
+
vec4 plantAt = vec4( position, 1.0 );
|
|
11
|
+
#ifdef USE_INSTANCING
|
|
12
|
+
outOfCrown = mat3( instanceMatrix ) * outOfCrown;
|
|
13
|
+
plantAt = instanceMatrix * plantAt;
|
|
14
|
+
#endif
|
|
15
|
+
outOfCrown = normalize( mat3( modelMatrix ) * outOfCrown );
|
|
16
|
+
plantAt = modelMatrix * plantAt;
|
|
17
|
+
plantStands = plantAt.xz;
|
|
18
|
+
// Which sun it stands in comes with the place (the instance's green).
|
|
19
|
+
vec3 sunHere = plantSun;
|
|
20
|
+
#ifdef USE_INSTANCING_COLOR
|
|
21
|
+
sunHere = mix( plantSunFront, plantSun, instanceColor.g );
|
|
22
|
+
#endif
|
|
23
|
+
// Light wraps round a crown: leaves let it through, and scatter it.
|
|
24
|
+
plantFacing = smoothstep( -0.5, 0.8, dot( outOfCrown, sunHere ) );
|
|
25
|
+
// How nearly the eye looks into the sun through this leaf.
|
|
26
|
+
plantAgainst = max( 0.0, dot( normalize( plantAt.xyz - cameraPosition ), sunHere ) );
|
|
27
|
+
// No two sprays are one green: each a little lighter or darker by where it hangs.
|
|
28
|
+
plantOwn = fract( sin( dot( floor( plantAt.xyz * 2.3 ), vec3( 12.9898, 78.233, 37.719 ) ) ) * 43758.5453 );`),l.fragmentShader=l.fragmentShader.replace("#include <common>",`#include <common>
|
|
29
|
+
uniform vec3 plantSkyLight;
|
|
30
|
+
uniform vec3 plantSunLight;
|
|
31
|
+
uniform vec3 plantThrough;
|
|
32
|
+
uniform vec4 plantInside[ 4 ];
|
|
33
|
+
varying float plantFacing;
|
|
34
|
+
varying float plantAgainst;
|
|
35
|
+
varying float plantOwn;
|
|
36
|
+
varying vec2 plantStands;`).replace("#include <color_fragment>",`// A grass against a wall leans on it: what would come through into a room is not there.
|
|
37
|
+
for ( int each = 0; each < 4; each ++ ) {
|
|
38
|
+
vec4 room = plantInside[ each ];
|
|
39
|
+
if ( plantStands.x > room.x && plantStands.y > room.y && plantStands.x < room.z && plantStands.y < room.w ) discard;
|
|
40
|
+
}
|
|
41
|
+
// Seen from far off a leaf is smaller than a pixel, and a spray of
|
|
42
|
+
// them averages out to less than the cut-off: a crown thins to a
|
|
43
|
+
// stipple. The further off (the smaller the picture is drawn), the
|
|
44
|
+
// more firmly what is there is kept.
|
|
45
|
+
vec2 drawn = vMapUv * 2048.0;
|
|
46
|
+
float small = max( 0.0, 0.5 * log2( max( dot( dFdx( drawn ), dFdx( drawn ) ), dot( dFdy( drawn ), dFdy( drawn ) ) ) ) );
|
|
47
|
+
diffuseColor.a *= 1.0 + small * 0.4;
|
|
48
|
+
float openToSky = vColor.r;
|
|
49
|
+
float sunHere = vColor.b;
|
|
50
|
+
// Deep in a crown there is little of either light.
|
|
51
|
+
float depth = openToSky * openToSky;
|
|
52
|
+
vec3 plantLight = plantSkyLight * ( 0.25 + 0.75 * depth )
|
|
53
|
+
+ plantSunLight * ( sunHere * plantFacing * ( 0.3 + 0.7 * openToSky ) )
|
|
54
|
+
+ plantThrough * ( sunHere * ${u?"1.0":"0.0"} * ( 0.25 + 0.75 * plantAgainst * plantAgainst ) * ( 1.0 - plantFacing ) * openToSky );
|
|
55
|
+
diffuseColor.rgb *= plantLight * ( 0.82 + 0.36 * plantOwn );
|
|
56
|
+
diffuseColor.rgb = mix( diffuseColor.rgb, vec3( dot( diffuseColor.rgb, vec3( 0.2126, 0.7152, 0.0722 ) ) ), ${Vo.toFixed(2)} );`);},a.customProgramCacheKey=()=>`plant-${u}`,a}a(Xo,"plantMaterial");var jo=new Set(["floor","terrace","ground"]),Ko=new Set(["rooms","floor","furniture"]),Zo={color:"#a3b0b6",metalness:.9,opacity:.72,reflects:.45},$o={color:"#ffffff",metalness:0,opacity:.03,reflects:.1},It=Math.PI/20,Qo=new Set(["glass","glassSolar"]),qo=700;function Jo(t){let e=document.createElement("canvas");e.width=2048,e.height=1024;let r=e.getContext("2d");if(!r)return null;let s=e.height*(Math.PI/2-xe.above+It)/Math.PI,u=e.height*(Math.PI/2+xe.below+It)/Math.PI;r.drawImage(t,0,0,t.width,2,0,0,e.width,s+1),r.drawImage(t,0,t.height-2,t.width,2,0,u-1,e.width,e.height-u+1),r.drawImage(t,0,s,e.width,u-s);let a=new CanvasTexture(e);return a.mapping=EquirectangularReflectionMapping,a.colorSpace=SRGBColorSpace,a}a(Jo,"skyReflection");var en=1.5;function tn(t,e){Object.assign(t.uniforms,e),t.vertexShader=t.vertexShader.replace("#include <common>",`#include <common>
|
|
57
|
+
varying vec3 houseWorld;`).replace("#include <project_vertex>",`#include <project_vertex>
|
|
58
|
+
houseWorld = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;`),t.fragmentShader=t.fragmentShader.replace("#include <common>",`#include <common>
|
|
59
|
+
varying vec3 houseWorld;
|
|
60
|
+
uniform sampler2D mirrorMap;
|
|
61
|
+
uniform mat4 mirrorMatrix;
|
|
62
|
+
uniform float mirrorStrength;
|
|
63
|
+
uniform float mirrorBlur;`).replace("#include <map_fragment>",`#include <map_fragment>
|
|
64
|
+
if ( mirrorStrength > 0.0 ) {
|
|
65
|
+
vec4 seen = mirrorMatrix * vec4( houseWorld, 1.0 );
|
|
66
|
+
float grain = dot( diffuseColor.rgb, vec3( 0.333 ) );
|
|
67
|
+
vec2 at = seen.xy / seen.w * 0.5 + 0.5 + ( grain - 0.5 ) * vec2( 0.006, 0.01 );
|
|
68
|
+
float glancing = 1.0 - clamp( normalize( cameraPosition - houseWorld ).y, 0.0, 1.0 );
|
|
69
|
+
float share = ( 0.05 + 0.95 * pow( glancing, 4.0 ) ) * mirrorStrength * ( 0.75 + 0.5 * grain );
|
|
70
|
+
// What it shows is light, not paint: it is not to be darkened by the
|
|
71
|
+
// floor's own baked light afterwards, so it is given that back here.
|
|
72
|
+
diffuseColor.rgb = mix( diffuseColor.rgb, textureLod( mirrorMap, at, mirrorBlur + 1.0 ).rgb * ${en.toFixed(2)}, share );
|
|
73
|
+
}`);}a(tn,"polish");function on(t,e,r){t.uniforms.houseSun={value:r.sun},t.uniforms.houseSunFront={value:r.sunFront},t.uniforms.houseFront={value:r.front},t.vertexShader=t.vertexShader.replace("#include <common>",`#include <common>
|
|
74
|
+
varying vec3 reliefWorld;`).replace("#include <project_vertex>",`#include <project_vertex>
|
|
75
|
+
reliefWorld = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;`),t.fragmentShader=t.fragmentShader.replace("#include <common>",`#include <common>
|
|
76
|
+
uniform vec3 houseSun;
|
|
77
|
+
uniform vec3 houseSunFront;
|
|
78
|
+
uniform vec2 houseFront;
|
|
79
|
+
varying vec3 reliefWorld;`).replace("#include <normal_fragment_maps>",ShaderChunk.normal_fragment_maps.replace("mapN.xy *= normalScale;","mapN.xy *= normalScale * ( 1.0 - 2.0 * mod( floor( vNormalMapUv ), 2.0 ) );")).replace("#include <lights_fragment_maps>",`// Only the baked light falls here: not the scene's ambient, nor the sky dome's.
|
|
80
|
+
irradiance = vec3( 0.0 );
|
|
81
|
+
#include <lights_fragment_maps>
|
|
82
|
+
iblIrradiance = vec3( 0.0 );
|
|
83
|
+
// The bake knows a wall as flat. Its relief \u2014 the grain of render, the
|
|
84
|
+
// gap between two boards \u2014 takes the sun by which way each grain faces
|
|
85
|
+
// it: more where it turns towards the sun, less where it turns away,
|
|
86
|
+
// and a little less of the sky in every hollow. (Which sun: by where
|
|
87
|
+
// the surface stands, as the bake chose.)
|
|
88
|
+
#if defined( USE_NORMALMAP_TANGENTSPACE ) && defined( USE_LIGHTMAP )
|
|
89
|
+
{
|
|
90
|
+
float toFront = 1.0 - smoothstep( houseFront.x, houseFront.y, reliefWorld.z );
|
|
91
|
+
vec3 towards = normalize( ( viewMatrix * vec4( mix( houseSun, houseSunFront, toFront ), 0.0 ) ).xyz );
|
|
92
|
+
float flatLit = max( dot( nonPerturbedNormal, towards ), 0.0 );
|
|
93
|
+
float lit = max( dot( normal, towards ), 0.0 );
|
|
94
|
+
float sunny = smoothstep( 0.3, 0.75, dot( lightMapIrradiance, vec3( 0.333 ) ) * RECIPROCAL_PI ) * smoothstep( 0.03, 0.15, flatLit );
|
|
95
|
+
float relief = mix( 1.0, lit / max( flatLit, 0.2 ), sunny );
|
|
96
|
+
relief *= mix( 1.0, pow( max( dot( normal, nonPerturbedNormal ), 0.0 ), 6.0 ), 0.5 );
|
|
97
|
+
irradiance *= clamp( relief, 0.35, 1.7 );
|
|
98
|
+
}
|
|
99
|
+
#endif`).replace("#include <lights_fragment_end>",`#include <lights_fragment_end>
|
|
100
|
+
// Nor the scene's sun: its shadow is in the bake, and a second sun has none.
|
|
101
|
+
reflectedLight.directDiffuse = vec3( 0.0 );
|
|
102
|
+
reflectedLight.directSpecular = vec3( 0.0 );
|
|
103
|
+
float housesLight = 1.0;
|
|
104
|
+
#ifdef USE_LIGHTMAP
|
|
105
|
+
housesLight = smoothstep( 0.03, 0.3, dot( lightMapIrradiance, vec3( 0.333 ) ) * RECIPROCAL_PI );
|
|
106
|
+
#endif
|
|
107
|
+
reflectedLight.indirectSpecular *= housesLight * ${e.toFixed(3)};`);}a(on,"physical");var te={side:22,reach:10.5,dense:150,blades:5,tall:.085};function nn(){let t=[],e=[],r=[],s=(()=>{let l=20261121;return ()=>(l=Math.imul(l,1664525)+1013904223>>>0,l/4294967296)})(),u=3;for(let l=0;l<te.blades;l++){let d=s()*Math.PI*2,c=.25+s()*.55,f=te.tall*(.65+s()*.6),S=.0035+s()*.0025,[w,_]=[(s()-.5)*.05,(s()-.5)*.05],[g,z]=[Math.cos(d),Math.sin(d)],H=t.length/3;for(let R=0;R<=u;R++){let h=R/u,O=c*f*h*h,v=f*h*(1-.25*c*h),m=S*(1-h*.85);for(let I of [-1,1])t.push(w+g*O-z*m*I,v,_+z*O+g*m*I),e.push(h,l/te.blades);}for(let R=0;R<u;R++){let h=H+R*2;r.push(h,h+1,h+2,h+1,h+3,h+2);}}let a=new BufferGeometry;return a.setAttribute("position",new Float32BufferAttribute(t,3)),a.setAttribute("blade",new Float32BufferAttribute(e,2)),a.setIndex(r),a}a(nn,"grassTuft");function rn(t,e,r){let s=t.lawn,u=e.material.lightMap,[a$1,l]=[e.geometry.getAttribute("position"),e.geometry.getAttribute("uv1")];if(!s||!u||!a$1||!l)return null;e.updateWorldMatrix(true,false);let d=a(k=>new Vector3().fromBufferAttribute(a$1,k).applyMatrix4(e.matrixWorld),"corner"),[c,f]=[d(0),d(1)],S=2;for(;S<a$1.count-1&&Math.abs((f.x-c.x)*(d(S).z-c.z)-(f.z-c.z)*(d(S).x-c.x))<.001;)S++;let w=d(S),[_,g,z,H]=[f.x-c.x,f.z-c.z,w.x-c.x,w.z-c.z],R=_*H-g*z;if(Math.abs(R)<1e-6)return null;let h=a(k=>new Vector2(l.getX(k),l.getY(k)),"uv"),[O,v,m]=[h(0),h(1).sub(h(0)),h(S).sub(h(0))],I=v.clone().multiplyScalar(H/R).add(m.clone().multiplyScalar(-g/R)),b=v.clone().multiplyScalar(-z/R).add(m.clone().multiplyScalar(_/R)),y=O.clone().sub(I.clone().multiplyScalar(c.x)).sub(b.clone().multiplyScalar(c.z)),x=s.bare.slice(0,8).map(k=>new Vector4(k.minX,k.minZ,k.maxX,k.maxZ));for(;x.length<8;)x.push(new Vector4(0,0,0,0));let L={grassEye:{value:new Vector3},grassSide:{value:te.side},grassReach:{value:te.reach},grassPlot:{value:new Vector4(t.plot.minX+.4,t.plot.minZ+.4,t.plot.maxX-.4,t.plot.maxZ-.4)},grassBare:{value:x},grassColour:{value:r},lawnLight:{value:u},lawnLightScale:{value:e.material.lightMapIntensity},lawnFrom:{value:y},lawnPerX:{value:I},lawnPerZ:{value:b}},P=new MeshBasicMaterial({side:DoubleSide});P.onBeforeCompile=k=>{Object.assign(k.uniforms,L),k.vertexShader=k.vertexShader.replace("#include <common>",`#include <common>
|
|
108
|
+
attribute vec2 blade;
|
|
109
|
+
uniform vec3 grassEye;
|
|
110
|
+
uniform float grassSide;
|
|
111
|
+
uniform float grassReach;
|
|
112
|
+
uniform vec4 grassPlot;
|
|
113
|
+
uniform vec4 grassBare[ 8 ];
|
|
114
|
+
uniform vec3 grassColour;
|
|
115
|
+
uniform sampler2D lawnLight;
|
|
116
|
+
uniform float lawnLightScale;
|
|
117
|
+
uniform vec2 lawnFrom;
|
|
118
|
+
uniform vec2 lawnPerX;
|
|
119
|
+
uniform vec2 lawnPerZ;
|
|
120
|
+
varying vec3 grassShade;`).replace("#include <project_vertex>",`// The square of tufts, wrapped round the eye: this one's nearest self.
|
|
121
|
+
vec3 root = instanceMatrix[ 3 ].xyz;
|
|
122
|
+
vec2 away = mod( root.xz - grassEye.xz + grassSide * 0.5, grassSide ) - grassSide * 0.5;
|
|
123
|
+
vec2 spot = grassEye.xz + away;
|
|
124
|
+
// Towards the square's edge it sinks into the lawn's photograph.
|
|
125
|
+
float grown = 1.0 - smoothstep( grassReach * 0.5, grassReach, length( away ) );
|
|
126
|
+
if ( spot.x < grassPlot.x || spot.y < grassPlot.y || spot.x > grassPlot.z || spot.y > grassPlot.w ) grown = 0.0;
|
|
127
|
+
for ( int each = 0; each < 8; each ++ ) {
|
|
128
|
+
vec4 box = grassBare[ each ];
|
|
129
|
+
if ( spot.x > box.x && spot.y > box.y && spot.x < box.z && spot.y < box.w ) grown = 0.0;
|
|
130
|
+
}
|
|
131
|
+
vec4 mvPosition = instanceMatrix * vec4( transformed * vec3( 1.0, grown, 1.0 ), 1.0 );
|
|
132
|
+
mvPosition.xz += spot - root.xz;
|
|
133
|
+
mvPosition = modelViewMatrix * mvPosition;
|
|
134
|
+
gl_Position = projectionMatrix * mvPosition;
|
|
135
|
+
// The lawn's own light at its root; darker at the foot, where blades stand in each other's shade.
|
|
136
|
+
vec3 lit = texture2D( lawnLight, lawnFrom + lawnPerX * spot.x + lawnPerZ * spot.y ).rgb * lawnLightScale * RECIPROCAL_PI;
|
|
137
|
+
float own = fract( sin( dot( root.xz, vec2( 12.9898, 78.233 ) ) ) * 43758.5453 );
|
|
138
|
+
grassShade = grassColour * lit * mix( 0.5, 1.3, blade.x ) * ( 0.85 + 0.3 * own )
|
|
139
|
+
* mix( vec3( 1.0 ), vec3( 1.1, 1.04, 0.82 ), step( 0.93, own ) * blade.x );`),k.fragmentShader=k.fragmentShader.replace("#include <common>",`#include <common>
|
|
140
|
+
varying vec3 grassShade;`).replace("#include <color_fragment>","diffuseColor.rgb = grassShade;");},P.customProgramCacheKey=()=>"house-grass";let E=Math.round(te.side*te.side*te.dense),p=new InstancedMesh(nn(),P,E);p.name="lawn-grass";let[D,U,K,q]=[new Matrix4,new Quaternion,new Vector3,new Vector3],J=new Vector3(0,1,0),Y=7,A=a(()=>(Y=Math.imul(Y,1664525)+1013904223>>>0,Y/4294967296),"random");for(let k=0;k<E;k++){let B=.75+A()*.6;D.compose(q.set(A()*te.side,s.height,A()*te.side),U.setFromAxisAngle(J,A()*Math.PI*2),K.set(B,B*(.8+A()*.5),B)),p.setMatrixAt(k,D);}return p.instanceMatrix.needsUpdate=true,p.frustumCulled=false,{tufts:p,material:P,follow(k){L.grassEye.value.copy(k.position);}}}a(rn,"growLawn");function an(t){t.onBeforeCompile=e=>{e.fragmentShader=e.fragmentShader.replace("#include <common>",`#include <common>
|
|
141
|
+
float lawnSpot( vec2 at ) {
|
|
142
|
+
return fract( sin( dot( at, vec2( 127.1, 311.7 ) ) ) * 43758.5453 );
|
|
143
|
+
}
|
|
144
|
+
float lawnDrift( vec2 at ) {
|
|
145
|
+
vec2 cell = floor( at );
|
|
146
|
+
vec2 within = fract( at );
|
|
147
|
+
within = within * within * ( 3.0 - 2.0 * within );
|
|
148
|
+
return mix(
|
|
149
|
+
mix( lawnSpot( cell ), lawnSpot( cell + vec2( 1.0, 0.0 ) ), within.x ),
|
|
150
|
+
mix( lawnSpot( cell + vec2( 0.0, 1.0 ) ), lawnSpot( cell + vec2( 1.0, 1.0 ) ), within.x ),
|
|
151
|
+
within.y
|
|
152
|
+
);
|
|
153
|
+
}`).replace("#include <map_fragment>",`#include <map_fragment>
|
|
154
|
+
float lawnPatch = lawnDrift( vMapUv * 0.21 ) * 0.6 + lawnDrift( vMapUv * 0.83 + 7.3 ) * 0.4 - 0.5;
|
|
155
|
+
diffuseColor.rgb *= 1.0 + lawnPatch * 0.34;
|
|
156
|
+
diffuseColor.rgb *= mix( vec3( 1.0 ), vec3( 1.07, 1.02, 0.84 ), smoothstep( 0.08, 0.34, lawnPatch ) );`);};}a(an,"varyLawn");function Ye(t,{lightmaps:e=1,base:r=Ho}={}){let s=null,u=[],a$1=null,l=null,d=e<1?null:Lt({scale:.5,strength:.9}),{room:c,group:f,own:S,layout:w}=vt(t,{name:"showroom-house",model:`${r}/house.glb`,layout:`${r}/house.json`,background:Ct,lightmaps:e,dress(O,v){let m=v,I=new Vector3(...O.sun).normalize(),b=new Vector3(...O.sunFront).normalize(),y={sun:I,sunFront:b,front:new Vector2(...O.front??[1.3,2.4])},x=(O.inside??[]).slice(0,4).map(L=>new Vector4(L.minX,L.minZ,L.maxX,L.maxZ));for(;x.length<4;)x.push(new Vector4(0,0,0,0));return {material(L,P,E=v,p){let D=p?.color.clone()??new Color("#ffffff"),U=O.tints?.[p?.name??""];U&&D.multiply(new Color().setRGB(...U));let K={color:D,map:p?.map??null,lightMap:P,side:p?.side??FrontSide,lightMapIntensity:p?.emissiveIntensity??Ue};if(P&&E(P),p?.map&&(p.map.anisotropy=8,E(p.map)),p?.map?.name.startsWith("lawn")){let B=E(new MeshBasicMaterial(K));return an(B),p.name.startsWith("ground:")&&(a$1={material:B,picture:p.map}),B}let[q=""]=(p?.name??"").split(":"),J=Ko.has(q),Y=!!(d&&p?.map?.name.startsWith("oak")),A=E(new MeshStandardMaterial({...K,metalness:0,roughness:p?.roughnessMap?O.finishes?.[p.name]??1:p?.roughness??.8,polygonOffset:jo.has(q),polygonOffsetFactor:1,polygonOffsetUnits:2,roughnessMap:p?.roughnessMap??null,normalMap:p?.normalMap??null}));p?.normalMap&&(A.normalScale.copy(p.normalScale).multiplyScalar(O.bumps?.[p.name]??1),p.normalMap.anisotropy=8,E(p.normalMap)),p?.roughnessMap&&E(p.roughnessMap);let k=Y?0:J?.5:1;return A.onBeforeCompile=B=>{on(B,k,y),Y&&d&&tn(B,d.uniforms);},A.customProgramCacheKey=()=>`house-physical-${k}-${Y}`,J||(A.envMapRotation.set(0,Oe,0),s?A.envMap=s:u.push(A)),A},prop(L){if(L.name.startsWith("plant-")){let p=m(Xo(L,I,b,x));return L.map&&(L.map.anisotropy=4,m(L.map)),p}let P=(O.lightScale?.props??Ue)/Math.PI,E=m(new MeshStandardMaterial({color:L.color.clone().multiplyScalar(P),map:L.map,vertexColors:true,alphaTest:L.alphaTest,side:L.side,metalness:0,roughness:L.roughness}));return E.onBeforeCompile=p=>{p.fragmentShader=p.fragmentShader.replace("#include <lights_fragment_maps>",`irradiance = vec3( 0.0 );
|
|
157
|
+
#include <lights_fragment_maps>
|
|
158
|
+
iblIrradiance = vec3( 0.0 );`).replace("#include <lights_fragment_end>",`#include <lights_fragment_end>
|
|
159
|
+
reflectedLight.directDiffuse = vec3( 0.0 );
|
|
160
|
+
reflectedLight.directSpecular = vec3( 0.0 );
|
|
161
|
+
reflectedLight.indirectDiffuse = diffuseColor.rgb;
|
|
162
|
+
reflectedLight.indirectSpecular *= 0.5 * smoothstep( 0.02, 0.2, dot( vColor.rgb, vec3( 0.333 ) ) );`);},E.customProgramCacheKey=()=>"house-prop",L.map&&m(L.map),E}}},loaded(O){let v={x:(O.plot.minX+O.plot.maxX)/2,z:(O.plot.minZ+O.plot.maxZ)/2},m=new TextureLoader,I=S(new MeshBasicMaterial({color:Ct,side:BackSide,depthWrite:false,toneMapped:false})),b=S(m.load(`${r}/${e<1?"sky-small.jpg":"sky.jpg"}`,A=>{let k=document.createElement("canvas");k.width=k.height=1;let B=k.getContext("2d");if(!B)return;let i=A.image;B.drawImage(i,0,0,i.width,4,0,0,1,1);let[W,C,F]=B.getImageData(0,0,1,1).data;I.color.setRGB(W/255,C/255,F/255,SRGBColorSpace);let G=Jo(i);if(G){s=S(G);for(let X of u)X.envMap=G,X.needsUpdate=true;u.length=0;}}));b.colorSpace=SRGBColorSpace,b.anisotropy=4,b.wrapS=RepeatWrapping,b.repeat.x=-1;let y=Math.PI/2-xe.above,x=new Mesh(S(new SphereGeometry(Tt,64,12,0,Math.PI*2,y,xe.above+xe.below)),S(new MeshBasicMaterial({map:b,side:BackSide,depthWrite:false,toneMapped:false}))),L=new Mesh(S(new SphereGeometry(Tt,32,6,0,Math.PI*2,0,y)),I);for(let[A,k]of [["sky",x],["sky-crown",L]])k.name=A,k.renderOrder=-1,k.rotation.y=Oe,k.position.set(v.x,1.6,v.z),f.add(k);f.add(new AmbientLight("#fffaf2",1));let P=new DirectionalLight("#ffeacc",1.8);P.position.set((O.sun[0]+O.sunFront[0])*20,(O.sun[1]+O.sunFront[1])*20,(O.sun[2]+O.sunFront[2])*20),f.add(P);let E=new Map;for(let A of O.planting)E.set(A.plant,[...E.get(A.plant)??[],A]);let[p,D,U,K]=[new Vector3,new Quaternion,new Vector3,new Matrix4],q=new Vector3(0,1,0),J=new Color;for(let[A,k]of E){let B=f.getObjectByName(`props-plant-${A}`);B&&(B.updateWorldMatrix(true,true),B.traverse(i=>{let W=i;if(!W.isMesh)return;let C=new InstancedMesh(W.geometry,W.material,k.length);C.name=`plant-${A}`;for(let[F,G]of k.entries())K.compose(p.set(G.x,G.y,G.z),D.setFromAxisAngle(q,G.turn),U.setScalar(G.scale)),C.setMatrixAt(F,K.multiply(W.matrixWorld)),C.setColorAt(F,J.setRGB(1,G.front?0:1,G.lit));C.instanceMatrix.needsUpdate=true,C.computeBoundingSphere(),f.add(C);}),B.removeFromParent());}let Y=a$1;if(Y&&e>=1){let A=null;f.traverse(W=>{W.isMesh&&W.material===Y.material&&(A=W);});let k=document.createElement("canvas");k.width=k.height=1;let B=k.getContext("2d"),i=new Color("#5a6b2c");if(B&&Y.picture.image){B.drawImage(Y.picture.image,0,0,1,1);let[W,C,F]=B.getImageData(0,0,1,1).data;i.setRGB(W/255,C/255,F/255,SRGBColorSpace);}A&&(l=rn(O,A,i)),l&&(S(l.tufts.geometry),S(l.material),f.add(l.tufts));}c.probe={x:7.3,y:1.6,z:14};}});d&&S(d);let _=[],g=new Box3,z=new Vector3,H=0;function R(O,v){O.traverse(m=>{let I=m;if(!I.isMesh||Array.isArray(I.material))return;let b=I.material;if(!Qo.has(b.name)||b.userData.housePane)return;g.setFromObject(I).getCenter(z);let y=null,x=9;for(let P of v.places){let E=(P.x-z.x)**2+(P.z-z.z)**2;E<x&&(x=E,y=P);}if(!y)return;let L=S(b.clone());L.userData.housePane=true,L.roughness=.04,L.envMapRotation.set(0,Oe,0),I.material=L,_.push({pane:I,material:L,x:y.x,z:y.z,outX:-Math.sin(y.rotationY),outZ:-Math.cos(y.rotationY),outside:null});});}a(R,"findPanes");let h=null;return c.beforeDraw=(O,v,m)=>{let{x:I,z:b}=m.position,y=w()?.indoors?.some(P=>I>P.minX&&I<P.maxX&&b>P.minZ&&b<P.maxZ)??true;if(s){v.environment&&v.environment!==s&&(h=v.environment);let P=y?h:s;P&&v.environment!==P&&(v.environment=P,v.environmentRotation.set(0,y?0:Oe,0),v.environmentIntensity=y?.35:.85);}d&&(y?(l&&(l.tufts.visible=false),d.render(O,v,m),l&&(l.tufts.visible=true)):d.uniforms.mirrorStrength.value=0),l?.follow(m);let x=w();if(!x||!s)return;let L=performance.now();if(L-H>qo){H=L;for(let P=_.length-1;P>=0;P--){let{pane:E,material:p}=_[P],D=E;for(;D.parent;)D=D.parent;(D!==v||E.material!==p)&&_.splice(P,1);}R(v,x);}for(let P of _){let E=(m.position.x-P.x)*P.outX+(m.position.z-P.z)*P.outZ>0;if(E===P.outside)continue;P.outside=E;let p=E?Zo:$o,{material:D}=P;D.color.set(p.color),D.metalness=p.metalness,D.opacity=p.opacity,D.transparent=true,D.envMapIntensity=p.reflects,D.envMap!==s&&(D.envMap=s,D.needsUpdate=true);}},c.arrange=O=>{let v=w();return v?v.places.flatMap(m=>{for(let[I,b]of O.entries()){let y=b.modules.findIndex(x=>x.code?.toUpperCase()===m.module);if(y!==-1)return [{line:I,module:y,tone:0,cluster:m.key,spot:{kind:"wall",x:m.x,y:m.y,z:m.z,rotationY:m.rotationY,maxWidth:m.width,maxHeight:m.height,passage:m.passage}}]}return []}):[]},c.reachable=(O,v)=>{let m=w();return m?!m.colliders.some(I=>Ge(O,v,I)):false},c}a(Ye,"createHouseRoom");var sn=1.58,ln=2.4,cn=4.2,Gt=9,mn=1.7,un=.0022,pn=.0036,Bt=.8,Ht=6,hn=1/120;function Ut(t){return t<.5?4*t*t*t:1-(-2*t+2)**3/2}a(Ut,"easeInOut");function Nt(t){return Math.atan2(Math.sin(t),Math.cos(t))}a(Nt,"wrapAngle");var ie={forward:["KeyW","ArrowUp"],back:["KeyS","ArrowDown"],left:["KeyA"],right:["KeyD"],turnLeft:["ArrowLeft","KeyQ"],turnRight:["ArrowRight","KeyE"],run:["ShiftLeft","ShiftRight"]},gn=new Set(Object.values(ie).flat());function Xe(t,e,r,{pointerLock:s,clear:u,onClick:a$1,onUserMove:l,onLockChange:d}){let c=r.start.x,f=r.start.z,S=r.start.yaw,w=r.start.pitch??-0.06,_=S,g=w,z=new Vector2,H=false,R=new Set,h=null,O=r.floorHeight?.(c,f)??0,v=O,m=null,I=a(()=>document.pointerLockElement===e,"isLocked");function b(){m&&(m.resolve(),m=null);}a(b,"cancelGlide");function y(i,W,C){b(),l(),_-=i*C,g=Math.max(-Bt,Math.min(Bt,g-W*C));}a(y,"look");function x(){let{bounds:i}=r;c=Math.min(i.maxX,Math.max(i.minX,c)),f=Math.min(i.maxZ,Math.max(i.minZ,f));for(let W=0;W<2;W++){for(let F of r.obstacles){if(!we(F,v))continue;let G=F.halfX+.35,X=F.halfZ+.35,$=c-F.x,N=f-F.z;Math.abs($)<G&&Math.abs(N)<X&&(G-Math.abs($)<X-Math.abs(N)?c=F.x+Math.sign($||1)*G:f=F.z+Math.sign(N||1)*X);}if(!u)break;let C=u(c,f);if(C.x===c&&C.z===f)break;c=C.x,f=C.z;}}a(x,"constrain");function L(i){!H||!I()||y(i.movementX,i.movementY,un);}a(L,"onMouseMove");function P(){d?.(I());}a(P,"onLockState");function E(i){if(!(!H||h)){if(s()&&!I()){Promise.resolve(e.requestPointerLock()).catch(()=>{});return}h={id:i.pointerId,x:i.clientX,y:i.clientY,travelled:0},I()||e.setPointerCapture(i.pointerId);}}a(E,"onPointerDown");function p(i){if(!h||i.pointerId!==h.id||I())return;let W=i.clientX-h.x,C=i.clientY-h.y;h.travelled+=Math.abs(W)+Math.abs(C),h.x=i.clientX,h.y=i.clientY,h.travelled>=Ht&&y(-W,-C,pn);}a(p,"onPointerMove");function D(i){if(!h||i.pointerId!==h.id)return;let W=h.travelled<Ht;if(h=null,e.hasPointerCapture(i.pointerId)&&e.releasePointerCapture(i.pointerId),!W||!H)return;if(I()){a$1(new Vector2(0,0));return}let C=e.getBoundingClientRect();a$1(new Vector2((i.clientX-C.left)/C.width*2-1,-((i.clientY-C.top)/C.height)*2+1));}a(D,"onPointerUp");function U(i){if(!H)return;i.preventDefault(),b(),l();let W=Math.max(-1,Math.min(1,-i.deltaY/120));z.x+=-Math.sin(S)*W*1.6,z.y+=-Math.cos(S)*W*1.6;}a(U,"onWheel");function K(i){!H||i.target?.closest("input, textarea, select, [contenteditable]")||gn.has(i.code)&&(i.preventDefault(),R.add(i.code),b(),l());}a(K,"onKeyDown");function q(i){R.delete(i.code);}a(q,"onKeyUp");function J(){R.clear();}a(J,"onBlur"),e.addEventListener("pointerdown",E),e.addEventListener("pointermove",p),e.addEventListener("pointerup",D),e.addEventListener("pointercancel",D),e.addEventListener("wheel",U,{passive:false}),document.addEventListener("mousemove",L),document.addEventListener("pointerlockchange",P),window.addEventListener("keydown",K),window.addEventListener("keyup",q),window.addEventListener("blur",J);let Y=a(i=>i.some(W=>R.has(W))?1:0,"held");function A(){t.position.set(c,sn+O,f),t.rotation.set(w,S,0,"YXZ");}a(A,"apply"),A();function k(i){v=r.floorHeight?.(c,f,v)??0,O+=(v-O)*(1-Math.exp(-12*i));}a(k,"followGround");function B(i){_+=(Y(ie.turnLeft)-Y(ie.turnRight))*mn*i;let W=1-Math.exp(-16*i);S+=Nt(_-S)*W,w+=(g-w)*W;let C=Y(ie.forward)-Y(ie.back),F=Y(ie.right)-Y(ie.left),G=Y(ie.run)?cn:ln,X=(-Math.sin(S)*C+Math.cos(S)*F)*G,$=(-Math.cos(S)*C-Math.sin(S)*F)*G,N=Math.exp(-Gt*i),Q=(1-N)/Gt;c+=X*i+(z.x-X)*Q,f+=$*i+(z.y-$)*Q,z.x=X+(z.x-X)*N,z.y=$+(z.y-$)*N,x(),k(i);}return a(B,"walk"),{get enabled(){return H},set enabled(i){H=i,i||(R.clear(),z.set(0,0));},get locked(){return I()},lock(){!s()||I()||Promise.resolve(e.requestPointerLock()).catch(()=>{});},unlock(){I()&&document.exitPointerLock();},update(i){if(m){m.elapsed+=i;let{from:C,to:F,duration:G}=m.legs[m.leg],X=Math.min(1,m.elapsed/G),[$,N]=[m.leg===0,m.leg===m.legs.length-1],Q=$&&N?Ut(X):$?1-Math.cos(X*Math.PI/2):N?Math.sin(X*Math.PI/2):X;c=C.x+(F.x-C.x)*Q,f=C.z+(F.z-C.z)*Q;let oe=$&&N?Q:Ut(Math.min(1,X*1.6));if(S=_=C.yaw+Nt(F.yaw-C.yaw)*oe,w=g=C.pitch+(F.pitch-C.pitch)*oe,m.elapsed>=G&&(m.elapsed-=G,m.leg++,m.leg>=m.legs.length)){let ne=m.resolve;m=null,ne();}z.set(0,0),k(i),A();return}let W=Math.max(1,Math.ceil(i/hn-1e-6));for(let C=0;C<W;C++)B(i/W);A();},glideTo(i,W){b();let C=a((N,Q)=>Math.atan2(N.x-Q.x,N.z-Q.z),"heading"),F=r.route?.({x:c,z:f},i)??[],G=[{x:c,z:f,yaw:S,pitch:w}];for(let N of F){let Q=G.at(-1);G.push({x:N.x,z:N.z,yaw:C(Q,N),pitch:-0.05});}let X=u?.(i.x,i.z)??i;G.push({x:X.x,z:X.z,yaw:i.yaw??(F.length?C(G.at(-1),i):S),pitch:i.pitch??w});let $=G.slice(1).map((N,Q)=>{let oe=G[Q],ne=Math.hypot(N.x-oe.x,N.z-oe.z),ve=G.length>2&&(Q===0||Q===G.length-2),ke=G.length===2?W??Math.min(3,Math.max(.8,ne/2.4)):Math.max(.35,ne/2.6*(ve?Math.PI/2:1));return {from:oe,to:N,duration:ke}});return new Promise(N=>{m={legs:$,leg:0,elapsed:0,resolve:N};})},jumpTo(i){b(),c=i.x,f=i.z,S=_=i.yaw??S,w=g=i.pitch??w,z.set(0,0),O=v=r.floorHeight?.(c,f)??0,A();},position(){return {x:c,z:f,y:v}},dispose(){b(),I()&&document.exitPointerLock(),e.removeEventListener("pointerdown",E),e.removeEventListener("pointermove",p),e.removeEventListener("pointerup",D),e.removeEventListener("pointercancel",D),e.removeEventListener("wheel",U),document.removeEventListener("mousemove",L),document.removeEventListener("pointerlockchange",P),window.removeEventListener("keydown",K),window.removeEventListener("keyup",q),window.removeEventListener("blur",J);}}}a(Xe,"createWalkControls");function je(t,e,r){let s=new PMREMGenerator(t);try{let u=r.probe??{x:r.start.x,y:1.6,z:r.start.z-4},a=s.fromScene(e,.015,.1,100,{position:new Vector3(u.x,u.y,u.z)}).texture;return e.environment=a,a}finally{s.dispose();}}a(je,"roomEnvironment");var Me={high:{name:"high",pixelRatio:1.5,samples:4,ambientOcclusion:true,occlusionScale:.5,occlusionSamples:16,bloom:true,areaLights:true,lod:[4.5,10],lightmaps:1,floorMirror:.5},low:{name:"low",pixelRatio:1,samples:0,ambientOcclusion:false,occlusionScale:.5,occlusionSamples:16,bloom:false,areaLights:false,lod:[2.5,6],lightmaps:.5,floorMirror:.3}},Rn=/mali|adreno|powervr|videocore|apple a\d|intel(?!.*(arc|iris\s*xe))|hd graphics|uhd graphics/i;function Ke(t){let e=b$1(t);if(a$2(e)||Rn.test(e)||window.matchMedia("(pointer: coarse)").matches)return "low";let r=navigator.deviceMemory;return r!==void 0&&r<=4||navigator.hardwareConcurrency&&navigator.hardwareConcurrency<=4?"low":"high"}a(Ke,"guessQuality");function Ze(t,e,r,s,u,a$1,l){if(!s.samples&&!s.ambientOcclusion&&!s.bloom)return {render:a(()=>t.render(e,r),"render"),setSize(){},dispose(){}};let d=new WebGLRenderTarget(u,a$1,{type:HalfFloatType,samples:s.samples,depthTexture:s.ambientOcclusion?new DepthTexture(u,a$1):null}),c=s.ambientOcclusion?new WebGLRenderTarget(u,a$1,{type:HalfFloatType,depthBuffer:false}):null,f=null;if(s.ambientOcclusion){let g=new GTAOPass(e,r,u,a$1);g.updateGtaoMaterial({radius:.4,distanceExponent:1.5,thickness:.3,scale:1,samples:s.occlusionSamples}),g.updatePdMaterial({samples:s.occlusionSamples}),g.blendIntensity=.65;let z=g;z._renderGBuffer=false;for(let R of [g.gtaoMaterial,g.pdMaterial])R.defines.NORMAL_VECTOR_TYPE=0,R.defines.DEPTH_SWIZZLING="x",R.uniforms.tNormal.value=null,R.uniforms.tDepth.value=d.depthTexture,R.needsUpdate=true;let H=g.setSize.bind(g);g.setSize=(R,h)=>{let O=s.occlusionScale;H(Math.max(1,Math.round(R*O)),Math.max(1,Math.round(h*O))),z.normalRenderTarget.setSize(1,1);},f=g;}let S=s.bloom?new UnrealBloomPass(new Vector2(u,a$1),.2,.55,.9):null,w=new OutputPass;if(w.renderToScreen=true,l){let g=w.material;g.fragmentShader=g.fragmentShader.replace("// color space",`{
|
|
163
|
+
vec3 seen = max( gl_FragColor.rgb, 0.0 );
|
|
164
|
+
float grey = dot( seen, vec3( 0.2126, 0.7152, 0.0722 ) );
|
|
165
|
+
seen = mix( vec3( grey ), seen, ${l.colour.toFixed(3)} );
|
|
166
|
+
// Deeper below the middle, lighter above it, white and black where they were.
|
|
167
|
+
vec3 curved = seen * seen * ( 3.0 - 2.0 * seen );
|
|
168
|
+
gl_FragColor.rgb = mix( seen, curved, ${(l.contrast-1).toFixed(3)} );
|
|
169
|
+
}
|
|
170
|
+
// color space`),g.needsUpdate=true;}function _(g,z){let H=t.getPixelRatio(),[R,h]=[Math.floor(g*H),Math.floor(z*H)];d.setSize(R,h),c?.setSize(R,h),f?.setSize(R,h),S?.setSize(R,h);}return a(_,"setSize"),_(u,a$1),{render(){t.setRenderTarget(d),t.render(e,r);let g=d;f&&c&&(f.render(t,c,d,0,false),g=c),S?.render(t,g,g,0,false),w.render(t,g,g,0,false);},setSize:_,dispose(){f?.dispose(),S?.dispose(),w.dispose(),d.depthTexture?.dispose(),d.dispose(),c?.dispose();}}}a(Ze,"createShowroomPicture");function $e(t){t.solid?.traverse(e=>{let r=e;!r.isMesh||r.geometry.boundsTree||(r.geometry.boundsTree=new a$3(r.geometry,{indirect:true}),r.raycast=b$2);});}a($e,"accelerateSolid");var Dn="https://www.gstatic.com/draco/versioned/decoders/1.5.7/",Gn=3,Bn=2.6,Hn=1.5,Xt=.8,Un=1.2,Nn=.05,Yn=22;function Vn(t,e){let r={...Me.low,samples:2};return t==="preview"?{...r,samples:4,pixelRatio:1,lightmaps:.5,floorMirror:0}:t==="low"?r:t==="high"?Me.high:Ke(e)==="high"?Me.high:r}a(Vn,"qualityOf");function Xn(t){let e=new Box3;return t.updateMatrixWorld(true),t.traverseVisible(r=>{r.isMesh&&!r.userData.isCollider&&e.expandByObject(r);}),e}a(Xn,"visibleBox");async function Qr(t,e={}){if(!e.client&&!e.instance)throw new a$1("invalid_state","mountShowroom needs `instance` or `client`");let r$1=e.client??d({instance:e.instance});k(e.dracoDecoderPath??Dn);let s$1=r$1.showroom(),u=e.mode??"preview",a$2=e.view??"street",l$1=me.find(o=>o.name===a$2);if(!l$1)throw new a$1("unknown_view",`No view "${a$2}" (${me.map(o=>o.name).join(", ")})`);let d$1=!(t instanceof HTMLCanvasElement),c=d$1?document.createElement("canvas"):t;d$1&&(c.style.display="block",c.style.width="100%",c.style.height="100%",t.appendChild(c));let f=c.style.touchAction,S=a(()=>({width:Math.max(1,t.clientWidth),height:Math.max(1,t.clientHeight)}),"sizeOf"),w=new WebGLRenderer({canvas:c,antialias:true,powerPreference:u==="walk"?"high-performance":"default"}),_=e.quality??(u==="walk"?"auto":"preview"),g=Vn(_,w),{width:z,height:H}=S();w.setPixelRatio(Math.min(window.devicePixelRatio,e.pixelRatio??g.pixelRatio)),w.setSize(z,H,false),w.toneMapping=AgXToneMapping,w.toneMappingExposure=Se.exposure,w.localClippingEnabled=true,w.info.autoReset=false;let R=new Scene,h=new PerspectiveCamera(60,z/H,.05,150);h.layers.enable(le);let O=null,v=null,m=null,I=null,b=false,y=e.fps??0,x=a(()=>y>0?y:u==="preview"?30:0,"frameCap"),L=0,P=0,E=new Float32Array(32);function p(o=500){L=Math.max(L,performance.now()+o);}a(p,"invalidate");let D=e.drift??true,U=false,K=performance.now(),q=new Clock;function J(o){let M=m?.position();if(M)for(let T of re){if(!T.spot.passage||!T.module)continue;let V=Math.hypot(T.spot.x-M.x,T.spot.z-M.z)<Bn,j=Math.min(1,Math.max(0,T.open+(V?o:-o)/Hn));j!==T.open&&(T.open=j,l(T.anchor,"open",j),p());}}a(J,"swingPassages");function Y(o){if(!O||!v)return;let M=Math.min(q.getDelta(),.25);m&&(m.update(M),u==="walk"&&J(M),u==="preview"&&D&&!U&&(h.rotation.y+=Nn*Math.sin((o-K)/1e3/Yn*2*Math.PI))),h.updateMatrixWorld();let[T,V]=[h.matrixWorld.elements,h.projectionMatrix.elements],j=false;for(let Z=0;Z<16;Z++)Math.abs(E[Z]-T[Z])>1e-6&&(j=true),Math.abs(E[Z+16]-V[Z])>1e-6&&(j=true);v.update?.(h,w)&&p(),!(!j&&o>L&&o-P<1e3)&&(E.set(T),E.set(V,16),P=o,w.info.reset(),v.beforeDraw?.(w,R,h),O.render());}a(Y,"draw");let A=0,k$1=0;function B(o){A=requestAnimationFrame(B);let M=x();M>0&&o-k$1<1e3/M-4||(k$1=o,Y(o));}a(B,"loop");let i=true,W=false,C=e.pauseOffscreen??true;function F(){let o=!b&&!W&&!document.hidden&&(i||!C);o&&!A?(q.getDelta(),A=requestAnimationFrame(B)):!o&&A&&(cancelAnimationFrame(A),A=0);}a(F,"syncRunning");let G=new IntersectionObserver(o=>{i=o.some(M=>M.isIntersecting),F();});G.observe(t),document.addEventListener("visibilitychange",F);let X=new ResizeObserver(()=>{let o=S();w.setSize(o.width,o.height,false),h.aspect=o.width/o.height,h.updateProjectionMatrix(),O?.setSize(o.width,o.height),p();});X.observe(t);let $=new Map;function N(o,M){for(let T of $.get(o)??[])try{T(M);}catch(V){console.error(`[konfigure] ${o} listener failed`,V);}}a(N,"emit");function Q(o){e.onError?e.onError(o):console.error("[konfigure] showroom",o);}a(Q,"fail");function oe(o){throw b=true,F(),G.disconnect(),X.disconnect(),document.removeEventListener("visibilitychange",F),v?.dispose(),O?.dispose(),I?.dispose(),w.dispose(),d$1&&c.remove(),o}a(oe,"abandon");let ne=await s$1.catch(oe);v=Ye(R,{lightmaps:g.lightmaps,base:ne.files});let ve=new HemisphereLight("#ffffff","#ddd8cf",.25);R.add(ve),O=Ze(w,R,h,g,z,H,Se.grade);function ke(){R.traverse(M=>{M.isRectAreaLight&&(M.visible=g.areaLights);});let o=Se.productLight;R.environmentIntensity=g.areaLights?o:o*1.55,ve.intensity=g.areaLights?.25:.6,p();}a(ke,"lightScene"),h.position.set(l$1.x,1.58,l$1.z),h.rotation.set(l$1.pitch,l$1.yaw,0,"YXZ"),F(),await v.ready.catch(oe),I=je(w,R,v),ke(),R.updateMatrixWorld(true),R.traverse(o=>{o!==R&&(o.matrixAutoUpdate=false);});let Ce=new Raycaster;Ce.layers.enableAll();let Qe=false,qe=new Set;v.floor.traverse(o=>qe.add(o));function jt(o){if(!v)return;Qe||($e(v),Qe=true),Ce.setFromCamera(o,h);let M=re.flatMap(Z=>Z.target?[Z.target]:[]),V=Ce.intersectObjects([...M,...v.solid?[v.solid]:[],v.floor],true)[0];if(!V)return;let j=re.find(Z=>Z.target===V.object);if(j){N("exhibit",_e(j)),Kt(j);return}qe.has(V.object)&&m&&(U=true,m.glideTo({x:V.point.x,z:V.point.z}).then(()=>U=false));}a(jt,"pick");function Kt(o){if(!m||!v)return;let{spot:M,place:T}=o,[V,j]=[Math.sin(M.rotationY),Math.cos(M.rotationY)],Z=m.position(),de=(Z.x-M.x)*V+(Z.z-M.z)*j>=0?1:-1,nt=Math.tan(h.fov/2*Math.PI/180),rt=Math.max(Un,T.height/2/(nt*Xt),T.width/2/(nt*h.aspect*Xt)),to=a((fe,he)=>!v.obstacles.some(ge=>we(ge,Z.y)&&Math.abs(fe-ge.x)<ge.halfX+.35&&Math.abs(he-ge.z)<ge.halfZ+.35),"free"),Fe=rt;for(let fe=0;fe<=8;fe++){let he=rt+fe*.25;if(to(M.x+V*he*de,M.z+j*he*de)){Fe=he;break}}U=true,m.glideTo({x:M.x+V*Fe*de,z:M.z+j*Fe*de,yaw:de>0?M.rotationY:M.rotationY+Math.PI,pitch:-0.05}).then(()=>U=false);}a(Kt,"stepUpTo"),m=Xe(h,c,v,{pointerLock:a(()=>u==="walk"&&!!e.pointerLock&&matchMedia("(any-pointer: fine)").matches,"pointerLock"),onClick:jt,onUserMove:a(()=>{U=false,p();},"onUserMove")});let ue=e.input??u==="walk";function Te(){m&&(m.enabled=ue,c.style.touchAction=ue?"none":f,c.style.cursor=ue?"grab":"",ue||m.unlock());}a(Te,"applyInput"),Te(),m.jumpTo(l$1);let Ie=l$1.name;p(3e3),N("room",void 0);let Re=new Map;function Zt(o){let M=Re.get(o);return M||(M=(async()=>{let T=e.configurator?.catalog.productLine.id===o?e.configurator.catalog:await r$1.catalog(o);return {catalog:T,index:a$4(T),builder:s({catalog:T,anisotropy:w.capabilities.getMaxAnisotropy(),environment:a(()=>I,"environment"),invalidate:a(()=>p(),"invalidate")})}})(),M.catch(()=>Re.delete(o)),Re.set(o,M)),M}a(Zt,"lineOf");let Le=e.configurator??null,Ae=new Set(Le?e.configuratorPlaces??ne.places.filter(o=>o.productLineId===Le.catalog.productLine.id).map(o=>o.key):[]),$t=ne.places.map(o=>({name:o.name,slug:null,modular:false,modules:[{footprint:Math.max(o.width,.1),code:o.moduleCode}]})),Qt=v.arrange?.($t,Math.random)??[],re=[];for(let o of Qt){let M=ne.places.find(V=>V.key===o.cluster);if(!M||M.moduleId==null||M.productLineId==null)continue;let T=new Group;T.position.set(o.spot.x,o.spot.y,o.spot.z),T.rotation.y=o.spot.rotationY,R.add(T),re.push({place:M,spot:o.spot,anchor:T,module:null,target:null,generation:0,open:0});}function _e(o){return {...o.place,configured:Ae.has(o.place.key)}}a(_e,"exhibitOf");let Je=Le?.toJSON()??null;async function qt(o){let M=++o.generation,T=await Zt(o.place.productLineId),V=Ae.has(o.place.key),j=await T.builder.build(gt(T.index,o.place,V?Je:null));if(b||M!==o.generation){r(j.moduleGroup);return}o.module&&(o.anchor.remove(o.module.moduleGroup),r(o.module.moduleGroup)),o.module=j,o.anchor.add(j.moduleGroup),o.open>0&&l(o.anchor,"open",o.open);let Z=Xn(o.anchor);o.target||(o.target=new Mesh(et,tt),o.target.visible=false,R.add(o.target)),Z.getCenter(o.target.position),Z.getSize(o.target.scale),o.target.updateMatrixWorld(true),p(1500),N("placed",_e(o));}a(qt,"build");let et=new BoxGeometry(1,1,1),tt=new MeshBasicMaterial({side:DoubleSide});async function ot(o){let M=[...o].sort((T,V)=>Math.hypot(T.spot.x-h.position.x,T.spot.z-h.position.z)-Math.hypot(V.spot.x-h.position.x,V.spot.z-h.position.z));await Promise.all(Array.from({length:Math.min(Gn,M.length)},async()=>{for(let T=M.shift();T;T=M.shift())await qt(T).catch(Q);}));}a(ot,"buildAll");let We=ot(re),Jt=Le?.on("change",({state:o})=>{Je=o;let M=re.filter(T=>Ae.has(T.place.key));We=Promise.all([We,ot(M)]).then(()=>{});})??null;function eo(o){u=o,ue=o==="walk",Te(),K=performance.now(),p();}return a(eo,"setMode"),{whenReady:a(()=>We,"whenReady"),views:a(()=>me.map(({name:o,label:M})=>({name:o,label:M})),"views"),view:a(()=>Ie,"view"),async setView(o,{seconds:M}={}){let T=me.find(j=>j.name===o);if(!T){let j=me.map(Z=>Z.name).join(", ");throw new a$1("unknown_view",`No view "${o}" (${j})`)}if(!m)return;let V=M===0||M===void 0&&u==="preview";Ie=null,V?m.jumpTo(T):(U=true,await m.glideTo(T,M),U=false),K=performance.now(),Ie=o,p(),N("view",o);},exhibits:a(()=>re.map(_e),"exhibits"),mode:a(()=>u,"mode"),setMode:eo,setInput(o){ue=o,Te();},setDrift(o){D=o,K=performance.now(),p();},pause(){W=true,F();},resume(){W=false,F(),p();},on(o,M){let T=$.get(o);return T||$.set(o,T=new Set),T.add(M),()=>{T.delete(M);}},capture(){return v?.beforeDraw?.(w,R,h),O?.render(),c.toDataURL("image/png")},stats(){return {quality:g.name==="high"?"high":_==="preview"?"preview":"low",pixelRatio:w.getPixelRatio(),triangles:w.info.render.triangles,calls:w.info.render.calls,textures:w.info.memory.textures,geometries:w.info.memory.geometries}},renderer:w,scene:R,camera:h,dispose(){if(!b){b=true,Jt?.(),F(),G.disconnect(),X.disconnect(),document.removeEventListener("visibilitychange",F),$.clear(),m?.dispose();for(let o of re)o.module&&r(o.module.moduleGroup),R.remove(o.anchor);et.dispose(),tt.dispose(),Promise.all(Re.values()).then(o=>o.forEach(M=>M.builder.dispose())),v?.dispose(),O?.dispose(),I?.dispose(),w.dispose(),c.style.touchAction=f,d$1&&c.remove();}}}}a(Qr,"mountShowroom");
|
|
171
|
+
export{Qr as mountShowroom};
|