Object *convertSig2ClassArray(char **sig_pntr, Class *declaring_class) { char *sig = *sig_pntr; int no_params, i = 0; Class **params; Object *array; for(no_params = 0; *++sig != ')'; no_params++) { if(*sig == '[') while(*++sig == '['); if(*sig == 'L') while(*++sig != ';'); } if((array = allocArray(class_array_class, no_params, sizeof(Class*))) == NULL) return NULL; params = ARRAY_DATA(array, Class*); *sig_pntr += 1; while(**sig_pntr != ')') if((params[i++] = convertSigElement2Class(sig_pntr, declaring_class)) == NULL) return NULL; return array; }
int main(int argc, char *argv[]) { Class *array_class, *main_class; Object *system_loader, *array; MethodBlock *mb; InitArgs args; int class_arg; char *cpntr; int status; int i; setDefaultInitArgs(&args); class_arg = parseCommandLine(argc, argv, &args); args.main_stack_base = &array_class; if(!initVM(&args)) { printf("Could not initialise VM. Aborting.\n"); exit(1); } if((system_loader = getSystemClassLoader()) == NULL) goto error; mainThreadSetContextClassLoader(system_loader); for(cpntr = argv[class_arg]; *cpntr; cpntr++) if(*cpntr == '.') *cpntr = '/'; main_class = findClassFromClassLoader(argv[class_arg], system_loader); if(main_class != NULL) initClass(main_class); if(exceptionOccurred()) goto error; mb = lookupMethod(main_class, SYMBOL(main), SYMBOL(_array_java_lang_String__V)); if(mb == NULL || !(mb->access_flags & ACC_STATIC)) { signalException(java_lang_NoSuchMethodError, "main"); goto error; } /* Create the String array holding the command line args */ i = class_arg + 1; if((array_class = findArrayClass(SYMBOL(array_java_lang_String))) && (array = allocArray(array_class, argc - i, sizeof(Object*)))) { Object **args = ARRAY_DATA(array, Object*) - i; for(; i < argc; i++) if(!(args[i] = Cstr2String(argv[i]))) break; /* Call the main method */ if(i == argc) executeStaticMethod(main_class, mb, array); }
jobjectArray jmm_GetMemoryManagers(JNIEnv *env, jobject obj) { Class *array_class = findArrayClass(SYMBOL(array_java_lang_String)); if(array_class == NULL) return NULL; return allocArray(array_class, 0, sizeof(Object*)); }
SEXP kz3d(SEXP x, SEXP window, SEXP iterations) { int i, j, l; SEXP ans, tmp, dim; SEXP index; int offset, offset_a; int m1, m2, m3; if (length(window)<3) {m1 = m2 = m3 = INTEGER_VALUE(window);} else {m1 = INTEGER(window)[0]; m2 = INTEGER(window)[1]; m3 = INTEGER(window)[2];} dim = GET_DIM(x); PROTECT(index = allocVector(INTSXP, LENGTH(dim))); PROTECT(ans = allocArray(REALSXP, dim)); PROTECT(tmp = allocArray(REALSXP, dim)); copyArray(ans, x); for(l=0; l<INTEGER_VALUE(iterations); l++) { copyArray(tmp, ans); for(INTEGER(index)[0]=0; INTEGER(index)[0]<INTEGER(dim)[0]; INTEGER(index)[0]++) { for(INTEGER(index)[1]=0; INTEGER(index)[1]<INTEGER(dim)[1]; INTEGER(index)[1]++) { for(INTEGER(index)[2]=0; INTEGER(index)[2]<INTEGER(dim)[2]; INTEGER(index)[2]++) { /* offset += INTEGER(index)[0]; offset += INTEGER(dim)[0]*INTEGER(index)[1]; offset += INTEGER(dim)[0]*INTEGER(dim)[1]*INTEGER(index)[2]; offset += INTEGER(dim)[0]*INTEGER(dim)[1]*INTEGER(dim)[2]*INTEGER(index)[3]; */ /* find offset into array */ for(i=0, offset=0; i<LENGTH(dim); i++) { for(j=0, offset_a=1; j<i; j++) { offset_a *= INTEGER(dim)[j]; } offset += offset_a * INTEGER(index)[i]; } REAL(ans)[offset] = averaged(tmp, index, m1, m2, m3); } } } } UNPROTECT(3); return ans; }
HdfNode* allocHdfNode(HdfPool* pool){ assert(pool); if(pool->cursor == pool->length){ die("Reach Capacity Of HdfPool"); } HdfNode* node = pool->buffer+pool->cursor++; node->children = allocArray(); node->value = allocCSValue(); return node; }
template<class T> void Stack<T>::expandCapacity() { unsigned int newCapacity = m_capacity == 0 ? INITIAL_SIZE : m_capacity * 2; T* newArray = allocArray(newCapacity); for (unsigned int i = 0; i < m_size; i++) { newArray[i] = m_array[i]; } SAFE_ARRAY_DELETE(m_array); m_array = newArray; m_capacity = newCapacity; }
template<class T> void Stack<T>::resize(unsigned int newSize) { if (newSize > m_size) { T* newArray = allocArray(newSize); for (unsigned int i = 0; i < min(m_size,newSize); i++) { newArray[i] = m_array[i]; } SAFE_ARRAY_DELETE(m_array); m_array = newArray; m_capacity = newSize; } m_size = newSize; }
template<class T> void Stack<T>::reserve(unsigned int newCapacity) { if (newCapacity > m_capacity) { T* newArray = allocArray(newCapacity); for (unsigned int i = 0; i < m_size; i++) { newArray[i] = m_array[i]; } SAFE_ARRAY_DELETE(m_array); m_array = newArray; m_capacity = newCapacity; } }
static R_INLINE SEXP makearray (int rank, int *dim) { int nprotect = 0; int *dimp, k; double *xp; SEXP dimx, x; PROTECT(dimx = NEW_INTEGER(rank)); nprotect++; dimp = INTEGER(dimx); for (k = 0; k < rank; k++) dimp[k] = dim[k]; PROTECT(x = allocArray(REALSXP,dimx)); nprotect++; xp = REAL(x); for (k = 0; k < length(x); k++) xp[k] = NA_REAL; UNPROTECT(nprotect); return x; }
Object *getExceptionTypes(MethodBlock *mb) { int i; Object *array; Class **excps; if((array = allocArray(class_array_class, mb->throw_table_size, sizeof(Class*))) == NULL) return NULL; excps = ARRAY_DATA(array, Class*); for(i = 0; i < mb->throw_table_size; i++) if((excps[i] = resolveClass(mb->class, mb->throw_table[i], FALSE)) == NULL) return NULL; return array; }
template<class T> Stack<T>& Stack<T>::operator=(const Stack<T>& other) { if (this == &other) return *this; if (m_capacity < other.m_size) { SAFE_ARRAY_DELETE(m_array); m_capacity = other.m_size; m_array = allocArray(m_capacity); } m_size = other.m_size; for (unsigned int i = 0; i < other.m_size; i++) { m_array[i] = other.m_array[i]; } return *this; }
template<class T> Stack<T>::Stack(const Stack<T>& other) { if (other.m_size != 0) { m_capacity = other.m_size; } else { m_capacity = INITIAL_SIZE; } m_array = allocArray(m_capacity); m_size = other.m_size; for (unsigned int i = 0; i < other.m_size; i++) { m_array[i] = other.m_array[i]; } }
void setFaceSet(ReallocArray* facesets, int material, int smooth, int index) { OBJFaceSet* edit = NULL; OBJFaceSet* last = NULL; if (facesets->size > 0) last = ((OBJFaceSet*)facesets->data) + (facesets->size-1); if (last && (last->material == material || material == -1) && last->smooth == smooth) return; //nothing to do if (last && last->indexStart == index) //no faces in set last set { if (material == -1 && smooth == -1) //unique combination to mark end of faceset { facesets->size -= 1; //end of unused faceset. remove return; } edit = last; } else { //update end index if (last) last->indexEnd = index; if (material == -1 && smooth == -1) //unique combination to mark end of faceset return; //append new faceset facesets->size += 1; allocArray(facesets); edit = ((OBJFaceSet*)facesets->data) + (facesets->size-1); edit->indexStart = index; edit->indexEnd = index; //unnecessary, but just in case } if (last && material == -1) edit->material = last->material; //use previous material (eg for changing smooth state) else edit->material = material; //simply update material. may be -1 edit->smooth = smooth; }
off_t DataSet::open(const char *fileName, int npoleGuess, float sampRate) { if ((_fdesc = ::open(fileName, O_RDONLY)) < 0) { ::rterror("dataset", "Can't open %s", fileName); return -1; } _nPoles = npoleGuess; // in case we are not using headers ::rtcmix_advise("dataset", "Opened lpc dataset %s.", fileName); #ifdef USE_HEADERS Bool isSwapped = NO; if ((_lpHeaderSize = ::checkForHeader(_fdesc, &_nPoles, sampRate, &isSwapped)) < 0) { ::rterror("dataset", "Failed to check header"); return -1; } _swapped = (isSwapped != 0); #else if (!_nPoles) { return -1; } #endif /* USE_HEADERS */ allocArray(_nPoles); _npolem1=_nPoles-1; _framsize=_nPoles+4; _recsize=_fprec*_framsize; _bprec=_recsize*FLOAT; _bpframe=_framsize*FLOAT; struct stat st; /* store and return number of frames in datafile */ if (::stat(fileName, &st) >= 0) { _frameCount = (st.st_size-_lpHeaderSize) / _bpframe; return _frameCount; } else { ::rterror("dataset", "Unable to stat dataset file."); return -1; } }
mesh_t *createSphere(float radius, int rings, int sectors, texture_t *texture, program_t *program) { // Inspired by http://stackoverflow.com/questions/7946770/calculating-a-sphere-in-opengl const float R = 1.0f / (rings-1); const float S = 1.0f / (sectors-1); int r, s; vertex_t *vertices = allocArray(vertex_t, rings * sectors); vertex_t *vertexIterator = vertices; mesh_t *sphere; for (r = 0; r < rings; r++) { for (s = 0; s < sectors; s++) { const float x = Math.cos(2.0f * Math.pi * s * S) * Math.sin(Math.pi * r * R); const float y = Math.sin(2.0f * Math.pi * s * S) * Math.sin(Math.pi * r * R); const float z = Math.sin(-0.5f * Math.pi + Math.pi * r * R); vertexIterator->coords.x = _cursorPos[0] + x * radius; vertexIterator->coords.y = _cursorPos[1] + y * radius; vertexIterator->coords.z = _cursorPos[2] + z * radius; Vector.rotate((float*)&vertexIterator->coords, _localAxis); vertexIterator->texCoords.u = s * S; vertexIterator->texCoords.v = 1.0f - r * R; vertexIterator->normal.x = x; vertexIterator->normal.y = y; vertexIterator->normal.z = z; vertexIterator++; } } sphere = Mesh.newMesh(); for (r = 0; r < rings; r++) { for (s = 0; s < sectors; s++) { face_t *currentFace; vertex_t **currentVertices; vertex_t *v1 = &vertices[((r+0)%rings) * sectors + ((s+0)%sectors)]; vertex_t *v2 = &vertices[((r+0)%rings) * sectors + ((s+1)%sectors)]; vertex_t *v3 = &vertices[((r+1)%rings) * sectors + ((s+1)%sectors)]; vertex_t *v4 = &vertices[((r+1)%rings) * sectors + ((s+0)%sectors)]; currentFace = Mesh.addFaceToMesh(sphere); currentFace->texture = texture; currentFace->program = program; currentVertices = allocArray(vertex_t*, 3); currentVertices[0] = v1; currentVertices[1] = v2; currentVertices[2] = v3; currentFace->vertices = currentVertices; currentFace->nbVertices = 3; currentFace = Mesh.addFaceToMesh(sphere); currentFace->texture = texture; currentFace->program = program; currentVertices = allocArray(vertex_t*, 3); currentVertices[0] = v3; currentVertices[1] = v4; currentVertices[2] = v1; currentFace->vertices = currentVertices; currentFace->nbVertices = 3; } } Mesh.updateGeometry(sphere); return sphere; }
SEXP attribute_hidden do_subset_dflt(SEXP call, SEXP op, SEXP args, SEXP rho) { SEXP ans, ax, px, x, subs; int drop, i, nsubs, type; /* By default we drop extents of length 1 */ /* Handle cases of extracting a single element from a simple vector or matrix directly to improve speed for these simple cases. */ SEXP cdrArgs = CDR(args); SEXP cddrArgs = CDR(cdrArgs); if (cdrArgs != R_NilValue && cddrArgs == R_NilValue && TAG(cdrArgs) == R_NilValue) { /* one index, not named */ SEXP x = CAR(args); if (ATTRIB(x) == R_NilValue) { SEXP s = CAR(cdrArgs); R_xlen_t i = scalarIndex(s); switch (TYPEOF(x)) { case REALSXP: if (i >= 1 && i <= XLENGTH(x)) return ScalarReal( REAL(x)[i-1] ); break; case INTSXP: if (i >= 1 && i <= XLENGTH(x)) return ScalarInteger( INTEGER(x)[i-1] ); break; case LGLSXP: if (i >= 1 && i <= XLENGTH(x)) return ScalarLogical( LOGICAL(x)[i-1] ); break; // do the more rare cases as well, since we've already prepared everything: case CPLXSXP: if (i >= 1 && i <= XLENGTH(x)) return ScalarComplex( COMPLEX(x)[i-1] ); break; case RAWSXP: if (i >= 1 && i <= XLENGTH(x)) return ScalarRaw( RAW(x)[i-1] ); break; default: break; } } } else if (cddrArgs != R_NilValue && CDR(cddrArgs) == R_NilValue && TAG(cdrArgs) == R_NilValue && TAG(cddrArgs) == R_NilValue) { /* two indices, not named */ SEXP x = CAR(args); SEXP attr = ATTRIB(x); if (TAG(attr) == R_DimSymbol && CDR(attr) == R_NilValue) { /* only attribute of x is 'dim' */ SEXP dim = CAR(attr); if (TYPEOF(dim) == INTSXP && LENGTH(dim) == 2) { /* x is a matrix */ SEXP si = CAR(cdrArgs); SEXP sj = CAR(cddrArgs); R_xlen_t i = scalarIndex(si); R_xlen_t j = scalarIndex(sj); int nrow = INTEGER(dim)[0]; int ncol = INTEGER(dim)[1]; if (i > 0 && j > 0 && i <= nrow && j <= ncol) { /* indices are legal scalars */ R_xlen_t k = i - 1 + nrow * (j - 1); switch (TYPEOF(x)) { case REALSXP: if (k < LENGTH(x)) return ScalarReal( REAL(x)[k] ); break; case INTSXP: if (k < LENGTH(x)) return ScalarInteger( INTEGER(x)[k] ); break; case LGLSXP: if (k < LENGTH(x)) return ScalarLogical( LOGICAL(x)[k] ); break; case CPLXSXP: if (k < LENGTH(x)) return ScalarComplex( COMPLEX(x)[k] ); break; case RAWSXP: if (k < LENGTH(x)) return ScalarRaw( RAW(x)[k] ); break; default: break; } } } } } PROTECT(args); drop = 1; ExtractDropArg(args, &drop); x = CAR(args); /* This was intended for compatibility with S, */ /* but in fact S does not do this. */ /* FIXME: replace the test by isNull ... ? */ if (x == R_NilValue) { UNPROTECT(1); return x; } subs = CDR(args); nsubs = length(subs); /* Will be short */ type = TYPEOF(x); /* Here coerce pair-based objects into generic vectors. */ /* All subsetting takes place on the generic vector form. */ ax = x; if (isVector(x)) PROTECT(ax); else if (isPairList(x)) { SEXP dim = getAttrib(x, R_DimSymbol); int ndim = length(dim); if (ndim > 1) { PROTECT(ax = allocArray(VECSXP, dim)); setAttrib(ax, R_DimNamesSymbol, getAttrib(x, R_DimNamesSymbol)); setAttrib(ax, R_NamesSymbol, getAttrib(x, R_DimNamesSymbol)); } else { PROTECT(ax = allocVector(VECSXP, length(x))); setAttrib(ax, R_NamesSymbol, getAttrib(x, R_NamesSymbol)); } for(px = x, i = 0 ; px != R_NilValue ; px = CDR(px)) SET_VECTOR_ELT(ax, i++, CAR(px)); } else errorcall(call, R_MSG_ob_nonsub, type2char(TYPEOF(x))); /* This is the actual subsetting code. */ /* The separation of arrays and matrices is purely an optimization. */ if(nsubs < 2) { SEXP dim = getAttrib(x, R_DimSymbol); int ndim = length(dim); PROTECT(ans = VectorSubset(ax, (nsubs == 1 ? CAR(subs) : R_MissingArg), call)); /* one-dimensional arrays went through here, and they should have their dimensions dropped only if the result has length one and drop == TRUE */ if(ndim == 1) { SEXP attr, attrib, nattrib; int len = length(ans); if(!drop || len > 1) { // must grab these before the dim is set. SEXP nm = PROTECT(getAttrib(ans, R_NamesSymbol)); PROTECT(attr = allocVector(INTSXP, 1)); INTEGER(attr)[0] = length(ans); setAttrib(ans, R_DimSymbol, attr); if((attrib = getAttrib(x, R_DimNamesSymbol)) != R_NilValue) { /* reinstate dimnames, include names of dimnames */ PROTECT(nattrib = duplicate(attrib)); SET_VECTOR_ELT(nattrib, 0, nm); setAttrib(ans, R_DimNamesSymbol, nattrib); setAttrib(ans, R_NamesSymbol, R_NilValue); UNPROTECT(1); } UNPROTECT(2); } } } else { if (nsubs != length(getAttrib(x, R_DimSymbol))) errorcall(call, _("incorrect number of dimensions")); if (nsubs == 2) ans = MatrixSubset(ax, subs, call, drop); else ans = ArraySubset(ax, subs, call, drop); PROTECT(ans); } /* Note: we do not coerce back to pair-based lists. */ /* They are "defunct" in this version of R. */ if (type == LANGSXP) { ax = ans; PROTECT(ans = allocList(LENGTH(ax))); if ( LENGTH(ax) > 0 ) SET_TYPEOF(ans, LANGSXP); for(px = ans, i = 0 ; px != R_NilValue ; px = CDR(px)) SETCAR(px, VECTOR_ELT(ax, i++)); setAttrib(ans, R_DimSymbol, getAttrib(ax, R_DimSymbol)); setAttrib(ans, R_DimNamesSymbol, getAttrib(ax, R_DimNamesSymbol)); setAttrib(ans, R_NamesSymbol, getAttrib(ax, R_NamesSymbol)); SET_NAMED(ans, NAMED(ax)); /* PR#7924 */ } else { PROTECT(ans); } if (ATTRIB(ans) != R_NilValue) { /* remove probably erroneous attr's */ setAttrib(ans, R_TspSymbol, R_NilValue); #ifdef _S4_subsettable if(!IS_S4_OBJECT(x)) #endif setAttrib(ans, R_ClassSymbol, R_NilValue); } UNPROTECT(4); return ans; }
SEXP _ini_array(SEXP d, SEXP p, SEXP v, SEXP s) { if (TYPEOF(d) != INTSXP || TYPEOF(p) != INTSXP || TYPEOF(s) != INTSXP) error("'d, p, s' not integer"); int n, m; SEXP r, dd; if (!isVector(v)) error("'v' not a vector"); if (isMatrix(p)) { r = getAttrib(p, R_DimSymbol); n = INTEGER(r)[0]; if (n != LENGTH(v)) error("'p' and 'v' do not conform"); m = INTEGER(r)[1]; if (m != LENGTH(d)) error("'p' and 'd' do not conform"); r = PROTECT(allocArray(TYPEOF(v), d)); } else { n = LENGTH(p); if (n != LENGTH(v)) error("'p' and 'v' do not conform"); m = 1; if (m != LENGTH(d)) error("'p' and 'd' do not conform"); r = PROTECT(allocVector(TYPEOF(v), INTEGER(d)[0])); } switch(TYPEOF(v)) { case LGLSXP: case INTSXP: memset(INTEGER(r), 0, sizeof(int) * LENGTH(r)); break; case REALSXP: memset(REAL(r), 0, sizeof(double) * LENGTH(r)); break; case RAWSXP: memset(RAW(r), 0, sizeof(char) * LENGTH(r)); break; case CPLXSXP: memset(COMPLEX(r), 0, sizeof(Rcomplex) * LENGTH(r)); break; case EXPRSXP: case VECSXP: for (int i = 0; i < LENGTH(r); i++) SET_VECTOR_ELT(r, i, R_NilValue); break; case STRSXP: for (int i = 0; i < LENGTH(r); i++) SET_STRING_ELT(r, i, R_BlankString); break; default: error("type of 'v' not supported"); } if (m > 2) { dd = PROTECT(duplicate(d)); for (int i = 1; i < m - 1; i++) INTEGER(dd)[i] *= INTEGER(dd)[i-1]; } else dd = d; for (int i = 0; i < LENGTH(s); i++) { int k = INTEGER(s)[i]; if (k < 1 || k > n) error("'s' invalid"); k--; int h = k; int l = INTEGER(p)[k]; if (l < 1 || l > INTEGER(d)[0]) error("'p' invalid"); l--; for (int j = 1; j < m; j++) { k += n; int ll = INTEGER(p)[k]; if (ll < 1 || ll > INTEGER(d)[j]) error("'p' invalid"); ll--; l += INTEGER(dd)[j - 1] * ll; } switch(TYPEOF(v)) { case LGLSXP: case INTSXP: INTEGER(r)[l] = INTEGER(v)[h]; break; case REALSXP: REAL(r)[l] = REAL(v)[h]; break; case RAWSXP: RAW(r)[l] = RAW(v)[h]; break; case CPLXSXP: COMPLEX(r)[l] = COMPLEX(v)[h]; break; case EXPRSXP: case VECSXP: SET_VECTOR_ELT(r, l, VECTOR_ELT(v, h)); break; case STRSXP: SET_STRING_ELT(r, l, STRING_ELT(v, h)); break; default: error("type of 'v' not supported"); } } UNPROTECT(1 + (m > 2)); return r; }
template<class T> Stack<T>::Stack(unsigned int initiailSize) { m_capacity = initiailSize; m_array = allocArray(m_capacity); m_size = 0; }
void Vertex::operator =(const Vertex& other){ allocArray(); for (int i=0;i<3;i++){ arry[i]=other.arry[i]; } }
SEXP TransPROBIPCW2( SEXP object, SEXP UT, SEXP UX, SEXP h, SEXP window, SEXP methodweights, SEXP nboot, SEXP methodest) { SEXP data, T1, E1, S, E, X; data = VECTOR_ELT(object, 0); T1 = VECTOR_ELT(data, 0); E1 = VECTOR_ELT(data, 1); S = VECTOR_ELT(data, 2); E = VECTOR_ELT(data, 3); X = VECTOR_ELT(data, 4); int len = GET_LENGTH(T1), nt = GET_LENGTH(UT), nx = GET_LENGTH(UX); Kfunc kfunc = kchar2ptr(window); // declare and get pointer to function Wfunc wfunc = NWWeights; // declare and assign pointer to function if (strcmp(CHAR( STRING_ELT(methodweights, 0) ), "LL") == 0) wfunc = LLWeights; SEXP dims, P, list; PROTECT( dims = allocVector(INTSXP, 4) ); INTEGER(dims)[0] = *INTEGER(nboot); INTEGER(dims)[1] = nt; INTEGER(dims)[2] = nx; INTEGER(dims)[3] = 4; PROTECT( P = allocArray(REALSXP, dims) ); PROTECT( list = NEW_LIST(2) ); void (*func)(CintCP, CdoubleCP, CintCP, CdoubleCP, CintCP, CdoubleCP, CstypeCP, CintCP, CintCP, CintCP, CdoubleCP, CintCP, CdoubleCP, CdoubleCP, Kfunc, Wfunc, CintCP, doubleCP, CintCP, CintCP, transIPCWW *); switch ( *INTEGER(methodest) ) { case 2: func = transIPCW4I; break; default: func = transIPCW3I; } int b, t, nth = 1; transIPCWW *WORK = (transIPCWW*)malloc( global_num_threads*sizeof(transIPCWW) ); // allocate memory block if (WORK == NULL) error("TransPROBIPCW2: No more memory\n"); for (t = 0; t < global_num_threads; t++) { // allocate per thread memory if ( ( WORK[t].K = (double*)malloc( len*sizeof(double) ) ) == NULL ) error("TransPROBIPCW2: No more memory\n"); if ( ( WORK[t].SV = (double*)malloc( len*sizeof(double) ) ) == NULL ) error("TransPROBIPCW2: No more memory\n"); } if (*INTEGER(nboot) > 1) nth = global_num_threads; int **index0 = (int**)malloc( nth*sizeof(int*) ); // allocate memory block if (index0 == NULL) error("TransPROBIPCW2: No more memory\n"); int **index1 = (int**)malloc( nth*sizeof(int*) ); // allocate memory block if (index1 == NULL) error("TransPROBIPCW2: No more memory\n"); for (t = 0; t < nth; t++) { // allocate per thread memory if ( ( index0[t] = (int*)malloc( len*sizeof(int) ) ) == NULL ) error("TransPROBIPCW2: No more memory\n"); if ( ( index1[t] = (int*)malloc( len*sizeof(int) ) ) == NULL ) error("TransPROBIPCW2: No more memory\n"); } stype SW; // declare stype structure SW.type = SINT_PTR; // type is a short int pointer SW.ptr.shortinteger = (short int*)malloc( len*sizeof(short int) ); // allocate memory block if (SW.ptr.shortinteger == NULL) error("TransPROBIPCW2: No more memory\n"); SW.length = len; // hold length of array for (b = 0; b < len; b++) SW.ptr.shortinteger[b] = 1; // weights should be equal to 1.0/len, however all weights equal to 1 yield an equivalent result in this case b = 0; // b = len, put it back to 0 or a crash might occur t = 0; // t = nth, put it back to 0 or a crash might occur indx_ii(&len, index0[0], index1[0]); // initialize indexes order_d(REAL(T1), index0[0], len, FALSE, FALSE, WORK[0].K); // get permuation order_d(REAL(S), index1[0], len, FALSE, FALSE, WORK[0].K); // get permuation func(&len, REAL(T1), INTEGER(E1), REAL(S), INTEGER(E), REAL(X), &SW, index0[0], index1[0], &nt, REAL(UT), &nx, REAL(UX), REAL(h), kfunc, wfunc, INTEGER(nboot), REAL(P), &b, &t, WORK); // compute transition probabilities if (*INTEGER(nboot) > 1) { #ifdef _OPENMP #pragma omp parallel num_threads(global_num_threads) private(b, t) #endif { #ifdef _OPENMP t = omp_get_thread_num(); #else t = 0; #endif #ifdef _OPENMP #pragma omp for #endif for (b = 1; b < *INTEGER(nboot); b++) { boot_ii(RngArray[t], &len, index0[t], index1[t]); // bootstrap indexes order_d(REAL(T1), index0[t], len, FALSE, FALSE, WORK[t].K); // get permuation order_d(REAL(S), index1[t], len, FALSE, FALSE, WORK[t].K); // get permuation func(&len, REAL(T1), INTEGER(E1), REAL(S), INTEGER(E), REAL(X), &SW, index0[t], index1[t], &nt, REAL(UT), &nx, REAL(UX), REAL(h), kfunc, wfunc, INTEGER(nboot), REAL(P), &b, &t, WORK); // compute transition probabilities } } } for (t = nth-1; t >= 0; t--) { free(index0[t]); // free memory block free(index1[t]); // free memory block } free(index0); // free memory block free(index1); // free memory block for (t = global_num_threads-1; t >= 0; t--) { free(WORK[t].K); // free memory block free(WORK[t].SV); // free memory block } free(WORK); // free memory block free(SW.ptr.shortinteger); // free memory block SET_ELEMENT(list, 0, P); SET_ELEMENT(list, 1, h); UNPROTECT(3); return list; } // TransPROBIPCW2
int main(int argc, char **argv) { //printf("n_threads: %d\n", omp_get_num_threads()); char * lcs_result = NULL; InputInfo * inputInfo = NULL; // read input inputInfo = readInput(argv[1]); if(inputInfo == NULL) { printf("input info is NULL\n"); return -1; } int matx_max = inputInfo->size_x; int maty_max = inputInfo->size_y; int i,j; CellVal **matrix = allocArray(matx_max, maty_max); // define the number of cells on the auxiliar matrix int block_x_size = (matx_max > 20)? 20 : matx_max / 5; int block_y_size = (maty_max > 300)? 300 : maty_max / 5; int tabx_max = matx_max / block_x_size; int taby_max = maty_max / block_y_size; CellVal **table = allocArray(tabx_max, taby_max); // initialize table: 1 for the sides, 2 for the 1st square, 0 for the rest for(i = 0; i < tabx_max; i++) { for(j = 0; j < taby_max; j++) { if(i==0 && j==0) table[i][j] = 2; else if(i==0 || j==0) table[i][j] = 1; else table[i][j] = 0; } } // initialize the global vars that are used on the generation of new blocks int remainderX = matx_max % block_x_size; int extra_per_cellX = remainderX / tabx_max; extra_remainderX = remainderX % tabx_max; n_mat_coords_per_cellX = block_x_size + extra_per_cellX; int remainderY = maty_max % block_y_size; int extra_per_cellY = remainderY / taby_max; extra_remainderY = remainderY % taby_max; n_mat_coords_per_cellY = block_y_size + extra_per_cellY; // initialize the block stack with the first block to be processed Stack * stack = new_stack(max(tabx_max, taby_max)); push(stack, new_square(0, 0, matx_max, maty_max, tabx_max, taby_max)); Square * square = NULL; // holds the block for processing CellVal x,y; int notFinished = 1; // false #pragma omp parallel private(square, x, y, notFinished) { notFinished = 1; while(notFinished) { square = NULL; // wait for a block to process while(square == NULL && notFinished) { #pragma omp critical { if(!empty(stack)) { square = pop(stack); table[square->tabX][square->tabY]++; } } if(square == NULL) notFinished = notFinishedTab(table, tabx_max, taby_max); } if(!notFinished) break; // process the block for(x = square->x_min; x < square->x_max; x++) { for(y = square->y_min; y < square->y_max; y++) { calc(x,y, matrix, inputInfo->X, inputInfo->Y); } } // update the auxiliar table and add to the stack the blocks that now can be processed #pragma omp critical { if(square->tabX + 1 < tabx_max) { table[square->tabX + 1][square->tabY]++; if(table[square->tabX + 1][square->tabY] == 2) { push(stack, new_square(square->tabX + 1, square->tabY, matx_max, maty_max, tabx_max, taby_max)); } } if(square->tabY +1 < taby_max) { table[square->tabX][square->tabY + 1]++; if(table[square->tabX][square->tabY + 1] == 2) { push(stack, new_square(square->tabX, square->tabY + 1, matx_max, maty_max, tabx_max, taby_max)); } } } free(square); notFinished = notFinishedTab(table, tabx_max, taby_max); } } free(table); delete_stack(stack); // lcs_result = lcs(matrix, inputInfo->X, inputInfo->Y, matx_max, maty_max); printf("%d\n", matrix[matx_max-1][maty_max-1]); printf("%s\n", lcs_result); return 0; }
static void PrintGenericVector(SEXP s, SEXP env) { int i, taglen, ns, w, d, e, wr, dr, er, wi, di, ei; SEXP dims, t, names, newcall, tmp; char pbuf[115], *ptag, save[TAGBUFLEN0]; ns = length(s); if((dims = getAttrib(s, R_DimSymbol)) != R_NilValue && length(dims) > 1) { // special case: array-like list PROTECT(dims); PROTECT(t = allocArray(STRSXP, dims)); /* FIXME: check (ns <= R_print.max +1) ? ns : R_print.max; */ for (i = 0; i < ns; i++) { switch(TYPEOF(PROTECT(tmp = VECTOR_ELT(s, i)))) { case NILSXP: snprintf(pbuf, 115, "NULL"); break; case LGLSXP: if (LENGTH(tmp) == 1) { const int *x = LOGICAL_RO(tmp); formatLogical(x, 1, &w); snprintf(pbuf, 115, "%s", EncodeLogical(x[0], w)); } else snprintf(pbuf, 115, "Logical,%d", LENGTH(tmp)); break; case INTSXP: /* factors are stored as integers */ if (inherits(tmp, "factor")) { snprintf(pbuf, 115, "factor,%d", LENGTH(tmp)); } else { if (LENGTH(tmp) == 1) { const int *x = INTEGER_RO(tmp); formatInteger(x, 1, &w); snprintf(pbuf, 115, "%s", EncodeInteger(x[0], w)); } else snprintf(pbuf, 115, "Integer,%d", LENGTH(tmp)); } break; case REALSXP: if (LENGTH(tmp) == 1) { const double *x = REAL_RO(tmp); formatReal(x, 1, &w, &d, &e, 0); snprintf(pbuf, 115, "%s", EncodeReal0(x[0], w, d, e, OutDec)); } else snprintf(pbuf, 115, "Numeric,%d", LENGTH(tmp)); break; case CPLXSXP: if (LENGTH(tmp) == 1) { const Rcomplex *x = COMPLEX_RO(tmp); if (ISNA(x[0].r) || ISNA(x[0].i)) /* formatReal(NA) --> w=R_print.na_width, d=0, e=0 */ snprintf(pbuf, 115, "%s", EncodeReal0(NA_REAL, R_print.na_width, 0, 0, OutDec)); else { formatComplex(x, 1, &wr, &dr, &er, &wi, &di, &ei, 0); snprintf(pbuf, 115, "%s", EncodeComplex(x[0], wr, dr, er, wi, di, ei, OutDec)); } } else snprintf(pbuf, 115, "Complex,%d", LENGTH(tmp)); break; case STRSXP: if (LENGTH(tmp) == 1) { const void *vmax = vmaxget(); /* This can potentially overflow */ const char *ctmp = translateChar(STRING_ELT(tmp, 0)); int len = (int) strlen(ctmp); if(len < 100) snprintf(pbuf, 115, "\"%s\"", ctmp); else { snprintf(pbuf, 101, "\"%s\"", ctmp); pbuf[100] = '"'; pbuf[101] = '\0'; strcat(pbuf, " [truncated]"); } vmaxset(vmax); } else snprintf(pbuf, 115, "Character,%d", LENGTH(tmp)); break; case RAWSXP: snprintf(pbuf, 115, "Raw,%d", LENGTH(tmp)); break; case LISTSXP: case VECSXP: snprintf(pbuf, 115, "List,%d", length(tmp)); break; case LANGSXP: snprintf(pbuf, 115, "Expression"); break; default: snprintf(pbuf, 115, "?"); break; } UNPROTECT(1); /* tmp */ pbuf[114] = '\0'; SET_STRING_ELT(t, i, mkChar(pbuf)); } if (LENGTH(dims) == 2) { SEXP rl, cl; const char *rn, *cn; GetMatrixDimnames(s, &rl, &cl, &rn, &cn); /* as from 1.5.0: don't quote here as didn't in array case */ printMatrix(t, 0, dims, 0, R_print.right, rl, cl, rn, cn); } else { PROTECT(names = GetArrayDimnames(s)); printArray(t, dims, 0, Rprt_adj_left, names); UNPROTECT(1); } UNPROTECT(2); } else { // no dim() PROTECT(names = getAttrib(s, R_NamesSymbol)); taglen = (int) strlen(tagbuf); ptag = tagbuf + taglen; PROTECT(newcall = allocList(2)); SETCAR(newcall, install("print")); SET_TYPEOF(newcall, LANGSXP); if(ns > 0) { int n_pr = (ns <= R_print.max +1) ? ns : R_print.max; /* '...max +1' ==> will omit at least 2 ==> plural in msg below */ for (i = 0; i < n_pr; i++) { if (i > 0) Rprintf("\n"); if (names != R_NilValue && STRING_ELT(names, i) != R_NilValue && *CHAR(STRING_ELT(names, i)) != '\0') { const void *vmax = vmaxget(); /* Bug for L <- list(`a\\b` = 1, `a\\c` = 2) : const char *ss = translateChar(STRING_ELT(names, i)); */ const char *ss = EncodeChar(STRING_ELT(names, i)); #ifdef Win32 /* FIXME: double translation to native encoding, in EncodeChar and translateChar; it is however necessary to call isValidName() on a string without Rgui escapes, because Rgui escapes cause a name to be regarded invalid; note also differences with printList */ const char *st = ss; if (WinUTF8out) st = translateChar(STRING_ELT(names, i)); #endif if (taglen + strlen(ss) > TAGBUFLEN) { if (taglen <= TAGBUFLEN) sprintf(ptag, "$..."); } else { /* we need to distinguish character NA from "NA", which is a valid (if non-syntactic) name */ if (STRING_ELT(names, i) == NA_STRING) sprintf(ptag, "$<NA>"); #ifdef Win32 else if( isValidName(st) ) #else else if( isValidName(ss) ) #endif sprintf(ptag, "$%s", ss); else sprintf(ptag, "$`%s`", ss); } vmaxset(vmax); } else { if (taglen + IndexWidth(i) > TAGBUFLEN) { if (taglen <= TAGBUFLEN) sprintf(ptag, "$..."); } else sprintf(ptag, "[[%d]]", i+1); } Rprintf("%s\n", tagbuf); if(isObject(VECTOR_ELT(s, i))) { SEXP x = VECTOR_ELT(s, i); int nprot = 0; if (TYPEOF(x) == LANGSXP) { // quote(x) to not accidentally evaluate it with newcall() below: x = PROTECT(lang2(R_Primitive("quote"), x)); nprot++; } /* need to preserve tagbuf */ strcpy(save, tagbuf); SETCADR(newcall, x); eval(newcall, env); strcpy(tagbuf, save); UNPROTECT(nprot); } else PrintValueRec(VECTOR_ELT(s, i), env); *ptag = '\0'; } Rprintf("\n"); if(n_pr < ns) Rprintf(" [ reached getOption(\"max.print\") -- omitted %d entries ]\n", ns - n_pr); }
static SEXP Julia_R_MD_NA(jl_value_t *Var) { SEXP ans = R_NilValue; char *strData = "Varname0tmp.data"; char *strNA = "bitunpack(Varname0tmp.na)"; jl_set_global(jl_main_module, jl_symbol("Varname0tmp"), (jl_value_t *)Var); jl_value_t *retData = jl_eval_string(strData); jl_value_t *retNA = jl_eval_string(strNA); jl_value_t *val; if (((jl_array_t *)retData)->ptrarray) val = jl_cellref(retData, 0); else val = jl_arrayref((jl_array_t *)retData, 0); int len = jl_array_len(retData); if (len == 0) return ans; int ndims = jl_array_ndims(retData); SEXP dims; PROTECT(dims = allocVector(INTSXP, ndims)); for (size_t i = 0; i < ndims; i++) INTEGER(dims)[i] = jl_array_dim(retData, i); UNPROTECT(1); //bool array char *pNA = (char *) jl_array_data(retNA); if (jl_is_bool(val)) { char *p = (char *) jl_array_data(retData); PROTECT(ans = allocArray(LGLSXP, dims)); for (size_t i = 0; i < len; i++) if (pNA[i]) LOGICAL(ans)[i] = NA_LOGICAL; else LOGICAL(ans)[i] = p[i]; UNPROTECT(1); } else if (jl_is_int32(val)) { int32_t *p = (int32_t *) jl_array_data(retData); jlint_to_r_na; } //int64 else if (jl_is_int64(val)) { int64_t *p = (int64_t *) jl_array_data(retData); jlbiggerint_to_r_na; } //more integer type else if (jl_is_int8(val)) { int8_t *p = (int8_t *) jl_array_data(retData); jlint_to_r_na; } else if (jl_is_int16(val)) { int16_t *p = (int16_t *) jl_array_data(retData); jlint_to_r_na; } else if (jl_is_uint8(val)) { uint8_t *p = (uint8_t *) jl_array_data(retData); jlint_to_r_na; } else if (jl_is_uint16(val)) { uint16_t *p = (uint16_t *) jl_array_data(retData); jlint_to_r_na; } else if (jl_is_uint32(val)) { uint32_t *p = (uint32_t *) jl_array_data(retData); jlbiggerint_to_r_na; } else if (jl_is_uint64(val)) { uint64_t *p = (uint64_t *) jl_array_data(retData); jlbiggerint_to_r_na; } //double else if (jl_is_float64(val)) { double *p = (double *) jl_array_data(retData); jlfloat_to_r_na; } else if (jl_is_float32(val)) { float *p = (float *) jl_array_data(retData); jlfloat_to_r_na; } //convert string array to STRSXP else if (jl_is_utf8_string(val)) { PROTECT(ans = allocArray(STRSXP, dims)); for (size_t i = 0; i < len; i++) if (pNA[i]) SET_STRING_ELT(ans, i, NA_STRING); else SET_STRING_ELT(ans, i, mkCharCE(jl_string_data(jl_cellref(retData, i)), CE_UTF8)); UNPROTECT(1); } else if (jl_is_ascii_string(val)) { PROTECT(ans = allocArray(STRSXP, dims)); for (size_t i = 0; i < len; i++) if (pNA[i]) SET_STRING_ELT(ans, i, NA_STRING); else SET_STRING_ELT(ans, i, mkChar(jl_string_data(jl_cellref(retData, i)))); UNPROTECT(1); } return ans; }
static SEXP Julia_R_MD(jl_value_t *Var) { SEXP ans = R_NilValue; jl_value_t *val; if (((jl_array_t *)Var)->ptrarray) val = jl_cellref(Var, 0); else val = jl_arrayref((jl_array_t *)Var, 0); //get Julia dims and set R array Dims int len = jl_array_len(Var); if (len == 0) return ans; int ndims = jl_array_ndims(Var); SEXP dims; PROTECT(dims = allocVector(INTSXP, ndims)); for (size_t i = 0; i < ndims; i++) { INTEGER(dims)[i] = jl_array_dim(Var, i); } UNPROTECT(1); if (jl_is_bool(val)) { char *p = (char *) jl_array_data(Var); PROTECT(ans = allocArray(LGLSXP, dims)); for (size_t i = 0; i < len; i++) LOGICAL(ans)[i] = p[i]; UNPROTECT(1); } else if (jl_is_int32(val)) { int32_t *p = (int32_t *) jl_array_data(Var); jlint_to_r; } //int64 else if (jl_is_int64(val)) { int64_t *p = (int64_t *) jl_array_data(Var); jlbiggerint_to_r; } //more integer type else if (jl_is_int8(val)) { int8_t *p = (int8_t *) jl_array_data(Var); jlint_to_r; } else if (jl_is_int16(val)) { int16_t *p = (int16_t *) jl_array_data(Var); jlint_to_r; } else if (jl_is_uint8(val)) { uint8_t *p = (uint8_t *) jl_array_data(Var); jlint_to_r; } else if (jl_is_uint16(val)) { uint16_t *p = (uint16_t *) jl_array_data(Var); jlint_to_r; } else if (jl_is_uint32(val)) { uint32_t *p = (uint32_t *) jl_array_data(Var); jlbiggerint_to_r; } else if (jl_is_uint64(val)) { uint64_t *p = (uint64_t *) jl_array_data(Var); jlbiggerint_to_r; } //double else if (jl_is_float64(val)) { double *p = (double *) jl_array_data(Var); jlfloat_to_r; } else if (jl_is_float32(val)) { float *p = (float *) jl_array_data(Var); jlfloat_to_r; } //convert string array to STRSXP ,but not sure it is corret? else if (jl_is_utf8_string(val)) { PROTECT(ans = allocArray(STRSXP, dims)); for (size_t i = 0; i < len; i++) SET_STRING_ELT(ans, i, mkCharCE(jl_string_data(jl_cellref(Var, i)), CE_UTF8)); UNPROTECT(1); } else if (jl_is_ascii_string(val)) { PROTECT(ans = allocArray(STRSXP, dims)); for (size_t i = 0; i < len; i++) SET_STRING_ELT(ans, i, mkChar(jl_string_data(jl_cellref(Var, i)))); UNPROTECT(1); } return ans; }
int main(int argc, char *argv[]) { Class *array_class, *main_class; Object *system_loader, *array; MethodBlock *mb; InitArgs args; int class_arg; char *cpntr; int status; int i; setDefaultInitArgs(&args); class_arg = parseCommandLine(argc, argv, &args); args.main_stack_base = &array_class; initVM(&args); if((system_loader = getSystemClassLoader()) == NULL) { printf("Cannot create system class loader\n"); printException(); exitVM(1); } mainThreadSetContextClassLoader(system_loader); for(cpntr = argv[class_arg]; *cpntr; cpntr++) if(*cpntr == '.') *cpntr = '/'; if((main_class = findClassFromClassLoader(argv[class_arg], system_loader)) != NULL) initClass(main_class); if(exceptionOccurred()) { printException(); exitVM(1); } mb = lookupMethod(main_class, SYMBOL(main), SYMBOL(_array_java_lang_String__V)); if(!mb || !(mb->access_flags & ACC_STATIC)) { printf("Static method \"main\" not found in %s\n", argv[class_arg]); exitVM(1); } /* Create the String array holding the command line args */ i = class_arg + 1; if((array_class = findArrayClass(SYMBOL(array_java_lang_String))) && (array = allocArray(array_class, argc - i, sizeof(Object*)))) { Object **args = (Object**)ARRAY_DATA(array) - i; for(; i < argc; i++) if(!(args[i] = Cstr2String(argv[i]))) break; /* Call the main method */ if(i == argc) executeStaticMethod(main_class, mb, array); } /* ExceptionOccurred returns the exception or NULL, which is OK for normal conditionals, but not here... */ if((status = exceptionOccurred() ? 1 : 0)) printException(); /* Wait for all but daemon threads to die */ mainThreadWaitToExitVM(); exitVM(status); }
inline T * allocArray(const trace::Value *value, size_t sizeof_T = sizeof(T)) { return static_cast<T *>(allocArray(value, sizeof_T)); }
OBJMesh* objMeshLoad(const char* filename) { int linenum = 0; int warning = 0; int fatalError = 0; //open the ascii file FILE* file = fopen(filename, "r"); //check it actually opened if (!file) { perror(filename); return NULL; } //the mesh we're going to return OBJMesh* mesh = (OBJMesh*)malloc(sizeof(OBJMesh)); memset(mesh, 0, sizeof(OBJMesh)); //we don't know how much data the obj file has, so we start with one and keep realloc-ing double ReallocArray vertices, faceSets, vertexHash, positions, normals, texCoords, triangles; initArray(&vertexHash, sizeof(VertHash*)); //array of hash record pointers (for freeing) initArray(&positions, sizeof(float) * 3); initArray(&normals, sizeof(float) * 3); initArray(&texCoords, sizeof(float) * 2); initArray(&triangles, sizeof(unsigned int) * 3); initArray(&faceSets, sizeof(OBJFaceSet)); vertices.size = 0; //vertices are allocated later (at first face) //obj indices start at 1. we'll use the zero element for "error", giving with zero data positions.size = 1; normals.size = 1; texCoords.size = 1; allocArray(&positions); allocArray(&normals); allocArray(&texCoords); memset(positions.data, 0, positions.blockSize); memset(normals.data, 0, normals.blockSize); memset(texCoords.data, 0, texCoords.blockSize); //vertex combinations v/t/n are not always the same index. different vertex //combinations are hashed and reused, saving memory //see uthash.h (http://uthash.sourceforge.net/) VertHash* vertexRecords = NULL; //materials are referenced by name. this hash maps a name to material index MatHash* materialRecords = NULL; //whether the mesh contains normals or texture coordinates, and hence //the vertex data stride, is decided at the first face line ("f ...") int reachedFirstFace = 0; //current shading state int smoothShaded = 1; //start reading, line by line char* tmpTok; char line[OBJ_MAX_LINE_LEN]; while (fgets(line, OBJ_MAX_LINE_LEN, file) != NULL) { //split line by spaces strtok_r(line, " ", &tmpTok); //what data does this line give us, if any? if (line[0] == 'v') { //this line contains vertex data if (line[1] == '\0') //\0 as strtok replaced the space { //position data. allocate more memory if needed positions.size++; allocArray(&positions); //read data from string ((float*)positions.data)[(positions.size-1)*3+0] = readTokFloat(&tmpTok, &warning); ((float*)positions.data)[(positions.size-1)*3+1] = readTokFloat(&tmpTok, &warning); ((float*)positions.data)[(positions.size-1)*3+2] = readTokFloat(&tmpTok, &warning); } else if (line[1] == 'n') { //normal data. allocate more memory if needed normals.size++; allocArray(&normals); //read data from string ((float*)normals.data)[(normals.size-1)*3+0] = readTokFloat(&tmpTok, &warning); ((float*)normals.data)[(normals.size-1)*3+1] = readTokFloat(&tmpTok, &warning); ((float*)normals.data)[(normals.size-1)*3+2] = readTokFloat(&tmpTok, &warning); } else if (line[1] == 't') { //texture data. allocate more memory if needed texCoords.size++; allocArray(&texCoords); //read data from string ((float*)texCoords.data)[(texCoords.size-1)*2+0] = readTokFloat(&tmpTok, &warning); ((float*)texCoords.data)[(texCoords.size-1)*2+1] = readTokFloat(&tmpTok, &warning); } } else if (line[0] == 'f') { //this line contains face data. this may have many vertices //but we just want triangles. so we triangulate. //NOTE: ALL vertex data must be given before being referenced by a face //NOTE: At least one vt or vn must be specified before the first f, or the rest will be ignored if (!reachedFirstFace) { //must have previously specified vertex positions if (positions.size == 1) { fatalError = 1; break; } //calculate vertex stride mesh->hasNormals = (normals.size > 1) ? 1 : 0; mesh->hasTexCoords = (texCoords.size > 1) ? 1 : 0; mesh->normalOffset = 3 * sizeof(float); mesh->texcoordOffset = mesh->normalOffset + mesh->hasNormals * 3 * sizeof(float); mesh->stride = mesh->texcoordOffset + mesh->hasTexCoords * 2 * sizeof(float); initArray(&vertices, mesh->stride); reachedFirstFace = 1; } //start by extracting groups of vertex data (pos/tex/norm) int i = 0; char* vert[OBJ_MAX_POLYGON]; while ((vert[i] = strtok_r(NULL, " ", &tmpTok)) != NULL && i < OBJ_MAX_POLYGON) ++i; //triangulate using the "fan" method int triVert = 0; //triVert contains the current face's vertex index. may not equal v as vertices can be ignored. int triangulate[2]; for (int v = 0; v < i; ++v) { //split groups by "/" and store in inds[3] int t = 0; int inds[3]; char* tok = strtok_r(vert[v], "/", &tmpTok); while (tok != NULL && t < 3) { inds[t++] = atoi(tok); tok = strtok_r(NULL, "/", &tmpTok); } while (t < 3) inds[t++] = 0; //set provided, yet unused indices as invalid. this //prevents unnecessary unique vertices being created if (!mesh->hasTexCoords) inds[1] = -1; if (!mesh->hasNormals) inds[2] = -1; //ignore vertex if position indices are out of bounds if (inds[0] < 0 || inds[0] >= positions.size) { warning = 1; continue; } //use zero for out of bound normals and texture coordinates if ((mesh->hasTexCoords && (inds[1] < 0 || inds[1] >= texCoords.size)) || (mesh->hasNormals && (inds[2] < 0 || inds[2] >= normals.size))) { warning = 1; } //since vertices will be reused a lot, we need to hash the v/t/n combination int uniqueVertIndex; //check if the vertex already exists in hash VertHash h; VertHash* found = NULL; memset(&h, 0, sizeof(VertHash)); h.key.v = inds[0]; h.key.t = inds[1]; h.key.n = inds[2]; //printf("looking up %i/%i/%i\n", h.key.v, h.key.t, h.key.n); HASH_FIND(hh, vertexRecords, &h.key, sizeof(VertHashKey), found); //printf("done looking up\n"); if (found) { //found. use that vertex //printf("vert %i/%i/%i already exists as %i\n", inds[0], inds[1], inds[2], found->index); uniqueVertIndex = found->index; } else { //printf("new vert %i/%i/%i\n", inds[0], inds[1], inds[2]); //not found. create a new vertex uniqueVertIndex = vertices.size++; allocArray(&vertices); //copy data for vertex memcpy(((float*)vertices.data) + uniqueVertIndex * mesh->stride / sizeof(float), ((float*)positions.data) + inds[0] * 3, sizeof(float) * 3); if (mesh->hasTexCoords) memcpy(((float*)vertices.data) + (uniqueVertIndex * mesh->stride + mesh->texcoordOffset) / sizeof(float), ((float*)texCoords.data) + inds[1] * 2, sizeof(float) * 2); if (mesh->hasNormals) memcpy(((float*)vertices.data) + (uniqueVertIndex * mesh->stride + mesh->normalOffset) / sizeof(float), ((float*)normals.data) + inds[2] * 3, sizeof(float) * 3); //add vertex to hash table vertexHash.size++; allocArray(&vertexHash); VertHash* newRecord = (VertHash*)malloc(sizeof(VertHash)); ((VertHash**)vertexHash.data)[vertexHash.size-1] = newRecord; //store pointer to quickly free hash records later h.index = uniqueVertIndex; *newRecord = h; HASH_ADD(hh, vertexRecords, key, sizeof(VertHashKey), newRecord); } if (triVert == 0) { //store the first vertex triangulate[0] = uniqueVertIndex; } else if (triVert > 1) { //printf("tri %i->%i->%i\n", triangulate[0], triangulate[1], uniqueVertIndex); //this is at least the 3rd vertex - we have a new triangle to add //always create triangles between the current, previous and first vertex triangles.size++; allocArray(&triangles); //read data from string ((unsigned int*)triangles.data)[(triangles.size-1)*3+0] = triangulate[0]; ((unsigned int*)triangles.data)[(triangles.size-1)*3+1] = triangulate[1]; ((unsigned int*)triangles.data)[(triangles.size-1)*3+2] = uniqueVertIndex; } //store the last vertex triangulate[1] = uniqueVertIndex; ++triVert; } } else if (strcmp(line, "usemtl") == 0) { //the material state has changed - create a new faceset char* mtlname = strtok_r(NULL, " ", &tmpTok); trimRight(mtlname); //find the corresponding material MatHash* matRecord; HASH_FIND_STR(materialRecords, mtlname, matRecord); if (matRecord) { //printf("material: '%s'\n", mtlname); setFaceSet(&faceSets, matRecord->index, smoothShaded, triangles.size * 3); } else { warning = 1; printf("Undefined material: '%s'\n", mtlname); setFaceSet(&faceSets, -1, -1, triangles.size * 3); } } else if (strcmp(line, "mtllib") == 0) { //load all materials from the given .mtl file if (mesh->numMaterials > 0) { fatalError = 1; //shouldn't specify multiple .mtl files break; } char* mtlname = strtok_r(NULL, " ", &tmpTok); trimRight(mtlname); if (mtlname) parseMaterials(mesh, mtlname); //add all materials to the hash MatHash* matRecord; for (int m = 0; m < mesh->numMaterials; ++m) { HASH_FIND_STR(materialRecords, mesh->materials[m].name, matRecord); if (matRecord) { warning = 1; printf("Multiple materials with name '%s'\n", mesh->materials[m].name); continue; //can't have multiple definitions of the same material } matRecord = (MatHash*)malloc(sizeof(MatHash)); matRecord->name = mesh->materials[m].name; matRecord->index = m; HASH_ADD_KEYPTR(hh, materialRecords, matRecord->name, strlen(matRecord->name), matRecord); } } else if (line[0] == 's') { #if !IGNORE_SMOOTHING //smooth shading has been changed - create a new faceset char* smooth = strtok_r(NULL, " ", &tmpTok); trimRight(smooth); smoothShaded = atoi(smooth); if (strcmp(smooth, "on") == 0) smoothShaded = 1; if (strcmp(smooth, "off") == 0) smoothShaded = 0; setFaceSet(&faceSets, -1, smoothShaded, triangles.size * 3); #endif } //options o and g are ignored linenum++; //for warnings/errors } setFaceSet(&faceSets, -1, -1, triangles.size * 3); //update end of final faceset //fill the rest of the mesh structure exactAllocArray(&vertices); exactAllocArray(&triangles); exactAllocArray(&faceSets); mesh->vertices = (float*)vertices.data; mesh->indices = (unsigned int*)triangles.data; mesh->facesets = (OBJFaceSet*)faceSets.data; mesh->numVertices = vertices.size; mesh->numIndices = triangles.size * 3; mesh->numFacesets = faceSets.size; //cleanup //NOTE: vertices and indices are used in the returned mesh data and are not freed MatHash* matRecord; MatHash* matTmp; HASH_ITER(hh, materialRecords, matRecord, matTmp) { HASH_DEL(materialRecords, matRecord); free(matRecord); }
/* vis: * Given a vconfig_t conf, representing polygonal barriers, * compute the visibility graph of the vertices of conf. * The graph is stored in conf->vis. */ void vis (vconfig_t *conf) { conf->vis = allocArray (conf->N, 2); compVis(conf, 0); }
mesh_t *createRing(float innerRadius, float outerRadius, int sectors, texture_t *texture, program_t *program) { const float S = 1.0f / (sectors-1); const int vertexCount = 2 * sectors; int s; vertex_t *vertices = allocArray(vertex_t, vertexCount); vertex_t *vertexIterator = vertices; mesh_t *ring; for (s = 0; s < sectors; s++) { const float x = Math.cos(2.0f * Math.pi * s * S); const float y = Math.sin(2.0f * Math.pi * s * S); const float z = 0.0f; vertexIterator->coords.x = _cursorPos[0] + x * innerRadius; vertexIterator->coords.y = _cursorPos[1] + y * innerRadius; vertexIterator->coords.z = _cursorPos[2] + z * innerRadius; Vector.rotate((float*)&vertexIterator->coords, _localAxis); vertexIterator->texCoords.u = 1.0f; vertexIterator->texCoords.v = 0.0f; vertexIterator->normal.x = x; vertexIterator->normal.y = y; vertexIterator->normal.z = z; vertexIterator++; vertexIterator->coords.x = _cursorPos[0] + x * outerRadius; vertexIterator->coords.y = _cursorPos[1] + y * outerRadius; vertexIterator->coords.z = _cursorPos[2] + z * outerRadius; Vector.rotate((float*)&vertexIterator->coords, _localAxis); vertexIterator->texCoords.u = 0.0f; vertexIterator->texCoords.v = 0.0f; vertexIterator->normal.x = x; vertexIterator->normal.y = y; vertexIterator->normal.z = z; vertexIterator++; } ring = Mesh.newMesh(); for (s = 0; s < sectors; s++) { face_t *currentFace; vertex_t **currentVertices; vertex_t *v1 = &vertices[(2 * s + 0) % (vertexCount)]; vertex_t *v2 = &vertices[(2 * s + 1) % (vertexCount)]; vertex_t *v3 = &vertices[(2 * s + 3) % (vertexCount)]; vertex_t *v4 = &vertices[(2 * s + 2) % (vertexCount)]; currentFace = Mesh.addFaceToMesh(ring); currentFace->texture = texture; currentFace->program = program; currentVertices = allocArray(vertex_t*, 3); currentVertices[0] = v1; currentVertices[1] = v2; currentVertices[2] = v3; currentFace->vertices = currentVertices; currentFace->nbVertices = 3; currentFace = Mesh.addFaceToMesh(ring); currentFace->texture = texture; currentFace->program = program; currentVertices = allocArray(vertex_t*, 3); currentVertices[0] = v3; currentVertices[1] = v4; currentVertices[2] = v1; currentFace->vertices = currentVertices; currentFace->nbVertices = 3; } Mesh.updateGeometry(ring); return ring; }