Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add gcode line number information for the colorizers #9

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 55 additions & 4 deletions example/index.html

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion src/LinePoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ export class LinePoint {
public readonly point: Vector3
public readonly radius: number
public readonly color: Color
public readonly alpha: number

constructor(point: Vector3, radius: number, color: Color = new Color("#29BEB0")) {
constructor(point: Vector3, radius: number, color: Color = new Color("#29BEB0"), alpha: number = 1.0) {
this.point = point
this.radius = radius
this.color = color
this.alpha = alpha
}
}
31 changes: 19 additions & 12 deletions src/LineTubeGeometry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ interface PointData {
vertices: number[]
normals: number[]
colors: number[]
alpha: number
}

/**
Expand All @@ -38,8 +39,9 @@ export class LineTubeGeometry extends BufferGeometry {
private vertices: number[] = []
private normals: number[] = []
private colors: number[] = []
private uvs: number[] = [];
private indices: number[] = [];
private alphas: number[] = []
private uvs: number[] = []
private indices: number[] = []

private segmentsRadialNumbers: number[] = []

Expand All @@ -56,6 +58,7 @@ export class LineTubeGeometry extends BufferGeometry {
this.normals = []
this.vertices = []
this.colors = []
this.alphas = []
this.uvs = []
this.indices = []
this.segmentsRadialNumbers = []
Expand Down Expand Up @@ -83,10 +86,11 @@ export class LineTubeGeometry extends BufferGeometry {
this.generateSegment(1);
}

console.log(this.alphas.filter(a => a === 0).length, this.alphas.filter(a => a === 1).length)
this.setAttribute('position', new Float32BufferAttribute(this.vertices, 3));
this.setAttribute('normal', new Float32BufferAttribute(this.normals, 3));
this.setAttribute('color', new Float32BufferAttribute(this.colors, 3));

this.setAttribute('alpha', new Float32BufferAttribute(this.alphas, 1));
this.generateUVs();
this.setAttribute('uv', new Float32BufferAttribute(this.uvs, 2));

Expand All @@ -100,6 +104,7 @@ export class LineTubeGeometry extends BufferGeometry {
// these are now in the attribute buffers - can be deleted
this.normals = []
this.colors = []
this.alphas = []
this.uvs = []

// The vertices are needed to slice. For now they need to be kept.
Expand Down Expand Up @@ -162,7 +167,7 @@ export class LineTubeGeometry extends BufferGeometry {

const lastRadius = this.pointsBuffer[i-1]?.radius || 0

function createPointData(pointNr: number, radialNr: number, normal: Vector3, point: Vector3, radius: number, color: Color): PointData {
function createPointData(pointNr: number, radialNr: number, normal: Vector3, point: Vector3, radius: number, color: Color, alpha: number): PointData {
return {
pointNr,
radialNr,
Expand All @@ -172,7 +177,8 @@ export class LineTubeGeometry extends BufferGeometry {
point.y + radius * normal.y,
point.z + radius * normal.z
],
colors: color.toArray()
colors: color.toArray(),
alpha,
}
}

Expand Down Expand Up @@ -200,27 +206,28 @@ export class LineTubeGeometry extends BufferGeometry {
// When the previous point doesn't exist, create one with the radius 0 (lastRadius is set to 0 in this case),
// to create a closed starting point.
if (prevPoint === undefined) {
segmentsPoints[0].push(createPointData(i, j, normal, point.point, lastRadius, point.color))
segmentsPoints[0].push(createPointData(i, j, normal, point.point, lastRadius, point.color, point.alpha))
}

// Then insert the current point with the current radius
segmentsPoints[1].push(createPointData(i, j, normal, point.point, point.radius, point.color))
segmentsPoints[1].push(createPointData(i, j, normal, point.point, point.radius, point.color, point.alpha))

// And also the next point with the current radius to finish the current line.
segmentsPoints[2].push(createPointData(i, j, normal, nextPoint.point, point.radius, point.color))
segmentsPoints[2].push(createPointData(i, j, normal, nextPoint.point, point.radius, point.color, point.alpha))

// if the next point is the last one, also finish the line by inserting one with zero radius.
if (nextNextPoint === undefined) {
segmentsPoints[3].push(createPointData(i+1, j, normal, nextPoint.point, 0, point.color))
segmentsPoints[3].push(createPointData(i+1, j, normal, nextPoint.point, 0, point.color, point.alpha))
}
}

// Save everything into the buffers.
segmentsPoints.forEach((p) => {
p.forEach((pp) => {
pp.normals && this.normals.push(...pp.normals);
pp.vertices && this.vertices.push(...pp.vertices);
pp.colors && this.colors.push(...pp.colors);
this.normals.push(...pp.normals);
this.vertices.push(...pp.vertices);
this.colors.push(...pp.colors);
this.alphas.push(pp.alpha);
});
this.segmentsRadialNumbers.push(...p.map((cur) => cur.radialNr))
})
Expand Down
39 changes: 37 additions & 2 deletions src/SegmentColorizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,52 @@ export interface SegmentMetadata {
temp: number
speed: number

// TODO: Linetype based on comments in gcode
gCodeLine: number
}

const DEFAULT_COLOR = new Color("#29BEB0")

export interface SegmentColorizer {
getColor(meta: SegmentMetadata): Color
}


export interface LineColorizerOptions {
defaultColor: Color
}

export type LineColorConfig = {toLine: number, color: Color}[]

export class LineColorizer {
// This assumes that getColor is called ordered by gCodeLine.
private currentConfigIndex: number = 0

constructor(
private readonly lineColorConfig: LineColorConfig,
private readonly options?: LineColorizerOptions
) {}

getColor(meta: SegmentMetadata): Color {
// Safeguard check if the config is too short.
if (this.lineColorConfig[this.currentConfigIndex] === undefined) {
return this.options?.defaultColor || DEFAULT_COLOR
}

if (this.lineColorConfig[this.currentConfigIndex].toLine < meta.gCodeLine) {
this.currentConfigIndex++
}

if (meta.gCodeLine < 50)
console.log(meta.gCodeLine)

return this.lineColorConfig[this.currentConfigIndex].color || this.options?.defaultColor || DEFAULT_COLOR
}
}

export class SimpleColorizer implements SegmentColorizer {
private readonly color

constructor(color = new Color("#29BEB0")) {
constructor(color = DEFAULT_COLOR) {
this.color = color
}

Expand Down
37 changes: 35 additions & 2 deletions src/gcode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,43 @@ import {
AmbientLight,
SpotLight,
MeshPhongMaterial,
RawShaderMaterial,
ShaderMaterial,
TangentSpaceNormalMap,
Vector2,
MultiplyOperation,
UniformsUtils,
ShaderLib,
Blending,
NormalBlending,
} from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { lineMaterialFragmentShader } from './meshphong_frag.glsl'
import { lineMaterialVertexShader } from './meshphong_vert.glsl'
import { GCodeParser } from './parser'
import { SegmentColorizer } from './SegmentColorizer'

class LineMaterial extends ShaderMaterial {
constructor() {
super({
name: 'line-material',
vertexShader: lineMaterialVertexShader,
fragmentShader: lineMaterialFragmentShader,
lights: true,
vertexColors: true,
blending: NormalBlending,
})

this.setValues({
uniforms: UniformsUtils.merge([
ShaderLib.phong.uniforms,
{ diffuse: { value: new Color('#ffffff') } },
{ time: { value: 0.0 } }
])
})
}
}

/**
* GCode renderer which parses a GCode file and displays it using
* three.js. Use .element() to retrieve the DOM canvas element.
Expand All @@ -25,7 +57,7 @@ export class GCodeRenderer {

private camera: PerspectiveCamera

private lineMaterial = new MeshPhongMaterial({ vertexColors: true } )
private lineMaterial = new LineMaterial()

private readonly parser: GCodeParser

Expand Down Expand Up @@ -153,7 +185,7 @@ export class GCodeRenderer {
*/
constructor(gCode: string, width: number, height: number, background: Color) {
this.scene = new Scene()
this.renderer = new WebGLRenderer()
this.renderer = new WebGLRenderer({alpha: true})
this.renderer.setSize(width, height)
this.renderer.setClearColor(background, 1)
this.camera = this.newCamera(width, height)
Expand Down Expand Up @@ -228,6 +260,7 @@ export class GCodeRenderer {
return
}

this.renderer.clear()
this.renderer.render(this.scene, this.camera)
}

Expand Down
81 changes: 81 additions & 0 deletions src/meshphong_frag.glsl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
export const lineMaterialFragmentShader = /* glsl */`
#define LINE

uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;

#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <uv2_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <cube_uv_reflection_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <lights_phong_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>

varying float alpha;

void main() {
// if (alpha == 0.0)
// {
// discard;
// return;
// }

#include <clipping_planes_fragment>

vec4 diffuseColor = vec4( diffuse, opacity );
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;

#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <specularmap_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <emissivemap_fragment>

// accumulation
#include <lights_phong_fragment>
#include <lights_fragment_begin>
#include <lights_fragment_maps>
#include <lights_fragment_end>

// modulation
#include <aomap_fragment>

vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;

#include <envmap_fragment>

gl_FragColor = vec4( outgoingLight, diffuseColor.a );

#include <tonemapping_fragment>
#include <encodings_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}
`;
60 changes: 60 additions & 0 deletions src/meshphong_vert.glsl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
export const lineMaterialVertexShader = /* glsl */`
#define PHONG

varying vec3 vViewPosition;

#ifndef FLAT_SHADED

varying vec3 vNormal;

#endif

#include <common>
#include <uv_pars_vertex>
#include <uv2_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>

varying float alpha;

void main() {
#include <uv_vertex>
#include <uv2_vertex>
#include <color_vertex>

#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>

#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED

vNormal = normalize( transformedNormal );

#endif

#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>

vViewPosition = - mvPosition.xyz;

#include <worldpos_vertex>
#include <envmap_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>

}
`;
Loading