Debian Codegraph @

DisplayCAL/x3dom.py

raw
1 """Convert VRML files to X3D and HTML using X3DOM.
2
3 It includes utilities for parsing VRML, updating color spaces, managing
4 resources, and handling 3D transformations. The module also supports caching
5 and embedding resources for efficient processing.
6 """
7
8 from __future__ import annotations
9
10 import http.client
11 import os
12 import re
13 import string
14 import urllib.error
15 import urllib.parse
16 import urllib.request
17 from typing import TYPE_CHECKING
18
19 from DisplayCAL import colormath
20 from DisplayCAL import localization as lang
21 from DisplayCAL.config import get_data_path
22 from DisplayCAL.defaultpaths import CACHE as CACHEPATH
23 from DisplayCAL.log import safe_print as _safe_print
24 from DisplayCAL.meta import DOMAIN
25 from DisplayCAL.options import DEBUG
26 from DisplayCAL.util_io import GzipFileProper
27 from DisplayCAL.util_str import StrList, create_replace_function
28
29 if TYPE_CHECKING:
30 from DisplayCAL.worker import Worker
31
32
33 class VRMLParseError(Exception):
34 """Exception raised for errors in the VRML parsing process."""
35
36
37 class Tag:
38 """X3D Tag.
39
40 Args:
41 tagname (str): The name of the tag.
42 **attributes: Optional attributes for the tag.
43 """
44
45 def __init__(self, tagname: str, **attributes) -> None:
46 self.parent = None
47 self.tagname = tagname
48 self.children = []
49 self.attributes = attributes
50
51 def __str__(self) -> str:
52 """Return a string representation of the tag."""
53 return self.markup()
54
55 def markup(self, allow_empty_element_tag: bool = False, x3dom: bool = False) -> str:
56 """Return the X3D markup for this tag.
57
58 Args:
59 allow_empty_element_tag (bool): If True, allows the tag to be
60 self-closing. Defaults to False.
61 x3dom (bool): If True, generates X3DOM compatible markup.
62 Defaults to False.
63
64 Returns:
65 str: The X3D markup for this tag.
66 """
67 markup = [f"<{self.tagname}"]
68 attrs = []
69 for key in self.attributes:
70 value = self.attributes[key]
71 value = (
72 value.strip()
73 .replace("<", "&lt;")
74 .replace(">", "&gt;")
75 .replace("&", "&amp;")
76 .replace("'", "&#39;")
77 )
78 if value in ("FALSE", "TRUE"):
79 value = value.lower()
80 attrs.append(f"{key}='{value}'")
81 if attrs:
82 markup.append(" " + " ".join(attrs))
83 if not allow_empty_element_tag:
84 markup.append(">")
85 if self.children:
86 if allow_empty_element_tag:
87 markup.append(">")
88 markup.append("\n")
89 for child in self.children:
90 markup.extend(
91 f"\t{line}\n"
92 for line in child.markup(
93 allow_empty_element_tag, x3dom
94 ).splitlines()
95 )
96 if not allow_empty_element_tag or self.children:
97 # Not XML, or XML with children
98 markup.append(f"</{self.tagname}>\n")
99 else:
100 # XML, no children
101 markup.append("/>")
102 if (
103 self.tagname == "Material"
104 and float(self.attributes.get("transparency", "0").strip())
105 not in (0.0, 1.0)
106 and x3dom
107 ):
108 # Fix z-fighting in X3DOM renderer
109 markup.append("<DepthMode readOnly='true'></DepthMode>")
110 return "".join(markup)
111
112 def append_child(self, child: Tag) -> None:
113 """Append a child tag to this tag.
114
115 Args:
116 child (Tag): The child tag to append.
117 """
118 child.parent = self
119 self.children.append(child)
120
121 @classmethod
122 def ensure_cache_directory(cls, cache_dir: str) -> None:
123 """Ensure the cache directory exists.
124
125 Args:
126 cache_dir (str): The path to the cache directory.
127 """
128 if not os.path.isdir(cache_dir):
129 _safe_print("Creating cache directory:", cache_dir)
130 os.makedirs(cache_dir)
131
132 @classmethod
133 def get_resource_from_cache(cls, force: bool, cachefilename: str) -> str:
134 """Get resource from cache if available.
135
136 Args:
137 force (bool): If True, forces re-download of the resource.
138 cachefilename (str): The path to the cached file.
139
140 Returns:
141 str: The content of the cached file if it exists, otherwise an
142 empty string.
143 """
144 body = ""
145 if not force and os.path.isfile(cachefilename):
146 _safe_print("Using cached file:", cachefilename)
147 with open(cachefilename, "rb") as cachefile:
148 body = cachefile.read()
149 return body
150
151 @classmethod
152 def request_url_content(cls, url: str) -> bytes:
153 """Request content from a URL.
154
155 Args:
156 url (str): The URL to fetch content from.
157
158 Returns:
159 bytes: The content of the URL if successful, otherwise an empty
160 byte string.
161 """
162 body = b""
163 for url_ in [url, url.replace("https://", "http://")]:
164 _safe_print("Requesting:", url_)
165 try:
166 response = urllib.request.urlopen(url_) # noqa: S310
167 except (
168 OSError,
169 urllib.error.URLError,
170 http.client.HTTPException,
171 ) as exception:
172 _safe_print(exception)
173 else:
174 body = response.read()
175 response.close()
176 break
177 return body
178
179 @classmethod
180 def get_local_resources(cls, basename: str) -> None | bytes:
181 """Get local resources.
182
183 Args:
184 basename (str): The name of the resource file to fetch.
185
186 Returns:
187 None | bytes: The content of the resource file if found,
188 otherwise None.
189 """
190 url = get_data_path(f"x3d-viewer/{basename}")
191 if not url:
192 _safe_print("Error: Resource not found:", basename)
193 return None
194 with open(url, "rb") as resource_file:
195 return resource_file.read()
196
197 @classmethod
198 def get_resource(
199 cls, url: str, source: bool = True, force: bool = False, cache: bool = True
200 ) -> None | str:
201 """Collect resources.
202
203 Args:
204 url (str): The URL of the resource to fetch.
205 source (bool): If True, returns the resource content,
206 otherwise returns the file path.
207 force (bool): If True, forces fetching the resource even if
208 it is already cached.
209 cache (bool): If True, caches the resource locally.
210
211 Returns:
212 None | str: The content of the resource if source is True,
213 or the file path if source is False. Returns None if the
214 resource could not be fetched or is empty.
215 """
216 baseurl, basename = os.path.split(url)
217 # Strip protocol
218 cache_uri = re.sub(r"^\w+://", "", baseurl)
219 # Strip www
220 cache_uri = re.sub(r"^(?:www\.)?", "", cache_uri)
221 # domain.com -> com.domain
222 domain, path = cache_uri.split("/", 1)
223 cache_uri = "/".join([".".join(reversed(domain.split("."))), path])
224 # com.domain/path -> com.domain.path
225 cache_uri = re.sub(r"^([^/]+)/", "\\1.", cache_uri)
226 cache_dir = os.path.join(CACHEPATH, os.path.join(*cache_uri.split("/")))
227 cls.ensure_cache_directory(cache_dir)
228 cachefilename = os.path.join(cache_dir, basename)
229 body = cls.get_resource_from_cache(force, cachefilename)
230 if not body.strip():
231 body = cls.request_url_content(url)
232 if not body.strip():
233 # Fallback to local copy
234 body = cls.get_local_resources(basename)
235 if body.strip():
236 if cache and (force or not os.path.isfile(cachefilename)):
237 with open(cachefilename, "wb") as cachefile:
238 cachefile.write(body)
239 if source and not basename.endswith(".swf"):
240 if basename.endswith(".css"):
241 return f"<style>{body}</style>"
242 if basename.endswith(".js"):
243 return f"<script>{body}"
244 return body
245 return "file:///" + str(cachefilename).lstrip("/").replace(os.path.sep, "/")
246 _safe_print("Error: Empty document:", url)
247 if os.path.isfile(cachefilename):
248 _safe_print("Removing", cachefilename)
249 os.remove(cachefilename)
250 return None
251
252 def html(
253 self,
254 title: str = "Untitled",
255 xhtml: bool = False,
256 embed: bool = False,
257 force: bool = False,
258 cache: bool = True,
259 ) -> str:
260 """Convert X3D to HTML.
261
262 This will generate HTML5 by default unless you set xhtml=True.
263
264 If embed is True, the X3DOM runtime and X3D viewer will be embedded in
265 the HTML (increases filesize considerably).
266
267 Args:
268 title (str): The title of the HTML document.
269 xhtml (bool): If True, generates XHTML output. Defaults to False.
270 embed (bool): If True, embeds the X3DOM runtime in the HTML.
271 Defaults to False.
272 force (bool): If True, forces re-download of resources. Defaults
273 to False.
274 cache (bool): If True, caches resources. Defaults to True.
275
276 Returns:
277 str: The HTML representation of the tag, including the X3D content
278 and necessary resources.
279 """
280 # Get children of X3D document
281 x3d_html = re.sub(r"\s*</?X3D(?:\s+[^>]*)?>\s*", "", self.markup(xhtml, True))
282 if not xhtml:
283 # Convert uppercase letters at start of tag name to lowercase
284 x3d_html = re.sub(
285 r"(</?[0-9A-Z]+)", lambda match: match.groups()[0].lower(), x3d_html
286 )
287 # Indent
288 x3d_html = "\n".join(
289 ["\t" * 2 + line for line in x3d_html.splitlines()]
290 ).lstrip()
291
292 # Get HTML template from cache or online
293 html = self.get_resource(
294 f"https://{DOMAIN}/x3d-viewer/release/x3d-viewer.html", True, force, cache
295 ).decode("utf-8")
296 if cache or embed:
297 # Update resources in HTML
298 restags = re.findall(r"<[^>]+\s+data-fallback-\w+=[^>]*>", html)
299 for restag in restags:
300 attrname = re.search(r"\s+data-fallback-(\w+)=", restag).groups()[0]
301 url = re.search(rf"\s+{attrname}=([\"'])(.+?)\1", restag).groups()[1]
302 if url.endswith(".swf") and not cache:
303 continue
304 resource = self.get_resource(url, embed, force, cache)
305 if not resource:
306 continue
307 if embed and not url.endswith(".swf"):
308 html = html.replace(restag, resource)
309 else:
310 updated_restag = re.sub(
311 rf"(\s+data-fallback-{attrname}=)([\"']).+?\2",
312 create_replace_function(r"\1\2%s\2", resource),
313 restag,
314 )
315 html = html.replace(restag, updated_restag)
316 # Update title
317 html = re.sub(
318 r"(<title>)[^<]*(</title>)",
319 create_replace_function(r"\1%s\2", str(title)),
320 html,
321 )
322 # Insert X3D
323 html = html.replace("</x3d>", "\t" + x3d_html + "\n\t\t</x3d>")
324 # Finish
325 if xhtml:
326 html = "<?xml version='1.0' encoding='UTF-8'?>\n" + html
327 html = re.sub(r"\s*/>", " />", html)
328 else:
329 html = re.sub(r"\s*/>", ">", html)
330 return html
331
332 def xhtml(self, *args, **kwargs) -> str:
333 """Return XHTML representation of the tag.
334
335 Args:
336 *args: Positional arguments to pass to the html method.
337 **kwargs: Keyword arguments to pass to the html method.
338 If `xhtml` is not set, it will be set to True.
339
340 Returns:
341 str: The XHTML representation of the tag.
342 """
343 kwargs["xhtml"] = True
344 return self.html(*args, **kwargs)
345
346 def x3d(self) -> str:
347 """Return X3D representation of the tag.
348
349 Returns:
350 str: The X3D representation of the tag, including the XML
351 declaration and DOCTYPE.
352 """
353 return "\n".join(
354 [
355 "<?xml version='1.0' encoding='UTF-8'?>",
356 '<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN" '
357 '"http://www.web3d.org/specifications/x3d-3.0.dtd">',
358 self.markup(allow_empty_element_tag=True),
359 ]
360 )
361
362
363 def _attrchk(attribute: bool, token: str, tag: Tag, indent: str) -> bool:
364 """Check if the current token is an attribute and update the tag accordingly.
365
366 Args:
367 attribute (bool): Whether the current token is an attribute.
368 token (str): The current token being processed.
369 tag (Tag): The current tag being processed.
370 indent (str): The current indentation level for debug output.
371
372 Returns:
373 bool: Updated attribute status.
374 """
375 if attribute:
376 if DEBUG and tag.attributes.get(token):
377 safe_print(indent, f"attribute {token!r} {tag.attributes[token]!r}")
378 attribute = False
379 return attribute
380
381
382 def get_vrml_axes(
383 xlabel: str = "X",
384 ylabel: str = "Y",
385 zlabel: str = "Z",
386 offsetx: float = 0,
387 offsety: float = 0,
388 offsetz: float = 0,
389 maxx: float = 100,
390 maxy: float = 100,
391 maxz: float = 100,
392 zero: bool = True,
393 ) -> str:
394 """Generate VRML axes.
395
396 Args:
397 xlabel (str): Label for the X axis.
398 ylabel (str): Label for the Y axis.
399 zlabel (str): Label for the Z axis.
400 offsetx (float): Offset for the X axis.
401 offsety (float): Offset for the Y axis.
402 offsetz (float): Offset for the Z axis.
403 maxx (float): Maximum value for the X axis.
404 maxy (float): Maximum value for the Y axis.
405 maxz (float): Maximum value for the Z axis.
406 zero (bool): If True, adds a label at the origin.
407
408 Returns:
409 str: VRML string representing the axes and labels.
410 """
411 return """# Z axis
412 Transform {{
413 translation {offsetx:.1f} {offsety:.1f} {offsetz:.1f}
414 children [
415 Shape {{
416 geometry Box {{ size 2.0 2.0 {maxz:.1f} }}
417 appearance Appearance {{
418 material Material {{ diffuseColor 0.7 0.7 0.7 }}
419 }}
420 }}
421 ]
422 }}
423 # Z axis label
424 Transform {{
425 translation {zlabelx:.1f} {zlabely:.1f} {zlabelz:.1f}
426 children [
427 Shape {{
428 geometry Text {{
429 string ["{zlabel}"]
430 fontStyle FontStyle {{ family "SANS" style "BOLD" size 10.0 }}
431 }}
432 appearance Appearance {{
433 material Material {{ diffuseColor 0.7 0.7 0.7 }}
434 }}
435 }}
436 ]
437 }}
438 # X axis
439 Transform {{
440 translation {xaxisx:.1f} {offsety:.1f} {xyaxisz:.1f}
441 children [
442 Shape {{
443 geometry Box {{ size {maxx:.1f} 2.0 2.0 }}
444 appearance Appearance {{
445 material Material {{ diffuseColor 0.7 0.7 0.7 }}
446 }}
447 }}
448 ]
449 }}
450 # X axis label
451 Transform {{
452 translation {xlabelx:.1f} {xlabely:.1f} {xyaxisz:.1f}
453 children [
454 Shape {{
455 geometry Text {{
456 string ["{xlabel}"]
457 fontStyle FontStyle {{ family "SANS" style "BOLD" size 10.0 }}
458 }}
459 appearance Appearance {{
460 material Material {{ diffuseColor 0.7 0.7 0.7 }}
461 }}
462 }}
463 ]
464 }}
465 # Y axis
466 Transform {{
467 translation {offsetx:.1f} {yaxisy:.1f} {xyaxisz:.1f}
468 children [
469 Shape {{
470 geometry Box {{ size 2.0 {maxy:.1f} 2.0 }}
471 appearance Appearance {{
472 material Material {{ diffuseColor 0.7 0.7 0.7 }}
473 }}
474 }}
475 ]
476 }}
477 # Y axis label
478 Transform {{
479 translation {ylabelx:.1f} {ylabely:.1f} {xyaxisz:.1f}
480 children [
481 Shape {{
482 geometry Text {{
483 string ["{ylabel}"]
484 fontStyle FontStyle {{ family "SANS" style "BOLD" size 10.0 }}
485 }}
486 appearance Appearance {{
487 material Material {{ diffuseColor 0.7 0.7 0.7 }}
488 }}
489 }}
490 ]
491 }}
492 # Zero
493 Transform {{
494 translation {zerox:.1f} {zeroy:.1f} {zeroz:.1f}
495 children [
496 Shape {{
497 geometry Text {{
498 string ["{zerolabel}"]
499 fontStyle FontStyle {{ family "SANS" style "BOLD" size 10.0 }}
500 }}
501 appearance Appearance {{
502 material Material {{ diffuseColor 0.7 0.7 0.7 }}
503 }}
504 }}
505 ]
506 }}""".format(
507 maxx=maxx,
508 maxy=maxy,
509 maxz=maxz,
510 offsetx=offsetx,
511 offsety=offsety,
512 offsetz=offsetz,
513 xaxisx=maxx / 2.0 + offsetx,
514 xlabel=xlabel,
515 xlabelx=maxx + offsetx + 5,
516 xlabely=offsety - 5,
517 xyaxisz=offsetz - maxz / 2.0,
518 yaxisy=maxy / 2.0 + offsety,
519 ylabel=ylabel,
520 ylabelx=offsetx - 5,
521 ylabely=maxy + offsety + 5,
522 zerolabel="0" if zero else "",
523 zerox=offsetx - 10,
524 zeroy=offsety - 10,
525 zeroz=offsetz - maxz / 2.0 - 5,
526 zlabel=zlabel,
527 zlabelx=offsetx - 10,
528 zlabely=offsety - 10,
529 zlabelz=maxz / 2.0 + offsetz + 5,
530 )
531
532
533 def safe_print(*args, **kwargs) -> None:
534 """Print to stdout if DEBUG is enabled."""
535 if DEBUG:
536 _safe_print(*args, **kwargs)
537
538
539 def update_xyz(
540 xyz: str,
541 colorspace: str = "Luv",
542 offsetx: float = 0,
543 offsety: float = 0,
544 scale: float = 100,
545 maxz: float = 100,
546 ) -> str:
547 """Update XYZ coordinates to the specified colorspace.
548
549 Args:
550 xyz (str): The XYZ coordinates as a string, e.g. "x y z".
551 colorspace (str): The target colorspace, e.g. "Luv", "DIN99", etc.
552 offsetx (float): Offset for x coordinate.
553 offsety (float): Offset for y coordinate.
554 scale (float): Scale factor for the coordinates.
555 maxz (float): Maximum z value.
556
557 Returns:
558 str: The updated coordinates as a string in the specified colorspace.
559 """
560 x, y, z = [float(v) for v in xyz.split()]
561 a, b, L = x, y, z + 50 # noqa: N806
562 X, Y, Z = colormath.Lab2XYZ(L, a, b, scale=100) # noqa: N806
563 if colorspace.startswith("DIN99"):
564 if colorspace == "DIN99":
565 z, x, y = colormath.Lab2DIN99(L, a, b)
566 elif colorspace == "DIN99b":
567 z, x, y = colormath.Lab2DIN99b(L, a, b)
568 elif colorspace == "DIN99c":
569 z, x, y = colormath.XYZ2DIN99c(X, Y, Z)
570 else:
571 z, x, y = colormath.XYZ2DIN99d(X, Y, Z)
572 x, y, z = x * scale, y * scale, z / 100.0 * maxz
573 elif colorspace == "Luv":
574 z, x, y = colormath.XYZ2Luv(X, Y, Z)
575 elif colorspace == "Lu'v'":
576 L, u_, v_ = colormath.XYZ2Lu_v_(X, Y, Z) # noqa: N806
577 x, y, z = ((u_ + offsetx) * scale, (v_ + offsety) * scale, L / 100.0 * maxz)
578 elif colorspace == "xyY":
579 x, y, Y = colormath.XYZ2xyY(X, Y, Z) # noqa: N806
580 x, y, z = ((x + offsetx) * scale, (y + offsety) * scale, Y / 100.0 * maxz)
581 elif colorspace == "ICtCp":
582 I, Ct, Cp = colormath.XYZ2ICtCp( # noqa: N806
583 X / 100.0, Y / 100.0, Z / 100.0, clamp=False
584 )
585 z, x, y = I * 100, Ct * 100, Cp * 100
586 elif colorspace == "IPT":
587 I, P, T = colormath.XYZ2IPT(X / 100.0, Y / 100.0, Z / 100.0) # noqa: N806
588 z, x, y = I * 100, P * 100, T * 100
589 elif colorspace == "Lpt":
590 z, x, y = colormath.XYZ2Lpt(X, Y, Z)
591 z -= maxz / 2.0
592 return " ".join([f"{v:.6f}" for v in (x, y, z)])
593
594
595 def get_offset_and_scale_from_colorspace(
596 colorspace: str, maxxy: float
597 ) -> tuple[float, float, float]:
598 """Get offset and scale based on the colorspace.
599
600 Args:
601 colorspace (str): The colorspace to determine the offset and scale for.
602 maxxy (float): The maximum value for x and y coordinates.
603
604 Returns:
605 tuple[float, float, float]: A tuple containing the offset for x, offset
606 for y, and scale.
607 """
608 if colorspace.startswith("DIN99"):
609 scale = 1.0
610 elif colorspace == "Lu'v'":
611 offsetx, offsety = -0.3, -0.3
612 scale = maxxy / 0.6
613 elif colorspace == "xyY":
614 offsetx, offsety = -0.4, -0.4
615 scale = maxxy / 0.8
616 return offsetx, offsety, scale
617
618
619 def update_point_lists(
620 vrml: str,
621 colorspace: str,
622 offsetx: float,
623 offsety: float,
624 scale: float,
625 maxz: float,
626 ) -> str:
627 """Update point lists in VRML.
628
629 Args:
630 vrml (str): The VRML content as a string.
631 colorspace (str): The target colorspace, e.g. "Luv", "DIN99", etc.
632 offsetx (float): Offset for x coordinate.
633 offsety (float): Offset for y coordinate.
634 scale (float): Scale factor for the coordinates.
635 maxz (float): Maximum z value.
636
637 Returns:
638 str: The updated VRML content with modified point lists.
639 """
640 for item in re.findall(r"point\s*\[[^\]]+\]", vrml):
641 item = item[:-1].rstrip()
642 # Remove comments
643 points = re.sub(r"#[^\n\r]*", "", item)
644 # Get actual points
645 points = re.match(r"point\s*\[(.+)", points, re.S).groups()[0]
646 points = points.strip().split(",")
647 for i, xyz in enumerate(points):
648 xyz = xyz.strip()
649 if xyz:
650 points[i] = update_xyz(xyz, colorspace, offsetx, offsety, scale, maxz)
651 vrml = vrml.replace(
652 item,
653 "point [{}{}".format(os.linesep, ("," + os.linesep).join(points).rstrip()),
654 )
655 return vrml
656
657
658 def update_spheres(
659 vrml: str,
660 colorspace: str = "Luv",
661 offsetx: float = 0,
662 offsety: float = 0,
663 scale: float = 100,
664 maxz: float = 100,
665 ) -> str:
666 """Update sphere coordinates in VRML.
667
668 Args:
669 vrml (str): The VRML content as a string.
670 colorspace (str): The target colorspace, e.g. "Luv", "DIN99", etc.
671 offsetx (float): Offset for x coordinate.
672 offsety (float): Offset for y coordinate.
673 scale (float): Scale factor for the coordinates.
674 maxz (float): Maximum z value.
675
676 Returns:
677 str: The updated VRML content with modified sphere coordinates.
678 """
679 spheres = re.findall(
680 r"Transform\s*\{\s*translation\s+[+\-0-9.]+\s*[+\-0-9.]+\s*[+\-0-9.]+\s+"
681 r"children\s*\[\s*Shape\s*\{\s*geometry\s+Sphere\s*\{[^}]*\}\s*"
682 r"appearance\s+Appearance\s*\{\s*material\s+"
683 r"Material\s*\{[^}]*\}\s*\}\s*\}\s*\]\s*\}",
684 vrml,
685 )
686 for sphere in spheres:
687 coords = re.search(
688 r"translation\s+([+\-0-9.]+\s+[+\-0-9.]+\s+[+\-0-9.]+)", sphere
689 )
690 if not coords:
691 continue
692 vrml = vrml.replace(
693 sphere,
694 sphere.replace(
695 coords.group(),
696 "translation {}".format(
697 update_xyz(
698 coords.groups()[0],
699 colorspace,
700 offsetx,
701 offsety,
702 scale,
703 maxz,
704 )
705 ),
706 ),
707 )
708 return vrml
709
710
711 def update_vrml_for_din99(
712 vrml: str,
713 colorspace: str,
714 offsetx: float,
715 offsety: float,
716 scale: float,
717 maxz: float,
718 ) -> str:
719 """Update VRML for DIN99 colorspace.
720
721 Args:
722 vrml (str): The VRML content as a string.
723 colorspace (str): The target colorspace, e.g. "DIN99", "DIN99b", etc.
724 offsetx (float): Offset for x coordinate.
725 offsety (float): Offset for y coordinate.
726 scale (float): Scale factor for the coordinates.
727 maxz (float): Maximum z value.
728
729 Returns:
730 str: The modified VRML content with DIN99 specific adjustments.
731 """
732 # Remove * from L*a*b* and add range
733
734 # Pristine Argyll CMS VRML
735 vrml = re.sub(r'(string\s*\[")(\+?)(L)\*("\])', r'\1\3", "\2\0$\4', vrml)
736 vrml = vrml.replace("\0$", "100")
737 vrml = re.sub(r'(string\s*\[")([+\-]?)(a)\*("\])', r'\1\3", "\2\0$\4', vrml)
738 vrml = re.sub(r'(string\s*\[")([+\-]?)(b)\*("\])', r"\1\3 \2\0$\4", vrml)
739
740 # DisplayCAL tweaked VRML created by worker.Worker.calculate_gamut()
741 vrml = re.sub(r'(string\s*\["a)\*",\s*"([+\-]?)\d+("\])', r'\1", "\2\0$\3', vrml)
742 vrml = re.sub(r'(string\s*\["b)\*\s+([+\-]?)\d+("\])', r"\1 \2\0$\3", vrml)
743
744 vrml = vrml.replace("\0$", f"{round(100.0 / scale)}")
745
746 # Add colorspace information
747 return re.sub(
748 r"(Viewpoint\s*\{[^}]+\})",
749 rf"""\1
750 Transform {{
751 translation {maxz + offsetx:.6f} {maxz + offsety:.6f} {-maxz / 2.0:.6f}
752 children [
753 Shape {{
754 geometry Text {{
755 string ["{colorspace}"]
756 fontStyle FontStyle {{ family "SANS" style "BOLD" size 10.0 }}
757 }}
758 appearance Appearance {{
759 material Material {{ diffuseColor 0.7 0.7 0.7 }}
760 }}
761 }}
762 ]
763 }}""",
764 vrml,
765 )
766
767
768 def update_vrml_for_luv(vrml: str) -> str:
769 """Update VRML for Luv colorspace.
770
771 Args:
772 vrml (str): The VRML content as a string.
773
774 Returns:
775 str: The modified VRML content with Luv specific adjustments.
776 """
777 # Replace a* b* labels with u* v*
778 vrml = re.sub(r'(string\s*\["[+\-]?)a(\*)', r"\1u\2", vrml)
779 vrml = re.sub(r'(string\s*\["[+\-]?)b(\*)', r"\1v\2", vrml)
780
781
782 def update_vrml_for_luv_and_xyy(
783 vrml: str,
784 colorspace: str,
785 offsetx: float,
786 offsety: float,
787 scale: float,
788 maxxy: float,
789 maxz: float,
790 ) -> str:
791 """Update VRML for Luv and xyY colorspaces.
792
793 Args:
794 vrml (str): The VRML content as a string.
795 colorspace (str): The target colorspace, e.g. "Luv", "xyY".
796 offsetx (float): Offset for x coordinate.
797 offsety (float): Offset for y coordinate.
798 scale (float): Scale factor for the coordinates.
799 maxxy (float): Maximum value for x and y coordinates.
800 maxz (float): Maximum z value.
801
802 Returns:
803 str: The modified VRML content with Luv and xyY specific adjustments.
804 """
805 # Remove axes
806 vrml = re.sub(
807 r"Transform\s*\{\s*translation\s+[+\-0-9.]+\s*[+\-0-9.]+\s*[+\-0-9.]+\s+"
808 r"children\s*\[\s*Shape\s*\{\s*geometry\s+Box\s*\{[^}]*\}\s*appearance\s+"
809 r"Appearance\s*\{\s*material\s+Material\s*\{[^}]*\}\s*\}\s*\}\s*\]\s*\}",
810 "",
811 vrml,
812 )
813 # Remove axis labels
814 vrml = re.sub(
815 r"Transform\s*\{\s*translation\s+[+\-0-9.]+\s*[+\-0-9.]+\s*[+\-0-9.]+\s+"
816 r"children\s*\[\s*Shape\s*\{\s*geometry\s+Text\s*\{\s*"
817 r"string\s*\[[^\]]*\]\s*fontStyle\s+FontStyle\s*\{[^}]*\}\s*\}\s*"
818 r"appearance\s+Appearance\s*\{\s*material\s+"
819 r"Material\s*{[^}]*\}\s*\}\s*\}\s*\]\s*\}",
820 "",
821 vrml,
822 )
823 # Add new axes + labels
824 if colorspace == "Lu'v'":
825 xlabel, ylabel, zlabel = "u' 0.6", "v' 0.6", "L* 100"
826 else:
827 xlabel, ylabel, zlabel = "x 0.8", "y 0.8", "Y 100"
828 return re.sub(
829 r"(Viewpoint\s*\{[^}]+\})",
830 r"\1\n"
831 + get_vrml_axes(
832 xlabel,
833 ylabel,
834 zlabel,
835 offsetx * scale,
836 offsety * scale,
837 0,
838 maxxy,
839 maxxy,
840 maxz,
841 ),
842 vrml,
843 )
844
845
846 def update_vrml_for_ictcp(vrml: str) -> str:
847 """Update VRML for ICtCp colorspace.
848
849 Args:
850 vrml (str): The VRML content as a string.
851
852 Returns:
853 str: The modified VRML content with ICtCp specific adjustments.
854 """
855 # Replace L* a* b* labels with I Ct Cp
856 vrml = re.sub(r'(string\s*\["[+\-]?)L\*?', r"\1I", vrml)
857 vrml = re.sub(r'(string\s*\["[+\-]?)a\*?', r"\1Ct", vrml)
858 vrml = re.sub(r'(string\s*\["[+\-]?)b\*?', r"\1Cp", vrml)
859 # Change axis colors
860 axes = re.findall(
861 r"Shape\s*\{\s*geometry\s*(?:Box|Text)\s*\{\s*(?:"
862 r'size\s+\d+\.0+\s+\d+\.0+\s+\d+\.0+|string\s+\["[^"]*"\]\s*'
863 r"fontStyle\s+FontStyle\s*\{[^}]+\})\s*\}\s*appearance\s+"
864 r"Appearance\s*\{\s*material\s*Material\s*\{[^}]+}\s*\}\s*\}",
865 vrml,
866 )
867 for axis in axes:
868 # Red -> purpleish blue
869 vrml = vrml.replace(
870 axis,
871 re.sub(
872 r"diffuseColor\s+1\.0+\s+0\.0+\s+0\.0+",
873 "diffuseColor 0.5 0.0 1.0",
874 axis,
875 ),
876 )
877 # Green -> yellowish green
878 vrml = vrml.replace(
879 axis,
880 re.sub(
881 r"diffuseColor\s+0\.0+\s+1\.0+\s+0\.0+",
882 "diffuseColor 0.8 1.0 0.0",
883 axis,
884 ),
885 )
886 # Yellow -> magentaish red
887 vrml = vrml.replace(
888 axis,
889 re.sub(
890 r"diffuseColor\s+1\.0+\s+1\.0+\s+0\.0+",
891 "diffuseColor 1.0 0.0 0.25",
892 axis,
893 ),
894 )
895 # Blue -> cyan
896 vrml = vrml.replace(
897 axis,
898 re.sub(
899 r"diffuseColor\s+0\.0+\s+0\.0+\s+1\.0+",
900 "diffuseColor 0.0 1.0 1.0",
901 axis,
902 ),
903 )
904
905
906 def update_vrml_for_ipt(vrml: str) -> str:
907 """Update VRML for IPT colorspace.
908
909 Args:
910 vrml (str): The VRML content as a string.
911
912 Returns:
913 str: The modified VRML content with IPT specific adjustments.
914 """
915 # Replace L* a* b* labels with I P T
916 vrml = re.sub(r'(string\s*\["[+\-]?)L\*?', r"\1I", vrml)
917 vrml = re.sub(r'(string\s*\["[+\-]?)a\*?', r"\1P", vrml)
918 return re.sub(r'(string\s*\["[+\-]?)b\*?', r"\1T", vrml)
919
920
921 def update_vrml_for_lpt(vrml: str) -> str:
922 """Update VRML for Lpt colorspace.
923
924 Args:
925 vrml (str): The VRML content as a string.
926
927 Returns:
928 str: The modified VRML content with Lpt specific adjustments.
929 """
930 # Replace a* b* labels with p* t*
931 vrml = re.sub(r'(string\s*\["[+\-]?)a\*?', r"\1p", vrml)
932 return re.sub(r'(string\s*\["[+\-]?)b\*?', r"\1t", vrml)
933
934
935 def update_vrml(vrml: str, colorspace: str) -> str:
936 """Update color and axes in VRML.
937
938 Args:
939 vrml (str): The VRML content as a string.
940 colorspace (str): The target colorspace, e.g. "Luv", "DIN99", etc.
941
942 Returns:
943 str: The updated VRML content as a string.
944 """
945 offsetx, offsety = 0, 0
946 maxz = scale = 100
947 maxxy = 200
948 offsetx, offsety, scale = get_offset_and_scale_from_colorspace(colorspace, maxxy)
949
950 # Update point lists
951 vrml = update_point_lists(vrml, colorspace, offsetx, offsety, scale, maxz)
952
953 # Update spheres
954 vrml = update_spheres(vrml, colorspace, offsetx, offsety, scale, maxz)
955
956 if colorspace.startswith("DIN99"):
957 vrml = update_vrml_for_din99(vrml, colorspace, offsetx, offsety, scale, maxz)
958 elif colorspace == "Luv":
959 vrml = update_vrml_for_luv(vrml)
960 elif colorspace in ("Lu'v'", "xyY"):
961 vrml = update_vrml_for_luv_and_xyy(
962 vrml, colorspace, offsetx, offsety, scale, maxxy, maxz
963 )
964 elif colorspace == "ICtCp":
965 vrml = update_vrml_for_ictcp(vrml)
966 elif colorspace == "IPT":
967 vrml = update_vrml_for_ipt(vrml)
968 elif colorspace == "Lpt":
969 vrml = update_vrml_for_lpt(vrml)
970 return vrml
971
972
973 def vrml2x3dom(vrml: str, worker: None | Worker = None) -> Tag:
974 """Convert VRML to X3D.
975
976 Args:
977 vrml (str): The VRML content as a string.
978 worker (None | Worker): Optional worker instance for progress updates.
979
980 Raises:
981 VRMLParseError: If there is an error in the VRML parsing process.
982
983 Returns:
984 Tag: The root X3D tag containing the converted VRML content.
985 """
986 x3d = Tag(
987 "X3D",
988 **{
989 "xmlns:xsd": "http://www.w3.org/2001/XMLSchema-instance",
990 "profile": "Immersive",
991 "version": "3.0",
992 "xsd:noNamespaceSchemaLocation": "http://www.web3d.org/specifications/x3d-3.0.xsd",
993 },
994 )
995 tag = Tag("Scene")
996 x3d.append_child(tag)
997 token = ""
998 attribute = False
999 quote = 0
1000 listing = False
1001 # Remove comments
1002 vrml = re.sub(r"#[^\n\r]*", "", vrml)
1003 # <class> <Token> { -> <Token> {
1004 vrml = re.sub(r"\w+[ \t]+(\w+\s*\{)", "\\1", vrml)
1005 # Remove commas
1006 vrml = re.sub(r",\s*", " ", vrml)
1007 indent = ""
1008 maxi = len(vrml) - 1.0
1009 lastprogress = 0
1010 for i, c in enumerate(vrml):
1011 curprogress = int(i / maxi * 100)
1012 if worker:
1013 if curprogress > lastprogress:
1014 worker.lastmsg.write(f"{curprogress}%\n")
1015 if getattr(worker, "thread_abort", False):
1016 return False
1017 if curprogress > lastprogress:
1018 lastprogress = curprogress
1019 end = None if curprogress < 100 else "\n"
1020 _safe_print.write(f"\r{curprogress}%", end=end)
1021 validate_character(c)
1022 tag, token, attribute, quote, listing, indent = parse_vrml_character(
1023 c, tag, token, attribute, quote, listing, indent
1024 )
1025 return x3d
1026
1027
1028 def validate_character(c: str) -> None:
1029 """Validate a character in the VRML content.
1030
1031 Args:
1032 c (str): The character to validate.
1033
1034 Raises:
1035 VRMLParseError: If the character is invalid.
1036 """
1037 if ord(c) < 32 and c not in "\n\r\t":
1038 raise VRMLParseError(f"Parse error: Got invalid character {c!r}")
1039
1040
1041 def parse_vrml_character(
1042 c: str,
1043 tag: Tag,
1044 token: str,
1045 attribute: bool,
1046 quote: int,
1047 listing: bool,
1048 indent: str,
1049 ) -> tuple[Tag, str, bool, int, bool, str]:
1050 """Parse a character in the VRML content.
1051
1052 Args:
1053 c (str): The character to parse.
1054 tag (Tag): The current tag being processed.
1055 token (str): The current token being built.
1056 attribute (bool): Whether the current token is an attribute.
1057 quote (int): The number of quotes encountered.
1058 listing (bool): Whether we are currently in a listing context.
1059 indent (str): The current indentation level for debug output.
1060
1061 Raises:
1062 VRMLParseError: If there is an error in the parsing process.
1063
1064 Returns:
1065 tuple[Tag, str, bool, int, bool, str]: Updated tag, token, attribute,
1066 quote count, listing status, and indentation.
1067 """
1068 valid_token_chars = string.ascii_letters + string.digits + "_"
1069 if c == "{":
1070 tag, token, attribute, indent = start_new_tag(tag, token, indent)
1071 elif c == "}":
1072 tag, token, attribute, indent = end_new_tag(tag, token, attribute, indent)
1073 elif c == "[":
1074 listing = True if log_listing_token(token, indent) else listing
1075 elif c == "]":
1076 token, attribute, listing = reset_token_and_attribute(
1077 tag, token, attribute, indent
1078 )
1079 elif attribute:
1080 tag, token, attribute, quote, listing, indent = parse_attribute_value(
1081 c, tag, token, attribute, quote, listing, indent
1082 )
1083 elif c not in " \n\r\t":
1084 if c in valid_token_chars:
1085 token += c
1086 else:
1087 raise VRMLParseError(f"Parse error: Got invalid character {c!r}")
1088 elif token:
1089 tag, token, attribute = handle_token(c, tag, token, attribute)
1090 return tag, token, attribute, quote, listing, indent
1091
1092
1093 def start_new_tag(tag: Tag, token: str, indent: str) -> tuple[Tag, str, bool, str]:
1094 """Start a new tag in the VRML content.
1095
1096 Args:
1097 tag (Tag): The current tag being processed.
1098 token (str): The current token being built.
1099 indent (str): The current indentation level for debug output.
1100
1101 Returns:
1102 tuple[Tag, str, bool, str]: Updated tag, token, attribute status,
1103 and indentation.
1104 """
1105 safe_print(indent, f"start tag {token!r}")
1106 indent += " "
1107 attribute = False
1108 validate_token(token)
1109 child = Tag(token)
1110 tag.append_child(child)
1111 tag = child
1112 token = ""
1113 return tag, token, attribute, indent
1114
1115
1116 def end_new_tag(
1117 tag: Tag, token: str, attribute: bool, indent: str
1118 ) -> tuple[Tag, str, bool, str]:
1119 """End the current tag in the VRML content.
1120
1121 Args:
1122 tag (Tag): The current tag being processed.
1123 token (str): The current token being built.
1124 attribute (bool): Whether the current token is an attribute.
1125 indent (str): The current indentation level for debug output.
1126
1127 Returns:
1128 tuple[Tag, str, bool, str]: Updated tag, token, attribute status,
1129 and indentation.
1130 """
1131 attribute = _attrchk(attribute, token, tag, indent)
1132 indent = indent[:-2]
1133 safe_print(indent, f"end tag {tag.tagname!r}")
1134 if tag.parent:
1135 tag = tag.parent
1136 else:
1137 raise VRMLParseError("Parse error: Stray '}'")
1138 token = ""
1139 return tag, token, attribute, indent
1140
1141
1142 def log_listing_token(token: str, indent: str) -> bool:
1143 """Log the listing token if it is not empty.
1144
1145 Args:
1146 token (str): The current token being processed.
1147 indent (str): The current indentation level for debug output.
1148
1149 Returns:
1150 bool: True if the token is not empty, False otherwise.
1151 """
1152 if token:
1153 safe_print(indent, f"listing {token!r}")
1154 return True
1155 return False
1156
1157
1158 def reset_token_and_attribute(
1159 tag: Tag, token: str, attribute: bool, indent: str
1160 ) -> tuple[str, bool, bool]:
1161 """Reset the token and attribute status after a listing.
1162
1163 Args:
1164 tag (Tag): The current tag being processed.
1165 token (str): The current token being built.
1166 attribute (bool): Whether the current token is an attribute.
1167 indent (str): The current indentation level for debug output.
1168
1169 Returns:
1170 tuple[str, bool, bool]: Updated token, attribute status, and listing status.
1171 """
1172 attribute = _attrchk(attribute, token, tag, indent)
1173 token = ""
1174 listing = False
1175 return token, attribute, listing
1176
1177
1178 def parse_attribute_value(
1179 c: str,
1180 tag: Tag,
1181 token: str,
1182 attribute: bool,
1183 quote: int,
1184 listing: bool,
1185 indent: str,
1186 ) -> tuple[Tag, str, bool, int, bool, str]:
1187 """Parse a character as part of an attribute value.
1188
1189 Notes:
1190 - Handles special cases for whitespace, newlines, and quoted values.
1191 - Specifically checks for the "style" attribute in "FontStyle" tags to
1192 handle quotes differently.
1193 - Uses a helper function '_attrchk' to finalize attribute values when
1194 appropriate.
1195 - Assumes 'StrList' is a custom list-like class for attribute value
1196 storage.
1197
1198 Args:
1199 c (str): The current character being parsed.
1200 tag (Tag): A Tag instange whose attributes are being updated.
1201 token (str): The current attribute name being processed.
1202 attribute (bool): The current attribute state.
1203 quote (int): Counter for quote characters to determine quoted attribute
1204 values.
1205 listing (bool): Flag indicating if the parser is in a listing mode
1206 (affects whitespace handling).
1207 indent (str): Current indentation as str.
1208
1209 Returns:
1210 tuple[Tag, str, bool, int, bool, str]: Updated (tag, token, attribute,
1211 quote, listing, indent) after processing the character.
1212 """
1213 if c in "\n\r":
1214 if listing:
1215 if tag.attributes.get(token) and tag.attributes[token][-1] != " ":
1216 tag.attributes[token] += " "
1217 else:
1218 attribute = _attrchk(attribute, token, tag, indent)
1219 token = ""
1220 else:
1221 if token not in tag.attributes:
1222 tag.attributes[token] = StrList()
1223 if not (c.strip() or tag.attributes[token]):
1224 return tag, token, attribute, quote, listing, indent
1225 if c == '"':
1226 quote += 1
1227 if (c != '"' or tag.tagname != "FontStyle" or token != "style") and (
1228 c != " " or (tag.attributes[token] and tag.attributes[token][-1] != " ")
1229 ):
1230 tag.attributes[token] += c
1231 if quote == 2:
1232 if not listing:
1233 attribute = _attrchk(attribute, token, tag, indent)
1234 token = ""
1235 quote = 0
1236 return tag, token, attribute, quote, listing, indent
1237
1238
1239 def validate_token(token: str) -> None:
1240 """Validate a token in the VRML content.
1241
1242 Args:
1243 token (str): The token to validate.
1244
1245 Raises:
1246 VRMLParseError: If the token is invalid.
1247 """
1248 if token:
1249 if token[0] not in string.ascii_letters:
1250 raise VRMLParseError("Invalid token", token)
1251 else:
1252 raise VRMLParseError("Parse error: Empty token")
1253
1254
1255 def handle_token(
1256 c: str, tag: Tag, token: str, attribute: bool
1257 ) -> tuple[Tag, str, bool]:
1258 """Handle a token in the VRML content.
1259
1260 Args:
1261 c (str): The current character being processed.
1262 tag (Tag): The current tag being processed.
1263 token (str): The current token being built.
1264 attribute (bool): Whether the current token is an attribute.
1265
1266 Returns:
1267 tuple[Tag, str, bool]: Updated tag, token, and attribute status.
1268 """
1269 validate_token(token)
1270 if token == "children":
1271 token = ""
1272 elif c in " \t" and not attribute:
1273 attribute = True
1274 if token in tag.attributes:
1275 # Overwrite existing attribute
1276 tag.attributes[token] = StrList()
1277 return tag, token, attribute
1278
1279
1280 def vrmlfile2x3dfile(
1281 vrmlpath: str,
1282 x3dpath: str,
1283 html: bool = True,
1284 embed: bool = False,
1285 force: bool = False,
1286 cache: bool = True,
1287 worker: None | Worker = None,
1288 ) -> bool:
1289 """Convert VRML file located at vrmlpath to HTML and write to x3dpath.
1290
1291 Args:
1292 vrmlpath (str): Path to the VRML file.
1293 x3dpath (str): Path where the X3D file will be written.
1294 html (bool): If True, generates HTML output. Defaults to True.
1295 embed (bool): If True, embeds the X3DOM runtime in the HTML. Defaults
1296 to False.
1297 force (bool): If True, forces re-download of resources. Defaults to
1298 False.
1299 cache (bool): If True, caches resources. Defaults to True.
1300 worker (None | Worker): Optional worker instance for progress updates.
1301
1302 Returns:
1303 bool: True if conversion was successful, False if aborted or an error
1304 occurred.
1305 """
1306 filename, ext = os.path.splitext(vrmlpath)
1307 reader = open
1308 if ext.lower() in (".gz", ".wrz"):
1309 reader = GzipFileProper
1310
1311 with reader(vrmlpath, "rb") as vrmlfile:
1312 vrml = vrmlfile.read()
1313
1314 if isinstance(vrml, bytes):
1315 vrml = vrml.decode("utf-8")
1316
1317 if worker:
1318 worker.recent.write(
1319 "{} {}\n".format(lang.getstr("converting"), os.path.basename(vrmlpath))
1320 )
1321 _safe_print(lang.getstr("converting"), vrmlpath)
1322 filename, ext = os.path.splitext(x3dpath)
1323 try:
1324 x3d = vrml2x3dom(vrml, worker)
1325 if not x3d:
1326 _safe_print(lang.getstr("aborted"))
1327 return False
1328 if not html:
1329 _safe_print("Writing", x3dpath)
1330 with open(x3dpath, "w") as x3dfile:
1331 x3dfile.write(x3d.x3d())
1332 else:
1333 html = x3d.html(
1334 title=os.path.basename(filename), embed=embed, force=force, cache=cache
1335 )
1336 _safe_print("Writing", f"{x3dpath}.html")
1337 with open(f"{x3dpath}.html", "w") as htmlfile:
1338 htmlfile.write(html)
1339 except KeyboardInterrupt:
1340 x3d = False
1341 except VRMLParseError as exception:
1342 return exception
1343 except OSError as exception:
1344 return exception
1345 except Exception as exception:
1346 import traceback
1347
1348 _safe_print(traceback.format_exc())
1349 return exception
1350 return True