Add an optional 3D view to the act-structure and act-links graphs

A "2D | 3D" switch on /graph/act, /graph/acts and the console's #/graph tabs.
2D (Cytoscape) stays the default. 3D draws legal-memory's "burst": the act,
its units and articles as a tree, the references inside the act, linked acts
on an outer shell and, once case law is ready, the judgments citing it. It
uses three.js 0.183.0 and 3d-force-graph 1.80.0 (both MIT), vendored,
same-origin and lazy-loaded, with UnrealBloomPass glow. The CSP is unchanged.

Python caps the data at 2,500 nodes (/graph/act/3d, /graph/acts/3d). The
choice is kept in localStorage (default 2D) and in ?view=3d. The selection
and the side panel survive a switch, and going back to 2D disposes the
renderer. Without WebGL the page stays in 2D.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-24 12:41:32 +02:00
co-authored by Claude Opus 5.5
parent 0ad581b3f1
commit df4290f688
22 changed files with 2112 additions and 13 deletions
+3 -1
View File
@@ -67,13 +67,15 @@ Deliberately **not** used: Surya (GPL + restricted weights), MinerU (AGPL), mark
| [eurlex-builder](https://github.com/tseidl/eurlex-builder) (Timo Seidl), commit `4d61904`, 0.3.0 | MIT | the CELLAR SPARQL shapes (type/sector filters, corrigendum and consolidated-CELEX exclusions) and the EUR-Lex XHTML structure pass (`ti-art` / `oj-ti-art` / `title-article-norm` headings, `sti-art` subtitles, annex and stop classes, consolidation markers) — vendored and adapted in `backend/app/integrations/cellar_builder/` (licence header kept). Not a dependency: its closure (duckdb, polars, pyarrow, lxml, SPARQLWrapper, requests…) is far heavier than what Insider uses, and its HTTP would bypass `SourceClient` |
| [Cytoscape.js](https://js.cytoscape.org) 3.30.4 (`dist/cytoscape.min.js`, sha256 `1bb5340e…b3b9`) | MIT | the 2D drawing of the reference graph — `frontend/vendor/cytoscape-3.30.4.min.js` beside its LICENSE, same-origin |
| [three.js](https://threejs.org) 0.183.0 (`build/three.module.min.js` sha256 `e3ec4d5d…6eda` + `build/three.core.min.js` sha256 `c5f69a04…c4fd`; from `examples/jsm`: `postprocessing/Pass.js`, `postprocessing/UnrealBloomPass.js`, `shaders/CopyShader.js`, `shaders/LuminosityHighPassShader.js`, their bare `'three'` import rewritten to the relative `../../three.module.min.js` — the only change) | MIT | the OPTIONAL 3D view of the reference graph (`frontend/graph3d.js`) and its glow (UnrealBloomPass: GLSL shaders compiled by WebGL, no JavaScript eval) — `frontend/vendor/three-0.183.0/` beside its LICENSE, same-origin, loaded only when a viewer picks "3D" |
| [3d-force-graph](https://github.com/vasturiano/3d-force-graph) 1.80.0 (`dist/3d-force-graph.min.js`, sha256 `d96e738e…2e42`; bundles its MIT/ISC/BSD dependencies — three-render-objects, three-forcegraph, d3-force-3d, kapsule) | MIT | the 3D force layout and camera controls of the optional 3D view — `frontend/vendor/3d-force-graph-1.80.0.min.js` beside its LICENSE, same-origin, loaded only on "3D"; it reads the vendored three.js from `window.THREE`. Its ngraph engine (which builds code with `new Function`) is never selected — the default d3 engine runs, so the CSP needs no `unsafe-eval` (checked in a browser: no violation) |
| [htmx](https://htmx.org) 2.0.4 (`dist/htmx.min.js`, sha256 `e209dda5…b447`) | 0BSD | the `/graph` pages' partial requests — `frontend/vendor/htmx-2.0.4.min.js` beside its LICENSE, configured with `allowEval: false` (no eval, so the console's CSP holds) |
## Ideas and fixtures ported
| Project | License | What Insider took |
|---|---|---|
| [tobayah/legal-memory](https://github.com/tobayah/legal-memory) (Tobiasz; commit `bb93733`) | **Apache-2.0** (LICENSE in the repository) | the graph model (Act › Księga › Tytuł › Dział › Rozdział › Oddział › Article; article→article edges with their type and the citing sentence), the in-body reference rules of `src/refs-inbody.ts` (the list / range continuation, the 80-article range cap, `ODSYLA_DO` / `STOSUJE_ODPOWIEDNIO` / `Z_ZASTRZEZENIEM` with their confidences, precision over recall), the MCP shape `find_article` / `references` / `trace_path`, and its self-checks as `backend/tests/test_legalref.py`. From its RAG reader (`rag/answer_l1.py`, `HANDOFF.md`): the second few-shot example that refuses although the right act is among the sources (`backend/app/ai/prompts/answer.json`), the citation checks of its `_check` (source numbers in range, "art. N" / act dates absent from the context, no citation), the "graph as expander over retrieval, not instead of it" design, and the ops note that amending-act titles quote whole EU acts — re-implemented and extended in `services/grounding.py` (checks against the CITED passage, lexical support through Insider's analyzer) Re-implemented in Python (a lark grammar instead of the TypeScript regexes, Postgres instead of a JSON file); no code copied verbatim |
| [tobayah/legal-memory](https://github.com/tobayah/legal-memory) (Tobiasz; commit `bb93733`) | **Apache-2.0** (LICENSE in the repository) | the graph model (Act › Księga › Tytuł › Dział › Rozdział › Oddział › Article; article→article edges with their type and the citing sentence), the in-body reference rules of `src/refs-inbody.ts` (the list / range continuation, the 80-article range cap, `ODSYLA_DO` / `STOSUJE_ODPOWIEDNIO` / `Z_ZASTRZEZENIEM` with their confidences, precision over recall), the MCP shape `find_article` / `references` / `trace_path`, and its self-checks as `backend/tests/test_legalref.py`. From its RAG reader (`rag/answer_l1.py`, `HANDOFF.md`): the second few-shot example that refuses although the right act is among the sources (`backend/app/ai/prompts/answer.json`), the citation checks of its `_check` (source numbers in range, "art. N" / act dates absent from the context, no citation), the "graph as expander over retrieval, not instead of it" design, and the ops note that amending-act titles quote whole EU acts — re-implemented and extended in `services/grounding.py` (checks against the CITED passage, lexical support through Insider's analyzer) Re-implemented in Python (a lark grammar instead of the TypeScript regexes, Postgres instead of a JSON file); no code copied verbatim. The optional 3D view (`frontend/graph3d.js`) follows its `web/` look — the act as a glowing burst, node colours pushed above 1.0 so the bloom makes coronas, edge weight as colour intensity under additive blending, framing on the 92nd percentile of distance — re-implemented, not copied |
## Data sources
+35 -1
View File
@@ -18,7 +18,7 @@ from pathlib import Path
from typing import Literal
from fastapi import APIRouter, Depends, Query, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from ..deps import get_current_user
@@ -282,3 +282,37 @@ async def act_top_page(request: Request, act: str = _text(),
error, building = _say_acts(exc), isinstance(exc, ConflictError)
return _page(request, "graph/top.html", tab="top", act=act, data=data, error=error,
building=building, graph=data["graph"] if data else None)
# ── the optional 3D views' data (frontend/graph3d.js, loaded only when "3D" is chosen) ──────────
# JSON, not a partial: the 3D drawing is not swapped in by htmx, it is fetched by the toggle. The
# cap (`legalgraph.VIEW3D_NODES`) and every filter are still decided here.
def _json(body: dict, status: int = 200) -> JSONResponse:
return JSONResponse(body, status_code=status, headers={"Cache-Control": "no-store"})
@router.get("/act/3d", response_class=JSONResponse)
async def act_3d(act: str = Query(min_length=1, max_length=200), kind: list[str] = Query([]),
_user: AppUser = Depends(get_current_user),
legal: Legal = Depends(get_legal)) -> JSONResponse:
try:
return _json({"graph": await legal.act_structure3d(act, kinds=_kinds(kind))})
except AppError as exc:
return _json({"error": _say_acts(exc), "building": isinstance(exc, ConflictError)}, 200)
@router.get("/acts/3d", response_class=JSONResponse)
async def acts_3d(act: str = _text(), top: int = Query(60, ge=2, le=500),
depth: int = Query(1, ge=1, le=2),
direction: Literal["both", "in", "out"] = "both",
kind: list[str] = Query([]), min_weight: int = _min_weight(),
_user: AppUser = Depends(get_current_user),
legal: Legal = Depends(get_legal)) -> JSONResponse:
try:
graph = await legal.acts_graph3d(act or None, top=top, depth=depth, direction=direction,
kinds=_kinds(kind), min_weight=min_weight)
except AppError as exc:
return _json({"error": _say_acts(exc), "building": isinstance(exc, ConflictError)})
from ..services.legalgraph import VIEW3D_NODES
graph["cap"] = VIEW3D_NODES
return _json({"graph": graph})
+53
View File
@@ -54,6 +54,10 @@ from .htmltext import (
log = logging.getLogger("insider.legal")
#: the 3D act structure's case-law particles: at most this many judgments, this many per article
CASES3D = 150
CASES3D_PER = 5
class GraphBuilding(ConflictError):
"""The act-level graph views before the reference graph's first complete build."""
@@ -876,6 +880,55 @@ class Legal:
a["case_law"] = (cases.get((out["eli"], a["ord"])) or {}).get("judgments", 0) if out["case_law_ready"] else None
return out
async def act_structure3d(self, act: str, *, kinds: set[str] | None = None) -> dict:
"""`LegalGraph.structure3d` + — once the case-law pass is complete — the judgments citing
the act's most-cited-in-case-law articles as small particles on the outer layer, capped
(`CASES3D` judgments, `CASES3D_PER` per article), inside the same node cap."""
from .legalgraph import VIEW3D_NODES
g = self._graph()
out = await self._graph_call(g.structure3d, act, kinds=kinds)
out["case_law"] = False
cl = self._caselaw()
room = VIEW3D_NODES - len(out["nodes"])
if cl is None or room <= 0:
return out
try:
if not await asyncio.to_thread(cl.ready):
return out
arts = [(n["id"].split("#")[0], int(n["id"].split("#")[1]))
for n in out["nodes"] if n["t"] == "art"]
counts = await asyncio.to_thread(cl.counts, arts)
top = sorted((k for k in counts if counts[k].get("judgments")),
key=lambda k: (-counts[k]["judgments"], k))[:CASES3D // CASES3D_PER]
seen: set[int] = set()
for key in top:
rows = await asyncio.to_thread(cl.store.case_refs_to, key, CASES3D_PER, None)
for r in rows:
jid = r["judgment_id"]
if len(seen) >= min(CASES3D, room):
break
if jid not in seen:
seen.add(jid)
out["nodes"].append({"id": f"j:{jid}", "t": "case",
"label": r.get("court_type") or "orzeczenie",
"title": " ".join(x for x in (
r.get("court_type"), r.get("judgment_date")) if x)
or "orzeczenie"})
out["edges"].append({"source": f"j:{jid}", "target": f"{key[0]}#{key[1]}",
"t": "case"})
out["case_law"] = True
out["shown"] = len(out["nodes"])
except Exception: # noqa: BLE001 — the drawing without the particles
log.warning("case_ref particles failed", exc_info=True)
return out
async def acts_graph3d(self, act: str | None, **kw) -> dict:
"""The act graph for the 3D view: the same data as `acts_graph`, a higher cap."""
from .legalgraph import VIEW3D_NODES
g = self._graph()
return await self._built_graph(g.acts_view, act, ceiling=VIEW3D_NODES,
max_nodes=VIEW3D_NODES, **kw)
async def _alias_lookup(self, keys: list[str]) -> list[dict] | None:
"""The alias table's rows for any of `keys` — ONE indexed lookup. None when there is no
table to ask (LIVE mode: never touched; INDEXED before alembic 0010 or on any error)."""
+110 -3
View File
@@ -51,6 +51,10 @@ VIEW_EDGES = 5000
#: aggregate rows read per query, acts expanded per hop, hops, top acts by default, articles
#: ranked and articles in the mini-graph — whatever the request asks
ACT_NODES = 500
#: the optional 3D views (`structure3d`, `acts_view(..., ceiling=VIEW3D_NODES)`): WebGL draws more
#: than Cytoscape's canvas, so their cap is higher — but still decided here, never in the browser
VIEW3D_NODES = 2500
LINKED3D_ACTS = 60
ACT_LINK_ROWS = 20000
ACT_FRONTIER = 500
ACT_DEPTH = 2
@@ -480,6 +484,108 @@ class LegalGraph:
"cited_by": counts.get((eli, o), (0, 0))[0],
"refs_out": counts.get((eli, o), (0, 0))[1]} for o, n in nums]}
def structure3d(self, act: str, *, kinds: set[str] | None = None,
max_nodes: int = VIEW3D_NODES) -> dict | None:
"""One act as the optional 3D "burst" (legal-memory's look): the act at the root, its units
(Księga › Tytuł › Dział › Rozdział › Oddział, from the article paths) as branches, its
articles as leaves (`tree` edges), the article→article references inside the act (`ref`
edges), and the acts linked to it as an outer layer (`link` edges: regulations implementing
it, acts it cites, acts citing it). At most `max_nodes` (≤ `VIEW3D_NODES`) nodes: the most
cited articles are kept (and their units), then the strongest linked acts."""
out = self.outline(act)
if out is None:
return None
res = self.resolver()
eli, title = out["eli"], out["title"]
max_nodes = max(10, min(int(max_nodes), VIEW3D_NODES))
arts = out["articles"]
budget = max_nodes - 1 - min(LINKED3D_ACTS, max_nodes // 10)
def units_of(a):
return [p.strip() for p in (a["path"] or "").split("›") if p.strip()]
# the articles that fit with their units, the most cited first (ties: document order)
order = sorted(range(len(arts)), key=lambda i: (-arts[i]["cited_by"], i))
units: dict[str, dict] = {}
chosen: set[int] = set()
for i in order:
parts, new_units, prefix = units_of(arts[i]), [], ""
for p in parts:
prefix += "›" + p
if prefix not in units:
new_units.append(prefix)
if len(chosen) + len(units) + len(new_units) + 1 > budget:
continue
chosen.add(i)
for u in new_units:
units[u] = {}
nodes = [{"id": eli, "t": "act", "label": short_title(title), "title": title, "lvl": 0}]
edges: list[dict] = []
seen_units: set[str] = set()
for i, a in enumerate(arts):
if i not in chosen:
continue
parent, prefix = eli, ""
for depth, p in enumerate(units_of(a)):
prefix += "›" + p
uid = "u:" + prefix
if prefix not in seen_units:
seen_units.add(prefix)
nodes.append({"id": uid, "t": "unit", "label": p, "title": p, "lvl": depth + 1,
"arts": 0})
edges.append({"source": parent, "target": uid, "t": "tree"})
parent = uid
aid = f"{eli}#{a['ord']}"
nodes.append({"id": aid, "t": "art", "label": f"art. {a['num'] or a['ord']}",
"title": f"art. {a['num'] or a['ord']}" + (f" — {a['path']}" if a["path"] else ""),
"cited_by": a["cited_by"], "refs_out": a["refs_out"]})
edges.append({"source": parent, "target": aid, "t": "tree"})
by_unit = {n["id"]: n for n in nodes if n["t"] == "unit"}
parent_of = {e["target"]: e["source"] for e in edges}
for n in nodes:
if n["t"] == "art":
p = parent_of.get(n["id"])
while p in by_unit:
by_unit[p]["arts"] += 1
p = parent_of.get(p)
kept = {n["id"] for n in nodes}
pairs = set()
for r in self.store.act_edges(eli, VIEW_EDGES):
if kinds and r["kind"] not in kinds:
continue
a, b = f"{eli}#{r['src_ord']}", f"{eli}#{r['dst_ord']}"
if a != b and a in kept and b in kept and (a, b) not in pairs:
pairs.add((a, b))
edges.append({"source": a, "target": b, "t": "ref", "kind": r["kind"]})
# the outer layer: the acts linked to this one, strongest first
linked: dict[str, dict] = {}
for r in self.store.act_links([eli], mode="both", kinds=kinds, limit=ACT_LINK_ROWS):
out_way = r["src_eli"] == eli
other = r["dst_eli"] if out_way else r["src_eli"]
x = linked.setdefault(other, {"weight": 0, "out": 0, "in": 0})
x["weight"] += r["refs"]
x["out" if out_way else "in"] += r["refs"]
room = max(0, max_nodes - len(nodes))
best = sorted(linked, key=lambda e: (-linked[e]["weight"], e))[:min(room, LINKED3D_ACTS)]
for e in best:
x = linked[e]
role = ("reg" if self.delegation(e, eli) else "in" if x["in"] >= x["out"] else "out")
t = res.title.get(e, e)
nodes.append({"id": e, "t": "linked", "role": role, "label": short_title(t),
"title": t, "weight": x["weight"]})
edges.append({"source": e, "target": eli, "t": "link", "role": role,
"weight": x["weight"]})
total = 1 + len(arts) + len({u for a in arts for u in self._prefixes(units_of(a))}) + len(linked)
return {"kind": "structure", "eli": eli, "title": title, "nodes": nodes, "edges": edges,
"total": total, "shown": len(nodes), "truncated": len(nodes) < total,
"cap": max_nodes}
@staticmethod
def _prefixes(parts: list[str]) -> list[str]:
out, prefix = [], ""
for p in parts:
prefix += "›" + p
out.append(prefix)
return out
def counts(self, keys: list[tuple[str, int]]) -> dict[tuple[str, int], tuple[int, int]]:
return self.store.ref_counts(keys)
@@ -492,7 +598,7 @@ class LegalGraph:
def acts_view(self, act: str | None = None, *, top: int = TOP_ACTS, depth: int = 1,
direction: str = "both", kinds: set[str] | None = None, min_weight: int = 1,
max_nodes: int = ACT_NODES) -> dict | None:
max_nodes: int = ACT_NODES, ceiling: int = ACT_NODES) -> dict | None:
"""The act graph: one node per act, one edge per (citing act, cited act) weighing the
article-level references between them (split by kind). Scope: `act`'s neighbourhood,
`depth` ≤ 2 hops `direction`, or — no act — the `top` acts by act PageRank and the
@@ -500,7 +606,8 @@ class LegalGraph:
connected kept; `min_weight` drops thinner edges. Every bound is decided here; node size
and edge width too (log scales), so the browser only draws."""
res = self.resolver()
max_nodes = max(2, min(int(max_nodes), ACT_NODES))
ceiling = min(int(ceiling), VIEW3D_NODES)
max_nodes = max(2, min(int(max_nodes), ceiling))
depth = max(1, min(int(depth), ACT_DEPTH))
min_weight = max(1, int(min_weight))
center = None
@@ -525,7 +632,7 @@ class LegalGraph:
break
scope = "act"
else:
top = max(2, min(int(top), ACT_NODES))
top = max(2, min(int(top), ceiling))
ranked = [e for e, _v in self.store.top_acts(top * 3)
if res.current.get(e) == e][:top] # a base / superseded ELI: its t.j.
rows = self.store.act_links(ranked, mode="among", kinds=kinds, limit=ACT_LINK_ROWS)
@@ -2,6 +2,7 @@
{% if error %}
<div class="g-msg {{ 'faint' if building else 'err' }}" role="{{ 'status' if building else 'alert' }}"{% if building %} data-building{% endif %}>{{ error }}</div>
{% elif graph %}
<div class="g-mode" data-3d="acts/3d?{{ request.url.query }}"></div>
<div class="g-meta faint tiny">
{{ graph.nodes|length }} aktów, {{ graph.edges|length }} powiązań
{% if graph.truncated %} — pokazano najmocniej powiązane (limit 500){% endif %}
+1
View File
@@ -15,6 +15,7 @@
{% endif %}
{% endblock %}
{% block view %}
{% if outline %}<div class="g-mode" data-3d="act/3d?act={{ outline.eli|urlencode }}{% for k in chosen %}&amp;kind={{ k|urlencode }}{% endfor %}"></div>{% endif %}
{% include "graph/_view.html" %}
{% if outline %}
<details class="g-outline" open>
+1 -1
View File
@@ -15,7 +15,7 @@
<script src="../vendor/cytoscape-3.30.4.min.js" defer></script>
<script src="../graph.js" defer></script>
</head>
<body class="graph-page">
<body class="graph-page" data-tab="{{ tab }}">
<header class="g-head">
<a class="g-brand" href="../#/" target="_parent">← Insider</a>
<nav class="g-tabs" aria-label="Widoki grafu">
+285
View File
@@ -0,0 +1,285 @@
"""The OPTIONAL 3D views of /graph (graph3d.js over three.js + 3d-force-graph), DB-free: the data
routes (refusal, shape, the server-side cap), the vendoring and the CSP (unchanged, nothing new to
allow), that nothing 3D loads before a viewer asks for it, and — in Node, over a tiny stub DOM — the
2D | 3D switch: its state, the per-viewer memory (localStorage, default 2D), the URL, and that going
back to 2D disposes the WebGL view."""
from __future__ import annotations
import json
import re
import shutil
import subprocess
import pytest
from fastapi.testclient import TestClient
from test_graph_pages import KP, ROOT, TEMPLATES, app_, client, graph_store # noqa: F401 — fixtures
from app import edge
from app.services import legalgraph as lg
FRONT = ROOT / "frontend"
VENDOR = FRONT / "vendor"
# ── the data routes ─────────────────────────────────────────────────────────────────────────────
def test_the_3d_routes_refuse_a_stranger(app_): # noqa: F811
with TestClient(app_) as c:
for url in (f"/graph/act/3d?act={KP}", "/graph/acts/3d"):
r = c.get(url)
assert r.status_code == 401, url
assert r.headers["content-type"].startswith("application/problem+json")
def test_the_3d_act_structure(client): # noqa: F811
r = client.get("/graph/act/3d", params={"act": "Kodeks pracy"})
assert r.status_code == 200 and r.headers["cache-control"] == "no-store"
g = r.json()["graph"]
assert g["kind"] == "structure" and g["eli"] == KP and g["cap"] == lg.VIEW3D_NODES
kinds = {n["t"] for n in g["nodes"]}
assert {"act", "unit", "art"} <= kinds
ids = {n["id"] for n in g["nodes"]}
assert len(ids) == len(g["nodes"]) == g["shown"] <= g["total"]
for e in g["edges"]:
assert e["source"] in ids and e["target"] in ids
tree = [e for e in g["edges"] if e["t"] == "tree"]
parents = {e["target"]: e["source"] for e in tree}
for n in g["nodes"]: # every unit and article hangs off the act
if n["t"] in ("unit", "art"):
x, seen = n["id"], 0
while x != KP:
x = parents[x]
seen += 1
assert seen < 10
assert any(e["t"] == "ref" for e in g["edges"])
assert all(e["t"] == "link" and e["target"] == KP for e in g["edges"]
if e["source"] in {n["id"] for n in g["nodes"] if n["t"] == "linked"})
assert client.get("/graph/act/3d").status_code == 422
assert "Nie ma takiego aktu" in client.get("/graph/act/3d?act=DU/1900/1").json()["error"]
def test_the_3d_act_graph_is_the_2d_data(client): # noqa: F811
g3 = client.get("/graph/acts/3d?top=30").json()["graph"]
page = client.get("/graph/acts?top=30").text
g2 = json.loads(re.search(r'<template id="graph-data">(.*?)</template>', page, re.S).group(1))
assert g3["kind"] == "acts" and {n["id"] for n in g3["nodes"]} == {n["id"] for n in g2["nodes"]}
assert g3["cap"] == lg.VIEW3D_NODES
assert client.get("/graph/acts/3d?top=501").status_code == 422
class _Big:
"""One act with 3,000 articles in 30 chapters, each article citing the next — over the 3D cap."""
E = "DU/2000/1"
def graph_heads(self):
return [{"eli": self.E, "title": "Ustawa o czymś", "year": 2000, "pos": 1, "type": "Ustawa",
"superseded": False, "base_eli": None},
{"eli": "DU/2001/2", "title": "Rozporządzenie w sprawie czegoś", "year": 2001, "pos": 2,
"type": "Rozporządzenie", "superseded": False, "base_eli": None}]
def article_nums(self, eli):
return [(o, str(o)) for o in range(1, 3001)]
def article_paths(self, eli, ords):
return {o: f"Rozdział {o % 30}" for o in ords}
def ref_counts(self, keys):
return {k: (k[1] % 7, 1) for k in keys}
def act_edges(self, eli, limit):
return [{"src_eli": eli, "src_ord": o, "dst_eli": eli, "dst_ord": o + 1, "kind": "ODSYLA_DO",
"at": 0} for o in range(1, 3000)][:limit]
def act_links(self, elis, *, mode, kinds=None, limit=20000):
return [{"src_eli": "DU/2001/2", "dst_eli": self.E, "kind": "ODSYLA_DO", "refs": 4}]
def test_the_3d_structure_never_draws_more_than_the_cap():
v = lg.LegalGraph(_Big()).structure3d(_Big.E, max_nodes=10_000)
assert lg.VIEW3D_NODES == 2500 and len(v["nodes"]) <= 2500 and v["truncated"]
assert v["total"] == 1 + 3000 + 30 + 1 and v["shown"] == len(v["nodes"])
ids = {n["id"] for n in v["nodes"]}
assert all(e["source"] in ids and e["target"] in ids for e in v["edges"])
kept = [n for n in v["nodes"] if n["t"] == "art"]
assert min(n["cited_by"] for n in kept) >= 0 and max(n["cited_by"] for n in kept) == 6
linked = [n for n in v["nodes"] if n["t"] == "linked"]
assert linked and linked[0]["role"] == "reg" # a regulation → delegation
small = lg.LegalGraph(_Big()).structure3d(_Big.E, max_nodes=100)
assert len(small["nodes"]) <= 100
def test_the_3d_act_graph_cap_is_python_s():
from test_graph_pages import _Wide # noqa: F401 — the 2D cap stays 500
assert lg.ACT_NODES == 500 and lg.VIEW3D_NODES == 2500
# ── vendoring, licences, CSP, lazy loading ───────────────────────────────────────────────────────
def test_vendored_pinned_and_permissive():
three = VENDOR / "three-0.183.0"
for f in ("three.module.min.js", "three.core.min.js", "LICENSE", "jsm/postprocessing/Pass.js",
"jsm/postprocessing/UnrealBloomPass.js", "jsm/shaders/CopyShader.js",
"jsm/shaders/LuminosityHighPassShader.js"):
assert (three / f).is_file(), f
assert "MIT License" in (three / "LICENSE").read_text(encoding="utf-8")
assert (VENDOR / "3d-force-graph-1.80.0.min.js").is_file()
assert "MIT License" in (VENDOR / "3d-force-graph.LICENSE").read_text(encoding="utf-8")
for f in (three / "jsm").rglob("*.js"): # no bare 'three' specifier: no import map needed
assert "from 'three'" not in f.read_text(encoding="utf-8"), f
credits = (ROOT / "CREDITS.md").read_text(encoding="utf-8")
assert "three.js" in credits and "3d-force-graph" in credits
def test_nothing_3d_loads_until_asked_and_the_csp_is_unchanged():
base = (TEMPLATES / "base.html").read_text(encoding="utf-8")
assert "three" not in base and "force-graph" not in base and "graph3d" not in base
js = (FRONT / "graph.js").read_text(encoding="utf-8")
assert "import(SCRIPT_BASE + 'vendor/three-0.183.0/three.module.min.js')" in js
assert "loadScript(SCRIPT_BASE + 'vendor/3d-force-graph-1.80.0.min.js')" in js
g3 = (FRONT / "graph3d.js").read_text(encoding="utf-8")
for src in (js, g3):
assert "eval(" not in src and "new Function" not in src and ".innerHTML" not in src
assert ".nodeLabel(null).linkLabel(null)" in g3 # 3d-force-graph's innerHTML tooltips off
assert "prefers-reduced-motion" in g3 and "autoRotate" in g3
# the CSP the 3D view runs under is the console's, word for word — no new origin, no eval
assert edge.GRAPH_CSP == edge.content_security_policy("'self'")
assert "unsafe-eval" not in edge.GRAPH_CSP and "worker-src" not in edge.GRAPH_CSP
assert "http" not in edge.GRAPH_CSP
def test_the_switch_is_in_the_pages_only_where_there_is_a_graph(client): # noqa: F811
act = client.get("/graph/act", params={"act": "Kodeks pracy"}).text
assert f'data-3d="act/3d?act={KP}"' in act
assert 'class="g-mode"' in client.get("/graph/acts?top=30").text
assert 'class="g-mode"' not in client.get("/graph/act").text # no act, no switch
assert 'class="g-mode"' not in client.get("/graph/path").text
# ── the switch, in Node over a stub DOM ─────────────────────────────────────────────────────────
NODE = shutil.which("node")
HARNESS = r"""
const fs = require('fs'); const vm = require('vm');
function El(tag) {
const e = { tagName: tag.toUpperCase(), children: [], parentNode: null, attrs: {}, dataset: {}, style: {},
hidden: false, listeners: {}, textContent: '', id: '' };
const cls = new Set();
e.classList = { add: (...c) => c.forEach((x) => cls.add(x)), remove: (...c) => c.forEach((x) => cls.delete(x)),
contains: (c) => cls.has(c), toggle: (c, on) => (on === undefined ? (cls.has(c) ? cls.delete(c) : cls.add(c)) : on ? cls.add(c) : cls.delete(c)) };
Object.defineProperty(e, 'className', { get: () => [...cls].join(' '), set: (v) => { cls.clear(); String(v).split(/\s+/).filter(Boolean).forEach((x) => cls.add(x)); } });
Object.defineProperty(e, 'firstChild', { get: () => e.children[0] || null });
e.appendChild = (c) => { if (c.parentNode) c.parentNode.removeChild(c); c.parentNode = e; e.children.push(c); return c; };
e.removeChild = (c) => { e.children.splice(e.children.indexOf(c), 1); c.parentNode = null; return c; };
e.insertBefore = (c, ref) => { if (c.parentNode) c.parentNode.removeChild(c); c.parentNode = e; const i = ref ? e.children.indexOf(ref) : -1; if (i < 0) e.children.push(c); else e.children.splice(i, 0, c); return c; };
Object.defineProperty(e, 'nextSibling', { get: () => { const p = e.parentNode; return p ? p.children[p.children.indexOf(e) + 1] || null : null; } });
e.setAttribute = (k, v) => { e.attrs[k] = String(v); }; e.getAttribute = (k) => (k in e.attrs ? e.attrs[k] : null);
e.addEventListener = (t, f) => { (e.listeners[t] = e.listeners[t] || []).push(f); };
e.dispatch = (t, ev) => (e.listeners[t] || []).forEach((f) => f(ev || { key: '', preventDefault() {} }));
e.click = () => e.dispatch('click');
e.focus = () => {};
e.getContext = () => ({});
e.querySelectorAll = (sel) => { const out = []; walk(e, (x) => { if (x !== e && matches(x, sel, e)) out.push(x); }); return out; };
e.querySelector = (sel) => e.querySelectorAll(sel)[0] || null;
return e;
}
function walk(n, f) { n.children.forEach((c) => { f(c); walk(c, f); }); }
function one(x, s) {
const m = s.match(/^([a-z0-9]*)((?:\.[\w-]+)*)(?:#([\w-]+))?(?:\[([\w-]+)="([^"]*)"\])?$/i);
if (!m) return false;
if (m[1] && x.tagName !== m[1].toUpperCase()) return false;
if (m[2] && !m[2].split('.').filter(Boolean).every((c) => x.classList.contains(c))) return false;
if (m[3] && x.id !== m[3]) return false;
if (m[4]) { const k = m[4].replace(/^data-/, ''); const v = m[4].startsWith('data-') ? x.dataset[k] : x.getAttribute(m[4]); if (v !== m[5]) return false; }
return true;
}
function matches(x, sel, root) {
const parts = sel.trim().split(/\s+/);
if (!one(x, parts[parts.length - 1])) return false;
let i = parts.length - 2, p = x.parentNode;
while (i >= 0 && p && p !== root.parentNode) { if (one(p, parts[i])) i--; p = p.parentNode; }
return i < 0;
}
const store = {}; let storeThrows = process.argv[3] === 'throw';
const body = El('body'); const view = El('section'); view.id = 'view'; body.appendChild(view);
const host = El('div'); host.className = 'g-mode'; host.dataset['3d'] = 'act/3d?act=DU%2F2026%2F1245'; view.appendChild(host);
const listeners = {};
const log = { loads: 0, fetches: [], mounts: 0, disposes: 0, urls: [] };
const search = process.argv[4] || '?act=Kodeks+pracy';
const ctx = { console, URL, Promise, setTimeout, JSON, Math, Object, String, WeakMap, Set,
CustomEvent: function (t, o) { this.type = t; this.detail = o && o.detail; },
document: { readyState: 'loading', documentElement: El('html'), body, head: El('head'), currentScript: { src: 'http://h/graph.js' },
getElementById: (id) => { let f = null; walk(body, (x) => { if (!f && x.id === id) f = x; }); return f; },
querySelector: (s) => body.querySelector(s), querySelectorAll: (s) => body.querySelectorAll(s),
createElement: (t) => El(t), addEventListener: (t, f) => { (listeners[t] = listeners[t] || []).push(f); },
createTreeWalker: () => ({ nextNode: () => null }) },
localStorage: { getItem: (k) => { if (storeThrows) throw new Error('blocked'); return k in store ? store[k] : null; },
setItem: (k, v) => { if (storeThrows) throw new Error('blocked'); store[k] = String(v); } },
location: { href: 'http://h/graph/act' + search, search, pathname: '/graph/act', hash: '' },
history: { state: null, replaceState: (s, t, u) => { log.urls.push(u); ctx.location.search = u.slice(u.indexOf('?') >= 0 ? u.indexOf('?') : u.length); ctx.location.href = 'http://h' + u; } },
getComputedStyle: () => ({ getPropertyValue: () => '' }),
matchMedia: () => ({ matches: false, addEventListener() {} }),
fetch: (u) => { log.fetches.push(u); return Promise.resolve({ json: () => ({ graph: { kind: 'structure', nodes: [{ id: 'a' }], edges: [], shown: 1, total: 1, cap: 2500 } }) }); },
};
ctx.window = ctx; ctx.self = ctx;
ctx.addEventListener = () => {};
ctx.WebGLRenderingContext = process.argv[5] === 'nogl' ? undefined : function () {};
ctx.__graph3dLibs = () => { log.loads++; return Promise.resolve({ Bloom: null }); };
ctx.Graph3D = { mount: () => { log.mounts++; return { dispose: () => { log.disposes++; }, select() {}, fit() {}, reset() {} }; } };
vm.createContext(ctx);
vm.runInContext(fs.readFileSync(process.argv[2], 'utf8'), ctx);
const seg = () => host.querySelectorAll('.g-seg button').map((b) => b.dataset.mode + ':' + b.getAttribute('aria-checked'));
const tick = () => new Promise((r) => setTimeout(r, 5));
(async () => {
(listeners.DOMContentLoaded || []).forEach((f) => f());
await tick();
const out = { start: { mode: ctx.graphView(), seg: seg(), loads: log.loads, is3d: view.classList.contains('is-3d') } };
const b3 = host.querySelector('[data-mode="3d"]'), b2 = host.querySelector('[data-mode="2d"]');
b3.click(); await tick();
out.after3d = { mode: ctx.graphView(), seg: seg(), loads: log.loads, mounts: log.mounts, fetch: log.fetches[0],
stored: storeThrows ? null : store.insider_graph_view, url: log.urls[log.urls.length - 1], is3d: view.classList.contains('is-3d') };
b2.dispatch('keydown', { key: 'ArrowRight', preventDefault() {} }); await tick(); /* keyboard: 2D ⇄ 3D */
out.after2d = { mode: ctx.graphView(), seg: seg(), disposes: log.disposes, stored: storeThrows ? null : store.insider_graph_view,
url: log.urls[log.urls.length - 1], is3d: view.classList.contains('is-3d'), wrapHidden: host.parentNode.querySelector('.g-3d-wrap').hidden,
wrapChildren: host.parentNode.querySelector('.g-3d-wrap').children.length };
ctx.setGraphView('3d'); await tick(); ctx.setGraphView('3d'); await tick();
out.twice = { mounts: log.mounts };
process.stdout.write(JSON.stringify(out));
})();
"""
def _run(tmp_path, *args):
h = tmp_path / "h.js"
h.write_text(HARNESS, encoding="utf-8")
r = subprocess.run([NODE, str(h), str(FRONT / "graph.js"), *args], capture_output=True, text=True,
encoding="utf-8")
assert r.returncode == 0, r.stderr
return json.loads(r.stdout)
@pytest.mark.skipif(NODE is None, reason="node is not installed")
def test_the_switch_persists_and_disposes(tmp_path):
out = _run(tmp_path)
assert out["start"] == {"mode": "2d", "seg": ["2d:true", "3d:false"], "loads": 0, "is3d": False}
a = out["after3d"]
assert a["mode"] == "3d" and a["seg"] == ["2d:false", "3d:true"] and a["is3d"]
assert a["loads"] == 1 and a["mounts"] == 1 and a["fetch"] == "act/3d?act=DU%2F2026%2F1245"
assert a["stored"] == "3d" and "view=3d" in a["url"]
b = out["after2d"]
assert b["mode"] == "2d" and b["seg"] == ["2d:true", "3d:false"] and not b["is3d"]
assert b["disposes"] == 1 and b["wrapHidden"] and b["wrapChildren"] == 0
assert b["stored"] == "2d" and "view=3d" not in b["url"]
assert out["twice"]["mounts"] == 2 # one mount per switch
@pytest.mark.skipif(NODE is None, reason="node is not installed")
def test_a_link_with_view_3d_opens_in_3d_and_blocked_storage_defaults_to_2d(tmp_path):
out = _run(tmp_path, "ok", "?act=x&view=3d")
assert out["start"]["mode"] == "3d" and out["start"]["loads"] == 1 and out["start"]["is3d"]
blocked = _run(tmp_path, "throw")
assert blocked["start"]["mode"] == "2d" and blocked["start"]["loads"] == 0
assert blocked["after3d"]["mode"] == "3d" # the URL still carries it
assert "view=3d" in blocked["after3d"]["url"]
@pytest.mark.skipif(NODE is None, reason="node is not installed")
def test_without_webgl_it_stays_in_2d(tmp_path):
out = _run(tmp_path, "ok", "?act=x", "nogl")
assert out["after3d"]["mode"] == "2d" and out["after3d"]["loads"] == 0 and not out["after3d"]["is3d"]
+22
View File
@@ -341,6 +341,28 @@ def test_an_act_graph_request_stays_under_a_memory_ceiling(infra, api, url):
assert peak < MEMORY_CEILING, f"{peak / 1e6:.1f} MB"
@pytest.mark.infra("bare", "full", "index_only", "fresh")
def test_the_optional_3d_views_follow_the_graph_state(infra, api):
"""The 3D views (graph3d.js): before the graph exists the acts page shows the building state and
no 2D | 3D switch, and the 3D data route says "building" (200, never a 500); with the graph the
switch is there and the data is capped in Python. No page ever names a 3D library: three.js and
3d-force-graph load only when a viewer picks 3D."""
page = api.get("/graph/acts")
data = api.get("/graph/acts/3d")
assert page.status_code == data.status_code == 200
for t in (page.text, api.get(f"/graph/act?act={KC_TJ}").text):
assert "three" not in t and "force-graph" not in t and "graph3d" not in t
if infra.profile.graph == "complete":
assert 'class="g-mode"' in page.text
g = data.json()["graph"]
assert g["nodes"] and len(g["nodes"]) <= g["cap"] == 2500
s = api.get("/graph/act/3d", params={"act": KC_TJ}).json()["graph"]
assert s["kind"] == "structure" and len(s["nodes"]) <= 2500
else:
assert "Graf jeszcze się buduje" in page.text and 'class="g-mode"' not in page.text
assert data.json().get("building") is True
# ── "cited in case law" (alembic 0012) ───────────────────────────────────────────────────────────────
def test_case_law_is_absent_or_building_until_its_first_pass(infra, api):
"""`/graph/case-law` and the panel: LIVE refuses (409, no graph); an INDEXED profile without
+63 -3
View File
@@ -208,6 +208,7 @@ const I18N = {
'Struktura aktu': 'Act structure',
'Najczęściej cytowane': 'Most cited',
'Ścieżka': 'Path',
'Widok grafu': 'Graph view', 'Widok 2D': '2D view', 'Widok 3D': '3D view',
'Sąsiedztwo artykułu': 'Article neighbourhood',
'Graf powiązań': 'Connections graph',
'Graf jeszcze się buduje': 'The graph is still being built',
@@ -1193,12 +1194,34 @@ function graphSrc(q) {
if (q.cases) p.set('cases', '1');
return 'graph/?' + p.toString();
}
if (tab === 'act') { if (q.act) p.set('act', q.act); return 'graph/act' + (q.act ? '?' + p : ''); }
const v3 = graphView3d(q);
if (tab === 'act') { if (q.act) p.set('act', q.act); if (q.act && v3) p.set('view', '3d'); return 'graph/act' + (q.act ? '?' + p : ''); }
if (tab === 'top') { if (q.act) p.set('act', q.act); return 'graph/top' + (q.act ? '?' + p : ''); }
if (tab === 'path') return 'graph/path';
if (q.act) { p.set('act', q.act); p.set('depth', '1'); } else p.set('top', '60');
if (v3) p.set('view', '3d');
return 'graph/acts?' + p.toString();
}
/* The 2D | 3D choice of the act-structure and links-between-acts views: the hash's `view` first (a
link opens the same mode), else the viewer's own stored choice (graph.js keeps it), else 2D. */
const GRAPH_VIEW_KEY = 'insider_graph_view';
function graphView3d(q) {
if (q.view === '3d' || q.view === '2d') return q.view === '3d';
try { return localStorage.getItem(GRAPH_VIEW_KEY) === '3d'; } catch { return false; }
}
function graphModeSeg(tab, is3d) {
const on = tab === 'act' || tab === 'acts';
return `<span class="grp gmode" role="radiogroup" aria-label="Widok grafu" ${on ? '' : 'hidden'}>${[['2d', '2D', 'Widok 2D'], ['3d', '3D', 'Widok 3D']].map(([v, l, t]) =>
`<button type="button" class="fchip ${(v === '3d') === is3d ? 'on' : ''}" role="radio" data-mode="${v}" aria-checked="${(v === '3d') === is3d}" title="${t}" aria-label="${t}">${l}</button>`).join('')}</span>`;
}
function paintGraphMode(m) {
document.querySelectorAll('.gmode [data-mode]').forEach((b) => {
const on = b.dataset.mode === m;
b.classList.toggle('on', on);
b.setAttribute('aria-checked', String(on));
b.tabIndex = on ? 0 : -1;
});
}
/* Which tab a framed URL belongs to (the frame can navigate on its own: a link in its panel). */
function graphTabOf(src) {
const path = String(src).split('?')[0];
@@ -1228,7 +1251,8 @@ async function viewGraph(C, q) {
<div id="gacts"></div>
<div class="chips"><span class="grp" role="tablist" aria-label="Widoki grafu">${GRAPH_TABS.map(([v, label]) =>
`<a class="fchip ${tab === v ? 'on' : ''}" role="tab" data-tab="${v}" aria-selected="${tab === v}" href="${esc(graphHash(v, q.act && v !== 'path' ? { act: q.act } : {}))}">${esc(label)}</a>`).join('')}
<span class="fchip ${tab === 'article' ? 'on' : ''}" role="tab" data-tab="article" aria-selected="${tab === 'article'}" ${tab === 'article' ? '' : 'hidden'}>Sąsiedztwo artykułu</span></span></div>
<span class="fchip ${tab === 'article' ? 'on' : ''}" role="tab" data-tab="article" aria-selected="${tab === 'article'}" ${tab === 'article' ? '' : 'hidden'}>Sąsiedztwo artykułu</span></span>
${graphModeSeg(tab, /[?&]view=3d(&|$)/.test(src))}</div>
<div id="gbuilding"></div>
<iframe class="graph-frame" id="gframe" title="Graf powiązań" src="${esc(src)}"></iframe>`;
$('gform').addEventListener('submit', (e) => { e.preventDefault(); graphSearch($('gin').value.trim()); });
@@ -1241,6 +1265,27 @@ async function viewGraph(C, q) {
window.addEventListener('resize', fit);
fit();
frame.addEventListener('load', () => graphFrameLoaded(frame));
/* the console's 2D | 3D drives the framed page (window.setGraphView, graph.js), which answers with
a 'graphview' event on its frame element — also when its own switch was used */
const setMode = (m) => {
let win = null;
try { win = frame.contentWindow; } catch { /* not same-origin */ }
if (win && win.setGraphView) win.setGraphView(m);
else { try { localStorage.setItem(GRAPH_VIEW_KEY, m); } catch { /* blocked */ } paintGraphMode(m); }
};
document.querySelectorAll('.gmode [data-mode]').forEach((b) => {
b.addEventListener('click', () => setMode(b.dataset.mode));
b.addEventListener('keydown', (e) => {
if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) return;
e.preventDefault();
const to = b.dataset.mode === '3d' ? '2d' : '3d';
setMode(to);
const nb = document.querySelector(`.gmode [data-mode="${to}"]`);
if (nb) nb.focus();
});
});
paintGraphMode(/[?&]view=3d(&|$)/.test(src) ? '3d' : '2d');
frame.addEventListener('graphview', (e) => { paintGraphMode(e.detail); graphMirror(frame); });
}
/* Each framed page: drop its own header (the console has the tabs), keep the language in step,
@@ -1259,11 +1304,26 @@ function graphFrameLoaded(frame) {
: '';
frame.hidden = !!building;
localize($('gbuilding'));
const gm = document.querySelector('.gmode');
if (gm) {
gm.hidden = !doc.querySelector('.g-mode');
if (win.graphView) paintGraphMode(win.graphView());
}
graphMirror(frame);
}
/* Mirror where the frame is (its page and its ?view=) into the console's hash. */
function graphMirror(frame) {
let win;
try { win = frame.contentWindow; } catch { return; }
if (!win || !$('gbuilding')) return;
const base = new URL('.', document.baseURI).pathname;
const loc = win.location;
if (!loc.pathname.startsWith(base)) return;
const rel = loc.pathname.slice(base.length) + loc.search;
if (rel === graphSrc(parseHash().q)) return;
const hq = parseHash().q;
/* the same page, unless its 3D comes only from this viewer's stored choice: then the hash says
view=3d too, so a copied link opens the same mode */
if (rel === graphSrc(hq) && (hq.view || hq.src || !/[?&]view=3d(&|$)/.test(rel))) return;
history.replaceState(null, '', '#/graph?src=' + encodeURIComponent(rel));
const t = graphTabOf(rel);
document.querySelectorAll('.chips [role="tab"]').forEach((a) => {
+21
View File
@@ -102,3 +102,24 @@ ol.g-refs { list-style: decimal; padding-left: 20px; }
border: 2px solid var(--at-border); border-top-color: var(--at-text-muted); animation: g-spin 1s linear infinite; }
@keyframes g-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .g-msg[data-building]::before { animation: none; } }
/* ── the optional 3D view (graph3d.js): a dark canvas in BOTH themes, as legal-memory's — a glow
only reads on dark, and the family chart colours in their dark-theme shades ── */
:root { --g3-bg: #0b0d14; --g3-fg: #f1f3f5; --g3-dim: #868e96; --g3-c1: #b197fc; --g3-c2: #63e6be; --g3-c3: #ffa94d; }
.g-mode { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin: 4px 0 8px; }
.g-seg { display: inline-flex; border: 1px solid var(--at-border); border-radius: var(--at-radius-full); padding: 2px; background: var(--at-surface); }
.g-seg button { font: inherit; font-size: 12px; font-weight: 600; min-width: 44px; padding: 4px 12px; border: 0; border-radius: var(--at-radius-full);
background: transparent; color: var(--at-text-muted); cursor: pointer; }
.g-seg button[aria-checked="true"] { background: var(--at-text); color: var(--at-surface); }
.g-seg button:focus-visible { outline: 2px solid var(--at-text); outline-offset: 2px; }
.g-3d-wrap { position: relative; }
.g-3d-wrap[hidden] { display: none; }
.g-3d { background: var(--g3-bg); border-color: #20232e; overflow: hidden; }
.g-3d-wrap .g-tool { background: rgba(20,23,32,.85); color: #e9ecef; border-color: #2c303c; }
.g-3d-wrap .g-tool:hover { background: #2c303c; }
.g-3d-wrap .g-tip { background: rgba(8,10,16,.92); color: #e9ecef; border-color: #2c303c; }
.g-3d-note { position: absolute; left: 12px; bottom: 10px; z-index: 2; font-size: 11px; color: #adb5bd; pointer-events: none; }
.g-3d-key { position: absolute; left: 12px; top: 10px; z-index: 2; display: flex; flex-direction: column; gap: 3px; font-size: 11px; color: #ced4da; pointer-events: none; }
.g-3d-key i { display: inline-block; width: 9px; height: 9px; border-radius: 50%; margin-right: 6px; vertical-align: -1px; box-shadow: 0 0 6px currentColor; }
.g-3d-msg { position: absolute; inset: 0; display: grid; place-items: center; color: #ced4da; font-size: 13px; padding: 24px; text-align: center; }
#view.is-3d > .g-meta, #view.is-3d > .g-legend, #view.is-3d > .g-stage, #view.is-3d > #cy, #view.is-3d > .g-msg { display: none; }
+257 -4
View File
@@ -305,6 +305,8 @@
if (resizer) { resizer.disconnect(); resizer = null; }
if (cy) { cy.destroy(); cy = null; }
if (!data || !box || !window.cytoscape) return;
rendered2d = true;
if (mode === '3d') { rendered2d = false; return; } /* 2D is drawn lazily, on the way back */
var g;
/* a <template>, not a <script type="application/json">: htmx (allowScriptTags:false) drops script
elements from swapped HTML, so every "Pokaż" used to swap in a graph with no data to draw */
@@ -361,9 +363,11 @@
openCentre = false;
window.htmx.ajax('GET', 'panel?node=' + encodeURIComponent(g.center) + kindQuery(), { target: '#panel', swap: 'innerHTML' });
}
if (selected && cy.getElementById(selected).length) cy.getElementById(selected).select();
cy.on('tap', 'node', function (evt) {
if (!window.htmx) return;
var id = evt.target.id();
selected = id;
if (!window.htmx) return;
window.htmx.ajax('GET', g.kind === 'acts' ? 'acts/panel?eli=' + encodeURIComponent(id)
: 'panel?node=' + encodeURIComponent(id) + kindQuery(), { target: '#panel', swap: 'innerHTML' });
});
@@ -384,6 +388,240 @@
}
}
/* ── the optional 3D view (graph3d.js) ─────────────────────────────────────────────────
On the act-structure and links-between-acts pages, a "2D | 3D" switch. 2D (Cytoscape) is the
default and stays the view for analysis. Nothing 3D loads until a viewer picks 3D: then three.js,
its bloom pass, 3d-force-graph and graph3d.js are fetched (same-origin, vendor/) and the data
comes from act/3d or acts/3d (JSON, capped in Python). The choice is remembered per viewer
(localStorage, default 2D) and mirrored in the URL (&view=3d) so a link opens the same mode;
the side panel and the selected node survive the switch; going back to 2D disposes the WebGL
renderer, the scene and the animation loop. */
var VIEW_KEY = 'insider_graph_view';
var SCRIPT_BASE = (document.currentScript && document.currentScript.src)
? new URL('.', document.currentScript.src).href : new URL('../', location.href).href;
var mode = '2d', three = null, rendered2d = false, selected = null, libP = null, mountSeq = 0;
function storedView() {
try { return localStorage.getItem(VIEW_KEY) === '3d' ? '3d' : '2d'; } catch (e) { return '2d'; }
}
function urlView() {
var m = /[?&]view=(2d|3d)(&|$)/.exec(location.search);
return m ? m[1] : null;
}
function hasWebGL() {
try {
var c = document.createElement('canvas');
return !!(window.WebGLRenderingContext && (c.getContext('webgl2') || c.getContext('webgl')));
} catch (e) { return false; }
}
function loadScript(src) {
return new Promise(function (ok, fail) {
var s = document.createElement('script');
s.src = src; s.async = false;
s.onload = ok; s.onerror = function () { fail(new Error(src)); };
document.head.appendChild(s);
});
}
/* three.js first: 3d-force-graph reads window.THREE when it evaluates — ONE three.js, not two */
function libs() {
if (libP) return libP;
libP = import(SCRIPT_BASE + 'vendor/three-0.183.0/three.module.min.js').then(function (T) {
window.THREE = T;
return Promise.all([
import(SCRIPT_BASE + 'vendor/three-0.183.0/jsm/postprocessing/UnrealBloomPass.js').catch(function () { return null; }),
loadScript(SCRIPT_BASE + 'vendor/3d-force-graph-1.80.0.min.js'),
loadScript(SCRIPT_BASE + 'graph3d.js')]);
}).then(function (r) { return { Bloom: r[0] && r[0].UnrealBloomPass }; }); /* no bloom: halos */
libP.catch(function () { libP = null; });
return libP;
}
function remember(m) {
try { localStorage.setItem(VIEW_KEY, m); } catch (e) { /* blocked: the URL still carries it */ }
try {
var u = new URL(location.href);
if (m === '3d') u.searchParams.set('view', '3d'); else u.searchParams.delete('view');
history.replaceState(history.state, '', u.pathname + u.search + u.hash);
} catch (e) { /* sandboxed */ }
try {
if (window.frameElement) window.frameElement.dispatchEvent(new CustomEvent('graphview', { detail: m }));
} catch (e) { /* not same-origin */ }
}
function dispose3d() {
mountSeq++;
if (three) { three.dispose(); three = null; }
}
function seg(host) {
var s = el('div', 'g-seg');
s.setAttribute('role', 'radiogroup'); s.setAttribute('aria-label', 'Widok grafu');
[['2d', '2D', 'Widok 2D'], ['3d', '3D', 'Widok 3D']].forEach(function (x) {
var b = el('button', null, x[1]);
b.type = 'button'; b.dataset.mode = x[0]; b.title = x[2];
b.setAttribute('role', 'radio'); b.setAttribute('aria-label', x[2]);
b.addEventListener('click', function () { setMode(x[0]); });
b.addEventListener('keydown', function (e) {
if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].indexOf(e.key) < 0) return;
e.preventDefault();
var to = mode === '3d' ? '2d' : '3d';
setMode(to);
var nb = s.querySelector('[data-mode="' + to + '"]');
if (nb) nb.focus();
});
s.appendChild(b);
});
host.appendChild(s);
if (LANG !== 'pl') localize(host);
return s;
}
function paintSeg() {
var host = document.querySelector('.g-mode');
if (!host) return;
var bs = host.querySelectorAll('.g-seg button');
for (var i = 0; i < bs.length; i++) {
var on = bs[i].dataset.mode === mode;
bs[i].setAttribute('aria-checked', String(on));
bs[i].tabIndex = on ? 0 : -1;
}
}
function wrap3d(host) {
var w = host.parentNode.querySelector('.g-3d-wrap');
if (w) return w;
w = el('div', 'g-3d-wrap'); w.hidden = true;
host.parentNode.insertBefore(w, host.nextSibling);
return w;
}
function clear(x) { while (x.firstChild) x.removeChild(x.firstChild); }
function say3d(w, text) {
clear(w);
var box = el('div', 'g-cy g-3d');
box.appendChild(el('div', 'g-3d-msg', text));
w.appendChild(box);
if (LANG !== 'pl') localize(w);
}
function setMode(m, quiet) {
var host = document.querySelector('.g-mode');
var view = document.getElementById('view');
if (!host || !view) return;
if (m === '3d' && !hasWebGL()) {
m = '2d';
var note = host.querySelector('.g-3d-none') || host.appendChild(el('span', 'g-3d-none faint tiny'));
note.textContent = 'Ta przeglądarka nie obsługuje WebGL — zostaje widok 2D.';
if (LANG !== 'pl') localize(host);
}
var changed = m !== mode;
mode = m;
paintSeg();
if (!quiet && changed) remember(m);
var w = wrap3d(host);
if (m === '2d') {
dispose3d();
w.hidden = true;
clear(w);
view.classList.remove('is-3d');
if (!rendered2d) render();
else if (cy) {
cy.resize(); fit(false);
cy.$(':selected').unselect();
if (selected && cy.getElementById(selected).length) cy.getElementById(selected).select();
}
return;
}
view.classList.add('is-3d');
w.hidden = false;
if (three) return;
say3d(w, 'Ładowanie widoku 3D…');
var seq = ++mountSeq;
var data = fetch(host.dataset['3d'], { credentials: 'same-origin', headers: { Accept: 'application/json' } })
.then(function (r) { return r.json(); });
Promise.all([(window.__graph3dLibs || libs)(), data]).then(function (got) { /* replaceable in tests */
if (seq !== mountSeq || mode !== '3d') return;
var body = got[1] || {};
if (!body.graph) { say3d(w, body.error || 'Nie udało się wczytać widoku 3D — zostaje widok 2D.'); return; }
mount3d(w, body.graph, got[0]);
}).catch(function () {
if (seq === mountSeq) say3d(w, 'Nie udało się wczytać widoku 3D — zostaje widok 2D.');
});
}
function mount3d(w, g, post) {
clear(w);
var box = el('div', 'g-cy g-3d');
box.setAttribute('role', 'img');
box.setAttribute('aria-label', g.kind === 'structure' ? 'Struktura aktu w 3D' : 'Graf powiązań między aktami w 3D');
w.appendChild(box);
var tip = el('div', 'g-tip'); tip.setAttribute('role', 'tooltip'); tip.hidden = true;
var tools = el('div', 'g-tools');
var key = el('div', 'g-3d-key');
var K = g.kind === 'structure'
? [['--g3-fg', 'akt'], ['--g3-c1', 'działy i rozdziały'], ['--g3-c1', 'artykuły (wielkość = cytowania)'],
['--g3-c2', 'akty powiązane']].concat(g.nodes.some(function (n) { return n.t === 'case'; }) ? [['--g3-c3', 'orzeczenia cytujące']] : [])
: [['--g3-c1', 'akty (wielkość = PageRank)'], ['--g3-c2', 'rozporządzenia'], ['--g3-c3', 'akty UE']];
K.forEach(function (k) {
var row = el('div'), i = el('i');
i.style.color = 'var(' + k[0] + ')'; i.style.background = 'var(' + k[0] + ')';
row.appendChild(i); row.appendChild(el('span', null, k[1])); key.appendChild(row);
});
var shown = g.kind === 'structure' ? g.shown : g.nodes.length;
var total = g.kind === 'structure' ? g.total : g.nodes.length;
var note = el('div', 'g-3d-note', (g.truncated
? 'pokazano ' + shown + (g.kind === 'structure' ? ' z ' + total : '') + ' węzłów (limit ' + g.cap + ')'
: shown + ' węzłów') + ' · ' + g.edges.length + ' krawędzi');
w.appendChild(tools); w.appendChild(key); w.appendChild(note); w.appendChild(tip);
var mx = 0, my = 0;
function place() {
tip.style.left = Math.min(box.clientWidth - 40, mx + 14) + 'px';
tip.style.top = Math.max(8, my - 10) + 'px';
}
box.addEventListener('mousemove', function (e) {
var r = box.getBoundingClientRect(); mx = e.clientX - r.left; my = e.clientY - r.top;
if (!tip.hidden) place();
});
three = window.Graph3D.mount(box, g, {
Bloom: post.Bloom,
onHover: function (n) {
if (!n) { tip.hidden = true; return; }
tip.textContent = '';
tip.appendChild(el('b', null, n.title || n.label || n.id));
var info = n.t === 'art' ? 'cytowany przez ' + (n.cited_by || 0) + ' · odwołania ' + (n.refs_out || 0)
: n.t === 'unit' ? (n.arts || 0) + ' art.' : n.t === 'linked' ? n.weight + ' odesłań'
: n.w_in != null ? (n.w_in || 0) + ' ← · → ' + (n.w_out || 0) : '';
if (info) tip.appendChild(el('div', 'faint', info));
place();
tip.hidden = false;
},
onSelect: function (n) {
selected = n.id;
if (!window.htmx) return;
var url = n.t === 'art' ? 'panel?node=' + encodeURIComponent(n.id) + kindQuery()
: (n.t === 'act' || n.t === 'linked' || g.kind !== 'structure') ? 'acts/panel?eli=' + encodeURIComponent(n.id) : null;
if (url) window.htmx.ajax('GET', url, { target: '#panel', swap: 'innerHTML' });
}
});
if (selected) three.select(selected);
tools.appendChild(tool('⤢', 'Dopasuj do okna', function () { if (three) three.fit(); }));
tools.appendChild(tool('⌂', 'Resetuj kamerę', function () { if (three) three.reset(); }));
if (LANG !== 'pl') localize(w);
}
/* After every page load and swap of #view: the switch (where the page has one) in its mode. */
function initMode() {
var host = document.querySelector('.g-mode');
var want = mode;
dispose3d();
if (!host) { mode = '2d'; return; }
if (!host.querySelector('.g-seg')) seg(host);
mode = '2d';
if (want === '3d') setMode('3d', true); else paintSeg();
}
/* the console's own "2D | 3D" (app.js) drives the framed page through these */
window.setGraphView = function (m) { if (m === '2d' || m === '3d') setMode(m); return mode; };
window.graphView = function () { return mode; };
/* hop = BFS distance from the centre, undirected, for the neighbourhood's rings */
function hops(els, center) {
var adj = {}, hop = {};
@@ -449,7 +687,14 @@
'Graf odesłań między artykułami': 'Graph of references between articles',
'Powiększ': 'Zoom in', 'Pomniejsz': 'Zoom out', 'Dopasuj do okna': 'Fit to view', 'Ułóż od nowa': 'Re-run the layout',
'ustawy i inne akty': 'statutes and other acts', 'rozporządzenia': 'regulations', 'akty UE': 'EU acts',
'ten akt': 'this act', 'inne akty': 'other acts'
'ten akt': 'this act', 'inne akty': 'other acts',
'Widok 3D': '3D view', 'Widok 2D': '2D view', 'Widok grafu': 'Graph view',
'Resetuj kamerę': 'Reset the camera', 'Ładowanie widoku 3D…': 'Loading the 3D view…',
'Ta przeglądarka nie obsługuje WebGL — zostaje widok 2D.': 'This browser has no WebGL — staying in 2D.',
'Nie udało się wczytać widoku 3D — zostaje widok 2D.': 'The 3D view could not be loaded — staying in 2D.',
'akt': 'the act', 'działy i rozdziały': 'parts and chapters', 'artykuły (wielkość = cytowania)': 'articles (size = citations)',
'akty powiązane': 'linked acts', 'orzeczenia cytujące': 'citing judgments', 'akty (wielkość = PageRank)': 'acts (size = PageRank)',
'Struktura aktu w 3D': 'Act structure in 3D', 'Graf powiązań między aktami w 3D': 'Graph of links between acts in 3D'
};
var LANG = 'pl';
try { LANG = localStorage.getItem('insider_lang') === 'en' ? 'en' : 'pl'; } catch (e) { /* blocked */ }
@@ -501,8 +746,16 @@
window.addEventListener('storage', function (e) {
if (e.key === 'insider_lang' && e.newValue) window.applyLang(e.newValue);
});
document.addEventListener('DOMContentLoaded', render);
function boot() {
var host = document.querySelector('.g-mode');
var want = !!host && (urlView() || storedView()) === '3d' && hasWebGL();
mode = want ? '3d' : '2d'; /* so render() leaves 2D for later instead of laying it out */
rendered2d = false;
render();
initMode();
}
document.addEventListener('DOMContentLoaded', boot);
document.addEventListener('htmx:afterSettle', function (evt) {
if (evt.target && (evt.target.id === 'view' || evt.target.querySelector && evt.target.querySelector('#graph-data'))) render();
if (evt.target && (evt.target.id === 'view' || evt.target.querySelector && evt.target.querySelector('#graph-data'))) boot();
});
})();
+366
View File
@@ -0,0 +1,366 @@
/* The reference graph's OPTIONAL 3D view (legal-memory's "burst"), loaded by graph.js only when a
viewer picks "3D" — never on page load. Same-origin, no eval, no innerHTML: three.js 0.183.0 (ES
module, MIT) and 3d-force-graph 1.80.0 (UMD, MIT) from frontend/vendor/, the glow from three's own
UnrealBloomPass (GLSL shaders compiled by WebGL — not JavaScript, so the CSP needs nothing new).
3d-force-graph's own HTML tooltips (nodeLabel/linkLabel set innerHTML) stay OFF; the tooltip is
graph.js's .g-tip, filled with textContent.
Python decides what is drawn (routers/graph.py `/act/3d`, `/acts/3d`, ≤ VIEW3D_NODES nodes); this
file only draws it: window.Graph3D.mount(box, graph, hooks) → { dispose, fit, reset, select }. */
(function () {
'use strict';
var THREE = window.THREE;
/* A dark canvas in both themes, as legal-memory: a glow only reads on dark (on a light canvas
bloom washes out to grey), and the palette is the family's chart set in its dark-theme shades. */
function palette() {
var cs = getComputedStyle(document.documentElement);
function v(n, f) { return (cs.getPropertyValue(n) || '').trim() || f; }
return { bg: v('--g3-bg', '#0b0d14'), fg: v('--g3-fg', '#e9ecef'), dim: v('--g3-dim', '#868e96'),
c1: v('--g3-c1', '#b197fc'), c2: v('--g3-c2', '#63e6be'), c3: v('--g3-c3', '#ffa94d'),
font: v('--at-font-sans', 'system-ui, sans-serif') };
}
var SPHERE = null, SPHERE_LO = null, HALO = null;
function haloTexture() {
if (HALO) return HALO;
var c = document.createElement('canvas'); c.width = c.height = 64;
var x = c.getContext('2d'), g = x.createRadialGradient(32, 32, 0, 32, 32, 32);
g.addColorStop(0, 'rgba(255,255,255,0.9)'); g.addColorStop(0.25, 'rgba(255,255,255,0.35)');
g.addColorStop(1, 'rgba(255,255,255,0)');
x.fillStyle = g; x.fillRect(0, 0, 64, 64);
HALO = new THREE.CanvasTexture(c);
return HALO;
}
function textSprite(text, color, font, px) {
var c = document.createElement('canvas'), x = c.getContext('2d'), f = '600 ' + px * 4 + 'px ' + font;
x.font = f;
var w = Math.ceil(x.measureText(text).width) + 24, h = px * 4 + 20;
c.width = w; c.height = h;
x.font = f; x.textBaseline = 'middle';
x.fillStyle = 'rgba(8,10,16,0.72)';
x.fillRect(0, 0, w, h);
x.fillStyle = color; x.fillText(text, 12, h / 2);
var t = new THREE.CanvasTexture(c); t.minFilter = THREE.LinearFilter;
var s = new THREE.Sprite(new THREE.SpriteMaterial({ map: t, depthWrite: false, depthTest: false, transparent: true }));
s.scale.set(w / 16, h / 16, 1);
s.renderOrder = 10;
return s;
}
function cut(s, n) { s = String(s || ''); return s.length > n ? s.slice(0, n - 1) + '…' : s; }
/* ── what each node is: colour, size, layer ─────────────────────────────────────────── */
function prepare(g, p) {
var max = 0;
var nodes = g.nodes.map(function (n) { return Object.assign({}, n); });
var byId = {};
nodes.forEach(function (n) { byId[n.id] = n; });
if (g.kind === 'structure') {
nodes.forEach(function (n) { if (n.t === 'art') max = Math.max(max, n.cited_by || 0); });
var wmax = 1;
nodes.forEach(function (n) { if (n.t === 'linked') wmax = Math.max(wmax, n.weight || 1); });
nodes.forEach(function (n) {
if (n.t === 'act') { n.r = 6; n.col = p.fg; n.score = 1e9; n.fx = 0; n.fy = 0; n.fz = 0; }
else if (n.t === 'unit') { n.r = 2.2 + 3.2 * Math.sqrt(Math.min(1, (n.arts || 1) / 120)) - 0.35 * (n.lvl - 1);
n.col = p.c1; n.score = 1e6 / n.lvl + (n.arts || 0); }
else if (n.t === 'art') { n.r = 0.9 + (max ? 3.4 * Math.sqrt((n.cited_by || 0) / max) : 0); n.col = p.c1; n.score = n.cited_by || 0; }
else if (n.t === 'linked') { n.r = 1.4 + 2.4 * Math.sqrt((n.weight || 1) / wmax); n.col = p.c2; n.score = 5e5 + (n.weight || 0); n.outer = 1; }
else { n.r = 0.7; n.col = p.c3; n.score = 0; n.outer = 2; }
});
} else {
nodes.forEach(function (n) { max = Math.max(max, n.rank || 0); });
nodes.forEach(function (n) {
n.r = max ? 1.5 + 7 * Math.sqrt((n.rank || 0) / max) : 2.5;
n.col = /^(EU|CELEX|OJ)\b/i.test(n.id) || /\((UE|WE|EWG|Euratom)\)/.test(n.title || '') ? p.c3
: /^rozporządzenie/i.test(n.title || '') ? p.c2 : p.c1;
n.score = n.rank || 0;
if (n.id === g.center) { n.fx = 0; n.fy = 0; n.fz = 0; }
});
}
var links = g.edges.filter(function (e) { return byId[e.source] && byId[e.target]; }).map(function (e) {
return Object.assign({ t: g.kind === 'structure' ? e.t : (e.delegation ? 'deleg' : 'ref') }, e);
});
return { nodes: nodes, links: links, byId: byId };
}
/* An outer layer: linked acts (and, further out, case-law particles) kept near a sphere around the
act, the radius following the structure's own spread — a d3-style custom force, no d3 needed. */
function shellForce(data) {
var nodes = [];
function f(alpha) {
var R = 0, k = 0;
data.nodes.forEach(function (n) { if (!n.outer && n.x !== undefined) { R = Math.max(R, Math.hypot(n.x, n.y, n.z)); } });
R = Math.max(R * 1.25, 120);
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i], d = Math.hypot(n.x, n.y, n.z) || 1, want = n.outer === 2 ? R * 1.18 : R;
k = (want - d) / d * alpha * 0.25;
n.vx += n.x * k; n.vy += n.y * k; n.vz += n.z * k;
}
}
f.initialize = function (ns) { nodes = ns.filter(function (n) { return n.outer; }); };
return f;
}
function mount(box, g, hooks) {
hooks = hooks || {};
var p = palette();
var reduced = !!(window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches);
var data = prepare(g, p);
SPHERE = SPHERE || new THREE.SphereGeometry(1, 14, 10);
SPHERE_LO = SPHERE_LO || new THREE.SphereGeometry(1, 7, 5); /* the small majority: a fifth of the triangles */
var mats = {}, hlMats = {};
function mat(col, hl) {
var cache = hl ? hlMats : mats;
if (!cache[col]) {
/* the colour pushed ABOVE 1.0: the excess is what the bloom turns into a corona — the
"stars" look (legal-memory's NodeCloud boost); without bloom it just clamps to the hue */
var c = new THREE.Color(col), br = (c.r + c.g + c.b) / 3;
c.multiplyScalar((1.2 + br * 0.8) * (hl ? 1.5 : 1));
cache[col] = new THREE.MeshBasicMaterial({ color: c, transparent: true, opacity: 1, toneMapped: false });
}
return cache[col];
}
var haloMats = {};
function haloMat(col) {
if (!haloMats[col]) haloMats[col] = new THREE.SpriteMaterial({ map: haloTexture(), color: new THREE.Color(col),
transparent: true, opacity: 0.55, depthWrite: false, blending: THREE.AdditiveBlending });
return haloMats[col];
}
/* labels: the top-N by size always, the rest on hover / focus */
var ranked = data.nodes.slice().sort(function (a, b) { return b.score - a.score; });
var TOPN = g.kind === 'structure' ? 12 : 20, topSet = {};
ranked.slice(0, TOPN).forEach(function (n) { topSet[n.id] = 1; });
var haloSet = {};
ranked.slice(0, 400).forEach(function (n) { haloSet[n.id] = 1; });
function nodeObject(n) {
var grp = new THREE.Group();
var m = new THREE.Mesh(n.r < 2.2 ? SPHERE_LO : SPHERE, mat(n.col)); m.scale.setScalar(n.r);
grp.add(m); n.__mesh = m;
if (!hooks.Bloom && (haloSet[n.id] || n.t === 'act')) { /* the fallback glow */
var h = new THREE.Sprite(haloMat(n.col)); h.scale.setScalar(n.r * 4.2); grp.add(h);
}
if (topSet[n.id]) showLabel(n, grp);
n.__grp = grp;
return grp;
}
function showLabel(n, grp) {
grp = grp || n.__grp;
if (!grp || n.__label) return;
var s = textSprite(cut(n.label || n.id, 42), n.t === 'act' ? p.fg : '#f1f3f5', p.font, n.t === 'act' ? 13 : 10);
s.position.set(0, n.r + 3.2, 0);
grp.add(s); n.__label = s;
}
function hideLabel(n) {
if (!n.__label || topSet[n.id] || n.id === selected) return;
n.__grp.remove(n.__label); n.__label.material.map.dispose(); n.__label.material.dispose(); n.__label = null;
}
/* an edge's weight is its colour's INTENSITY, not an alpha: with additive blending overlapping
lines add up to a glow along the branches, and a lone reference stays a faint thread */
function dim(hex, k) { return new THREE.Color(hex).multiplyScalar(k).getStyle(); }
var LC = { tree: dim(p.c1, 0.32), ref: dim(p.c3, 0.2), link: dim(p.c2, 0.3), case: dim(p.c3, 0.25),
deleg: dim(p.c1, 0.55), hl: dim('#ffffff', 0.9) };
function patchLinks() {
scene.traverse(function (o) {
var m = o.material;
if (m && (o.isLine || o.type === 'Line' || o.type === 'LineSegments') && !m.__glow) {
m.blending = THREE.AdditiveBlending; m.transparent = true; m.depthWrite = false;
m.toneMapped = false; m.__glow = true; m.needsUpdate = true;
}
});
}
var hover = null, hoverLinks = new Set(), hoverNodes = new Set(), selected = null;
var Graph = window.ForceGraph3D({ controlType: 'orbit', rendererConfig: { antialias: true, alpha: false, powerPreference: 'high-performance' } })(box)
.width(box.clientWidth).height(box.clientHeight)
.backgroundColor(p.bg)
.showNavInfo(false)
.nodeLabel(null).linkLabel(null)
.nodeId('id')
.nodeThreeObject(nodeObject)
.nodeThreeObjectExtend(false)
.linkColor(function (l) {
if (hover && hoverLinks.has(l)) return LC.hl;
return LC[l.t] || LC.ref;
})
.linkWidth(function (l) { return hover && hoverLinks.has(l) ? 0.6 : (l.t === 'deleg' ? 0.5 : 0); })
.linkOpacity(1)
/* every edge is drawn by ONE merged LineSegments (below): 3d-force-graph would make one
draw call per edge (5,500 at the cap). Its own link objects exist only for the hovered
node's edges, which carry the highlight and the directional particles. */
.linkVisibility(function (l) { return !!hover && hoverLinks.has(l); })
.linkDirectionalParticles(function (l) { return !reduced && hover && hoverLinks.has(l) && l.t !== 'tree' ? 3 : 0; })
.linkDirectionalParticleWidth(1.6)
.linkDirectionalParticleSpeed(0.008)
.linkDirectionalParticleColor(function () { return '#ffffff'; })
.warmupTicks(g.kind === 'structure' ? 60 : 30)
.cooldownTicks(reduced ? 80 : 220)
.d3VelocityDecay(0.32)
.enableNodeDrag(false)
.graphData({ nodes: data.nodes, links: data.links });
var link = Graph.d3Force('link');
if (link) {
link.distance(function (l) {
return l.t === 'tree' ? (l.target.t === 'art' ? 9 : 26) : l.t === 'link' ? 140 : l.t === 'case' ? 40 : 60;
}).strength(function (l) { return l.t === 'tree' ? 0.9 : l.t === 'ref' ? 0.02 : l.t === 'case' ? 0.2 : 0.5; });
}
var charge = Graph.d3Force('charge');
if (charge) charge.strength(function (n) { return n.t === 'art' || n.t === 'case' ? -8 : -60; });
if (g.kind === 'structure') Graph.d3Force('shell', shellForce(data));
var scene = Graph.scene(), renderer = Graph.renderer(), controls = Graph.controls();
scene.fog = new THREE.FogExp2(p.bg, 0.0011);
var segPos = new Float32Array(data.links.length * 6), segCol = new Float32Array(data.links.length * 6);
data.links.forEach(function (l, i) {
var c = new THREE.Color(LC[l.t] || LC.ref);
segCol.set([c.r, c.g, c.b, c.r, c.g, c.b], i * 6);
});
var segGeo = new THREE.BufferGeometry();
segGeo.setAttribute('position', new THREE.BufferAttribute(segPos, 3));
segGeo.setAttribute('color', new THREE.BufferAttribute(segCol, 3));
var segMat = new THREE.LineBasicMaterial({ vertexColors: true, transparent: true, depthWrite: false,
blending: THREE.AdditiveBlending, toneMapped: false });
var segs = new THREE.LineSegments(segGeo, segMat);
segs.frustumCulled = false;
scene.add(segs);
function syncSegs() {
data.links.forEach(function (l, i) {
var a = l.source, b = l.target;
if (typeof a !== 'object' || a.x === undefined) return;
segPos[i * 6] = a.x; segPos[i * 6 + 1] = a.y; segPos[i * 6 + 2] = a.z;
segPos[i * 6 + 3] = b.x; segPos[i * 6 + 4] = b.y; segPos[i * 6 + 5] = b.z;
});
segGeo.attributes.position.needsUpdate = true;
}
var bloom = null;
if (hooks.Bloom) {
bloom = new hooks.Bloom(new THREE.Vector2(box.clientWidth, box.clientHeight), 1.0, 0.55, 0.3);
Graph.postProcessingComposer().addPass(bloom);
/* measured: through 3d-force-graph's composer the colours already arrive encoded, so an sRGB
output here would encode them twice (the background turns slate grey) */
renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
}
/* slow auto-rotation that stops on the first interaction and never runs under reduced motion */
if (controls) {
controls.autoRotate = !reduced; controls.autoRotateSpeed = 0.45;
controls.enableDamping = !reduced;
controls.addEventListener('start', function () { controls.autoRotate = false; });
}
var fitted = false;
/* a first frame right away from the warm-up layout (a background tab ticks the engine slowly, so
waiting for its stop could leave the camera at its default distance) */
var framed = false;
Graph.onEngineTick(function () {
syncSegs();
if (framed) return;
var far = 0;
data.nodes.forEach(function (n) { if (n.x !== undefined) far = Math.max(far, Math.hypot(n.x, n.y, n.z)); });
if (far > 20) { framed = true; fit(0); patchLinks(); }
});
Graph.onEngineStop(function () {
syncSegs();
patchLinks();
if (!fitted) { fitted = true; fit(reduced ? 0 : 700); }
var R = 1;
data.nodes.forEach(function (n) { R = Math.max(R, Math.hypot(n.x || 0, n.y || 0, n.z || 0)); });
scene.fog.density = 0.32 / R; /* the far side fades, the near side stays crisp */
});
function setHover(n) {
if (hover === n) return;
if (hover) { hoverNodes.forEach(function (x) { if (x.__mesh) x.__mesh.material = mat(x.col); hideLabel(x); }); }
hoverLinks = new Set(); hoverNodes = new Set();
hover = n || null;
Object.keys(mats).forEach(function (k) { mats[k].opacity = hover ? 0.18 : 1; });
segMat.opacity = hover ? 0.25 : 1;
if (hover) {
hoverNodes.add(hover);
data.links.forEach(function (l) {
if (l.source === hover || l.target === hover) { hoverLinks.add(l); hoverNodes.add(l.source); hoverNodes.add(l.target); }
});
hoverNodes.forEach(function (x) { if (x.__mesh) x.__mesh.material = mat(x.col, true); });
showLabel(hover);
}
Graph.linkVisibility(Graph.linkVisibility()).linkColor(Graph.linkColor()).linkWidth(Graph.linkWidth())
.linkDirectionalParticles(Graph.linkDirectionalParticles());
patchLinks();
box.style.cursor = hover ? 'pointer' : '';
if (hooks.onHover) hooks.onHover(hover);
}
Graph.onNodeHover(function (n) { setHover(n); });
var lastClick = { id: null, at: 0 };
Graph.onNodeClick(function (n) {
if (controls) controls.autoRotate = false;
var now = Date.now();
if (lastClick.id === n.id && now - lastClick.at < 400) { focus(n); lastClick.id = null; return; }
lastClick = { id: n.id, at: now };
select(n.id);
if (hooks.onSelect) hooks.onSelect(n);
});
Graph.onBackgroundClick(function () { if (controls) controls.autoRotate = false; });
function focus(n) {
var d = 40 + n.r * 6, len = Math.hypot(n.x, n.y, n.z) || 1, k = 1 + d / len;
Graph.cameraPosition({ x: n.x * k, y: n.y * k, z: n.z * k }, n, reduced ? 0 : 900);
}
/* frame the core, not the outliers: the 92nd percentile of the distance from the centre (a few
far linked acts would otherwise leave the burst the size of a stamp) */
function fit(ms) {
var d = data.nodes.map(function (n) { return Math.hypot(n.x || 0, n.y || 0, n.z || 0); }).sort(function (a, b) { return a - b; });
var r = Math.max(30, d[Math.floor(d.length * 0.92)] || 0);
var cam = Graph.camera(), fov = (cam.fov || 50) * Math.PI / 360;
var aspect = Math.min(1, box.clientWidth / Math.max(1, box.clientHeight));
var dist = r / Math.sin(Math.atan(Math.tan(fov) * aspect)) * 1.05;
var p = Graph.cameraPosition(), len = Math.hypot(p.x, p.y, p.z) || 1;
Graph.cameraPosition({ x: p.x / len * dist, y: p.y / len * dist, z: p.z / len * dist }, { x: 0, y: 0, z: 0 },
ms === undefined ? (reduced ? 0 : 600) : ms);
}
function reset() { /* back to the opening view: on the z axis, the whole burst in frame */
if (controls) controls.autoRotate = false;
Graph.cameraPosition({ x: 0, y: 0, z: 1 }, { x: 0, y: 0, z: 0 }, 0);
fit();
}
function select(id) {
var prev = selected && data.byId[selected];
selected = id;
if (prev && prev.id !== id) hideLabel(prev);
var n = data.byId[id];
if (n) showLabel(n);
return !!n;
}
/* one tooltip position per frame from the hovered node's screen position */
var ro = window.ResizeObserver ? new ResizeObserver(function () {
Graph.width(box.clientWidth).height(box.clientHeight);
if (bloom) bloom.setSize(box.clientWidth, box.clientHeight);
}) : null;
if (ro) ro.observe(box);
function dispose() {
segGeo.dispose(); segMat.dispose();
if (ro) ro.disconnect();
try { Graph.pauseAnimation(); } catch (e) { /* already gone */ }
try { Graph._destructor(); } catch (e) { /* older builds */ }
scene.traverse(function (o) {
if (o.geometry && o.geometry !== SPHERE && o.geometry !== SPHERE_LO) o.geometry.dispose();
if (o.material && o.material.map && o.material.map !== HALO) o.material.map.dispose();
});
Object.keys(mats).concat(Object.keys(hlMats)).forEach(function (k) { (mats[k] || hlMats[k]).dispose(); });
Object.keys(haloMats).forEach(function (k) { haloMats[k].dispose(); });
if (bloom) bloom.dispose();
try { renderer.dispose(); renderer.forceContextLoss(); } catch (e) { /* lost already */ }
if (renderer.domElement && renderer.domElement.parentNode) renderer.domElement.parentNode.removeChild(renderer.domElement);
while (box.firstChild) box.removeChild(box.firstChild);
window.Graph3D.live = null;
}
var api = { dispose: dispose, fit: function () { fit(); }, reset: reset, select: select, focus: function (id) {
var n = data.byId[id]; if (n) focus(n); }, graph: Graph, nodes: data.nodes.length,
screen: function (n) { var c = Graph.graph2ScreenCoords(n.x, n.y, n.z); return c; } };
window.Graph3D.live = api;
return api;
}
window.Graph3D = { mount: mount, live: null };
})();
File diff suppressed because one or more lines are too long
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Vasco Asturiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
The MIT License
Copyright © 2010-2026 three.js authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+191
View File
@@ -0,0 +1,191 @@
import {
BufferGeometry,
Float32BufferAttribute,
OrthographicCamera,
Mesh
} from '../../three.module.min.js';
/**
* Abstract base class for all post processing passes.
*
* This module is only relevant for post processing with {@link WebGLRenderer}.
*
* @abstract
* @three_import import { Pass } from 'three/addons/postprocessing/Pass.js';
*/
class Pass {
/**
* Constructs a new pass.
*/
constructor() {
/**
* This flag can be used for type testing.
*
* @type {boolean}
* @readonly
* @default true
*/
this.isPass = true;
/**
* If set to `true`, the pass is processed by the composer.
*
* @type {boolean}
* @default true
*/
this.enabled = true;
/**
* If set to `true`, the pass indicates to swap read and write buffer after rendering.
*
* @type {boolean}
* @default true
*/
this.needsSwap = true;
/**
* If set to `true`, the pass clears its buffer before rendering
*
* @type {boolean}
* @default false
*/
this.clear = false;
/**
* If set to `true`, the result of the pass is rendered to screen. The last pass in the composers
* pass chain gets automatically rendered to screen, no matter how this property is configured.
*
* @type {boolean}
* @default false
*/
this.renderToScreen = false;
}
/**
* Sets the size of the pass.
*
* @abstract
* @param {number} width - The width to set.
* @param {number} height - The height to set.
*/
setSize( /* width, height */ ) {}
/**
* This method holds the render logic of a pass. It must be implemented in all derived classes.
*
* @abstract
* @param {WebGLRenderer} renderer - The renderer.
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
* destination for the pass.
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
* previous pass from this buffer.
* @param {number} deltaTime - The delta time in seconds.
* @param {boolean} maskActive - Whether masking is active or not.
*/
render( /* renderer, writeBuffer, readBuffer, deltaTime, maskActive */ ) {
console.error( 'THREE.Pass: .render() must be implemented in derived pass.' );
}
/**
* Frees the GPU-related resources allocated by this instance. Call this
* method whenever the pass is no longer used in your app.
*
* @abstract
*/
dispose() {}
}
// Helper for passes that need to fill the viewport with a single quad.
const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
// https://github.com/mrdoob/three.js/pull/21358
class FullscreenTriangleGeometry extends BufferGeometry {
constructor() {
super();
this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) );
}
}
const _geometry = new FullscreenTriangleGeometry();
/**
* This module is a helper for passes which need to render a full
* screen effect which is quite common in context of post processing.
*
* The intended usage is to reuse a single full screen quad for rendering
* subsequent passes by just reassigning the `material` reference.
*
* This module can only be used with {@link WebGLRenderer}.
*
* @augments Mesh
* @three_import import { FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
*/
class FullScreenQuad {
/**
* Constructs a new full screen quad.
*
* @param {?Material} material - The material to render te full screen quad with.
*/
constructor( material ) {
this._mesh = new Mesh( _geometry, material );
}
/**
* Frees the GPU-related resources allocated by this instance. Call this
* method whenever the instance is no longer used in your app.
*/
dispose() {
this._mesh.geometry.dispose();
}
/**
* Renders the full screen quad.
*
* @param {WebGLRenderer} renderer - The renderer.
*/
render( renderer ) {
renderer.render( this._mesh, _camera );
}
/**
* The quad's material.
*
* @type {?Material}
*/
get material() {
return this._mesh.material;
}
set material( value ) {
this._mesh.material = value;
}
}
export { Pass, FullScreenQuad };
@@ -0,0 +1,524 @@
import {
AdditiveBlending,
Color,
HalfFloatType,
MeshBasicMaterial,
ShaderMaterial,
UniformsUtils,
Vector2,
Vector3,
WebGLRenderTarget
} from '../../three.module.min.js';
import { Pass, FullScreenQuad } from './Pass.js';
import { CopyShader } from '../shaders/CopyShader.js';
import { LuminosityHighPassShader } from '../shaders/LuminosityHighPassShader.js';
/**
* This pass is inspired by the bloom pass of Unreal Engine. It creates a
* mip map chain of bloom textures and blurs them with different radii. Because
* of the weighted combination of mips, and because larger blurs are done on
* higher mips, this effect provides good quality and performance.
*
* When using this pass, tone mapping must be enabled in the renderer settings.
*
* Reference:
* - [Bloom in Unreal Engine](https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/Bloom/)
*
* ```js
* const resolution = new THREE.Vector2( window.innerWidth, window.innerHeight );
* const bloomPass = new UnrealBloomPass( resolution, 1.5, 0.4, 0.85 );
* composer.addPass( bloomPass );
* ```
*
* @augments Pass
* @three_import import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
*/
class UnrealBloomPass extends Pass {
/**
* Constructs a new Unreal Bloom pass.
*
* @param {Vector2} [resolution] - The effect's resolution.
* @param {number} [strength=1] - The Bloom strength.
* @param {number} radius - The Bloom radius.
* @param {number} threshold - The luminance threshold limits which bright areas contribute to the Bloom effect.
*/
constructor( resolution, strength = 1, radius, threshold ) {
super();
/**
* The Bloom strength.
*
* @type {number}
* @default 1
*/
this.strength = strength;
/**
* The Bloom radius. Must be in the range `[0,1]`.
*
* @type {number}
*/
this.radius = radius;
/**
* The luminance threshold limits which bright areas contribute to the Bloom effect.
*
* @type {number}
*/
this.threshold = threshold;
/**
* The effect's resolution.
*
* @type {Vector2}
* @default (256,256)
*/
this.resolution = ( resolution !== undefined ) ? new Vector2( resolution.x, resolution.y ) : new Vector2( 256, 256 );
/**
* The effect's clear color
*
* @type {Color}
* @default (0,0,0)
*/
this.clearColor = new Color( 0, 0, 0 );
/**
* Overwritten to disable the swap.
*
* @type {boolean}
* @default false
*/
this.needsSwap = false;
// internals
// render targets
this.renderTargetsHorizontal = [];
this.renderTargetsVertical = [];
this.nMips = 5;
let resx = Math.round( this.resolution.x / 2 );
let resy = Math.round( this.resolution.y / 2 );
this.renderTargetBright = new WebGLRenderTarget( resx, resy, { type: HalfFloatType } );
this.renderTargetBright.texture.name = 'UnrealBloomPass.bright';
this.renderTargetBright.texture.generateMipmaps = false;
for ( let i = 0; i < this.nMips; i ++ ) {
const renderTargetHorizontal = new WebGLRenderTarget( resx, resy, { type: HalfFloatType } );
renderTargetHorizontal.texture.name = 'UnrealBloomPass.h' + i;
renderTargetHorizontal.texture.generateMipmaps = false;
this.renderTargetsHorizontal.push( renderTargetHorizontal );
const renderTargetVertical = new WebGLRenderTarget( resx, resy, { type: HalfFloatType } );
renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i;
renderTargetVertical.texture.generateMipmaps = false;
this.renderTargetsVertical.push( renderTargetVertical );
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
}
// luminosity high pass material
const highPassShader = LuminosityHighPassShader;
this.highPassUniforms = UniformsUtils.clone( highPassShader.uniforms );
this.highPassUniforms[ 'luminosityThreshold' ].value = threshold;
this.highPassUniforms[ 'smoothWidth' ].value = 0.01;
this.materialHighPassFilter = new ShaderMaterial( {
uniforms: this.highPassUniforms,
vertexShader: highPassShader.vertexShader,
fragmentShader: highPassShader.fragmentShader
} );
// gaussian blur materials
this.separableBlurMaterials = [];
// These sizes have been changed to account for the altered coefficients-calculation to avoid blockiness,
// while retaining the same blur-strength. For details see https://github.com/mrdoob/three.js/pull/31528
const kernelSizeArray = [ 6, 10, 14, 18, 22 ];
resx = Math.round( this.resolution.x / 2 );
resy = Math.round( this.resolution.y / 2 );
for ( let i = 0; i < this.nMips; i ++ ) {
this.separableBlurMaterials.push( this._getSeparableBlurMaterial( kernelSizeArray[ i ] ) );
this.separableBlurMaterials[ i ].uniforms[ 'invSize' ].value = new Vector2( 1 / resx, 1 / resy );
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
}
// composite material
this.compositeMaterial = this._getCompositeMaterial( this.nMips );
this.compositeMaterial.uniforms[ 'blurTexture1' ].value = this.renderTargetsVertical[ 0 ].texture;
this.compositeMaterial.uniforms[ 'blurTexture2' ].value = this.renderTargetsVertical[ 1 ].texture;
this.compositeMaterial.uniforms[ 'blurTexture3' ].value = this.renderTargetsVertical[ 2 ].texture;
this.compositeMaterial.uniforms[ 'blurTexture4' ].value = this.renderTargetsVertical[ 3 ].texture;
this.compositeMaterial.uniforms[ 'blurTexture5' ].value = this.renderTargetsVertical[ 4 ].texture;
this.compositeMaterial.uniforms[ 'bloomStrength' ].value = strength;
this.compositeMaterial.uniforms[ 'bloomRadius' ].value = 0.1;
const bloomFactors = [ 1.0, 0.8, 0.6, 0.4, 0.2 ];
this.compositeMaterial.uniforms[ 'bloomFactors' ].value = bloomFactors;
this.bloomTintColors = [ new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ) ];
this.compositeMaterial.uniforms[ 'bloomTintColors' ].value = this.bloomTintColors;
// blend material
this.copyUniforms = UniformsUtils.clone( CopyShader.uniforms );
this.blendMaterial = new ShaderMaterial( {
uniforms: this.copyUniforms,
vertexShader: CopyShader.vertexShader,
fragmentShader: CopyShader.fragmentShader,
premultipliedAlpha: true,
blending: AdditiveBlending,
depthTest: false,
depthWrite: false,
transparent: true
} );
this._oldClearColor = new Color();
this._oldClearAlpha = 1;
this._basic = new MeshBasicMaterial();
this._fsQuad = new FullScreenQuad( null );
}
/**
* Frees the GPU-related resources allocated by this instance. Call this
* method whenever the pass is no longer used in your app.
*/
dispose() {
for ( let i = 0; i < this.renderTargetsHorizontal.length; i ++ ) {
this.renderTargetsHorizontal[ i ].dispose();
}
for ( let i = 0; i < this.renderTargetsVertical.length; i ++ ) {
this.renderTargetsVertical[ i ].dispose();
}
this.renderTargetBright.dispose();
//
for ( let i = 0; i < this.separableBlurMaterials.length; i ++ ) {
this.separableBlurMaterials[ i ].dispose();
}
this.compositeMaterial.dispose();
this.blendMaterial.dispose();
this._basic.dispose();
//
this._fsQuad.dispose();
}
/**
* Sets the size of the pass.
*
* @param {number} width - The width to set.
* @param {number} height - The height to set.
*/
setSize( width, height ) {
let resx = Math.round( width / 2 );
let resy = Math.round( height / 2 );
this.renderTargetBright.setSize( resx, resy );
for ( let i = 0; i < this.nMips; i ++ ) {
this.renderTargetsHorizontal[ i ].setSize( resx, resy );
this.renderTargetsVertical[ i ].setSize( resx, resy );
this.separableBlurMaterials[ i ].uniforms[ 'invSize' ].value = new Vector2( 1 / resx, 1 / resy );
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
}
}
/**
* Performs the Bloom pass.
*
* @param {WebGLRenderer} renderer - The renderer.
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
* destination for the pass.
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
* previous pass from this buffer.
* @param {number} deltaTime - The delta time in seconds.
* @param {boolean} maskActive - Whether masking is active or not.
*/
render( renderer, writeBuffer, readBuffer, deltaTime, maskActive ) {
renderer.getClearColor( this._oldClearColor );
this._oldClearAlpha = renderer.getClearAlpha();
const oldAutoClear = renderer.autoClear;
renderer.autoClear = false;
renderer.setClearColor( this.clearColor, 0 );
if ( maskActive ) renderer.state.buffers.stencil.setTest( false );
// Render input to screen
if ( this.renderToScreen ) {
this._fsQuad.material = this._basic;
this._basic.map = readBuffer.texture;
renderer.setRenderTarget( null );
renderer.clear();
this._fsQuad.render( renderer );
}
// 1. Extract Bright Areas
this.highPassUniforms[ 'tDiffuse' ].value = readBuffer.texture;
this.highPassUniforms[ 'luminosityThreshold' ].value = this.threshold;
this._fsQuad.material = this.materialHighPassFilter;
renderer.setRenderTarget( this.renderTargetBright );
renderer.clear();
this._fsQuad.render( renderer );
// 2. Blur All the mips progressively
let inputRenderTarget = this.renderTargetBright;
for ( let i = 0; i < this.nMips; i ++ ) {
this._fsQuad.material = this.separableBlurMaterials[ i ];
this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = inputRenderTarget.texture;
this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionX;
renderer.setRenderTarget( this.renderTargetsHorizontal[ i ] );
renderer.clear();
this._fsQuad.render( renderer );
this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = this.renderTargetsHorizontal[ i ].texture;
this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionY;
renderer.setRenderTarget( this.renderTargetsVertical[ i ] );
renderer.clear();
this._fsQuad.render( renderer );
inputRenderTarget = this.renderTargetsVertical[ i ];
}
// Composite All the mips
this._fsQuad.material = this.compositeMaterial;
this.compositeMaterial.uniforms[ 'bloomStrength' ].value = this.strength;
this.compositeMaterial.uniforms[ 'bloomRadius' ].value = this.radius;
this.compositeMaterial.uniforms[ 'bloomTintColors' ].value = this.bloomTintColors;
renderer.setRenderTarget( this.renderTargetsHorizontal[ 0 ] );
renderer.clear();
this._fsQuad.render( renderer );
// Blend it additively over the input texture
this._fsQuad.material = this.blendMaterial;
this.copyUniforms[ 'tDiffuse' ].value = this.renderTargetsHorizontal[ 0 ].texture;
if ( maskActive ) renderer.state.buffers.stencil.setTest( true );
if ( this.renderToScreen ) {
renderer.setRenderTarget( null );
this._fsQuad.render( renderer );
} else {
renderer.setRenderTarget( readBuffer );
this._fsQuad.render( renderer );
}
// Restore renderer settings
renderer.setClearColor( this._oldClearColor, this._oldClearAlpha );
renderer.autoClear = oldAutoClear;
}
// internals
_getSeparableBlurMaterial( kernelRadius ) {
const coefficients = [];
const sigma = kernelRadius / 3;
for ( let i = 0; i < kernelRadius; i ++ ) {
coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( sigma * sigma ) ) / sigma );
}
return new ShaderMaterial( {
defines: {
'KERNEL_RADIUS': kernelRadius
},
uniforms: {
'colorTexture': { value: null },
'invSize': { value: new Vector2( 0.5, 0.5 ) }, // inverse texture size
'direction': { value: new Vector2( 0.5, 0.5 ) },
'gaussianCoefficients': { value: coefficients } // precomputed Gaussian coefficients
},
vertexShader: /* glsl */`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,
fragmentShader: /* glsl */`
#include <common>
varying vec2 vUv;
uniform sampler2D colorTexture;
uniform vec2 invSize;
uniform vec2 direction;
uniform float gaussianCoefficients[KERNEL_RADIUS];
void main() {
float weightSum = gaussianCoefficients[0];
vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum;
for ( int i = 1; i < KERNEL_RADIUS; i ++ ) {
float x = float( i );
float w = gaussianCoefficients[i];
vec2 uvOffset = direction * invSize * x;
vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb;
vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb;
diffuseSum += ( sample1 + sample2 ) * w;
}
gl_FragColor = vec4( diffuseSum, 1.0 );
}`
} );
}
_getCompositeMaterial( nMips ) {
return new ShaderMaterial( {
defines: {
'NUM_MIPS': nMips
},
uniforms: {
'blurTexture1': { value: null },
'blurTexture2': { value: null },
'blurTexture3': { value: null },
'blurTexture4': { value: null },
'blurTexture5': { value: null },
'bloomStrength': { value: 1.0 },
'bloomFactors': { value: null },
'bloomTintColors': { value: null },
'bloomRadius': { value: 0.0 }
},
vertexShader: /* glsl */`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,
fragmentShader: /* glsl */`
varying vec2 vUv;
uniform sampler2D blurTexture1;
uniform sampler2D blurTexture2;
uniform sampler2D blurTexture3;
uniform sampler2D blurTexture4;
uniform sampler2D blurTexture5;
uniform float bloomStrength;
uniform float bloomRadius;
uniform float bloomFactors[NUM_MIPS];
uniform vec3 bloomTintColors[NUM_MIPS];
float lerpBloomFactor( const in float factor ) {
float mirrorFactor = 1.2 - factor;
return mix( factor, mirrorFactor, bloomRadius );
}
void main() {
// 3.0 for backwards compatibility with previous alpha-based intensity
vec3 bloom = 3.0 * bloomStrength * (
lerpBloomFactor( bloomFactors[ 0 ] ) * bloomTintColors[ 0 ] * texture2D( blurTexture1, vUv ).rgb +
lerpBloomFactor( bloomFactors[ 1 ] ) * bloomTintColors[ 1 ] * texture2D( blurTexture2, vUv ).rgb +
lerpBloomFactor( bloomFactors[ 2 ] ) * bloomTintColors[ 2 ] * texture2D( blurTexture3, vUv ).rgb +
lerpBloomFactor( bloomFactors[ 3 ] ) * bloomTintColors[ 3 ] * texture2D( blurTexture4, vUv ).rgb +
lerpBloomFactor( bloomFactors[ 4 ] ) * bloomTintColors[ 4 ] * texture2D( blurTexture5, vUv ).rgb
);
float bloomAlpha = max( bloom.r, max( bloom.g, bloom.b ) );
gl_FragColor = vec4( bloom, bloomAlpha );
}`
} );
}
}
UnrealBloomPass.BlurDirectionX = new Vector2( 1.0, 0.0 );
UnrealBloomPass.BlurDirectionY = new Vector2( 0.0, 1.0 );
export { UnrealBloomPass };
+52
View File
@@ -0,0 +1,52 @@
/**
* @module CopyShader
* @three_import import { CopyShader } from 'three/addons/shaders/CopyShader.js';
*/
/**
* Full-screen copy shader pass.
*
* @constant
* @type {ShaderMaterial~Shader}
*/
const CopyShader = {
name: 'CopyShader',
uniforms: {
'tDiffuse': { value: null },
'opacity': { value: 1.0 }
},
vertexShader: /* glsl */`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,
fragmentShader: /* glsl */`
uniform float opacity;
uniform sampler2D tDiffuse;
varying vec2 vUv;
void main() {
vec4 texel = texture2D( tDiffuse, vUv );
gl_FragColor = opacity * texel;
}`
};
export { CopyShader };
@@ -0,0 +1,68 @@
import {
Color
} from '../../three.module.min.js';
/**
* @module LuminosityHighPassShader
* @three_import import { LuminosityHighPassShader } from 'three/addons/shaders/LuminosityHighPassShader.js';
*/
/**
* Luminosity high pass shader.
*
* @constant
* @type {ShaderMaterial~Shader}
*/
const LuminosityHighPassShader = {
name: 'LuminosityHighPassShader',
uniforms: {
'tDiffuse': { value: null },
'luminosityThreshold': { value: 1.0 },
'smoothWidth': { value: 1.0 },
'defaultColor': { value: new Color( 0x000000 ) },
'defaultOpacity': { value: 0.0 }
},
vertexShader: /* glsl */`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,
fragmentShader: /* glsl */`
uniform sampler2D tDiffuse;
uniform vec3 defaultColor;
uniform float defaultOpacity;
uniform float luminosityThreshold;
uniform float smoothWidth;
varying vec2 vUv;
void main() {
vec4 texel = texture2D( tDiffuse, vUv );
float v = luminance( texel.xyz );
vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity );
float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v );
gl_FragColor = mix( outputColor, texel, alpha );
}`
};
export { LuminosityHighPassShader };
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long