-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathPGMLoader.js
110 lines (84 loc) · 2.41 KB
/
PGMLoader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import { PGMLoaderBase } from './PGMLoaderBase.js';
import {
DataTexture,
DefaultLoadingManager,
UnsignedByteType,
HalfFloatType,
sRGBEncoding,
LinearFilter,
LinearMipMapLinearFilter,
RGBAFormat,
LinearEncoding,
} from 'three';
/**
* Three.js implementation of PGMLoaderBase.
*/
export class PGMLoader extends PGMLoaderBase {
/**
* @param {LoadingManager} manager
*/
constructor( manager = DefaultLoadingManager ) {
super();
/**
* @member {LoadingManager}
* @default DefaultLoadingManager
*/
this.manager = manager;
}
/**
* Loads and parses the PGM file and returns a DataTexture. If a DataTexture is passed into
* the function the data is applied to it.
* @param {String} url
* @param {DataTexture} texture
* @returns {Promise<DataTexture>}
*/
load( url, texture = new DataTexture() ) {
const manager = this.manager;
manager.itemStart( url );
return super.load( url ).then( result => {
texture.copy( result );
texture.needsUpdate = true;
return texture;
} ).catch( err => {
manager.itemError( url, err );
throw err;
} ).finally( () => {
manager.itemEnd( url );
} );
}
/**
* Parses the contents of the given PGM file and returns a texture with the
* contents.
* @param {Uint8Array | ArrayBuffer} buffer
* @param {DataTexture} texture
* @returns {DataTexture}
*/
parse( buffer, texture = new DataTexture() ) {
let result = buffer;
if ( buffer instanceof ArrayBuffer || buffer instanceof Uint8Array ) {
result = super.parse( buffer );
}
const data = result.data;
const rgbaBuffer = new data.constructor( data.length * 4 );
for ( let i = 0, l = data.length; i < l; i ++ ) {
const v = data[ i ];
rgbaBuffer[ i * 4 + 0 ] = v;
rgbaBuffer[ i * 4 + 1 ] = v;
rgbaBuffer[ i * 4 + 2 ] = v;
rgbaBuffer[ i * 4 + 3 ] = 1;
}
// TODO: if type if HalfFloatType then do the values need to be normalized by maxValue?
texture.image.width = result.width;
texture.image.height = result.height;
texture.image.data = rgbaBuffer;
texture.minFilter = LinearMipMapLinearFilter;
texture.magFilter = LinearFilter;
texture.type = result.data.BYTES_PER_ELEMENT === 1 ? UnsignedByteType : HalfFloatType;
texture.encoding = result.data.BYTES_PER_ELEMENT === 1 ? sRGBEncoding : LinearEncoding;
texture.format = RGBAFormat;
texture.flipY = true;
texture.generateMipmaps = true;
texture.needsUpdate = true;
return texture;
}
}