/* ********************************************************************************************* */ int main(int argc, char* argv[]) { // Create Left Leg skeleton Skeleton LeftLegSkel; // Pointers to be used during the Skeleton building Matrix3d inertiaMatrix; inertiaMatrix << 0, 0, 0, 0, 0, 0, 0, 0, 0; double mass = 1.0; // ***** BodyNode 1: Left Hip Yaw (LHY) ***** * BodyNode* node = new BodyNode("LHY"); Joint* joint = create1DOFJoint(NULL, node, 0.0, 0.0, DART_PI, DOF_YAW); joint->setName("LHY"); Shape* shape = new BoxShape(Vector3d(0.3, 0.3, 1.0)); node->addVisualizationShape(shape); node->addCollisionShape(shape); node->setMass(mass); LeftLegSkel.addBodyNode(node); // ***** BodyNode 2: Left Hip Roll (LHR) whose parent is: LHY *****\ BodyNode* parent_node = LeftLegSkel.getBodyNode("LHY"); node = new BodyNode("LHR"); joint = create1DOFJoint(parent_node, node, 0.0, 0.0, DART_PI, DOF_ROLL); joint->setName("LHR"); Eigen::Isometry3d T(Eigen::Translation3d(0.0, 0.0, 0.5)); joint->setTransformFromParentBodyNode(T); shape = new BoxShape(Vector3d(0.3, 0.3, 1.0)); shape->setOffset(Vector3d(0.0, 0.0, 0.5)); node->setLocalCOM(shape->getOffset()); node->setMass(mass); node->addVisualizationShape(shape); node->addCollisionShape(shape); LeftLegSkel.addBodyNode(node); // ***** BodyNode 3: Left Hip Pitch (LHP) whose parent is: LHR ***** parent_node = LeftLegSkel.getBodyNode("LHR"); node = new BodyNode("LHP"); joint = create1DOFJoint(parent_node, node, 0.0, 0.0, DART_PI, DOF_ROLL); joint->setName("LHP"); T = Eigen::Translation3d(0.0, 0.0, 1.0); joint->setTransformFromParentBodyNode(T); shape = new BoxShape(Vector3d(0.3, 0.3, 1.0)); shape->setOffset(Vector3d(0.0, 0.0, 0.5)); node->setLocalCOM(shape->getOffset()); node->setMass(mass); Shape* shape1 = new EllipsoidShape(Vector3d(0.3, 0.3, 1.0)); shape1->setOffset(Vector3d(0.0, 0.0, 0.5)); node->addVisualizationShape(shape1); node->addCollisionShape(shape); LeftLegSkel.addBodyNode(node); // Initialize the skeleton LeftLegSkel.initDynamics(); // Window stuff MyWindow window(&LeftLegSkel); glutInit(&argc, argv); window.initWindow(640, 480, "Skeleton example"); glutMainLoop(); return 0; }
void __fastcall ViewUnitEditor::LoadDxfPattern (Blocks* pBlocks, NumberSortType eType) { if (pBlocks == NULL) { return; } // declare necessary variables Block* pBlock; Shape* pShape; int nBlockSize = pBlocks->size(); int nBlockShapeCount = 0; RECTFLOAT shapeRect; double dShapePointX; double dShapePointY; double dRadius; SHAPE_TYPE etype; int idx = 0; _pUnitdesigninfo->ResetAll(); // convert common shapes to ball data for (int idxBlock = 0 ; idxBlock < nBlockSize ; idxBlock++) { pBlock = pBlocks->at(idxBlock); if (pBlock == NULL) { continue; } if (pBlock->getShapes() == NULL) { continue; } nBlockShapeCount = pBlock->getShapes()->size(); for (int idxShape = 0 ; idxShape < nBlockShapeCount ; idxShape++) { pShape = pBlock->getShapes()->at(idxShape); if (pShape == NULL) { continue; } if (pShape->getType() == SHAPE_BLOCK_INSERT) { ((Block_Insert*)pShape)->setBlocks(pBlocks); } etype = pShape->getType(); if (!(etype == SHAPE_CIRCLE || etype == SHAPE_LINECIRCLE || etype == SHAPE_FILLCIRCLE)) { continue; } if (!pShape->getRegion(shapeRect)) { continue; } dRadius = ((shapeRect.right - shapeRect.left) / 2); if (dRadius <= 0) { continue; } dShapePointX = shapeRect.left + ((shapeRect.right - shapeRect.left) / 2) ; dShapePointY = shapeRect.bottom + ((shapeRect.top - shapeRect.bottom) / 2) ; _pUnitdesigninfo->SetBallCountX(1); _pUnitdesigninfo->SetBallCountY(_pUnitdesigninfo->GetBallCountY() + 1); _pUnitdesigninfo->SetBallPointManually (0, idx, dShapePointX, dShapePointY); _pUnitdesigninfo->SetBallRadius (0, idx, dRadius); idx++; } } // convert common shapes to ball data // sort ball data _pUnitdesigninfo->Sort(eType); // regen all view datas onRegen(); }
void js::ObjectImpl::checkShapeConsistency() { static int throttle = -1; if (throttle < 0) { if (const char *var = getenv("JS_CHECK_SHAPE_THROTTLE")) throttle = atoi(var); if (throttle < 0) throttle = 0; } if (throttle == 0) return; MOZ_ASSERT(isNative()); Shape *shape = lastProperty(); Shape *prev = NULL; if (inDictionaryMode()) { MOZ_ASSERT(shape->hasTable()); ShapeTable &table = shape->table(); for (uint32_t fslot = table.freelist; fslot != SHAPE_INVALID_SLOT; fslot = getSlot(fslot).toPrivateUint32()) { MOZ_ASSERT(fslot < slotSpan()); } for (int n = throttle; --n >= 0 && shape->parent; shape = shape->parent) { MOZ_ASSERT_IF(shape != lastProperty(), !shape->hasTable()); Shape **spp = table.search(shape->propid(), false); MOZ_ASSERT(SHAPE_FETCH(spp) == shape); } shape = lastProperty(); for (int n = throttle; --n >= 0 && shape; shape = shape->parent) { MOZ_ASSERT_IF(shape->slot() != SHAPE_INVALID_SLOT, shape->slot() < slotSpan()); if (!prev) { MOZ_ASSERT(shape == lastProperty()); MOZ_ASSERT(shape->listp == &shape_); } else { MOZ_ASSERT(shape->listp == &prev->parent); } prev = shape; } } else { for (int n = throttle; --n >= 0 && shape->parent; shape = shape->parent) { if (shape->hasTable()) { ShapeTable &table = shape->table(); MOZ_ASSERT(shape->parent); for (Shape::Range r(shape); !r.empty(); r.popFront()) { Shape **spp = table.search(r.front().propid(), false); MOZ_ASSERT(SHAPE_FETCH(spp) == &r.front()); } } if (prev) { MOZ_ASSERT(prev->maybeSlot() >= shape->maybeSlot()); shape->kids.checkConsistency(prev); } prev = shape; } } }
Shape * PropertyTree::getChild(ExclusiveContext *cx, Shape *parentArg, StackShape &unrootedChild) { RootedShape parent(cx, parentArg); MOZ_ASSERT(parent); Shape *existingShape = nullptr; /* * The property tree has extremely low fan-out below its root in * popular embeddings with real-world workloads. Patterns such as * defining closures that capture a constructor's environment as * getters or setters on the new object that is passed in as * |this| can significantly increase fan-out below the property * tree root -- see bug 335700 for details. */ KidsPointer *kidp = &parent->kids; if (kidp->isShape()) { Shape *kid = kidp->toShape(); if (kid->matches(unrootedChild)) existingShape = kid; } else if (kidp->isHash()) { if (KidsHash::Ptr p = kidp->toHash()->lookup(unrootedChild)) existingShape = *p; } else { /* If kidp->isNull(), we always insert. */ } #ifdef JSGC_INCREMENTAL if (existingShape) { JS::Zone *zone = existingShape->zone(); if (zone->needsIncrementalBarrier()) { /* * We need a read barrier for the shape tree, since these are weak * pointers. */ Shape *tmp = existingShape; MarkShapeUnbarriered(zone->barrierTracer(), &tmp, "read barrier"); MOZ_ASSERT(tmp == existingShape); } else if (zone->isGCSweeping() && !existingShape->isMarked() && !existingShape->arenaHeader()->allocatedDuringIncremental) { /* * The shape we've found is unreachable and due to be finalized, so * remove our weak reference to it and don't use it. */ MOZ_ASSERT(parent->isMarked()); parent->removeChild(existingShape); existingShape = nullptr; } else if (existingShape->isMarked(gc::GRAY)) { JS::UnmarkGrayGCThingRecursively(existingShape, JSTRACE_SHAPE); } } #endif if (existingShape) return existingShape; Shape *shape = Shape::new_(cx, unrootedChild, parent->numFixedSlots()); if (!shape) return nullptr; if (!insertChild(cx, parent, shape)) return nullptr; return shape; }
void Region::Shape::appendSpans(const Shape& shape, SpanIterator begin, SpanIterator end) { for (SpanIterator it = begin; it != end; ++it) appendSpan(it->y, shape.segmentsBegin(it), shape.segmentsEnd(it)); }
void RenderManager::RenderObjectAt(Shape& shape, const a2de::Vector2D& screen_position, bool filled) { a2de::Vector2D old_pos(shape.GetPosition()); shape.SetPosition(screen_position); RenderObject(shape, filled); shape.SetPosition(old_pos); }
void MyGlWindow::init(){ loadShader( program, "shader.vert", "shader.frag" ); if(!program){ cerr<<"Error setting up shaders!"<<endl; exit(1); } glGenVertexArrays(1, &vao); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glClearColor(0.0, 0.0, 0.33, 1.0); glCullFace(GL_BACK); float aspectRatio = (float)w()/(float)h(); cam = new camera(l, r, t, b, n, f, aspectRatio); shared_ptr<ObjParser> parser = make_shared<ObjParser>(); Shape s = parser->parse("Neutral.obj"); s.setVao(vao); if(SMOOTH) s.smoothNormals(); s.initBuffers(program, "vNeutral", "nNeutral"); s.setRotate(0, 1, 0, 0); shapes.push_back(s); Shape s2 = parser->parse("28_MouthSmile_L.obj"); s2.setVao(vao); if(SMOOTH) s2.smoothNormals(); s2.initBuffers(program, "vSmile_L", "nSmile_L"); s2.setRotate(0, 1, 0, 0); shapes.push_back(s2); Shape s3 = parser->parse("29_MouthSmile_R.obj"); s3.setVao(vao); if(SMOOTH) s3.smoothNormals(); s3.initBuffers(program, "vSmile_R", "nSmile_R"); s3.setRotate(0, 1, 0, 0); shapes.push_back(s3); Shape s4 = parser->parse("16_BrowsU_C.obj"); s4.setVao(vao); if(SMOOTH) s4.smoothNormals(); s4.initBuffers(program, "vBrowsup", "nBrowsup"); s4.setRotate(0, 1, 0, 0); shapes.push_back(s4); Shape s5 = parser->parse("21_JawOpen.obj"); s5.setVao(vao); if(SMOOTH) s5.smoothNormals(); s5.initBuffers(program, "vMouthopen", "nMouthopen"); s5.setRotate(0, 1, 0, 0); shapes.push_back(s5); Shape s6 = parser->parse("45_Puff.obj"); s6.setVao(vao); if(SMOOTH) s6.smoothNormals(); s6.initBuffers(program, "vPuff", "nPuff"); s6.setRotate(0, 1, 0, 0); shapes.push_back(s6); Shape s7 = parser->parse("44_Sneer.obj"); s7.setVao(vao); if(SMOOTH) s7.smoothNormals(); s7.initBuffers(program, "vSneer", "nSneer"); s7.setRotate(0, 1, 0, 0); shapes.push_back(s7); Shape s8 = parser->parse("41_LipsPucker.obj"); s8.setVao(vao); if(SMOOTH) s8.smoothNormals(); s8.initBuffers(program, "vKiss", "nKiss"); s8.setRotate(0, 1, 0, 0); shapes.push_back(s8); }
Shape * PropertyTree::getChild(ExclusiveContext *cx, Shape *parent_, uint32_t nfixed, const StackShape &child) { { Shape *shape = NULL; JS_ASSERT(parent_); /* * The property tree has extremely low fan-out below its root in * popular embeddings with real-world workloads. Patterns such as * defining closures that capture a constructor's environment as * getters or setters on the new object that is passed in as * |this| can significantly increase fan-out below the property * tree root -- see bug 335700 for details. */ KidsPointer *kidp = &parent_->kids; if (kidp->isShape()) { Shape *kid = kidp->toShape(); if (kid->matches(child)) shape = kid; } else if (kidp->isHash()) { if (KidsHash::Ptr p = kidp->toHash()->lookup(child)) shape = *p; } else { /* If kidp->isNull(), we always insert. */ } #ifdef JSGC_INCREMENTAL if (shape) { JS::Zone *zone = shape->zone(); if (zone->needsBarrier()) { /* * We need a read barrier for the shape tree, since these are weak * pointers. */ Shape *tmp = shape; MarkShapeUnbarriered(zone->barrierTracer(), &tmp, "read barrier"); JS_ASSERT(tmp == shape); } else if (zone->isGCSweeping() && !shape->isMarked() && !shape->arenaHeader()->allocatedDuringIncremental) { /* * The shape we've found is unreachable and due to be finalized, so * remove our weak reference to it and don't use it. */ JS_ASSERT(parent_->isMarked()); parent_->removeChild(shape); shape = NULL; } } #endif if (shape) return shape; } StackShape::AutoRooter childRoot(cx, &child); RootedShape parent(cx, parent_); Shape *shape = newShape(cx); if (!shape) return NULL; new (shape) Shape(child, nfixed); if (!insertChild(cx, parent, shape)) return NULL; return shape; }
int w_Shape_rayCast(lua_State * L) { Shape * t = luax_checkshape(L, 1); lua_remove(L, 1); ASSERT_GUARD(return t->rayCast(L);) }
void max_pool(const T* arg, T* out, const Shape& arg_shape, const Shape& out_shape, const Shape& window_shape, const Strides& window_movement_strides, const Shape& padding_below, const Shape& padding_above) { // At the outermost level we will walk over every output coordinate O. CoordinateTransform output_transform(out_shape); for (const Coordinate& out_coord : output_transform) { // Our output coordinate O will have the form: // // (N,chan,i_1,...,i_n) size_t batch_index = out_coord[0]; size_t channel = out_coord[1]; // For the input data we need to iterate the coordinate: // // I: // // over the range (noninclusive on the right): // // (N,chan,s_1*i_1,s_2*i_2,...,s_n*i_n) -> // // (N+1,chan+1,s_1*i_1 + window_shape_1,...,s_n*i_n + window_shape_n) // // with unit stride. // // We iterate this over the *padded* data, so below we will need to check for coordinates that fall in the padding area. size_t n_spatial_dimensions = arg_shape.size() - 2; Coordinate input_batch_transform_start(2 + n_spatial_dimensions); Coordinate input_batch_transform_end(2 + n_spatial_dimensions); Strides input_batch_transform_source_strides(2 + n_spatial_dimensions, 1); AxisVector input_batch_transform_source_axis_order(2 + n_spatial_dimensions); CoordinateDiff input_batch_transform_padding_below(2 + n_spatial_dimensions); CoordinateDiff input_batch_transform_padding_above(2 + n_spatial_dimensions); input_batch_transform_start[0] = batch_index; input_batch_transform_end[0] = batch_index + 1; input_batch_transform_start[1] = channel; input_batch_transform_end[1] = channel + 1; input_batch_transform_padding_below[0] = 0; input_batch_transform_padding_below[1] = 0; input_batch_transform_padding_above[0] = 0; input_batch_transform_padding_above[1] = 0; for (size_t i = 2; i < n_spatial_dimensions + 2; i++) { size_t window_shape_this_dim = window_shape[i - 2]; size_t movement_stride = window_movement_strides[i - 2]; input_batch_transform_start[i] = movement_stride * out_coord[i]; input_batch_transform_end[i] = input_batch_transform_start[i] + window_shape_this_dim; input_batch_transform_padding_below[i] = padding_below[i - 2]; input_batch_transform_padding_above[i] = padding_above[i - 2]; } for (size_t i = 0; i < arg_shape.size(); i++) { input_batch_transform_source_axis_order[i] = i; } CoordinateTransform input_batch_transform( arg_shape, input_batch_transform_start, input_batch_transform_end, input_batch_transform_source_strides, input_batch_transform_source_axis_order, input_batch_transform_padding_below, input_batch_transform_padding_above); // As we go, we compute the maximum value: // // output[O] = max(output[O],arg[I]) T result = std::numeric_limits<T>::lowest(); for (const Coordinate& input_batch_coord : input_batch_transform) { if (input_batch_transform.has_source_coordinate(input_batch_coord)) { T x = arg[input_batch_transform.index(input_batch_coord)]; result = x > result ? x : result; } } out[output_transform.index(out_coord)] = result; } }
void max_pool_backprop(const T* arg_forward, const T* delta, T* out, const Shape& delta_shape, const Shape& out_shape, // same as arg_forward_shape const Shape& window_shape, const Strides& window_movement_strides, const Shape& padding_below, const Shape& padding_above) { CoordinateTransform out_transform(out_shape); for (const Coordinate& out_coord : out_transform) { out[out_transform.index(out_coord)] = 0; } CoordinateTransform delta_transform(delta_shape); for (const Coordinate& delta_coord : delta_transform) { size_t img_index = delta_coord[0]; size_t channel = delta_coord[1]; size_t n_image_dimensions = out_shape.size() - 2; Coordinate source_window_transform_start(2 + n_image_dimensions); Coordinate source_window_transform_end(2 + n_image_dimensions); Strides source_window_transform_source_strides(2 + n_image_dimensions, 1); AxisVector source_window_transform_source_axis_order(2 + n_image_dimensions); CoordinateDiff source_window_transform_padding_below(2 + n_image_dimensions); CoordinateDiff source_window_transform_padding_above(2 + n_image_dimensions); source_window_transform_start[0] = img_index; source_window_transform_end[0] = img_index + 1; source_window_transform_start[1] = channel; source_window_transform_end[1] = channel + 1; source_window_transform_padding_below[0] = 0; source_window_transform_padding_below[1] = 0; source_window_transform_padding_above[0] = 0; source_window_transform_padding_above[1] = 0; for (size_t i = 2; i < n_image_dimensions + 2; i++) { size_t window_shape_this_dim = window_shape[i - 2]; size_t movement_stride = window_movement_strides[i - 2]; source_window_transform_start[i] = movement_stride * delta_coord[i]; source_window_transform_end[i] = source_window_transform_start[i] + window_shape_this_dim; source_window_transform_padding_below[i] = padding_below[i - 2]; source_window_transform_padding_above[i] = padding_above[i - 2]; } std::iota(begin(source_window_transform_source_axis_order), end(source_window_transform_source_axis_order), 0); CoordinateTransform source_window_transform( out_shape, source_window_transform_start, source_window_transform_end, source_window_transform_source_strides, source_window_transform_source_axis_order, source_window_transform_padding_below, source_window_transform_padding_above); Coordinate argmax_coord; bool argmax_coord_valid = false; T max_val = 0; // just initializing to keep compiler happy, this 0 is ignored for (const Coordinate& source_window_coord : source_window_transform) { if (source_window_transform.has_source_coordinate(source_window_coord)) { T candidate = arg_forward[source_window_transform.index(source_window_coord)]; if (!argmax_coord_valid || candidate > max_val) { max_val = candidate; argmax_coord = source_window_coord; argmax_coord_valid = true; } } } if (argmax_coord_valid) { out[source_window_transform.index(argmax_coord)] += delta[delta_transform.index(delta_coord)]; } } }
bool Mesh::loadFromShape(Shape& shape) { shape.loadIntoMesh(*this); return true; }
int main (){ Shape *cir = Shape::Create("circle"); if ( cir != NULL ) cir->draw(); return 0; }
static void StatsCellCallback(JSRuntime *rt, void *data, void *thing, JSGCTraceKind traceKind, size_t thingSize) { RuntimeStats *rtStats = static_cast<RuntimeStats *>(data); CompartmentStats *cStats = rtStats->currCompartmentStats; switch (traceKind) { case JSTRACE_OBJECT: { JSObject *obj = static_cast<JSObject *>(thing); if (obj->isFunction()) { cStats->gcHeapObjectsFunction += thingSize; } else { cStats->gcHeapObjectsNonFunction += thingSize; } size_t slotsSize, elementsSize, miscSize; obj->sizeOfExcludingThis(rtStats->mallocSizeOf, &slotsSize, &elementsSize, &miscSize); cStats->objectSlots += slotsSize; cStats->objectElements += elementsSize; cStats->objectMisc += miscSize; break; } case JSTRACE_STRING: { JSString *str = static_cast<JSString *>(thing); cStats->gcHeapStrings += thingSize; cStats->stringChars += str->sizeOfExcludingThis(rtStats->mallocSizeOf); break; } case JSTRACE_SHAPE: { Shape *shape = static_cast<Shape*>(thing); size_t propTableSize, kidsSize; shape->sizeOfExcludingThis(rtStats->mallocSizeOf, &propTableSize, &kidsSize); if (shape->inDictionary()) { cStats->gcHeapShapesDict += thingSize; cStats->shapesExtraDictTables += propTableSize; JS_ASSERT(kidsSize == 0); } else { cStats->gcHeapShapesTree += thingSize; cStats->shapesExtraTreeTables += propTableSize; cStats->shapesExtraTreeShapeKids += kidsSize; } break; } case JSTRACE_BASE_SHAPE: { cStats->gcHeapShapesBase += thingSize; break; } case JSTRACE_SCRIPT: { JSScript *script = static_cast<JSScript *>(thing); cStats->gcHeapScripts += thingSize; cStats->scriptData += script->sizeOfData(rtStats->mallocSizeOf); #ifdef JS_METHODJIT cStats->mjitData += script->sizeOfJitScripts(rtStats->mallocSizeOf); #endif break; } case JSTRACE_TYPE_OBJECT: { types::TypeObject *obj = static_cast<types::TypeObject *>(thing); cStats->gcHeapTypeObjects += thingSize; obj->sizeOfExcludingThis(&cStats->typeInferenceSizes, rtStats->mallocSizeOf); break; } #if JS_HAS_XML_SUPPORT case JSTRACE_XML: { cStats->gcHeapXML += thingSize; break; } #endif } // Yes, this is a subtraction: see StatsArenaCallback() for details. cStats->gcHeapArenaUnused -= thingSize; }
bool js::ForOfPIC::Chain::initialize(JSContext* cx) { MOZ_ASSERT(!initialized_); // Get the canonical Array.prototype RootedNativeObject arrayProto(cx, GlobalObject::getOrCreateArrayPrototype(cx, cx->global())); if (!arrayProto) return false; // Get the canonical ArrayIterator.prototype RootedNativeObject arrayIteratorProto(cx, GlobalObject::getOrCreateArrayIteratorPrototype(cx, cx->global())); if (!arrayIteratorProto) return false; // From this point on, we can't fail. Set initialized and fill the fields // for the canonical Array.prototype and ArrayIterator.prototype objects. initialized_ = true; arrayProto_ = arrayProto; arrayIteratorProto_ = arrayIteratorProto; // Shortcut returns below means Array for-of will never be optimizable, // do set disabled_ now, and clear it later when we succeed. disabled_ = true; // Look up Array.prototype[@@iterator], ensure it's a slotful shape. Shape* iterShape = arrayProto->lookup(cx, SYMBOL_TO_JSID(cx->wellKnownSymbols().iterator)); if (!iterShape || !iterShape->hasSlot() || !iterShape->hasDefaultGetter()) return true; // Get the referred value, and ensure it holds the canonical ArrayValues function. Value iterator = arrayProto->getSlot(iterShape->slot()); JSFunction* iterFun; if (!IsFunctionObject(iterator, &iterFun)) return true; if (!IsSelfHostedFunctionWithName(iterFun, cx->names().ArrayValues)) return true; // Look up the 'next' value on ArrayIterator.prototype Shape* nextShape = arrayIteratorProto->lookup(cx, cx->names().next); if (!nextShape || !nextShape->hasSlot()) return true; // Get the referred value, ensure it holds the canonical ArrayIteratorNext function. Value next = arrayIteratorProto->getSlot(nextShape->slot()); JSFunction* nextFun; if (!IsFunctionObject(next, &nextFun)) return true; if (!IsSelfHostedFunctionWithName(nextFun, cx->names().ArrayIteratorNext)) return true; disabled_ = false; arrayProtoShape_ = arrayProto->lastProperty(); arrayProtoIteratorSlot_ = iterShape->slot(); canonicalIteratorFunc_ = iterator; arrayIteratorProtoShape_ = arrayIteratorProto->lastProperty(); arrayIteratorProtoNextSlot_ = nextShape->slot(); canonicalNextFunc_ = next; return true; }
int w_Shape_computeMass(lua_State * L) { Shape * t = luax_checkshape(L, 1); lua_remove(L, 1); return t->computeMass(L); }
static void StatsCellCallback(JSRuntime *rt, void *data, void *thing, JSGCTraceKind traceKind, size_t thingSize) { IteratorClosure *closure = static_cast<IteratorClosure *>(data); RuntimeStats *rtStats = closure->rtStats; CompartmentStats *cStats = rtStats->currCompartmentStats; switch (traceKind) { case JSTRACE_OBJECT: { JSObject *obj = static_cast<JSObject *>(thing); if (obj->isFunction()) { cStats->gcHeapObjectsFunction += thingSize; } else if (obj->isDenseArray()) { cStats->gcHeapObjectsDenseArray += thingSize; } else if (obj->isSlowArray()) { cStats->gcHeapObjectsSlowArray += thingSize; } else if (obj->isCrossCompartmentWrapper()) { cStats->gcHeapObjectsCrossCompartmentWrapper += thingSize; } else { cStats->gcHeapObjectsOrdinary += thingSize; } size_t slotsSize, elementsSize, argumentsDataSize, regExpStaticsSize, propertyIteratorDataSize; obj->sizeOfExcludingThis(rtStats->mallocSizeOf, &slotsSize, &elementsSize, &argumentsDataSize, ®ExpStaticsSize, &propertyIteratorDataSize); cStats->objectsExtraSlots += slotsSize; cStats->objectsExtraElements += elementsSize; cStats->objectsExtraArgumentsData += argumentsDataSize; cStats->objectsExtraRegExpStatics += regExpStaticsSize; cStats->objectsExtraPropertyIteratorData += propertyIteratorDataSize; if (ObjectPrivateVisitor *opv = closure->opv) { js::Class *clazz = js::GetObjectClass(obj); if (clazz->flags & JSCLASS_HAS_PRIVATE && clazz->flags & JSCLASS_PRIVATE_IS_NSISUPPORTS) { cStats->objectsExtraPrivate += opv->sizeOfIncludingThis(GetObjectPrivate(obj)); } } break; } case JSTRACE_STRING: { JSString *str = static_cast<JSString *>(thing); size_t strSize = str->sizeOfExcludingThis(rtStats->mallocSizeOf); // If we can't grow hugeStrings, let's just call this string non-huge. // We're probably about to OOM anyway. if (strSize >= HugeStringInfo::MinSize() && cStats->hugeStrings.growBy(1)) { cStats->gcHeapStringsNormal += thingSize; HugeStringInfo &info = cStats->hugeStrings.back(); info.length = str->length(); info.size = strSize; PutEscapedString(info.buffer, sizeof(info.buffer), &str->asLinear(), 0); } else if (str->isShort()) { MOZ_ASSERT(strSize == 0); cStats->gcHeapStringsShort += thingSize; } else { cStats->gcHeapStringsNormal += thingSize; cStats->stringCharsNonHuge += strSize; } break; } case JSTRACE_SHAPE: { Shape *shape = static_cast<Shape*>(thing); size_t propTableSize, kidsSize; shape->sizeOfExcludingThis(rtStats->mallocSizeOf, &propTableSize, &kidsSize); if (shape->inDictionary()) { cStats->gcHeapShapesDict += thingSize; cStats->shapesExtraDictTables += propTableSize; JS_ASSERT(kidsSize == 0); } else { if (shape->base()->getObjectParent() == shape->compartment()->maybeGlobal()) { cStats->gcHeapShapesTreeGlobalParented += thingSize; } else { cStats->gcHeapShapesTreeNonGlobalParented += thingSize; } cStats->shapesExtraTreeTables += propTableSize; cStats->shapesExtraTreeShapeKids += kidsSize; } break; } case JSTRACE_BASE_SHAPE: { cStats->gcHeapShapesBase += thingSize; break; } case JSTRACE_SCRIPT: { JSScript *script = static_cast<JSScript *>(thing); cStats->gcHeapScripts += thingSize; cStats->scriptData += script->sizeOfData(rtStats->mallocSizeOf); #ifdef JS_METHODJIT cStats->jaegerData += script->sizeOfJitScripts(rtStats->mallocSizeOf); # ifdef JS_ION cStats->ionData += ion::MemoryUsed(script, rtStats->mallocSizeOf); # endif #endif ScriptSource *ss = script->scriptSource(); SourceSet::AddPtr entry = closure->seenSources.lookupForAdd(ss); if (!entry) { closure->seenSources.add(entry, ss); // Not much to be done on failure. rtStats->runtime.scriptSources += ss->sizeOfIncludingThis(rtStats->mallocSizeOf); } break; } case JSTRACE_IONCODE: { #ifdef JS_METHODJIT # ifdef JS_ION cStats->gcHeapIonCodes += thingSize; // The code for a script is counted in ExecutableAllocator::sizeOfCode(). # endif #endif break; } case JSTRACE_TYPE_OBJECT: { types::TypeObject *obj = static_cast<types::TypeObject *>(thing); cStats->gcHeapTypeObjects += thingSize; obj->sizeOfExcludingThis(&cStats->typeInferenceSizes, rtStats->mallocSizeOf); break; } #if JS_HAS_XML_SUPPORT case JSTRACE_XML: { cStats->gcHeapXML += thingSize; break; } #endif } // Yes, this is a subtraction: see StatsArenaCallback() for details. cStats->gcHeapUnusedGcThings -= thingSize; }
JS_GetPropertyDesc(JSContext *cx, JSObject *obj, JSScopeProperty *sprop, JSPropertyDesc *pd) { assertSameCompartment(cx, obj); Shape *shape = (Shape *) sprop; pd->id = IdToJsval(shape->propid()); JSBool wasThrowing = cx->isExceptionPending(); Value lastException = UndefinedValue(); if (wasThrowing) lastException = cx->getPendingException(); cx->clearPendingException(); if (!js_GetProperty(cx, obj, shape->propid(), &pd->value)) { if (!cx->isExceptionPending()) { pd->flags = JSPD_ERROR; pd->value = JSVAL_VOID; } else { pd->flags = JSPD_EXCEPTION; pd->value = cx->getPendingException(); } } else { pd->flags = 0; } if (wasThrowing) cx->setPendingException(lastException); pd->flags |= (shape->enumerable() ? JSPD_ENUMERATE : 0) | (!shape->writable() ? JSPD_READONLY : 0) | (!shape->configurable() ? JSPD_PERMANENT : 0); pd->spare = 0; if (shape->getter() == GetCallArg) { pd->slot = shape->shortid(); pd->flags |= JSPD_ARGUMENT; } else if (shape->getter() == GetCallVar) { pd->slot = shape->shortid(); pd->flags |= JSPD_VARIABLE; } else { pd->slot = 0; } pd->alias = JSVAL_VOID; if (obj->containsSlot(shape->slot())) { for (Shape::Range r = obj->lastProperty()->all(); !r.empty(); r.popFront()) { const Shape &aprop = r.front(); if (&aprop != shape && aprop.slot() == shape->slot()) { pd->alias = IdToJsval(aprop.propid()); break; } } } return JS_TRUE; }
void RenderManager::RenderObject(const Shape& shape, bool filled, ALLEGRO_BITMAP* texture) { //shape->Render(al_get_backbuffer(_display_context)); auto& verts = shape.GetVerticies(); std::vector<ALLEGRO_VERTEX> allegro_verts; allegro_verts.reserve(verts.size()); for(const auto& v : verts) { auto p = a2de::Math::ToScreenScale(v.GetPosition()); auto uv = v.GetUV(); auto c = v.GetColor(); allegro_verts.push_back( std::move(ALLEGRO_VERTEX{ static_cast<float>(p.GetX()), static_cast<float>(p.GetY()), static_cast<float>(p.GetZ()), static_cast<float>(uv.GetX()), static_cast<float>(uv.GetY()), c })); } switch(shape.GetShapeType()) { case Shape::ShapeType::Point: { al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_POINT_LIST); break; } case Shape::ShapeType::Line: { al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_LINE_LIST); break; } case Shape::ShapeType::Rectangle: { filled ? al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_TRIANGLE_LIST) : al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_LINE_LOOP); break; } case Shape::ShapeType::Circle: { filled ? al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_TRIANGLE_FAN) : al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_POINT_LIST); break; } case Shape::ShapeType::Ellipse: { filled ? al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_TRIANGLE_FAN) : al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_POINT_LIST); break; } case Shape::ShapeType::Triangle: { filled ? al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_TRIANGLE_LIST) : al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_LINE_LOOP); break; } case Shape::ShapeType::Arc: { al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_LINE_STRIP); break; } case Shape::ShapeType::Polygon: { filled ? al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_TRIANGLE_FAN) : al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_LINE_LOOP); break; } case Shape::ShapeType::Spline: { al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_LINE_STRIP); break; } case Shape::ShapeType::Sector: { filled ? al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_TRIANGLE_FAN) : al_draw_prim(allegro_verts.data(), nullptr, texture, 0, allegro_verts.size(), ALLEGRO_PRIM_LINE_LOOP); break; } default: { /* DO NOTHING: All cases handled */; } } }
void ShapeContainer::init(ShapeType _shape, int _numlevels, int _incr, float _w, float _h) { // initialise m_shapes m_shapes.resize(0); m_type = _shape; float w, h, d; float ow, oh, od; // construct structure based on type switch (m_type) { case PYRAMID: // structure based on pyramids w = _w; h = _h; d = _w; // regular pyramid has square base //pos = Vec3f(0, _numlevels*_h/2.0f, 0);- for (int k = 1; k <= _numlevels; k++) { // we're at level k (vertical) // dimension increase linearly int currentw = k; int currenth = k; // horizontal plane i x j for (int i = 0; i < currentw; i+=1) { for (int j = 0; j < currenth; j+=1) { // we are at i, j on horizontal plane at vertical level k // w, d, h are the dimensions of the object -> gridsize //h = (k%2 == 0) ? _h * -1 : _h; float x = i*w - currentw*w/2; float y = k*h - _numlevels*h/2.0f; // y is up; float z = j*d - currenth*d/2; Shape p = Shape(); p.init(x, y, z, w, -h, d, false); p.setCoordinates(i, k, j); Shape q = Shape(); q.init(x, y+h, z, w, h, d, false); q.setCoordinates(i, k+1, j); if (k%_incr == 0) { p.setActive(); q.setActive(); } if((i%2 == 0 && j%2 == 0) || k%2 == 0) { m_shapes.push_back( p ); m_shapes.push_back( q ); } } //j } //i } //k ow = w*_numlevels; oh = -h*_numlevels; od = d*_numlevels; m_structure.init(-w/2.f, h/2.f, -d/2.f, ow, oh, od, false); break; case TETRA: // structure based on tetrahedrons w = _w; d = tan(M_PI/3.0)*(_w/2.0); h = d; for (int k = 1; k <= _numlevels; k++) { // we're at level k (vertical) // horizontal plane i x j for (int j = 0; j < k; j++) { for (int i = 0; i < j; i++) { // we are at i, j on horizontal plane at vertical level k // w, d, h are the dimensions of the object -> gridsize float c = _w/2.0*tan(3.141593/6.0); float x = j*w - k*w/2 - i*w/2; float y = k*h - _numlevels*h/2.0f; // y is up; float z = i*d - k*c; //bool flipped = false; //(k%2 == 0) ? true : false; Shape p = Shape(); p.init(x, y, z, w, -h, d, false); p.setCoordinates(i, k, j); Shape q = Shape(); q.init(x, y, z, w, h, d, false); q.setCoordinates(i, k, j); if (k%_incr == 0) { p.setActive(); q.setActive(); } m_shapes.push_back( p ); m_shapes.push_back( q ); } // i } // j } // k ow = w*_numlevels; oh = -h*_numlevels; od = d*_numlevels; m_structure.init(0, 0, 0, ow, oh, od, false); break; default: break; } // set random indices for( vector<Shape>::iterator shapeIt = m_shapes.begin(); shapeIt != m_shapes.end(); ++shapeIt ) { int index = rand()%m_shapes.size(); shapeIt->setIndex(index); } random_shuffle(m_shapes.begin(), m_shapes.end()); }
static void StatsCellCallback(JSRuntime *rt, void *data, void *thing, JSGCTraceKind traceKind, size_t thingSize) { IteratorClosure *closure = static_cast<IteratorClosure *>(data); RuntimeStats *rtStats = closure->rtStats; CompartmentStats *cStats = rtStats->currCompartmentStats; switch (traceKind) { case JSTRACE_OBJECT: { JSObject *obj = static_cast<JSObject *>(thing); if (obj->isFunction()) { cStats->gcHeapObjectsFunction += thingSize; } else { cStats->gcHeapObjectsNonFunction += thingSize; } size_t slotsSize, elementsSize, miscSize; obj->sizeOfExcludingThis(rtStats->mallocSizeOf, &slotsSize, &elementsSize, &miscSize); cStats->objectSlots += slotsSize; cStats->objectElements += elementsSize; cStats->objectMisc += miscSize; if (ObjectPrivateVisitor *opv = closure->opv) { js::Class *clazz = js::GetObjectClass(obj); if (clazz->flags & JSCLASS_HAS_PRIVATE && clazz->flags & JSCLASS_PRIVATE_IS_NSISUPPORTS) { cStats->objectPrivate += opv->sizeOfIncludingThis(GetObjectPrivate(obj)); } } break; } case JSTRACE_STRING: { JSString *str = static_cast<JSString *>(thing); cStats->gcHeapStrings += thingSize; cStats->stringChars += str->sizeOfExcludingThis(rtStats->mallocSizeOf); break; } case JSTRACE_SHAPE: { Shape *shape = static_cast<Shape*>(thing); size_t propTableSize, kidsSize; shape->sizeOfExcludingThis(rtStats->mallocSizeOf, &propTableSize, &kidsSize); if (shape->inDictionary()) { cStats->gcHeapShapesDict += thingSize; cStats->shapesExtraDictTables += propTableSize; JS_ASSERT(kidsSize == 0); } else { cStats->gcHeapShapesTree += thingSize; cStats->shapesExtraTreeTables += propTableSize; cStats->shapesExtraTreeShapeKids += kidsSize; } break; } case JSTRACE_BASE_SHAPE: { cStats->gcHeapShapesBase += thingSize; break; } case JSTRACE_SCRIPT: { JSScript *script = static_cast<JSScript *>(thing); cStats->gcHeapScripts += thingSize; cStats->scriptData += script->sizeOfData(rtStats->mallocSizeOf); #ifdef JS_METHODJIT cStats->jaegerData += script->sizeOfJitScripts(rtStats->mallocSizeOf); # ifdef JS_ION if (script->hasIonScript()) cStats->ionData += script->ion->sizeOfIncludingThis(rtStats->mallocSizeOf); # endif #endif ScriptSource *ss = script->scriptSource(); SourceSet::AddPtr entry = closure->seenSources.lookupForAdd(ss); if (!entry) { closure->seenSources.add(entry, ss); // Not much to be done on failure. rtStats->runtime.scriptSources += ss->sizeOfIncludingThis(rtStats->mallocSizeOf); } break; } case JSTRACE_IONCODE: { #ifdef JS_METHODJIT # ifdef JS_ION cStats->gcHeapIonCodes += thingSize; // The code for a script is counted in ExecutableAllocator::sizeOfCode(). # endif #endif break; } case JSTRACE_TYPE_OBJECT: { types::TypeObject *obj = static_cast<types::TypeObject *>(thing); cStats->gcHeapTypeObjects += thingSize; obj->sizeOfExcludingThis(&cStats->typeInferenceSizes, rtStats->mallocSizeOf); break; } #if JS_HAS_XML_SUPPORT case JSTRACE_XML: { cStats->gcHeapXML += thingSize; break; } #endif } // Yes, this is a subtraction: see StatsArenaCallback() for details. cStats->gcHeapUnusedGcThings -= thingSize; }
static void StatsCellCallback(JSRuntime *rt, void *data, void *thing, JSGCTraceKind traceKind, size_t thingSize) { IteratorClosure *closure = static_cast<IteratorClosure *>(data); RuntimeStats *rtStats = closure->rtStats; ZoneStats *zStats = rtStats->currZoneStats; switch (traceKind) { case JSTRACE_OBJECT: { JSObject *obj = static_cast<JSObject *>(thing); CompartmentStats *cStats = GetCompartmentStats(obj->compartment()); if (obj->is<JSFunction>()) cStats->gcHeapObjectsFunction += thingSize; else if (obj->is<ArrayObject>()) cStats->gcHeapObjectsDenseArray += thingSize; else if (obj->isCrossCompartmentWrapper()) cStats->gcHeapObjectsCrossCompartmentWrapper += thingSize; else cStats->gcHeapObjectsOrdinary += thingSize; JS::ObjectsExtraSizes objectsExtra; obj->sizeOfExcludingThis(rtStats->mallocSizeOf_, &objectsExtra); cStats->objectsExtra.add(objectsExtra); // JSObject::sizeOfExcludingThis() doesn't measure objectsExtraPrivate, // so we do it here. if (ObjectPrivateVisitor *opv = closure->opv) { nsISupports *iface; if (opv->getISupports_(obj, &iface) && iface) { cStats->objectsExtra.private_ += opv->sizeOfIncludingThis(iface); } } break; } case JSTRACE_STRING: { JSString *str = static_cast<JSString *>(thing); size_t strSize = str->sizeOfExcludingThis(rtStats->mallocSizeOf_); // If we can't grow hugeStrings, let's just call this string non-huge. // We're probably about to OOM anyway. if (strSize >= JS::HugeStringInfo::MinSize() && zStats->hugeStrings.growBy(1)) { zStats->gcHeapStringsNormal += thingSize; JS::HugeStringInfo &info = zStats->hugeStrings.back(); info.length = str->length(); info.size = strSize; PutEscapedString(info.buffer, sizeof(info.buffer), &str->asLinear(), 0); } else if (str->isShort()) { MOZ_ASSERT(strSize == 0); zStats->gcHeapStringsShort += thingSize; } else { zStats->gcHeapStringsNormal += thingSize; zStats->stringCharsNonHuge += strSize; } break; } case JSTRACE_SHAPE: { Shape *shape = static_cast<Shape *>(thing); CompartmentStats *cStats = GetCompartmentStats(shape->compartment()); size_t propTableSize, kidsSize; shape->sizeOfExcludingThis(rtStats->mallocSizeOf_, &propTableSize, &kidsSize); if (shape->inDictionary()) { cStats->gcHeapShapesDict += thingSize; cStats->shapesExtraDictTables += propTableSize; JS_ASSERT(kidsSize == 0); } else { if (shape->base()->getObjectParent() == shape->compartment()->maybeGlobal()) { cStats->gcHeapShapesTreeGlobalParented += thingSize; } else { cStats->gcHeapShapesTreeNonGlobalParented += thingSize; } cStats->shapesExtraTreeTables += propTableSize; cStats->shapesExtraTreeShapeKids += kidsSize; } break; } case JSTRACE_BASE_SHAPE: { BaseShape *base = static_cast<BaseShape *>(thing); CompartmentStats *cStats = GetCompartmentStats(base->compartment()); cStats->gcHeapShapesBase += thingSize; break; } case JSTRACE_SCRIPT: { JSScript *script = static_cast<JSScript *>(thing); CompartmentStats *cStats = GetCompartmentStats(script->compartment()); cStats->gcHeapScripts += thingSize; cStats->scriptData += script->sizeOfData(rtStats->mallocSizeOf_); #ifdef JS_ION size_t baselineData = 0, baselineStubsFallback = 0; ion::SizeOfBaselineData(script, rtStats->mallocSizeOf_, &baselineData, &baselineStubsFallback); cStats->baselineData += baselineData; cStats->baselineStubsFallback += baselineStubsFallback; cStats->ionData += ion::SizeOfIonData(script, rtStats->mallocSizeOf_); #endif ScriptSource *ss = script->scriptSource(); SourceSet::AddPtr entry = closure->seenSources.lookupForAdd(ss); if (!entry) { closure->seenSources.add(entry, ss); // Not much to be done on failure. rtStats->runtime.scriptSources += ss->sizeOfIncludingThis(rtStats->mallocSizeOf_); } break; } case JSTRACE_LAZY_SCRIPT: { LazyScript *lazy = static_cast<LazyScript *>(thing); zStats->gcHeapLazyScripts += thingSize; zStats->lazyScripts += lazy->sizeOfExcludingThis(rtStats->mallocSizeOf_); break; } case JSTRACE_IONCODE: { #ifdef JS_ION zStats->gcHeapIonCodes += thingSize; // The code for a script is counted in ExecutableAllocator::sizeOfCode(). #endif break; } case JSTRACE_TYPE_OBJECT: { types::TypeObject *obj = static_cast<types::TypeObject *>(thing); zStats->gcHeapTypeObjects += thingSize; zStats->typeObjects += obj->sizeOfExcludingThis(rtStats->mallocSizeOf_); break; } } // Yes, this is a subtraction: see StatsArenaCallback() for details. zStats->gcHeapUnusedGcThings -= thingSize; }
bool Region::Shape::compareShapes(const Shape& aShape, const Shape& bShape) { bool result = CompareOperation::defaultResult; Shape::SpanIterator aSpan = aShape.spansBegin(); Shape::SpanIterator aSpanEnd = aShape.spansEnd(); Shape::SpanIterator bSpan = bShape.spansBegin(); Shape::SpanIterator bSpanEnd = bShape.spansEnd(); bool aHadSegmentInPreviousSpan = false; bool bHadSegmentInPreviousSpan = false; while (aSpan != aSpanEnd && aSpan + 1 != aSpanEnd && bSpan != bSpanEnd && bSpan + 1 != bSpanEnd) { int aY = aSpan->y; int aMaxY = (aSpan + 1)->y; int bY = bSpan->y; int bMaxY = (bSpan + 1)->y; Shape::SegmentIterator aSegment = aShape.segmentsBegin(aSpan); Shape::SegmentIterator aSegmentEnd = aShape.segmentsEnd(aSpan); Shape::SegmentIterator bSegment = bShape.segmentsBegin(bSpan); Shape::SegmentIterator bSegmentEnd = bShape.segmentsEnd(bSpan); // Look for a non-overlapping part of the spans. If B had a segment in its previous span, then we already tested A against B within that span. bool aHasSegmentInSpan = aSegment != aSegmentEnd; bool bHasSegmentInSpan = bSegment != bSegmentEnd; if (aY < bY && !bHadSegmentInPreviousSpan && aHasSegmentInSpan && CompareOperation::aOutsideB(result)) return result; if (bY < aY && !aHadSegmentInPreviousSpan && bHasSegmentInSpan && CompareOperation::bOutsideA(result)) return result; aHadSegmentInPreviousSpan = aHasSegmentInSpan; bHadSegmentInPreviousSpan = bHasSegmentInSpan; bool spansOverlap = bMaxY > aY && bY < aMaxY; if (spansOverlap) { while (aSegment != aSegmentEnd && bSegment != bSegmentEnd) { int aX = *aSegment; int aMaxX = *(aSegment + 1); int bX = *bSegment; int bMaxX = *(bSegment + 1); bool segmentsOverlap = bMaxX > aX && bX < aMaxX; if (segmentsOverlap && CompareOperation::aOverlapsB(result)) return result; if (aX < bX && CompareOperation::aOutsideB(result)) return result; if (bX < aX && CompareOperation::bOutsideA(result)) return result; if (aMaxX < bMaxX) { aSegment += 2; } else if (bMaxX < aMaxX) { bSegment += 2; } else { aSegment += 2; bSegment += 2; } } if (aSegment != aSegmentEnd && CompareOperation::aOutsideB(result)) return result; if (bSegment != bSegmentEnd && CompareOperation::bOutsideA(result)) return result; } if (aMaxY < bMaxY) { aSpan += 1; } else if (bMaxY < aMaxY) { bSpan += 1; } else { aSpan += 1; bSpan += 1; } } if (aSpan != aSpanEnd && aSpan + 1 != aSpanEnd && CompareOperation::aOutsideB(result)) return result; if (bSpan != bSpanEnd && bSpan + 1 != bSpanEnd && CompareOperation::bOutsideA(result)) return result; return result; }
int main() { std::string name, pointNum; printf("请输入图形的名字:"); getline(std::cin, name); if (name.empty()) { name = "T"; printf("你的输入为空,因此为你的图形命名(T)\n"); } printf("请输入图形的端点数量:"); getline(std::cin, pointNum); if (is_number(pointNum)) { std::cout << "你输入的是整数\n"; } else { std::cout << "你输入的不是整数\n"; } int num = atoi(pointNum.c_str()); Point *shapePoints = new Point[num]; for (int i = 0; i < num; ++i) { double x, y; printf("请输入第%d个点横坐标x = ", i + 1); scanf("%lf", &x); printf("请输入第%d个点纵坐标y = ", i + 1); scanf("%lf", &y); shapePoints[i].update(x, y); } std::cout << "你输入图形的名字为:" << name << " " << "你输入的端点数量为:" << pointNum << std::endl; Shape *shape = new Shape(shapePoints, num, name.c_str()); shape->printShape(); std::string command; bool flag = true; while (flag) { printf("\n请输入对图形的操作指令:"); std::cin.ignore(); getline(std::cin, command); std::vector<std::string> v; split_str(command, v); for (int i = 0; i < v.size(); i++) { std::cout << "v = " << v[i] << std::endl; } switch (resolveCommand(command)) { case Motion::Rotate: double angle; printf("请输入旋转角度,逆时针为正:"); scanf("%lf", &angle); shape->rotateShape(angle); break; case Motion::Move: double mx, my; printf("输入X方向移动距离:"); scanf("%lf", &mx); printf("输入Y方向移动距离:"); scanf("%lf", &my); shape->moveShape(mx, my); break; case Motion::Zoom: double zx, zy; printf("输入X方向缩放大小:"); scanf("%lf", &zx); printf("输入Y方向缩放大小:"); scanf("%lf", &zy); shape->zoomShape(zx, zy); break; default: flag = false; } shape->printShape(); } printf("Error!!!你输入的命令有误,已经退出指令模式退出\n"); delete shape; delete[] shapePoints; shapePoints = NULL; }
Region::Shape Region::Shape::shapeOperation(const Shape& shape1, const Shape& shape2) { COMPILE_ASSERT(!(!Operation::shouldAddRemainingSegmentsFromSpan1 && Operation::shouldAddRemainingSegmentsFromSpan2), invalid_segment_combination); COMPILE_ASSERT(!(!Operation::shouldAddRemainingSpansFromShape1 && Operation::shouldAddRemainingSpansFromShape2), invalid_span_combination); size_t segmentsCapacity = shape1.segmentsSize() + shape2.segmentsSize(); size_t spansCapacity = shape1.spansSize() + shape2.spansSize(); Shape result(segmentsCapacity, spansCapacity); if (Operation::trySimpleOperation(shape1, shape2, result)) return result; SpanIterator spans1 = shape1.spansBegin(); SpanIterator spans1End = shape1.spansEnd(); SpanIterator spans2 = shape2.spansBegin(); SpanIterator spans2End = shape2.spansEnd(); SegmentIterator segments1 = 0; SegmentIterator segments1End = 0; SegmentIterator segments2 = 0; SegmentIterator segments2End = 0; Vector<int, 32> segments; segments.reserveCapacity(std::max(shape1.segmentsSize(), shape2.segmentsSize())); // Iterate over all spans. while (spans1 != spans1End && spans2 != spans2End) { int y = 0; int test = spans1->y - spans2->y; if (test <= 0) { y = spans1->y; segments1 = shape1.segmentsBegin(spans1); segments1End = shape1.segmentsEnd(spans1); ++spans1; } if (test >= 0) { y = spans2->y; segments2 = shape2.segmentsBegin(spans2); segments2End = shape2.segmentsEnd(spans2); ++spans2; } int flag = 0; int oldFlag = 0; SegmentIterator s1 = segments1; SegmentIterator s2 = segments2; // Clear vector without dropping capacity. segments.resize(0); ASSERT(segments.capacity()); // Now iterate over the segments in each span and construct a new vector of segments. while (s1 != segments1End && s2 != segments2End) { int test = *s1 - *s2; int x; if (test <= 0) { x = *s1; flag = flag ^ 1; ++s1; } if (test >= 0) { x = *s2; flag = flag ^ 2; ++s2; } if (flag == Operation::opCode || oldFlag == Operation::opCode) segments.append(x); oldFlag = flag; } // Add any remaining segments. if (Operation::shouldAddRemainingSegmentsFromSpan1 && s1 != segments1End) segments.appendRange(s1, segments1End); else if (Operation::shouldAddRemainingSegmentsFromSpan2 && s2 != segments2End) segments.appendRange(s2, segments2End); // Add the span. if (!segments.isEmpty() || !result.isEmpty()) result.appendSpan(y, segments.data(), segments.data() + segments.size()); } // Add any remaining spans. if (Operation::shouldAddRemainingSpansFromShape1 && spans1 != spans1End) result.appendSpans(shape1, spans1, spans1End); else if (Operation::shouldAddRemainingSpansFromShape2 && spans2 != spans2End) result.appendSpans(shape2, spans2, spans2End); result.trimCapacities(); return result; }
ReflectionExample(void) : make_plane( Vec3f(), Vec3f(3.0f, 0.0f, 0.0f), Vec3f(0.0f, 0.0f, -3.0f), 15, 15 ), plane_instr(make_plane.Instructions()) , plane_indices(make_plane.Indices()) , make_shape() , shape_instr(make_shape.Instructions()) , shape_indices(make_shape.Indices()) , plane_vs(ObjectDesc("Plane vertex")) , shape_vs(ObjectDesc("Shape vertex")) , plane_fs(ObjectDesc("Plane fragment")) , shape_fs(ObjectDesc("Shape fragment")) , plane_projection_matrix(plane_prog, "ProjectionMatrix") , plane_camera_matrix(plane_prog, "CameraMatrix") , plane_model_matrix(plane_prog, "ModelMatrix") , shape_projection_matrix(shape_prog, "ProjectionMatrix") , shape_camera_matrix(shape_prog, "CameraMatrix") , shape_model_matrix(shape_prog, "ModelMatrix") , width(800) , height(600) , tex_size_div(2) { plane_vs.Source( "#version 330\n" "uniform vec3 LightPosition;" "uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;" "in vec4 Position;" "out vec3 vertLightDir;" "out vec4 vertTexCoord;" "void main(void)" "{" " gl_Position = ModelMatrix*Position;" " vertLightDir = LightPosition - gl_Position.xyz;" " gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;" " vertTexCoord = gl_Position;" "}" ); plane_vs.Compile(); plane_fs.Source( "#version 330\n" "uniform sampler2DRect ReflectTex;" "uniform vec3 Normal;" "in vec3 vertLightDir;" "in vec4 vertTexCoord;" "out vec3 fragColor;" "const int n = 5;" "const int ns = (n*n);" "const float blur = 0.15/n;" "void main(void)" "{" " float d = dot(Normal, normalize(vertLightDir));" " float intensity = 0.5 + pow(1.4*d, 2.0);" " vec3 color = vec3(0.0, 0.0, 0.0);" " int n = 2;" " float pct = 0.5/vertTexCoord.w;" " for(int y=-n; y!=(n+1); ++y)" " for(int x=-n; x!=(n+1); ++x)" " {" " vec2 coord = vertTexCoord.xy;" " coord += vec2(blur*x, blur*y);" " coord *= pct;" " coord += vec2(0.5, 0.5);" " coord *= textureSize(ReflectTex);" " color += texture(ReflectTex, coord).rgb/ns;" " }" " fragColor = color*intensity;" "}" ); plane_fs.Compile(); plane_prog.AttachShader(plane_vs); plane_prog.AttachShader(plane_fs); plane_prog.Link(); plane_prog.Use(); Vec3f lightPos(3.0f, 0.5f, 2.0f); Uniform<Vec3f>(plane_prog, "LightPosition").Set(lightPos); Uniform<Vec3f>(plane_prog, "Normal").Set(make_plane.Normal()); plane.Bind(); plane_verts.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint n_per_vertex = make_plane.Positions(data); Buffer::Data(Buffer::Target::Array, data); VertexAttribArray attr(plane_prog, "Position"); attr.Setup(n_per_vertex, DataType::Float); attr.Enable(); } // Texture::Active(1); { auto bound_tex = Bind(depth_tex, Texture::Target::Rectangle); bound_tex.MinFilter(TextureMinFilter::Linear); bound_tex.MagFilter(TextureMagFilter::Linear); bound_tex.WrapS(TextureWrap::ClampToEdge); bound_tex.WrapT(TextureWrap::ClampToEdge); } Texture::Active(0); ProgramUniformSampler(plane_prog, "ReflectTex").Set(0); { auto bound_tex = Bind(reflect_tex, Texture::Target::Rectangle); bound_tex.MinFilter(TextureMinFilter::Linear); bound_tex.MagFilter(TextureMagFilter::Linear); bound_tex.WrapS(TextureWrap::ClampToEdge); bound_tex.WrapT(TextureWrap::ClampToEdge); } { auto bound_fbo = Bind( fbo, Framebuffer::Target::Draw ); bound_fbo.AttachTexture( FramebufferAttachment::Color, reflect_tex, 0 ); bound_fbo.AttachTexture( FramebufferAttachment::Depth, depth_tex, 0 ); } shape_vs.Source( "#version 330\n" "uniform vec3 LightPosition;" "uniform mat4 ProjectionMatrix, ModelMatrix, CameraMatrix;" "in vec4 Position;" "in vec3 Normal;" "out vec3 vertNormal;" "out vec3 vertLightDir;" "out vec3 vertLightRefl;" "out vec3 vertViewDir;" "out vec3 vertColor;" "void main(void)" "{" " gl_Position = ModelMatrix * Position;" " vertLightDir = LightPosition - gl_Position.xyz;" " vertNormal = mat3(ModelMatrix)*Normal;" " vertLightRefl = reflect(" " -normalize(vertLightDir)," " normalize(vertNormal)" " );" " vertViewDir = (vec4(0.0, 0.0, 1.0, 1.0)*CameraMatrix).xyz;" " vertColor = vec3(1, 1, 1) - vertNormal;" " gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;" "}" ); shape_vs.Compile(); shape_fs.Source( "#version 330\n" "in vec3 vertNormal;" "in vec3 vertLightDir;" "in vec3 vertLightRefl;" "in vec3 vertViewDir;" "in vec3 vertColor;" "out vec3 fragColor;" "void main(void)" "{" " float l = length(vertLightDir);" " float d = dot(" " normalize(vertNormal), " " normalize(vertLightDir)" " ) / l;" " float s = dot(" " normalize(vertLightRefl)," " normalize(vertViewDir)" " );" " vec3 lt = vec3(1.0, 1.0, 1.0);" " fragColor = " " vertColor * 0.4 + " " (lt + vertColor)*pow(max(2.5*d, 0.0), 3) + " " lt * pow(max(s, 0.0), 64);" "}" ); shape_fs.Compile(); shape_prog.AttachShader(shape_vs); shape_prog.AttachShader(shape_fs); shape_prog.Link(); shape_prog.Use(); Uniform<Vec3f>(shape_prog, "LightPosition").Set(lightPos); shape.Bind(); shape_verts.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint n_per_vertex = make_shape.Positions(data); Buffer::Data(Buffer::Target::Array, data); VertexAttribArray attr(shape_prog, "Position"); attr.Setup(n_per_vertex, DataType::Float); attr.Enable(); } shape_normals.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint n_per_vertex = make_shape.Normals(data); Buffer::Data(Buffer::Target::Array, data); VertexAttribArray attr(shape_prog, "Normal"); attr.Setup(n_per_vertex, DataType::Float); attr.Enable(); } // gl.ClearColor(0.5f, 0.5f, 0.4f, 0.0f); gl.ClearDepth(1.0f); gl.Enable(Capability::DepthTest); gl.Enable(Capability::CullFace); }
void ViewUnitEditor::MakeCellHighlight (FLOAT x, FLOAT y) { if (this->layers() == NULL) { return; } if (this->layers()->empty()) { return; } Shape *pShape = NULL; Shape *pCompareShape = NULL; POINT point; RECTFLOAT originRect, compareRect; TColor clChecked = RGB(120, 170, 255); TColor clUnchecked = RGB(255, 255, 255); INT32 nColCount = _pUnitdesigninfo->GetBallCountX(); INT32 nRowCount = _pUnitdesigninfo->GetBallCountY(); pShape = this->GetMouseOverShape(x, y); if (pShape == NULL) { if (_highlightPoint.x >= 0 && _highlightPoint.y >= 0) { for (INT32 idx = 1 ; idx < _pGrid->RowCount ; idx++) { if (!GetCommaTextToPoint(_pGrid->Cells[INDEX_COLUMN][idx], point)) { return; } if (point.x < 0 || point.y < 0) { return; } if (point.x == _highlightPoint.x && point.y == _highlightPoint.y) { _pGrid->ColorRect(INDEX_COLUMN, idx, CHECKBOX_COLUMN, idx, clUnchecked); break; } } // for (INT32 idx = 1 ; idx < _pGrid->RowCount ; idx++) _highlightPoint.x = -1; _highlightPoint.y = -1; } // if (_highlightPoint.x >= 0 && _highlightPoint.y >= 0) return; } if (!pShape->getRegion(originRect)) { return; } for (INT32 idxCol = 0 ; idxCol < nColCount ; idxCol++) { for (INT32 idxRow = 0; idxRow < nRowCount ; idxRow++) { pCompareShape = GetSelectionShape(idxCol, idxRow); if (pCompareShape == NULL) { continue; } if (!pCompareShape->getRegion(compareRect)) { continue; } if (originRect.left == compareRect.left && originRect.top == compareRect.top && originRect.right == compareRect.right && originRect.bottom == compareRect.bottom) { if (_highlightPoint.x == idxCol && _highlightPoint.y == idxRow) { return; } int flag = 0; for (INT32 idx = 1 ; idx < _pGrid->RowCount ; idx++) { if (!GetCommaTextToPoint(_pGrid->Cells[INDEX_COLUMN][idx], point)) { return; } if (point.x < 0 || point.y < 0) { return; } if (point.x == idxCol && point.y == idxRow) { _pGrid->ColorRect(INDEX_COLUMN, idx, CHECKBOX_COLUMN, idx, clChecked); _pGrid->ScrollInView(INDEX_COLUMN, idx, 0); flag++; } if (point.x == _highlightPoint.x && point.y == _highlightPoint.y) { _pGrid->ColorRect(INDEX_COLUMN, idx, CHECKBOX_COLUMN, idx, clUnchecked); flag++; } if (flag >= 2 || (flag >= 1 && _highlightPoint.x < 0 && _highlightPoint.y < 0)) { break; } } // for (INT32 idx = 1 ; idx < _pGrid->RowCount ; idx++) _highlightPoint.x = idxCol; _highlightPoint.y = idxRow; return; } // if (originRect.left == compareRect.left && originRect.top == compareRect.top && // originRect.right == compareRect.right && originRect.bottom == compareRect.bottom) } // for (INT32 idxRow = 0; idxRow < nRowCount ; idxRow++) } // for (INT32 idxCol = 0 ; idxCol < nColCount ; idxCol++) }
int main () { int width = 0, length = 0, choice = 0; char symbol = ' '; do { Shape clear; clear.screen(); cout << "What would you like to draw?" << endl << endl; cout << "1) Vertical line\n"; cout << "2) Horizontal line\n"; cout << "3) Wide spaced horizontal line\n"; cout << "4) Hollow square\n"; cout << "5) Solid square\n"; cout << "6) Hollow rectangle\n"; cout << "7) Solid rectangle\n"; cout << "8) Regular triangle\n"; cout << "9) Upside down triangle\n"; cout << "0) Flag\n"; cout << "11) Quit\n"; cout << "\nEnter choice: "; cin >> choice; clear.screen(); if (choice == 11) { cout << "\n\nLive long and prosper\n\n"; return 0; } if (choice) { cout << "\nWhat symbol would you like to use? "; cin.ignore(); symbol = getchar(); cin.clear(); cin.ignore(9999, '\n'); } Rectangle rect; Triangle tri; rect.setSymbol( symbol); tri.setSymbol( symbol); switch (choice) { case 1: cout << "\nHow tall do you want the line? "; cout << "The value given must be between 1 and 35. "; cin >> width; length = width; if (rect.inputValidate( length, width)) rect.draw( 1, width, false); cout << "\nPress <enter> to return to the main menu. "; cin.get(); cin.ignore(); break; case 2: cout << "\nHow wide do you want the line? "; cout << "The value given must be between 1 and 35. "; cin >> width; length = width; if (rect.inputValidate( length, width)) rect.draw( width, 1, false); cout << "\nPress <enter> to return to the main menu. "; cin.get(); cin.ignore(); break; case 3: cout << "\nHow wide do you want the line? "; cout << "The value given must be between 1 and 35. "; cin >> width; length = width; Rectangle wide; if (rect.inputValidate( length, width)) rect.draw( width, 1, true); cout << "\nPress <enter> to return to the main menu. "; cin.get(); cin.ignore(); break; case 4: cout << "\nHow long do you want each side? "; cout << "The value given must be between 1 and 35. "; cin >> width; length = width; if (rect.inputValidate( length, width)) rect.hollow( length, width); cout << "\nPress <enter> to return to the main menu. "; cin.get(); cin.ignore(); break; case 5: cout << "\nHow long do you want each side? "; cout << "The value given must be between 1 and 35. "; cin >> width; length = width; if (rect.inputValidate( length, width)) rect.draw(length, width, true); cout << "\nPress <enter> to return to the main menu. "; cin.get(); cin.ignore(); break; case 6: cout << "\nHow long do you want the rectangle? "; cout << "The value given must be between 1 and 35. "; cin >> length; cout << "How wide do you want the rectangle? "; cout << "The value given must be between 1 and 35. "; cin >> width; if (rect.inputValidate( length, width)) rect.hollow( length, width); cout << "\nPress <enter> to return to the main menu. "; cin.get(); cin.ignore(); break; case 7: cout << "\nHow long do you want the rectangle? "; cout << "The value given must be between 1 and 35. "; cin >> length; cout << "How wide do you want the rectangle? "; cout << "The value given must be between 1 and 35. "; cin >> width; if (rect.inputValidate( length, width)) rect.draw( length, width, true); cout << "\nPress <enter> to return to the main menu. "; cin.get(); cin.ignore(); break; case 8: cout << "\nHow wide do you want the base of the triangle? "; cout << "The value given must be between 1 and 35. "; cin >> length; width = length; if (tri.inputValidate( length, width)) tri.draw(length, false); cout << "\nPress <enter> to return to the main menu. "; cin.get(); cin.ignore(); break; case 9: cout << "\nHow wide do you want the base of the triangle? "; cout << "The value given must be between 1 and 35. "; cin >> length; width = length; if (tri.inputValidate( length, width)) tri.draw( length, true); cout << "\nPress <enter> to return to the main menu. "; cin.get(); cin.ignore(); break; case 0: rect.flag(); cout << "\nPress <enter> to return to the main menu. "; cin.get(); cin.ignore(); break; default: cout << "You screwed the pooch this time...error in switch statement"; } }while(true); }
bool js::GetOwnProperty(JSContext *cx, Handle<ObjectImpl*> obj, PropertyId pid_, unsigned resolveFlags, PropDesc *desc) { NEW_OBJECT_REPRESENTATION_ONLY(); JS_CHECK_RECURSION(cx, return false); Rooted<PropertyId> pid(cx, pid_); if (static_cast<JSObject *>(obj.get())->isProxy()) { MOZ_NOT_REACHED("NYI: proxy [[GetOwnProperty]]"); return false; } Shape *shape = obj->nativeLookup(cx, pid); if (!shape) { /* Not found: attempt to resolve it. */ Class *clasp = obj->getClass(); JSResolveOp resolve = clasp->resolve; if (resolve != JS_ResolveStub) { Rooted<jsid> id(cx, pid.get().asId()); Rooted<JSObject*> robj(cx, static_cast<JSObject*>(obj.get())); if (clasp->flags & JSCLASS_NEW_RESOLVE) { Rooted<JSObject*> obj2(cx, NULL); JSNewResolveOp op = reinterpret_cast<JSNewResolveOp>(resolve); if (!op(cx, robj, id, resolveFlags, &obj2)) return false; } else { if (!resolve(cx, robj, id)) return false; } } /* Now look it up again. */ shape = obj->nativeLookup(cx, pid); if (!shape) { desc->setUndefined(); return true; } } if (shape->isDataDescriptor()) { *desc = PropDesc(obj->nativeGetSlot(shape->slot()), shape->writability(), shape->enumerability(), shape->configurability()); return true; } if (shape->isAccessorDescriptor()) { *desc = PropDesc(shape->getterValue(), shape->setterValue(), shape->enumerability(), shape->configurability()); return true; } MOZ_NOT_REACHED("NYI: PropertyOp-based properties"); return false; }
void History::Read(istream& is) { string line; do { vector<string> tokens; getline(is, line); split(line, tokens); if(tokens.size() > 0) { string cmd = tokens[0]; if(cmd == "S")// STRAIGHT LINE { try { vector<Vector2D> points; if(tokens.size() != 6) throw exception(); for(unsigned int i = 2; i < tokens.size(); i+=2) points.push_back(Vector2D(my_stoi(tokens[i]),my_stoi(tokens[i+1]))); Segment* seg = new Segment(tokens[1], points[0], points[1]); Add(seg); } catch(exception e) { Manager->Answer("Invalide syntax. Here is the truth: "); cout << "S name x y x' y'"; } } else if(cmd == "R")// FOUR RIGHT-ANGLED CORNER { try { vector<Vector2D> points; if(tokens.size() != 6) throw exception(); for(unsigned int i = 2; i < tokens.size(); i+=2) points.push_back(Vector2D(my_stoi(tokens[i]),my_stoi(tokens[i+1]))); Rectangle* rec = new Rectangle(tokens[1], points[0], points[1]); Add(rec); } catch(exception e) { Manager->Answer("Invalide syntax. Here is the truth: "); cout << "R name x y x' y'"; } } else if(cmd == "PC")// STAR ? WHAT DOES IT MEAN ? { try { vector<Vector2D> points; if(tokens.size()%2 == 1 || tokens.size() < 8) throw exception(); for(unsigned int i = 2; i < tokens.size(); i+=2) points.push_back(Vector2D(my_stoi(tokens[i]),my_stoi(tokens[i+1]))); if(PolyConv::VerifyConvexity(points)) { PolyConv* pc = new PolyConv(tokens[1], points); Add(pc); } else { Manager->Answer("Not a convex polygone :/ If you want to design this, try to unify more single shapes"); } } catch(exception e) { Manager->Answer("Invalide syntax. Here is the truth: "); cout << "PC name x0 y0 x1 y1 ... xn yn"; } } else if(cmd == "OI")// JUST KEEP THE COMMON THINGS { try { vector<string> notInTable; for(unsigned int i = 2; i < tokens.size(); i++) if(!Manager->IsInTable(tokens[i])) notInTable.push_back(tokens[i]); if(notInTable.size() == 0) { vector<Shape*> shapes1; for(unsigned int i = 2; i < tokens.size(); i++) shapes1.push_back(Manager->findShape(tokens[i])->Clone()); PolyIntersect* pi = new PolyIntersect(tokens[1], shapes1); Add(pi); } else { Manager->Answer("These names are not saved in the app."); for(string s : notInTable) cout << s << " | " ; cout << endl << endl; } } catch(exception e) { Manager->Answer("Invalid syntax, here lies the truth: "); Manager->Answer("OI name name0 name1 ... namen"); } } else if(cmd == "OR")// UNION IS ALWAYS BETTER { try { vector<string> notInTable; for(unsigned int i = 2; i < tokens.size(); i++) if(!Manager->IsInTable(tokens[i])) notInTable.push_back(tokens[i]); if(notInTable.size() == 0) { vector<Shape*> shapes1; for(unsigned int i = 2; i < tokens.size(); i++) shapes1.push_back(Manager->findShape(tokens[i])->Clone()); PolyUnion* pu = new PolyUnion(tokens[1], shapes1); Add(pu); } else { Manager->Answer("These names are not saved in the app."); for(string s : notInTable) cout << s << " | " ; cout << endl << endl; } } catch(exception e) { Manager->Answer("Invalid syntax, here lies the truth: "); Manager->Answer("OI name name0 name1 ... namen"); } } else if(cmd == "DELETE")// BYE BYE SHAPE ! { try { if(Manager->IsInTable(tokens[1])) { Do(new Delete(Manager->findShape(tokens[1])->Clone(), Manager)); Manager->Delete(tokens[1]); Manager->Answer("The shape " + tokens[1] + " has been successfully deleted", true); } } catch(exception e) { Manager->Answer("Invalide syntax. Here lies the truth: "); Manager->Answer("DELETE name"); } } else if(cmd == "CLEAR")// BACK TO THE BASE { Do(new DeleteAll(Manager)); if(Manager->Empty()) Manager->Answer("Cleared !", true); } else if(cmd == "MOVE")// MOVE OFFSET { try { if(tokens.size() != 4) throw exception(); Vector2D movement = Vector2D(my_stoi(tokens[2]), my_stoi(tokens[3])); Shape* shape; if(Manager->Move(tokens[1], movement)) { shape = Manager->findShape(tokens[1])->Clone(); Do(new Move(shape, movement, Manager)); Manager->Answer(tokens[1] + " has been moved from " + (shape->GetOffset() - movement).toString() + " to " + shape->GetOffset().toString(), true ); } } catch(exception e) { Manager->Answer("Invalide syntax. Here lies the truth: "); Manager->Answer("MOVE name dx dy"); } } else if(cmd == "HIT")// IS IN SHAPE ? { try { if(tokens.size() != 4) throw exception(); string name = tokens[1]; Vector2D point(my_stoi(tokens[2]),my_stoi(tokens[3])); Manager->Hit(name, point); } catch(exception e) { Manager->Answer("Invalide syntax. Here lies the truth : "); Manager->Answer("HIT name x y"); } } else if(cmd == "LIST")// WHAT'S IN MY APP ? { Manager->List(); } else if(cmd == "UNDO")// LET'S START AGAIN THIS ACTION { Undo(); } else if(cmd == "REDO")// COME BACK TO THE FUTURE { Redo(); } else if(cmd == "LOAD")// GUESS I WORKED HARD IN A PREVIOUS SESSION { try { if(tokens.size() != 2) throw exception(); Load(tokens[1]); } catch(exception e) { Manager->Answer("Invalid syntax."); } } else if(cmd == "STORE" || cmd == "SAVE")// DON'T WANT A WASTE OF TIME { try { if(tokens.size() != 2) throw exception(); Store(tokens[1]); } catch(exception e) { Manager->Answer("Invalid syntax."); } } else if(cmd != "EXIT")// HINTS ! { cout << "New into this ? Here is the help : " << endl; cout << " - EXIT : end the program" << endl << " - S [name] x y x' y' : create a segment beginning in x,y ending in x',y' " << endl << " - R [name] x y x' y' : create a rectangle with top left corner x,y end bottom right corner in x',y' " << endl << " - PC [name] x0 y0 x1 y1 ... xn yn : create a convex polygon with the following points " << endl << " - OR [name] <name0> <name1> ... <namen> : create an union of these shapes" << endl << " - OI [name] <name0> <name1> ... <namen> : create an intersection of these shapes" << endl << " - LIST : list the shapes storred" << endl << " - CLEAR : clear all shapes" << endl << " - LOAD <fileName> : load shapes from a file" << endl << " - SAVE <fileName> : store all shapes in a file" << endl << " - DELETE <name> : delete a shape " << endl << " - UNDO/REDO : rewind or forward in timeline of program (20 actions max)" << endl << " - HIT [name] x y : verify if the point is in the shape " << endl << endl; } } }while(line != "EXIT");//GET OUT OF THERE }