forked from PedroLopes/AR-Marker-Generator
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmarkergenerator.js
425 lines (326 loc) · 12.7 KB
/
markergenerator.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// author danilo gasques ( danilod100 at gmail.com )
// based on ASPePeX's https://github.com/ASPePeX/AR-Marker-Generator
// ====== Program output configuration ===========
// Marker size in pixels
window.markerSize = 512;
window.markerSizeMM = 80; // mm
window.markerName = "marker";
// ====== Triangle configuration =================
// Triangle max size in pixel
window.triangleSize = 128;
// Draw number of triangles per marker
window.triangleLimit = 10;
// Lines' width
window.triangleStrokeWidth = 10;
// Color limits to control overall color brightness
window.colorUpperLimit = 255;
window.colorLowerLimit = 128;
// Border size in percentage (it takes marker space
window.borderSizePercent = 0.25; // e.g., 0.25 for 25%
// Border color (initially set to black)
var borderColor = 0;
// Background clear color
window.backgroundColor = [255, 255, 255];
// user image related settings
window.guiImageControllers = {};
window.backgroundImage = undefined;
window.backgroundImageSet = false;
window.foregroundImage = undefined;
window.foregroundImageSet = false;
// ===== Variables and code below should be modified at your own risk ====
var markerCounter = 0;
var realMarkerSize, borderSize;
// ==== computer vision related ==== //
var featureCount = 0, corners = [];
window.minFeatures = 400;
// ==== Canvas related things === //
var p5canvas;
var gui;
var latestMarkerImageData, latestMarkerImage;
var generating = false;
// ==== PDF related things === //
window.savePDF = true;
window.paperSizeName = "letter";
window.paperSizeWidthMM = 215.9;
window.paperSizeHeightMM = 279.4;
window.paperSizesOptions = ['letter', 'a4', 'government-letter', 'legal', 'ledger', 'credit-card', 'a3', 'a5', 'dl', 'custom'];
window.paperSizesMM =
{
'a3': [297, 420],
'a4': [210, 297],
'a5': [148, 210],
'dl': [110, 220],
'letter': [215.9, 279.4],
'government-letter': [203, 267],
'legal': [216, 356],
'ledger': [279, 432],
'credit-card': [53.975, 85.725]
};
// ==== p5.js dom related ==== //
var statusText;
// ================================================================================================================== //
// ======================== P5js methods for drawing the marker and creating the menus ============================= //
// ================================================================================================================== //
// Creates a new random marker
function createMarker()
{
// finds border dimensions
borderSize = borderSizePercent*markerSize;
// finds out real space for markers
realMarkerSize = markerSize - 2*borderSize;
// cleans the screen
background(backgroundColor[0],backgroundColor[1],backgroundColor[2]);
// draws background image
if (backgroundImageSet)
{
image(backgroundImage,0,0,window.markerSize,window.markerSize);
}
// draw triangles
strokeWeight(triangleStrokeWidth);
for (var i = 0; i < triangleLimit; i++)
{
// Randoming triangle corners, in their own relative coordinate system
var a = createVector(random(-triangleSize/2, triangleSize/2), random(-triangleSize/2, triangleSize/2));
var b = createVector(random(-triangleSize/2, triangleSize/2), random(-triangleSize/2, triangleSize/2));
var c = createVector(random(-triangleSize/2, triangleSize/2), random(-triangleSize/2, triangleSize/2));
// Randoming the center position on the canvas
var p = new createVector( borderSize + random(realMarkerSize), borderSize + random(realMarkerSize));
// Randoming fill color
fill(random(colorLowerLimit, colorUpperLimit),random(colorLowerLimit, colorUpperLimit),random(colorLowerLimit, colorUpperLimit));
// Drawing the triangle
triangle(a.x + p.x, a.y + p.y,
b.x + p.x, b.y + p.y,
c.x + p.x, c.y + p.y);
}
// draw borders
strokeWeight(0);
fill(borderColor);
rect(0, 0, markerSize, borderSize); // up
rect(0, markerSize - borderSize, markerSize, borderSize + 1); // down
rect(0, 0, borderSize, markerSize); // left
rect(markerSize - borderSize, 0, borderSize + 1, markerSize); // right
// draws foreground
if (foregroundImageSet)
{
image(foregroundImage,0,0,window.markerSize,window.markerSize);
}
// save image in memory
latestMarkerImageData = p5canvas.drawingContext.getImageData(0, 0, width, height);
if (!generating)
latestMarkerImage = p5canvas.canvas.toDataURL("image/jpeg", 1.0);
findFeatures();
updateStatus();
}
function onErrorBackgroundImage()
{
backgroundImageSet = false;
alert('Could not load background image!');
}
function onErrorForegroundImage()
{
foregroundImageSet = false;
alert('Could not load foreground image!');
}
function onLoadBackgroundImage(backgroundImage)
{
console.log(backgroundImage);
backgroundImageSet = true;
createMarker();
guiImageControllers['background'].name("Remove bground");
}
function onLoadForegroundImage(foregroundImage)
{
console.log(foregroundImage);
foregroundImageSet = true;
createMarker();
guiImageControllers['foreground'].name("Remove fground");
}
function onForegroundImageChange()
{
if (userForegroundFilePicker.files.length > 0)
{
window.foregroundImage = loadImage(URL.createObjectURL(userForegroundFilePicker.files[0]), onLoadForegroundImage, onErrorForegroundImage);
}
}
function onBackgroundImageChange()
{
if (userBackgroundFilePicker.files.length > 0)
{
window.backgroundImage = loadImage(URL.createObjectURL(userBackgroundFilePicker.files[0]), onLoadBackgroundImage, onErrorBackgroundImage);
}
}
function clearBackgroundImage()
{
backgroundImageSet = false;
createMarker();
guiImageControllers['background'].name("Add background");
}
function clearForegroundImage()
{
foregroundImageSet = false;
createMarker();
guiImageControllers['foreground'].name("Add foreground");
}
function setup() {
// defines canvas size
p5canvas = createCanvas(markerSize, markerSize)
p5canvas.parent('markerholder');
// creates the menu
gui = new dat.GUI();
// images
var guiImages = gui.addFolder('Images');
window.userBackgroundFilePicker = document.getElementById('userBackgroundImage');
window.userForegroundFilePicker = document.getElementById('userForegroundImage');
window.userBackgroundFilePicker.onchange = onBackgroundImageChange;
window.userForegroundFilePicker.onchange = onForegroundImageChange;
guiImageControllers['background'] = guiImages.add({backgroundImage : function() { if (!backgroundImageSet) {userBackgroundFilePicker.click();} else {clearBackgroundImage()}}, gui: window.guiImageControllers}, 'backgroundImage').name("Add background");
guiImageControllers['foreground'] = guiImages.add({foregroundImage : function() { if (!foregroundImageSet) {userForegroundFilePicker.click();} else {clearForegroundImage()}}, gui: window.guiImageControllers}, 'foregroundImage').name("Add foreground");
guiImages.open();
// creates a folder for the marker
var guiMarker = gui.addFolder('Marker');
guiMarker.add(window, 'markerSize', 256, 1024).step(1).onChange(function() { p5canvas.size(markerSize, markerSize); createMarker(); });
guiMarker.add(window, 'borderSizePercent').min(0).step(0.025).max(0.5).onChange(createMarker);
guiMarker.open();
// floating gui
var guiProcedural = gui.addFolder('Settings');
guiProcedural.add(window, 'triangleSize', 5, 1024).onChange(createMarker);
guiProcedural.add(window, 'triangleLimit', 1, 200).onChange(createMarker);
guiProcedural.add(window, 'triangleStrokeWidth', 0, 30).onChange(createMarker);
guiProcedural.add(window, 'colorUpperLimit', 0, 255).onChange(createMarker);
guiProcedural.add(window, 'colorLowerLimit', 0, 255).onChange(createMarker);
guiProcedural.addColor(window, 'backgroundColor').onChange(createMarker);
// computer vision side of things
var guiTracking = gui.addFolder('Feature Tracking');
guiTracking.add(window, 'minFeatures', 200, 1000);
// pdf
var guiPDF = gui.addFolder('PDF');
guiPDF.add(window, 'savePDF');
guiPDF.add(window, 'markerSizeMM');
var paperSizeNameGui = guiPDF.add(window, 'paperSizeName', paperSizesOptions);
var paperSizeWidthMMGui = guiPDF.add(window, 'paperSizeWidthMM');
var paperSizeHeightMMGui = guiPDF.add(window, 'paperSizeHeightMM');
// whenever the paper size name changes, it also changes the dimensions
paperSizeNameGui.onChange(function()
{
if (paperSizeName != 'custom')
{
paperSizeWidthMM = paperSizesMM[paperSizeName][0];
paperSizeHeightMM = paperSizesMM[paperSizeName][1];
paperSizeWidthMMGui.updateDisplay();
paperSizeHeightMMGui.updateDisplay();
}
});
var changeToCustom = function() {
paperSizeName = 'custom';
paperSizeNameGui.updateDisplay();
}
paperSizeHeightMMGui.onChange(changeToCustom);
paperSizeHeightMMGui.onChange(changeToCustom);
// download
window.guiDownload = gui.addFolder('Download');
//gui.add(window, 'markerSizeCm', 5, 25).step(1).onChange();
var markerNameGui = guiDownload.add(window, 'markerName').onChange(function()
{
// remove illegal characters
markerName = markerName.replace(/\<|\>|\:|\"|\/|\\|\||\?|\*|/gi, function (x) {return '';});
markerNameGui.updateDisplay();
});
guiDownload.add(window, 'download');
// generate
gui.add(window, 'generate');
// dom gui
statusText = select('#status');
// creates a sample marker
createMarker();
}
function draw() {
if (generating)
{
createMarker();
if (featureCount > minFeatures)
{
generating = false;
guiDownload.open();
latestMarkerImage = p5canvas.canvas.toDataURL("image/jpeg");
updateStatus();
}
}
}
// ================================================================================================================== //
// ==================== Helper methods for updating status, generating pdf, downloading zip ========================= //
// ================================================================================================================== //
// updates status text at the top of the screen
function updateStatus()
{
statusText.html( (generating ? "Generating... / " : "") + markerSize + "x" + markerSize + " / " + featureCount + " features");
}
// starts generate animation
function generate()
{
guiDownload.close();
generating = true;
}
// creates and zips a pdf, patt file, readme.txt
function download()
{
// create zip file
var zip = new JSZip();
// image file (hopefully, jpeg)
var fileRe = /data:image\/(\w+);(\w+),(.*)/;
var pic = fileRe.exec(latestMarkerImage);
var picname = markerName+"."+pic[1];
zip.file(picname, pic[3], {base64: true});
// generate patt file(s)
var pattname = markerName+".patt";
zip.file(markerName+".patt", generatePatt());
// generate pdf
var pdfname = markerName+".pdf";
zip.file(markerName+".pdf", generatePDF(latestMarkerImage, pic[1].toUpperCase()), {blob: true});
// readme.txt
zip.file('ReadMe.txt', 'Marker from https://danilogr.github.io/AR-Marker-Generator/ on ' + (new Date()).toString()+ '\n\n'
+ picname + ' - Picture file that can be used on tools like Vuforia ' + '\n'
+ pattname + ' - .patt file designed for ARToolkit / AR.js ' + '\n'
+ pdfname + ' - Pdf with the proper printing dimensions' + '\n'
);
// download zip
zip.generateAsync({type:"blob"}).then(function(content) {
saveAs(content, markerName+".zip");
});
}
// generates .patt (arjs / artoolkit)
function generatePatt()
{
// gets image without the borders
var innerMarkerCanvas = document.createElement('canvas');
innerMarkerCanvas.width = realMarkerSize;
innerMarkerCanvas.height = realMarkerSize;
var imgData = p5canvas.drawingContext.getImageData(borderSize, borderSize, realMarkerSize, realMarkerSize);
innerMarkerCanvas.getContext('2d').putImageData(imgData, 0, 0);
// right now I am using what is available in AR.js source code
return THREEx.ArPatternFile.encodeImage(innerMarkerCanvas);
}
// generates pdf
function generatePDF(pic, picFormat)
{
// paper size
var pdfSize = (paperSizeName == 'custom') ? [paperSizeWidthMM, paperSizeHeightMM] : paperSizeName;
var doc = new jsPDF({
orientation: 'portrait',
unit: 'mm',
format: pdfSize
});
// add picture to it
doc.addImage(pic, picFormat, Math.round((paperSizeWidthMM - markerSizeMM) / 2) , Math.round((paperSizeHeightMM - markerSizeMM) / 2) , markerSizeMM, markerSizeMM, 'marker', 'NONE');
return doc.output('blob');
}
// uses tracking.js to find tracking features
function findFeatures()
{
var gray = tracking.Image.grayscale(latestMarkerImageData.data, markerSize, markerSize);
corners = tracking.Fast.findCorners(gray, width, height);
featureCount = corners.length;
// for (var i = 0; i < corners.length; i += 2) {
// context.fillStyle = '#f00';
// context.fillRect(corners[i], corners[i + 1], 3, 3);
// }
}