UNPKG

three-glyph

Version:

Provide geometry and material in THREE.js for MSDF (multi-channel signed distance fields) glyph and more

60 lines (47 loc) 1.24 kB
import { NodeMaterial } from "three"; import { vec2, vec3, vec4, texture, Fn, positionLocal, varyingProperty, varying, attribute, fwidth, clamp, min, max } from 'three/tsl'; export var median = Fn(([r, g, b]) => { return max(min(r, g), min(max(r, g), b)); }); export var sdGlyph = Fn(([sample]) => { var sd = median(sample.r, sample.g, sample.b).sub(0.5); return clamp(sd.div(fwidth(sd)).add(0.5), 0.0, 1.0); }); class GlyphNodeMaterial extends NodeMaterial { static get type() { return 'GlyphNodeMaterial'; } constructor( parameters ) { super(); this.isGlyphMaterial = true; this.transparent = true this.map = parameters.map this.setValues( parameters ); this.positionNode = Fn(() => { varyingProperty('vec2', 'vUv').assign(attribute('guv')); return positionLocal })(); this.colorNode = Fn(() => { const vUv = varying(vec2(), 'vUv'); const diffuseColor = vec3(0.0); var sample = texture(this.map, vUv); var alpha = sdGlyph(sample); return vec4(diffuseColor, alpha); })(); } } export default GlyphNodeMaterial;