Skip to content

Worldgen: styled buildings from outlines, props from land labels ​

@bendyline/molen-worldgen turns any outline into a styled building and any labeled polygon into deterministic prop placements. It knows nothing about maps: give it an outline in meters, a few opaque labels, a style, and a stable identity, and it returns typed-array mesh buffers. The sibling package @bendyline/molen-worldgen-earth is the binding that feeds it real map data: it adapts molen/terrain-semantics@1 tiles (Protomaps / OpenStreetMap footprints and land use) into those requests, resolves regional looks from a lon/lat atlas, and plugs the result into the terrain streamer as tile layers. A dungeon generator and the Earth renderer call the same functions.

1. The two layers ​

The default structure library contains 120 resizable structures in 13 taxonomies and 45 shared materials. The world explorer's /structures.html model sheet renders every entry and provides dimension, texture and detail controls.

For enterable buildings and lazy ground-floor furnishings, see Building interiors. For compact global ecological data, regional plant families, and ordinary building profiles, see Regional world content.

text
@bendyline/molen-worldgen           world-agnostic core
  /kernel   formats, footprint analysis, roofs and walls, batch generator, GLB encoder, seeds
  /client   buffers to three.js meshes, instanced boxes, style-pack loader

@bendyline/molen-worldgen-earth     Earth binding (terrain-semantics, OSM classes, lon/lat)
  /kernel   molen/region-atlas@1, tile adapter, tile-edge ownership, budgets by quality
  /client   TerrainSemanticTileRenderer implementations, atlas loader

molen.worldgen.default  content pack: the shipped looks (styles, scatter rules, structures)
molen.earth             content pack: world.atlas.json (which style applies where), business catalog

The npm packages carry code only. The default looks are content packs (molen/pack@1 zips), published with each release at https://molen.dev/packs/. In a project, npx molen pack fetch https://molen.dev/packs/index.json downloads them into packs/ and pins them in project.json, and an app serves the same zips from wherever it hosts them. Their sources are content/worldgen and content/earth in the engine repository.

The core package has no terrain dependency and a test forbids map vocabulary in its sources. Core inputs are BuildingRequest (identity, labels, outline, optional height/levels/minHeight) and ScatterRequest (labeled polygons, exclusions, an anchor frame, a keep fraction). Outputs are MeshBuffers (positions, normals, uvs, 8-bit colors, indices, material groups) and PlacementSets (10 floats per instance: position, yaw, scale, tint).

2. Quick start ​

World explorer, real data, in the browser:

From code, one building from one outline, no map involved:

ts
import { openPack } from '@bendyline/molen-pack';
import { createBuildingObject, createVertexColorMaterialSet } from '@bendyline/molen-worldgen/client';
import { resolveStylePackDocuments } from '@bendyline/molen-worldgen/kernel';

// The default style pack, from wherever the app hosts it.
const styles = await openPack('/packs/molen.worldgen.default.zip');
const pack = await resolveStylePackDocuments(await styles.readJson('stylepack.json'), (path) =>
  styles.readJson(path),
);
const style = pack.archstyles['molen.worldgen.fantasy.hall'];
const hall = createBuildingObject(
  { identity: 'room:hall-1', labels: ['hall'], outline: [[0, 0], [24, 0], [24, 10], [0, 10]], levels: 2 },
  style,
  { name: pack.root.name, version: pack.root.version },
  { materials: createVertexColorMaterialSet() },
);
viewer.renderer.worldRoot.add(hall);

Headless, in Node, the same thing produces buffers you can hash or encode:

ts
import { encodeGlb, generateWorldgenBatch } from '@bendyline/molen-worldgen/kernel';

const out = generateWorldgenBatch({ buildings: [request], pack });
const glb = encodeGlb(out.buildings);   // core glTF 2.0, one primitive per material group

From the command line (or the MCP tools of the same names), without writing code. The commands need a style pack: pass --pack (a content pack zip, a pack source directory, or a stylepack.json), list one in the project's packs, or set MOLEN_PACKS. In a project:

sh
npx molen pack fetch https://molen.dev/packs/index.json          # once: packs/ + project.json pins
npx molen worldgen preview --out preview.png --angles 4          # the lineup of every shape class
npx molen worldgen preview my.archstyle.json --out preview.png   # a style file, injected into the pack
npx molen worldgen bake --outline "0,0;18,0;18,9;10,9;10,14;0,14" --style molen.worldgen.fantasy.hall --out assets --id keep
npx molen worldgen bake hall.batch.json --out assets --id hall  # a molen/worldgen-batch@1 document
npx molen worldgen stats path/to/terrain-package.json --auto --dump tile.batch.json

preview generates in Node and renders the buffers, props, and scatter in headless Chromium from turntable angles (the MCP tool returns the images). bake writes a glTF asset with a molen/asset@1 sidecar under an assets root, so a dungeon scene references the hall as a plain gltf renderable; roof props and scatter are instanced placements and are reported, not baked. stats opens a real terrain package off disk, generates one tile twice, and reports counts, footprint and roof histograms, sizes, timings, and whether both runs hashed the same; --dump writes the adapted batch (molen/worldgen-batch@1, identities of clipped pieces suffixed so they stay unique) for preview and bake. A molen/worldgen-batch@1 document is the interchange: ground (flat or slope), building requests, optional mapped props and a scatter request, rules, and a detail tier; molen schema get worldgen-batch prints its schema. Two example batches live in the engine repository's content/worldgen/fixtures/, beside the pack source but not packed.

3. Authoring a look: molen/archstyle@1 ​

A style is one JSON document under a pack namespace. molen schema get archstyle prints the full JSON Schema with units on every field; molen validate styles/x.archstyle.json reports pinpoint errors with did-you-mean hints for palette names. The sections:

  • applicability: which labels and contexts the style is meant for (informational; a pack or atlas rule binds it, and a notice fires when a rule and the style disagree).
  • massing: floor heights, the heightFallback chain used only when a request carries neither height nor levels (ordered when rules, last one is a catch-all), how the platform follows the ground (platform-average keeps within 4 m of the mean, platform-max sits on the highest point), the exposed foundation, wing decomposition limits, and tower setbacks.
  • roof: weighted choices among flat | gable | hip | pyramid | shed | mansard | gambrel, each with a pitch range and optional eligibility (when: { elongationMin: 1.15 } keeps gables off square plans). Roofs are built per wing: an L becomes two gable wings meeting in a valley. Outlines that do not decompose, cut pieces at tile edges, and anything beyond maxWingSpan fall back to flat (with a parapet when the choice has one) or, for small irregular plans, a skillion. A parapet is drawn no taller than 0.9 m (MAX_PARAPET_HEIGHT) whatever the choice asks for, so a walker who lands on a flat roof can jump onto it and over; under a mapped height the wall below keeps whatever the parapet gives up. With fallback: 'hipped' a footprint the chosen pitched form cannot cover (an irregular plan, a block round a courtyard, a hall wider than maxWingSpan) takes slopes rising from every wall to a level deck instead of going flat, and under a mansard choice the slopes are the steep lower pitch. A plan too thin to inset keeps the flat or skillion roof. partyRidge turns the ridge of a building that shares walls with its neighbours (a request's partyEdges): between runs it from party wall to party wall, eaves to the street, and along runs it along them, a gable to the street. Such a roof is gabled, since a hip would slope down onto the neighbours.
  • facade: bay widths, window rhythm, base bands, and cornice. Windows and trim are generated geometry with cell UVs for glass and metric UVs for solid materials.
  • materials and palettes: one weighted material choice per part (wall, roof, trim, foundation, window) and named palettes with HSL jitter. Per-building variation costs nothing: a palette pick plus jitter becomes a vertex tint, and metric UVs get a seeded offset.
  • props: attachments (chimneys, rooftop units) with anchors, counts, and spacing.
  • lod.tiers: which features survive at each detail tier; beyond the last tier the building is an instanced tinted box.

Every choice is sampled from a named stream of the building seed, so editing the roof section never reshuffles the palettes.

Materials, windows, and props ​

A part's materials entry lists weighted material references. palette:#rrggbb is a flat color that lands in the vertex tint (it never costs a mesh group); matgraph:<pack material id> is a procedural texture document from the pack's materials map. Textured parts declare uvScale (meters per texture repeat); the generator emits UVs already divided by it, so a wall material shared by several styles still repeats at each style's scale. With tint: 'multiply' the sampled palette color multiplies the texture, so pack textures are authored light (the default pack asserts a mean luminance of at least 0.55 for every tinted material). Windows use tint: 'none' and uv: 'cell': every window is one texture repeat.

A material choice may name its own palette, which replaces the part's palette when that choice is picked. The material and the color are otherwise independent picks, so without it a brick wall can draw a concrete grey and a concrete panel can draw brick red. A choice may also carry its own uvScale, so a style that mixes brick, render and boarding draws each at its own course and board size instead of stretching all three to the part's scale. materials.flatRoof is an optional roof material used only when the style resolves a flat roof (a flat choice or the wide-footprint fallback). A pitched style keeps shingles or tile on its slopes and puts light membrane or gravel on its flat tops. Tile-edge cuts and dropped roof shapes keep roof, so a clipped house still matches its neighbors from above.

facade.windows places windows per bay and floor: punched (one window per bay, seeded probabilityPerBay), ribbon (one strip per floor), grid (glazing filling the bay), or none; groundFloor: 'storefront' adds ground-floor glazing even when upper windows are none. Window height caps the storefront glass below a solid wall band; window width controls its pane spacing. facade.bands adds a base band, floor lines, and a cornice from the trim material. Glazing uses surface quads, gated by facade-texture. The facade-bands feature adds raised window surrounds, sills, bounded storefront mullions, and projecting bands with exposed upper and lower faces. Structural entrance frames remain open at every tier; simplified frames omit depth and hidden faces to conserve the geometry budget. Shared linear-filtered worldgen textures use mipmaps and anisotropic filtering.

facade.details adds near-detail ornament fitted to the live outline: an entrance, shutters, cornerBoards, balconies, framing, awnings, a veranda, and a porch (a step in front of the entrance under a small canopy on two posts, 44 vertices, on the seeded probability share of the style's buildings). paint lists the colors a building paints its shutters and door leaf, one drawn per building; without it they take the trim darkened.

A request's partyEdges names the outline edges it shares with a neighbouring building. The walls are built, since neighbours differ in height, but take no windows, bands, ornament, storefront or entrance, and no interior opening. A request's crown adds what a building is known by from a distance, in the style's own wall and roof materials: a square tower under a spire or a low-capped belfry at one end of the long axis, a dome on a drum over the middle, a minaret at a corner, or a stepped shikhara. A crown is sized from the footprint, stands inside it, and is omitted on one narrower than 3.5 m.

props attach pack or builtin models: roof-ridge walks the ridge of the dominant wing (chimneys), roof-flat fills a flat roof with margin from every edge (rooftop units), roof-edge lines the outer edges at the parapet (canales), and ground-any sets models on the ground just out from the outer walls, spacing apart and margin from the corners, spread evenly round the building and clear of its entrance (foundation shrubs on regional houses). Prop models are pack assets (assets map, a molen/asset@1 sidecar next to model.glb); the default pack generates its materials and prop models from scripts/generate-pack.mjs and the build checks they are current. Placements come out of the batch as props:<model> placement sets, instanced like scatter.

Building scale and missing measurements ​

Supplied height sets the total envelope, including roof and raised clearance. When levels is also present, it controls the number of storeys: floor spacing fits the available wall height instead of deriving extra window rows from a nominal floor height. Without levels, the estimate accounts for the taller ground floor and reserved roof space. Budget variants retain the same window positions even when they omit the parapet.

The default commercial glass texture has one vertical row per generated storey. Untyped buildings and low-rise uses with no height or levels default to one or two storeys, independent of footprint area; explicitly identified offices retain their taller fallback rules. Big-box retail defaults to one tall storey with storefront glazing and solid walls above. These are conservative visual defaults, not recovered building measurements. Source heights and levels take precedence.

4. Seeds and identity ​

text
building seed:  wg1|b|<pack.name>@<pack.version>|<style.id>@<style.version>|<identity>
aspect seed:    <building seed>|massing | roof | facade | palette:<name> | material:<part> | props:<id>
prop salt:      wg1|p|<pack>@<version>|<scatter.id>@<version>|<rule.id>   then hashCoord(cellX, cellZ, salt)

The identity is caller-owned and opaque. The Earth binding uses the source feature id (f:<id>) because tile cutters clip one building into two tiles and the id is the same on both sides; without an id it quantizes the centroid to 0.5 projected units (c:<qx>,<qz>). Bumping a pack version, a style version, or the seed scheme is the only way to re-roll a world.

5. Placement rules: molen/scatter@1 ​

A scatter rule set maps land labels to weighted species with density per hectare, clustering noise, slope and altitude limits, clearances from roads, buildings, and water, and a keep fraction per detail tier. It also carries the surface colors the land-classification layer paints. Rules bind builtin procedural species, model ids from the pack, or an imported namespace such as molen.entities.

The sampler walks a jittered grid anchored to the request frame, not to the batch, so a cell yields the same candidate for every caller that covers it: neighbouring tiles never duplicate or miss a prop, and a coarser tile shows a nested subset of its children (the keep fraction and every cap thin by the same per-cell acceptance draw). Per batch it rasterizes the labeled polygons and the exclusions (roads and waterways as ribbons, buildings as dilated rings), then per rule visits only the cells under matching polygons, applies clustering noise, slope and altitude limits, picks a species by weight, and draws scale, heading, and tint from independent streams of the cell hash. Output is one PlacementSet per model (stride 10: position, yaw, scale, tint), ordered by cell.

On the client, ModelLibrary.prepare(ref) turns a glTF scene into one merged vertex-colored geometry (material colors baked in, so an authored tree with two materials is one draw), keeps builtin primitives (builtin:tree.conifer, builtin:shrub, builtin:rock, ...) for packs without assets, and createInstancedPlacements(set, geometry, material) uploads a placement set as one InstancedMesh. The legacy regional scatter packs use procedural fir, pine, oak, and birch (builtin:tree.conifer.fir|pine, builtin:tree.deciduous.oak|birch), clustered shrubs, and irregular rocks. Their opaque crowns, bark, and vertex colors share one geometry and material per species: no texture downloads, alpha cards, or per-tree scene objects. Conifers have a closed, scalloped crown that conceals the upper trunk; broadleaf crowns use overlapping foliage clumps. Tiles below the finest level use cached coarse crowns (132 triangles per conifer, 124 per broadleaf tree; 60 per shrub and 20 per rock), sharing the same material and instance transforms. The Earth renderer batches vegetation per terrain tile, split into quarters on the finest tiles (a batch picks one detail level for all its plants, so a camera inside a whole-tile batch drew every tree in it at near detail), and switches each batch from near to medium to distant geometry by its projected error, with 15% hysteresis to avoid flicker. A batch chooses again only when the camera, the batch's placement, the lens or the error policy changes, so a still view costs no per-batch matrix work. Distant crowns are opaque: a cone for conifers and one lumpy volume for broadleaf trees. Cells share geometry, materials, and instance buffers across levels and can be frustum-culled independently; no per-frame placement uploads are needed. propLod: false disables this camera LOD, and the explorer exposes ?propLod=0 for comparison. The explorer's AssetCache still resolves authored GLBs for custom packs and building props.

Ground cover is the knee-high layer under all of this: builtin:groundcover.tuft (a grass tussock) and builtin:groundcover.fern, each under 70 triangles, plus small shrubs and stones. A rule joins it with "layer": "groundcover", which gives it its own instance and model budget (maxGroundCoverInstances, maxGroundCoverModels), so thousands of clumps never thin the trees or take their model slots. Ground cover models draw only at the near level; the medium and far levels are empty, so the clumps stop drawing at 65% of the distance a shrub would hand over to its medium level (about 165 meters from a batch's edge at High on a 1080-line view) instead of shimmering. "layer": "understory" and "layer": "garden" are two more pools with budgets of their own (maxUnderstoryInstances, maxGardenInstances and their …Models): shoulder-height wild brush, and planted ground such as yards and park borders. The garden pool keeps models by role, each rule's commonest species first, and chooses them separately in each quarter of the batch, which is how a host draws them. The Earth adapter labels land that no map polygon covers open_ground (the OPEN_GROUND_LABEL export), as a tile-wide polygon that every mapped polygon paints over, so verges and unmapped meadows can carry ground cover too. The default packs place it in meadows, parks, yards, forest floors and open ground, on the finest tile level only, and not at Economy quality. In temperate and wet habitats the regional catalog's open_trees rule also plants a few clustered groves of park trees on open ground (14 per hectare before clustering), so unmapped institutional lawns and verges are not bare.

A population's optional widthScale: { min: 0.8, max: 1.25 } multiplies X/Z independently of its uniform scale, allowing tall narrow trees, broad bushy trees, and spreading shrubs in the same draw. Width uses its own cell-hash stream, so changing it preserves positions, heights, headings, tints, and the subset shared by neighbouring tiles and detail tiers. Omitting it keeps uniform scaling. Default vegetation rule sets are version 2 (new planting seeds); architecture seeds are unchanged.

6. Packs: molen/stylepack@1 ​

A style pack's source directory looks like this (the default pack's is content/worldgen/ in the engine repository); molen pack build <dir> turns one into a content pack.

text
my-stylepack/
  stylepack.json           name, version (seeds), namespace, id → path maps, defaults, imports
  styles/**/*.archstyle.json
  scatter/*.scatter.json
  materials/, assets/      matgraph documents and prop sidecars (later phases)

defaults.rules is the pack's own ordered style selection (when over labels, context, area, height presence, elongation, rectangularity) and defaults.style closes the chain. Loading a pack validates every document and cross-checks ids, material kinds, and model sources; a dangling id fails loudly with the candidate list. resolveStylePackDocuments(root, readDoc) is the pure resolver: give it a content pack's readJson and it reads everything from one zip. loadStylePack(baseUrl) fetches an extracted directory in the browser.

7. Earth binding: molen/region-atlas@1 ​

An atlas lists prioritized regions (a lon/lat bbox and/or polygons) with ordered style rules and a scatter set, plus a worldwide default chain. Precedence for a building is: region rules, region default, atlas default rules, atlas default style, pack rules, pack default style. The region is resolved once per tile at its centre; when a tile straddles regions every building resolves at its own centroid. Atlas geometry is projected once into the package's world meters, so lookups are comparisons.

When a composable regional environment is supplied, its architectural channel precedes this legacy chain and every building resolves at its own centroid. Its separate ecological channel selects each vegetation candidate by habitat geography. See Regional world content.

The adapter also decides tile-edge ownership: a footprint that appears complete in two tiles is rendered by the tile holding more of it, and a footprint cut by both buffers is rendered piecewise with seam walls and a flat roof. Both tiles reach the same verdict from their own copy.

Stock Protomaps buildings should be extracted through zoom 15. At zoom 14 and below the basemap merges footprints and rounds heights; zoom 15 retains individual features and the available unrounded heights. The adapter consumes height, minimum height, and building parts. The basemap derives some heights from floor counts, but does not retain raw floor counts, roof shape, roof material, or the original building type for ordinary outlines. Missing attributes remain estimates; residential land use is evidence of likely use, not a zoning or floor-count record.

Building context uses several points across the footprint. Mapped land use takes precedence over physical cover such as grass or woodland; among overlapping uses, the smaller polygon wins. Explicit building classifications override generic labels. Residential context selects residential styles even for large or long townhouse footprints, with a conservative two-floor fallback for larger footprints. Roof eligibility sees supplied or resolved floor counts: the default residential styles prefer pitched roofs through three floors and flat roofs from four upward. The Southwest style also allows flat roofs on low buildings. Wide, clipped, or unsuitable footprints can still require a flat roof for geometric reasons.

Rows, shops and places of worship ​

A map draws a terrace or an old town's block as footprints that touch, and nothing in it says so. The adapter probes every outline edge of a ground-standing mapped building: an edge whose far side, 0.6 m out at three points along it, lies inside another building's footprint is a party wall. Those edges become the request's partyEdges. A building of at least 40 m² that gives 22% of its outline to neighbours (the end house of a terrace gives a quarter, a house with a garage against it a seventh) also gains the attached label (ATTACHED_LABEL), which the regional rules send to their row-house styles. A mapped part and what remains of its building are one building, not each other's neighbours; generalized footprints, a host's buildings and inferred ones take no part. associatePartyWalls(pieces, tileSize) and isAttached are exported for other pipelines.

A recognized business gives its building a frontage and a sign. Whether it also replaces the building depends on the region. A regional profile with a style rule for the class shop_shell (SHOP_SHELL_CLASS; the default catalog's North American, Southwest and neutral profiles) builds every low building with a business as a store, as an arterial strip is. Elsewhere the building stays its region's unless it is purpose-built: free-standing on retail or commercial land, a catalog chain's own building, or a single footprint of 600 m² or more. A shop in a row or under flats keeps its walls and roof.

A POI that names a whole building (a hotel, a museum, a library, a theatre, a civic office) changes its inside at any size and its outside only from the size of one: 900 m² or a mapped 15 m for a lodging, 400–500 m² for the others. A guest house in a town house stays a town house. Size alone is not enough in an old town, where a hotel, a school or a museum occupies a building of the street: a footprint that is one of a row with no height mapped keeps its region's exterior, and so does one that holds four other businesses or a second institution, since old centers are often mapped a block to an outline (BuildingUseEvidence.shared).

How tall an unmeasured building is ​

A basemap carries a height or a level count for about one building in ten, and in many towns for none (of 37 town tiles surveyed in November 2026, 21 had heights on 2% of their buildings or fewer). Storeys therefore come from four places, in this order:

  1. A mapped height. The wall and roof fill it exactly; the style's storey height decides how many rows of windows that is, and the rows are stretched to fit.
  2. Mapped levels. That many rows, at the style's storey height.
  3. A dense-district prior (districtLevels): an unmeasured block of 250 m² or more on ground that footprints cover by a third or more, on commercial land or none, rises from 3 toward 10 levels as the cover does.
  4. The style's fallback (massing.heightFallback).

The last two are guesses, and a guess is bounded by its surroundings. measuredStoreys(tile, size) reads how tall a place is built from its own map: the storeys four in five of its measured buildings stay within, once at least eight footprints of 60 m² or more carry a height or a level count (a smaller one is a mast or a minaret). guessCeiling is that figure or the region's ordinary block of flats, whichever is greater: the upper end of the fallback of the style the region's rules give a block of flats, three storeys in the Cyclades and five in Naples. The district prior stops at the ceiling, and every mapped building with neither a height nor levels carries it as the request's fallbackLevelsMax, which the recipe applies to a fallback in levels (a hall's fallback in meters is one tall room and is left alone). A use says what a building is for, not how tall it is: the hotel style's own fallback is five to twelve storeys, and without the ceiling five lodgings in Mykonos were drawn seven storeys or taller and one in Chefchaouen twelve. Dense ground alone is not a downtown either; a medina covers as much of its ground at two storeys. Where a core's towers are measured, its unmeasured blocks still rise with them.

A mapped height is the wall's height, not always a count of floors. shaftLevels(height, area) recognizes a shaft: a whole building of under 250 m² (the plate a regional profile asks of its tower style) standing 20 m or more and five and a half times its footprint's side, as a bell tower, a tower house, a minaret, a chimney or a lighthouse does. It is drawn with a tier of openings every 11 m in its region's masonry. Divided into storeys, the Torre del Mangia (102 m on 21 m²) was 29 floors of flats. A slender part of a larger tower is that tower's and keeps its storeys, and so does a building whose levels the map counts.

A place of worship takes its region's worship style and a crown from its religion, which the basemap carries as the POI's kind_detail: worshipCrowns(religion, regionId, areaM2) returns a dome for Orthodox and Oriental churches (by region), a spire or a belfry for Western ones, a dome and a minaret for a mosque, a stepped tower for a Hindu or Jain temple, and nothing for traditions told by their roof and walls alone. A footprint from 25 m² is recognized when it carries the POI's id or holds its point alone; a hall up to 3,000 m² when the point is the only business in it. These are the commonest forms for a region, not a record of the building.

Inferred buildings where outlines are missing ​

Earth views enable neighborhood building infill by default. mountEarthView and createEarthWorldgen accept buildingInfill: false to disable it, or buildingInfill: { seed: 42, density: 0.7 } to choose a world seed and keep fraction. The lower-level renderer and tile generator opt in with the same option. The explorer exposes ?buildingInfill=0 and ?infillSeed=42 for comparisons.

Infill makes one row of lots on each side of residential, minor and collector streets. Frontage anchors repeat every 16 projected meters, with small gaps and varied widths. Every lot reserves an unobstructed approach from its street to its entrance or garage; homes never form landlocked rows inside a block. Visible ground-following paths and driveways connect the entrances to the roadside. Separately mapped sidewalks move the building setback behind the sidewalk while retaining access. Inferred homes without an attached garage also receive a simple driveway to the front of the house when the corridor is clear. Garage approaches and paths connect to the roadside. Weighted lotFences (none, timber, masonry, rail) select low decorative yard boundaries, including some fully open yards. Front fences leave gaps around every path and driveway and stay behind mapped sidewalks. Fences follow the terrain, exclude vegetation, use a cheaper shape with simplified nearby buildings, and disappear on distant tiles. They do not add physical collision barriers. Yard choices use an independent identity salt, so decorating a lot does not move or re-roll its house. Mapped footprints, occupied landmark extents, other streets, water and incompatible land uses such as parks, farmland, schools and parking exclude the entire parcel, including its approach. Slopes above 0.3 or more than three meters of height variation also exclude it. A named neighborhood outline excludes nothing, because it marks a place and not its ground. The Protomaps basemap reports one as land use other, in place of any residential or industrial use mapped on the same outline, so streets inside it are judged like streets without a land-use label.

Mapped residential, commercial and retail land-use polygons provide district evidence. Commercial and retail areas select commercial styles and shopfront plans; residential areas select homes. Without a land-use label, at least three nearby classified buildings with a 70% commercial majority can select commercial use. Otherwise a dense network of at least three separate street corridors establishes residential demand. Density considers streets within 240 meters and accounts for tile edges: 650 meters of road in the full window, or 300 meters with explicit suitable land use. Highways, paths, service roads, bridges and tunnels do not establish demand. Mapped buildings keep priority in the shared rendering budgets.

A house in a yard is one street pattern among several. The regional house style's optional lots says how the lots it invents line a street: rows is the share of blocks built as rows, fronts wall to wall at the back of the footway; units how many fronts stand to each 16 m of frontage (three is a 5.3 m tube house, one a 16 m front); setback, depth and levels their ranges; gap the share of frontages left open; and compact fills a detached lot's frontage close to the street. A block of 128 m is rows or yards as a whole, so one street keeps one pattern, and within a row the storeys and rear walls step from house to house while the fronts hold the street line. Each front is its own building with its own door and path, its side walls are party walls (partyEdges), and its style is the one the region's rules give the label terrace. The default catalog builds rows in most of the world: a Moroccan medina, a British terrace, Hanoi's tube houses and a Mexican street of continuous fronts are not suburbs. North America, Australia and the Pacific keep houses in yards.

The regional style's optional lotPlans weights select reusable, resizable plans: cottage (recessed porch), ranch (L-shaped), front-garage, side-garage, courtyard, compact, and shopfront. createLotBuildingPlan(shape, width, depth) is exported by worldgen's kernel for other procedural authors. Plans use local +Z inward from the frontage and return entrance anchors and an optional attached garage. Garages have their own single-storey mass and broad door. These plans only supply missing outlines; existing mapped outlines remain authoritative. The Southwest pool favors stucco, ceramic tile, ranches, courtyards and garages; the North American pool used in Washington favors siding and asphalt shingles. Other regional pools use their own materials and plan weights, with conservative cottage/ranch/compact forms when no style defines a pool.

A versioned seed and geographic frontage anchor determine each home's identity, footprint and floor count; that identity seeds its architectural appearance. Unloading and revisiting unchanged map data reproduces the same buildings, including through the worker path. Feature order and road direction do not reshuffle them. Reducing density retains an unchanged subset; generation settings and exclusion geometry participate in cache keys. Records carry the inferred label and an infill:v3 identity; they are visual estimates, not recovered footprints or verified addresses. Changes to source data, styles, seed or algorithm version can change the result. The frontage-based v3 algorithm regenerates older layouts once; subsequent visits reproduce the new layout.

Infill uses detailed footprints at the finest two terrain levels, skips generalized building data, and caps inferred lots at 3,072 per tile before shared rendering budgets. Entire parcels stay inside their owner tile, leaving a small margin at tile edges. A neighboring halo participates in corner-lot conflict resolution. Coverage depends on the roads and exclusions available in that tile. These are synthetic lots, not surveyed parcels or zoning; missing land-use data can still allow buildings on genuinely vacant land. Industrial land remains excluded. The same inferred footprints and approaches exclude vegetation in scatter-only requests when the source supplies matching semantic layers.

Inferred trees around homes ​

Atlas region bindings and the worldwide default accept treeFillFactor from 0 to 1. The shipped atlas uses 0.35 in North America, overridden by 0.9 in the Pacific Northwest and 0 in the Southwest; Japan uses 0.3 and unclassified regions use 0. These are configurable visual priors, not measured canopy percentages or a global climate dataset. Fill is resolved at each home's location, including region edges.

For complete low-rise footprints of 45–700 m², the Earth adapter adds an irregular yard patch roughly 18–26 meters beyond the home. Explicit house classifications qualify; small untyped buildings also qualify when land use does not contradict residential use. Known commercial buildings, elevated parts, tall buildings, and generalized or source-clipped footprints do not. No residential land-use polygon is required. Unknown parcels and driveways cannot be recovered from absent data, so this remains an estimate of open space.

The patch and its tree acceptance/species/size use a named yard-trees stream of the building seed. The shared world grid supplies candidate positions: overlapping yards have one stable owner per cell, feature ordering does not reshuffle trees, and lowering fill or detail keeps surviving instances unchanged. The serialized scatter polygon carries its optional uint32 seed. Existing unseeded scatter retains its previous placements.

Mapped woodland, parks, parking, playing fields, farmland, barren ground, and other incompatible land cover are cut out before planting. Road, building, water, and mapped-tree exclusions still apply, as do slope/altitude limits and instance budgets. Neighboring buffered footprints participate even when their building mesh belongs to another tile; trees emit only inside the current tile. Coverage still depends on the footprints supplied in the source tile buffer. When a terrain package declares features.buildingDetail, classification and building rendering share its detailed footprints and mapped trees. The same depth limit and missing-coverage fallback apply to both; water rendering does not wait for building detail.

The dedicated home_canopy scatter rule controls species, spacing, setbacks, and detail tiers; custom packs opt in by supplying this rule label. Species use the tile's regional scatter set, as with other vegetation. House infill runs in scatter-only worker requests and uses the same instanced vegetation and camera LOD as forest scatter. No individual tree records are required.

A supplied building height is the total ground-to-top envelope, including the roof and any minimum height. Roof geometry fits inside it instead of being added above it. Roof props may project above that envelope. Parts spatially contained in an outline replace the covered area; uncovered areas of the original outline remain. Related pieces receive a shared groundOutline for fitting their platform to terrain, and raised parts retain their minimum-height clearance. Containment is a spatial inference because stock Protomaps does not publish parent relation IDs.

Golf courses, cemeteries and sports pitches ​

A map names these places but does not carry what makes them recognizable, so the Earth adapter lays that out. prepareLandSites(tile, geometry) from @bendyline/molen-worldgen-earth/kernel returns the tile with extra land cover after its own, and landSiteProps(tile, geometry) returns point placements. The renderers and the batch adapter call both; a custom pipeline calls them the same way. Everything is a visual estimate: it reads as the place from the air and on foot, and is not the surveyed course, the real graves or the pitch as it is painted.

Mapped landWhat is addedDetail levels
golf_coursegolf_fairway, golf_green, golf_tee and golf_bunker groundFairways and greens on the finest three levels, tees and bunkers on the finest two
cemetery, grave_yardHeadstones: tinted builtin:box placements in rowsFinest level
pitchsports_turf, sports_court, sports_blacktop and sports_dirt ground, sports_line markingsGround on the finest two levels, lines on the finest

Golf holes sit on a fixed world grid of squares 640 projected meters across. Each square holds parallel corridors at least 70 m wide, running east-west in some squares and north-south in others, and each corridor holds holes end to end: short, medium and long ones, each with tees, a fairway that doglegs a little, a green in a collar of fairway-height turf, and greenside and fairway bunkers. The layout is clipped to the mapped course and kept off its mapped water, woods, sand and buildings. A green, tee or bunker is drawn whole or not at all; a fairway may end at the course boundary. The rough is the course's own grass. Because the grid is anchored to the world, not to a tile, every tile, level and visit draws the same holes. A third argument { seed } re-rolls them, and the headstones; the built-in renderers use seed 0.

Headstones stand in sections 64 projected meters across with grass lanes between, in rows 5 m apart, 2.4 m from stone to stone. One section in eight is open lawn and the rest are 30–90% occupied. Most stones are upright slabs, a fifth flat markers, a few tall monuments, in five stone colors. Stones stay 2.5 m inside the boundary, 1.5 m from buildings and water, and clear of roads, drives and paths; they may stand under the cemetery's mapped trees. A tile draws at most 3,000: past that, whole sections stay lawn so the others keep their rows. Each stone belongs to the tile its base is in, and ModelPlacementRequest.color (sRGB red, green and blue in 0–1) carries its tint.

A pitch's game is read from the outline's size and shape:

OutlineRead asMarkings
Rectangle 85–130 m long, at least 1.9 times its widthFootball fieldBoundary and a yard line every ten yards
Other rectangle 45–130 m longSoccer fieldTouchlines, halfway line, center circle, penalty and goal areas
Rectangle 20–45 m long, over 31 m or at least 2.05 times its widthTennis courtDoubles court, singles sidelines, service boxes, net
Other rectangle 20–45 m longBasketball courtBoundary, center line and circle, keys, three-point arcs
Rectangle 10–20 m longCourtBoundary
Near-square fan filling 68–90% of its bounding rectangleBall diamondSkinned infield, foul lines, and from 70 m foul lines a grass infield and mound
Anything else from 45 m longFieldNone

A rectangle under 10 m long, or any other small outline, is left as the map has it.

Markings are each sport's standard dimensions, scaled down where the outline is smaller. Home plate is where the two long edges of a fan would meet, so a backstop that cuts that corner off does not hide it. A pitch the source cut at a tile edge cannot be measured, so both tiles draw their piece as turf; the tile that holds a diamond's home plate adds the infield when all of it fits inside that tile. A court cut that way is turf too.

Palettes name the added classes like any other land cover. LAND_SITE_COLORS supplies defaults under the pack's and the host's colors: irrigated turf keeps one green in every habitat, so a desert course is green fairways in tan rough. Added ground has crisp edges, and no vegetation rule plants on it unless a pack names its class.

8. Budgets and quality ​

worldgenTileBudgetForQuality(quality, levelBelowMax) caps buildings and vertices per tile. The numbers are sized for real footprints: a zoom-15 suburb puts 800 to 1,600 houses in a zoom-14 tile, and a downtown about 1,700 footprints and parts.

A batch spends its budget in priority order, largest footprints first. That suits a view from the air; for someone on the ground the buildings that matter are the nearest. WorldgenBatchInput.focus ({ x, z, radius } in the buildings' frame) queues the buildings within radius of a viewer nearest first, ahead of every other, so the same budget details and opens the doors of what the viewer can walk up to. The Earth renderers set it themselves: once the position passed to updateInteriors is down among the buildings and moving at a walk, the finest tiles within 90 m are regenerated round it, and again each 36 m it moves (never while it is inside a building, and the tile shown stays until its replacement is ready). In a dense Seattle tile of 1,091 buildings, where the largest 75 were detailed, that details the nearest 148, out to 140 m. First every building gets walls and its roof shape (the style's coarsest tier); only when even that does not fit does a building become an instanced stand-in. Then buildings gain a simplified facade while it fits, then the largest (detailedCount) gain full detail. The simplified facade preserves the authored footprint, roof shape and, where the active style tier permits them, a window on every floor: walls with up to three bays keep their real windows, and longer walls draw each floor's punched or grid windows as one strip whose window texture repeats once per bay, four vertices a floor and wall. It uses shared vertex-colored materials during reservation; eligible simplified buildings recover their shared textures when material groups fit, even if no geometric detail fits. Interior openings come with full detail only: cut into every budget facade they would cost a crowded neighbourhood its windows. High admits 24 material groups at the finest level, including flat fallback slots. The fallback omits raised window surrounds, trim bands, overhangs, separate foundation meshes, and roof props. Simplified and coarse buildings extend their walls below the lowest sampled ground, keeping roofs and windows level without gaps on downhill sides or extra vertices and draw calls. Stand-ins do the same; intentionally elevated minHeight parts retain their clearance.

Stand-ins are instanced: builtin:box for flat-roofed buildings, and builtin:box.gable (set buildings:box.gable) for pitched ones, a box whose walls stop at the eave (GABLE_BOX_EAVE of its height) under a roof ridged along its longer side, the roof shaded darker than the walls. From the air a neighbourhood of stand-ins still reads as roofs. buildingBoxGeometry(modelRef) returns the shared geometry for either. Buildings beyond maxBuildings are still omitted. Quality and detail remain tile-based, not camera-distance updates per building. worldgenBuildingCellSize batches the finest level's buildings into 512 m cells and coarser levels' into 1024 m cells, since each cell is a draw.

Generation is cooperative: the renderer yields between chunks of both reservation and detail work, and aborts when a tile is evicted. The explorer HUD reports buildings, boxes, and generation time per tile.

Detail tiers come from the level below the finest (tier 0 at the finest level, 1 one level below, ...) plus one at economy quality. A style's lod.tiers say which features survive each tier: roof shape, roof features, facade windows, facade bands, props; beyond the last tier the building is a stand-in. maxMaterialGroups caps the mesh groups (draw calls) of one batch: once a batch would exceed it, later buildings render their textured parts as vertex colors (stats.materialsCollapsed), so the largest buildings keep their textures first.

Scatter is bounded the same way. maxInstances caps the props of one batch as a whole (the sampler thins uniformly across rules by the same acceptance draw, so a tighter budget is a subset of a looser one) and maxInstancesPerRule caps one rule. The tile budgets shrink both with the detail level: a tile one level below the finest covers four times the area with a fraction of the instances, two levels below keeps a sparse hint, and coarser tiles carry no props. Visible cells draw only their active LOD; keep maxPropModels small because each model needs a draw per visible cell. The per-tile placement budgets still bound the resident instance data. Balanced quality allows 6,000 nearby placements, 2,400 one level below, and 800 two levels below. Economy uses 2,200 / 800 / 200; high uses 9,000 / 3,600 / 1,200. Ground cover has its own budget on the finest level only: 6,500 placements and 7 models at Balanced, 10,000 and 10 at High, none at Economy. Planted ground (the garden layer) has 5,000 placements and 9 models at Balanced and 9,000 and 14 at High on the finest level, a few hundred one level below, and 700 and 3 at Economy. The forest rules fill nearby crowns while understory is limited to the finest tier; parks and yards retain lower densities and all placements retain road, building, and water clearances.

9. Wiring it yourself ​

ts
import { loadStylePack } from '@bendyline/molen-worldgen/client';
import { createRegionResolver, createWorldgenSemanticRenderers, loadRegionAtlas } from '@bendyline/molen-worldgen-earth/client';

const { pack } = await loadStylePack('/worldgen/default/');
const atlas = await loadRegionAtlas('/worldgen-earth/default/world.atlas.json');
const regions = createRegionResolver(atlas, { metersPerUnit });
const worldgen = createWorldgenSemanticRenderers(pack, { atlas, regions, metersPerUnit, quality });
const layers = await createProfiledTerrainPackageSemanticLayers(pkg, {
  baseUrl,
  landcoverLayer: { renderer: worldgen.classification },
  featuresLayer: { renderer: worldgen.humanFeatures },
});

10. Off the main thread, cached, and queryable ​

createWorldgenSemanticRenderers takes a generator: by default tiles generate on the calling thread in cooperative chunks; createWorldgenWorkerBridge(worker, { pack, atlas, metersPerUnit }) sends each tile (semantics, geometry, a transferable height grid) to a Worker that runs installWorldgenWorker(self) from @bendyline/molen-worldgen-earth/worker and hands back transferred buffers; aborting a tile cancels its generation between chunks. Both paths sample the ground through the same height grid, so their output is byte-identical (a test asserts it). A cache (createWorldgenTileCache) keeps generated tiles in CPU memory keyed by pack, atlas, quality, features, and address, so a tile that leaves and re-enters residency is uploaded, not regenerated. The explorer enables this worker by default; ?worker=0 selects the in-thread diagnostic path.

Land-cover polygon draping and vertex welding also run in a separate worker in the explorer. createTerrainLandcoverWorkerBridge (terrain client) supplies the renderer’s landcoverGenerator; the host’s worker entry calls installTerrainLandcoverWorker. It transfers an independent copy of the height samples and returns indexed geometry, preserving the rendered terrain grid. Only one job runs at a time in this worker; cancelled queued jobs are skipped. Road/parking construction also uses a dedicated surface worker in the explorer. Archive decoding, scene assembly, and GPU uploads still happen on the main thread.

A shared lodPolicy: ScreenSpaceLodPolicy enables projected-screen-size LOD for vegetation and buildings. Instanced vegetation measures the camera's distance to each batch's bounds, not to its bounding sphere: a tile-wide batch's sphere reaches hundreds of meters above the canopy, so an aerial camera would otherwise draw every plant in the tiles below at near detail. A level with no leaf cards (a tree's distant level, rocks and props) draws with an opaque twin of the alpha-tested scatter material: a shader that can discard switches off hidden-surface removal on tile-based GPUs, so a distant forest drawn with the card material shaded every layer of crowns behind the first. For the same reason a level drawn with cards hands over to the next at a quarter of the projected error its geometry alone would allow (a crown's cards overlap several deep), and the distant level neither casts nor receives sun shadows. In place of the shadows it does not read, the WebGL scatter material shades a plant's crown as one among its neighbours while the sun's shadows are drawn: the top in the sun, the rest in shade, more so the lower the sun. From the air the distant level starts a few hundred meters out, and without that the trees near an aircraft were a dark disc among bright ones. With the policy's distantShadows the distant level casts as well (and still receives none; the horizon level below never casts), so the ground past the near trees carries tree shadows too. That draws every tree out to the horizon level into the shadow map: over a wooded town at High detail 350 more draws and 0.85 million more triangles a frame, and 1.9 ms more main thread, so it is off unless a host turns it on. createInstancedPlacementLod takes an optional fourth, horizon model (ModelLibrary.prepare(ref, 'horizon')): a conifer's far level keeps three plain skirts, so a stand of firs is not a field of cones from a few hundred meters, and hands over to the one-cone horizon model where 2.5 m of error fits the budget (about 930 m at 2.5 pixels on a 1080-line view). A broadleaf or mangrove tree in leaf, 2.5 m or taller, has one too: its far crown with fewer faces and no trunk (30 triangles for 56), reaching a little further and a little lighter so that a wood keeps its cover and tone where the two levels meet. For every other model the horizon model is the far model and adds no level. That handover reads the policy's horizonPixelError (default maxPixelError): a host that relaxes maxPixelError with camera height, to shed leaf cards, keeps horizonPixelError at its base value, or every conifer under an aircraft is the cone. A batch within a quarter of a handover's distance asks for the material across it, so its shaders are built by the time it gets there. With vanishPixels a batch stops drawing once its largest instance spans fewer pixels than that from the batch's nearest point (15% hysteresis): the semantic renderers pass 1.5 for street props and signs, which from a few kilometers were a draw each for a pixel or less, but not for plants, as a distant forest is the sum of its trees. Buildings retain their structural faces while distant materials and facade details simplify; geometry attributes are shared across spatial cells and levels. setQuality(preset) changes future generation and queues resident architecture for replacement, one building batch at a time. The previous buildings stay visible until their replacements are ready; roads remain in place. Preset changes and eviction cancel obsolete replacements. Policy mutations immediately affect resident LODs; existing scatter keeps its generation density until reloaded. Generation cache keys include effective budgets/tier offsets; setCacheBudget(bytes) trims the cache in place. See Adaptive rendering performance for the explorer's device feedback controller, live terrain budgets and measurement limits.

Gameplay can ask what was generated: createWorldgenIndex(records, placements) buckets a batch (or several tiles, with add) and answers buildingAt(x, z), buildingsNear(x, z, r), and propsNear(x, z, r); installWorldgen(world, index) registers it on a kernel world as a side channel (never in world state or its hash) and worldgenScriptApi(handle) exposes it to scene scripts as molen.worldgen.* through buildWorld's scriptExtensions.

Scenes that are not maps carry a worldgenBuilding component (style id, outline in the entity frame, holes, height or levels, labels, seed, tier): createWorldgenEntityLayer(client, { pack }) renders every such entity on a live client under its transform, rebuilding when the component changes and disposing when the entity goes away.

11. Limits ​

  • Inputs include land classes, vector footprints and optional business/prop points; nothing samples imagery. See recognizable places.
  • Protomaps business identity comes from optional POIs at the finest detail level. Buildings mostly carry kind: building; rules lean on footprint metrics, height presence, and the surrounding land use. Context is available when land use and buildings share one archive (the Sammamish package does).
  • Roofs of clipped tile-edge pieces are flat; secondary wings share the main eave height. The hipped fallback ends in a level deck, not ridges: there is no straight skeleton.
  • Party walls are found between separately mapped footprints. A terrace mapped as one long outline is still one building under one roof.
  • Crowns are five forms, placed by rule (a tower at one end, a dome over the middle), not where the real building has them.
  • Windows are surface quads, not openings; dormers and setbacks are declared in the format but not built yet; the wall-any prop anchor places nothing yet. ground-any props do not know where driveways and paths run, so on a lot that is paved to the wall one can stand on the paving.
  • Builtin vegetation uses spatially batched distance or screen-space LOD. Custom GLBs retain their authored geometry; they need authored LOD assets or simplification before the same reduction is possible.
  • Baked assets hold the building mesh only; props and scatter stay instanced placements.
  • The entity layer places buildings statically (no tweening) and needs prop models prepared through a ModelLibrary to show roof props.

50 guides · 44 schema formats · 51 API entry points · 11 samples. API, CLI and schema pages are generated from the shipped build.