Skip to content

Commit 162bc15

Browse files
committed
implementing NFT with threading support
1 parent 9d1ecd2 commit 162bc15

File tree

12 files changed

+92187
-73337
lines changed

12 files changed

+92187
-73337
lines changed

build/artoolkitNft.debug.js

Lines changed: 91345 additions & 73302 deletions
Large diffs are not rendered by default.

build/artoolkitNft.min.js

Lines changed: 14 additions & 12 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

build/artoolkitNft.min.worker.js

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
// Copyright 2015 The Emscripten Authors. All rights reserved.
2+
// Emscripten is available under two separate licenses, the MIT license and the
3+
// University of Illinois/NCSA Open Source License. Both these licenses can be
4+
// found in the LICENSE file.
5+
6+
// Pthread Web Worker startup routine:
7+
// This is the entry point file that is loaded first by each Web Worker
8+
// that executes pthreads on the Emscripten application.
9+
10+
// Thread-local:
11+
var threadInfoStruct = 0; // Info area for this thread in Emscripten HEAP (shared). If zero, this worker is not currently hosting an executing pthread.
12+
var selfThreadId = 0; // The ID of this thread. 0 if not hosting a pthread.
13+
var parentThreadId = 0; // The ID of the parent pthread that launched this thread.
14+
var tempDoublePtr = 0; // A temporary memory area for global float and double marshalling operations.
15+
16+
// Thread-local: Each thread has its own allocated stack space.
17+
var STACK_BASE = 0;
18+
var STACKTOP = 0;
19+
var STACK_MAX = 0;
20+
21+
// These are system-wide memory area parameters that are set at main runtime startup in main thread, and stay constant throughout the application.
22+
var buffer; // All pthreads share the same Emscripten HEAP as SharedArrayBuffer with the main execution thread.
23+
var DYNAMICTOP_PTR = 0;
24+
var DYNAMIC_BASE = 0;
25+
26+
var ENVIRONMENT_IS_PTHREAD = true;
27+
var PthreadWorkerInit = {};
28+
29+
// performance.now() is specced to return a wallclock time in msecs since that Web Worker/main thread launched. However for pthreads this can cause
30+
// subtle problems in emscripten_get_now() as this essentially would measure time from pthread_create(), meaning that the clocks between each threads
31+
// would be wildly out of sync. Therefore sync all pthreads to the clock on the main browser thread, so that different threads see a somewhat
32+
// coherent clock across each of them (+/- 0.1msecs in testing)
33+
var __performance_now_clock_drift = 0;
34+
35+
// Cannot use console.log or console.error in a web worker, since that would risk a browser deadlock! https://bugzilla.mozilla.org/show_bug.cgi?id=1049091
36+
// Therefore implement custom logging facility for threads running in a worker, which queue the messages to main thread to print.
37+
var Module = {};
38+
39+
40+
// When error objects propagate from Web Worker to main thread, they lose helpful call stack and thread ID information, so print out errors early here,
41+
// before that happens.
42+
this.addEventListener('error', function(e) {
43+
if (e.message.indexOf('SimulateInfiniteLoop') != -1) return e.preventDefault();
44+
45+
var errorSource = ' in ' + e.filename + ':' + e.lineno + ':' + e.colno;
46+
console.error('Pthread ' + selfThreadId + ' uncaught exception' + (e.filename || e.lineno || e.colno ? errorSource : "") + ': ' + e.message + '. Error object:');
47+
console.error(e.error);
48+
});
49+
50+
function threadPrint() {
51+
var text = Array.prototype.slice.call(arguments).join(' ');
52+
console.log(text);
53+
}
54+
function threadPrintErr() {
55+
var text = Array.prototype.slice.call(arguments).join(' ');
56+
console.error(text);
57+
console.error(new Error().stack);
58+
}
59+
function threadAlert() {
60+
var text = Array.prototype.slice.call(arguments).join(' ');
61+
postMessage({cmd: 'alert', text: text, threadId: selfThreadId});
62+
}
63+
out = threadPrint;
64+
err = threadPrintErr;
65+
this.alert = threadAlert;
66+
67+
68+
var wasmModule;
69+
var wasmMemory;
70+
71+
this.onmessage = function(e) {
72+
try {
73+
if (e.data.cmd === 'load') { // Preload command that is called once per worker to parse and load the Emscripten code.
74+
// Initialize the thread-local field(s):
75+
tempDoublePtr = e.data.tempDoublePtr;
76+
77+
// Initialize the global "process"-wide fields:
78+
DYNAMIC_BASE = e.data.DYNAMIC_BASE;
79+
DYNAMICTOP_PTR = e.data.DYNAMICTOP_PTR;
80+
81+
buffer = e.data.buffer;
82+
83+
84+
85+
PthreadWorkerInit = e.data.PthreadWorkerInit;
86+
87+
if (typeof e.data.urlOrBlob === 'string') {
88+
importScripts(e.data.urlOrBlob);
89+
} else {
90+
var objectUrl = URL.createObjectURL(e.data.urlOrBlob);
91+
importScripts(objectUrl);
92+
URL.revokeObjectURL(objectUrl);
93+
}
94+
95+
96+
if (typeof FS !== 'undefined' && typeof FS.createStandardStreams === 'function') FS.createStandardStreams();
97+
postMessage({ cmd: 'loaded' });
98+
} else if (e.data.cmd === 'objectTransfer') {
99+
PThread.receiveObjectTransfer(e.data);
100+
} else if (e.data.cmd === 'run') { // This worker was idle, and now should start executing its pthread entry point.
101+
__performance_now_clock_drift = performance.now() - e.data.time; // Sync up to the clock of the main thread.
102+
threadInfoStruct = e.data.threadInfoStruct;
103+
__register_pthread_ptr(threadInfoStruct, /*isMainBrowserThread=*/0, /*isMainRuntimeThread=*/0); // Pass the thread address inside the asm.js scope to store it for fast access that avoids the need for a FFI out.
104+
selfThreadId = e.data.selfThreadId;
105+
parentThreadId = e.data.parentThreadId;
106+
// Establish the stack frame for this thread in global scope
107+
STACK_BASE = STACKTOP = e.data.stackBase;
108+
STACK_MAX = STACK_BASE + e.data.stackSize;
109+
// Call inside asm.js/wasm module to set up the stack frame for this pthread in asm.js/wasm module scope
110+
Module['establishStackSpace'](e.data.stackBase, e.data.stackBase + e.data.stackSize);
111+
112+
PThread.receiveObjectTransfer(e.data);
113+
PThread.setThreadStatus(_pthread_self(), 1/*EM_THREAD_STATUS_RUNNING*/);
114+
115+
try {
116+
// pthread entry points are always of signature 'void *ThreadMain(void *arg)'
117+
// Native codebases sometimes spawn threads with other thread entry point signatures,
118+
// such as void ThreadMain(void *arg), void *ThreadMain(), or void ThreadMain().
119+
// That is not acceptable per C/C++ specification, but x86 compiler ABI extensions
120+
// enable that to work. If you find the following line to crash, either change the signature
121+
// to "proper" void *ThreadMain(void *arg) form, or try linking with the Emscripten linker
122+
// flag -s EMULATE_FUNCTION_POINTER_CASTS=1 to add in emulation for this x86 ABI extension.
123+
var result = Module['dynCall_ii'](e.data.start_routine, e.data.arg);
124+
125+
126+
} catch(e) {
127+
if (e === 'Canceled!') {
128+
PThread.threadCancel();
129+
return;
130+
} else if (e === 'SimulateInfiniteLoop' || e === 'pthread_exit') {
131+
return;
132+
} else {
133+
Atomics.store(HEAPU32, (threadInfoStruct + 4 /*C_STRUCTS.pthread.threadExitCode*/ ) >> 2, (e instanceof ExitStatus) ? e.status : -2 /*A custom entry specific to Emscripten denoting that the thread crashed.*/);
134+
Atomics.store(HEAPU32, (threadInfoStruct + 0 /*C_STRUCTS.pthread.threadStatus*/ ) >> 2, 1); // Mark the thread as no longer running.
135+
_emscripten_futex_wake(threadInfoStruct + 0 /*C_STRUCTS.pthread.threadStatus*/, 0x7FFFFFFF/*INT_MAX*/); // Wake all threads waiting on this thread to finish.
136+
if (!(e instanceof ExitStatus)) throw e;
137+
}
138+
}
139+
// The thread might have finished without calling pthread_exit(). If so, then perform the exit operation ourselves.
140+
// (This is a no-op if explicit pthread_exit() had been called prior.)
141+
if (!Module['noExitRuntime']) PThread.threadExit(result);
142+
} else if (e.data.cmd === 'cancel') { // Main thread is asking for a pthread_cancel() on this thread.
143+
if (threadInfoStruct && PThread.thisThreadCancelState == 0/*PTHREAD_CANCEL_ENABLE*/) {
144+
PThread.threadCancel();
145+
}
146+
} else if (e.data.target === 'setimmediate') {
147+
// no-op
148+
} else if (e.data.cmd === 'processThreadQueue') {
149+
if (threadInfoStruct) { // If this thread is actually running?
150+
_emscripten_current_thread_process_queued_calls();
151+
}
152+
} else {
153+
err('worker.js received unknown command ' + e.data.cmd);
154+
console.error(e.data);
155+
}
156+
} catch(e) {
157+
console.error('worker.js onmessage() captured an uncaught exception: ' + e);
158+
console.error(e.stack);
159+
throw e;
160+
}
161+
}
162+
163+

build/artoolkitNft_wasm.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

build/artoolkitNft_wasm.wasm

126 KB
Binary file not shown.

emscripten/ARMarkerNFT.c

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
/*
2+
* ARMarkerNFT.c
3+
* ARToolKit5
4+
*
5+
* Disclaimer: IMPORTANT: This Daqri software is supplied to you by Daqri
6+
* LLC ("Daqri") in consideration of your agreement to the following
7+
* terms, and your use, installation, modification or redistribution of
8+
* this Daqri software constitutes acceptance of these terms. If you do
9+
* not agree with these terms, please do not use, install, modify or
10+
* redistribute this Daqri software.
11+
*
12+
* In consideration of your agreement to abide by the following terms, and
13+
* subject to these terms, Daqri grants you a personal, non-exclusive
14+
* license, under Daqri's copyrights in this original Daqri software (the
15+
* "Daqri Software"), to use, reproduce, modify and redistribute the Daqri
16+
* Software, with or without modifications, in source and/or binary forms;
17+
* provided that if you redistribute the Daqri Software in its entirety and
18+
* without modifications, you must retain this notice and the following
19+
* text and disclaimers in all such redistributions of the Daqri Software.
20+
* Neither the name, trademarks, service marks or logos of Daqri LLC may
21+
* be used to endorse or promote products derived from the Daqri Software
22+
* without specific prior written permission from Daqri. Except as
23+
* expressly stated in this notice, no other rights or licenses, express or
24+
* implied, are granted by Daqri herein, including but not limited to any
25+
* patent rights that may be infringed by your derivative works or by other
26+
* works in which the Daqri Software may be incorporated.
27+
*
28+
* The Daqri Software is provided by Daqri on an "AS IS" basis. DAQRI
29+
* MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
30+
* THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
31+
* FOR A PARTICULAR PURPOSE, REGARDING THE DAQRI SOFTWARE OR ITS USE AND
32+
* OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
33+
*
34+
* IN NO EVENT SHALL DAQRI BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
35+
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
36+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37+
* INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
38+
* MODIFICATION AND/OR DISTRIBUTION OF THE DAQRI SOFTWARE, HOWEVER CAUSED
39+
* AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
40+
* STRICT LIABILITY OR OTHERWISE, EVEN IF DAQRI HAS BEEN ADVISED OF THE
41+
* POSSIBILITY OF SUCH DAMAGE.
42+
*
43+
* Copyright 2015 Daqri LLC. All Rights Reserved.
44+
* Copyright 2013-2015 ARToolworks, Inc. All Rights Reserved.
45+
*
46+
* Author(s): Philip Lamb.
47+
*
48+
*/
49+
50+
#include "ARMarkerNFT.h"
51+
52+
#include <stdio.h>
53+
#include <string.h>
54+
#ifdef _WIN32
55+
# include <windows.h>
56+
# define MAXPATHLEN MAX_PATH
57+
#else
58+
# include <sys/param.h> // MAXPATHLEN
59+
#endif
60+
61+
62+
const ARPose ARPoseUnity = {{1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}};
63+
64+
static char *get_buff(char *buf, int n, FILE *fp, int skipblanks)
65+
{
66+
char *ret;
67+
size_t l;
68+
69+
do {
70+
ret = fgets(buf, n, fp);
71+
if (ret == NULL) return (NULL); // EOF or error.
72+
73+
// Remove NLs and CRs from end of string.
74+
l = strlen(buf);
75+
while (l > 0) {
76+
if (buf[l - 1] != '\n' && buf[l - 1] != '\r') break;
77+
l--;
78+
buf[l] = '\0';
79+
}
80+
} while (buf[0] == '#' || (skipblanks && buf[0] == '\0')); // Reject comments and blank lines.
81+
82+
return (ret);
83+
}
84+
85+
void newMarkers(const char *markersConfigDataFilePathC, ARMarkerNFT **markersNFT_out, int *markersNFTCount_out)
86+
{
87+
FILE *fp;
88+
char buf[MAXPATHLEN], buf1[MAXPATHLEN];
89+
int tempI;
90+
ARMarkerNFT *markersNFT;
91+
int markersNFTCount;
92+
ARdouble tempF;
93+
int i;
94+
char markersConfigDataDirC[MAXPATHLEN];
95+
size_t markersConfigDataDirCLen;
96+
97+
if (!markersConfigDataFilePathC || markersConfigDataFilePathC[0] == '\0' || !markersNFT_out || !markersNFTCount_out) return;
98+
99+
// Load the marker data file.
100+
ARLOGd("Opening marker config. data file from path '%s'.\n", markersConfigDataFilePathC);
101+
arUtilGetDirectoryNameFromPath(markersConfigDataDirC, markersConfigDataFilePathC, MAXPATHLEN, 1); // 1 = add '/' at end.
102+
markersConfigDataDirCLen = strlen(markersConfigDataDirC);
103+
if ((fp = fopen(markersConfigDataFilePathC, "r")) == NULL) {
104+
ARLOGe("Error: unable to locate marker config data file '%s'.\n", markersConfigDataFilePathC);
105+
return;
106+
}
107+
108+
// First line is number of markers to read.
109+
get_buff(buf, MAXPATHLEN, fp, 1);
110+
if (sscanf(buf, "%d", &tempI) != 1 ) {
111+
ARLOGe("Error in marker configuration data file; expected marker count.\n");
112+
fclose(fp);
113+
return;
114+
}
115+
116+
arMallocClear(markersNFT, ARMarkerNFT, tempI);
117+
markersNFTCount = tempI;
118+
119+
ARLOGd("Reading %d marker configuration(s).\n", markersNFTCount);
120+
121+
for (i = 0; i < markersNFTCount; i++) {
122+
123+
// Read marker name.
124+
if (!get_buff(buf, MAXPATHLEN, fp, 1)) {
125+
ARLOGe("Error in marker configuration data file; expected marker name.\n");
126+
break;
127+
}
128+
129+
// Read marker type.
130+
if (!get_buff(buf1, MAXPATHLEN, fp, 1)) {
131+
ARLOGe("Error in marker configuration data file; expected marker type.\n");
132+
break;
133+
}
134+
135+
// Interpret marker type, and read more data.
136+
if (strcmp(buf1, "SINGLE") == 0) {
137+
ARLOGe("Error in marker configuration data file; SINGLE markers not supported in this build.\n");
138+
} else if (strcmp(buf1, "MULTI") == 0) {
139+
ARLOGe("Error in marker configuration data file; MULTI markers not supported in this build.\n");
140+
} else if (strcmp(buf1, "NFT") == 0) {
141+
markersNFT[i].valid = markersNFT[i].validPrev = FALSE;
142+
arMalloc(markersNFT[i].datasetPathname, char, markersConfigDataDirCLen + strlen(buf) + 1);
143+
strcpy(markersNFT[i].datasetPathname, markersConfigDataDirC);
144+
strcpy(markersNFT[i].datasetPathname + markersConfigDataDirCLen, buf);
145+
markersNFT[i].pageNo = -1;
146+
} else {
147+
ARLOGe("Error in marker configuration data file; unsupported marker type %s.\n", buf1);
148+
}
149+
150+
// Look for optional tokens. A blank line marks end of options.
151+
while (get_buff(buf, MAXPATHLEN, fp, 0) && (buf[0] != '\0')) {
152+
if (strncmp(buf, "FILTER", 6) == 0) {
153+
markersNFT[i].filterCutoffFrequency = AR_FILTER_TRANS_MAT_CUTOFF_FREQ_DEFAULT;
154+
markersNFT[i].filterSampleRate = AR_FILTER_TRANS_MAT_SAMPLE_RATE_DEFAULT;
155+
if (strlen(buf) != 6) {
156+
if (sscanf(&buf[6],
157+
#ifdef ARDOUBLE_IS_FLOAT
158+
"%f"
159+
#else
160+
"%lf"
161+
#endif
162+
, &tempF) == 1) markersNFT[i].filterCutoffFrequency = tempF;
163+
}
164+
markersNFT[i].ftmi = arFilterTransMatInit(markersNFT[i].filterSampleRate, markersNFT[i].filterCutoffFrequency);
165+
}
166+
// Unknown tokens are ignored.
167+
}
168+
}
169+
fclose(fp);
170+
171+
// If not all markers were read, an error occurred.
172+
if (i < markersNFTCount) {
173+
174+
// Clean up.
175+
for (; i >= 0; i--) {
176+
if (markersNFT[i].datasetPathname) free(markersNFT[i].datasetPathname);
177+
if (markersNFT[i].ftmi) arFilterTransMatFinal(markersNFT[i].ftmi);
178+
}
179+
free(markersNFT);
180+
181+
*markersNFTCount_out = 0;
182+
*markersNFT_out = NULL;
183+
return;
184+
}
185+
186+
*markersNFTCount_out = markersNFTCount;
187+
*markersNFT_out = markersNFT;
188+
}
189+
190+
void deleteMarkers(ARMarkerNFT **markersNFT_p, int *markersNFTCount_p)
191+
{
192+
int i;
193+
194+
if (!markersNFT_p || !*markersNFT_p || !*markersNFTCount_p || *markersNFTCount_p < 1) return;
195+
196+
for (i = 0; i < *markersNFTCount_p; i++) {
197+
if ((*markersNFT_p)[i].datasetPathname) {
198+
free((*markersNFT_p)[i].datasetPathname);
199+
(*markersNFT_p)[i].datasetPathname = NULL;
200+
}
201+
if ((*markersNFT_p)[i].ftmi) {
202+
arFilterTransMatFinal((*markersNFT_p)[i].ftmi);
203+
(*markersNFT_p)[i].ftmi = NULL;
204+
}
205+
}
206+
free(*markersNFT_p);
207+
*markersNFT_p = NULL;
208+
*markersNFTCount_p = 0;
209+
}

0 commit comments

Comments
 (0)