void buildVector(TreeNode *root, int depth) { if(root == NULL) return; if(res.size() == depth) res.push_back(vector<int>()); res[depth].push_back(root->val); buildVector(root->left, depth + 1); buildVector(root->right, depth + 1); }
void buildVector(TreeNode *root, int depth, vector<vector<int>> &result) { if (!root) { return; } if (result.size() == depth) { result.push_back(vector<int>()); } result[depth].push_back(root->val); buildVector(root->left, depth+1, result); buildVector(root->right, depth+1, result); }
//Main: Initializing procedures int main(int argc, char** argv) { glutInit(&argc, argv); //starts up GLUT glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH); glutInitWindowSize(800, 800); glutInitWindowPosition(700,100); glutCreateWindow("particle fountain"); //creates the window initComments(); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_LIGHTING); //disregards face colour during drawing glEnable(GL_LIGHT0); //because we're going to use materials glEnable(GL_COLOR_MATERIAL); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-150, 150,-150, 150, -150, 150); glRotatef(10, 0, 1, 0); glMatrixMode(GL_MODELVIEW); buildVector(); glutSpecialFunc(special); glutKeyboardFunc(kbd); glutDisplayFunc(display); glutIdleFunc(idle); glutMainLoop(); return 0; }
void testSorting(int argc, char **argv) { Sorting t; vector<int> A = buildVector(argc, argv); t.flipSort(A); // t.radixSort(A); copy(A.begin(), A.end(), ostream_iterator<int>(cout, " ")); cout << endl; }
void testProb(int argc, char **argv){ Prob t; auto A = buildVector(argc, argv); auto ret = t.off_sampling(A, 3); copy(ret.begin(), ret.end(), ostream_iterator<int>(cout, " ")); cout << endl; }
void testBST(int argc, char **argv) { BST<int> t; auto A = buildVector(argc, argv); auto n=t.buildBSTfromVector(A, 0, A.size()-1); t.printTree(n); cout << endl; t.preorder_iterative(n); t.postorder_iterative(n); }
void testHeap(int argc, char ** argv) { Heap h; vector<int> A = buildVector(argc, argv); vector<int> ret = h.findKClosestMedian(A, 3); copy(ret.begin(), ret.end(), ostream_iterator<int>(cout, " ")); cout << endl; // vector<string> fins({"f1.csv", "f2.csv"}); //string out("out.csv"); // h.mergeSortedFiles(fins, out); }
vector<vector<int> > levelOrder(TreeNode *root) { vector<vector<int>> temp; buildVector(root, 0, temp); vector<vector<int>> result; int length = temp.size(); for (int i = 0; i < length; ++i) { result.push_back(temp[length-i-1]); } return result; }
void testLinkedList(int argc, char **argv) { LinkedList t; vector<int> A = buildVector(argc, argv); shared_ptr<LinkedList::Node> head = t.buildList(A); t.print(head);; t.print(head);; // shared_ptr<LinkedList::Node> even;// = t.evenOddList2(head); // even = t.evenOddList3(head); // t.print(even); // t.print(head); }
int test_meta(int argc, char **argv) { vector<int> arr=buildVector(argc-1, &argv[1]); printVector(arr); int k=atoi(argv[1]); Meta test; cout << test.count_score_permutation(k, arr) << endl; // cout << test.MaxMarginCoinGame(arr) << endl; return 0; }
void miscTest(int argc, char ** argv) { Misc mscTest; vector<int> A = buildVector(argc, argv); cout << mscTest.maxDiff_DP(A) << endl; cout << mscTest.maxDiff_divide(A) << endl; cout << mscTest.maxDiff_subArray(A) << endl; // mscTest.testprintA(); // vector<vector<int> > A{{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}}; // mscTest.printMatrixClockwisely(A); // vector<int> A = buildVector(argc, argv); // try { // cout << mscTest.findMajorityNum(A) << endl; // } catch (exception &e) { // cout << e.what() << endl; // } // cout << mscTest.getLongestSymmetrySubString(string(argv[1])) << endl; // mscTest.calcProbDices(atoi(argv[1])); // cout << endl; // mscTest.calcProbDices_DP(atoi(argv[1])); // cout << mscTest.addWithConstrains(atoi(argv[1])) << endl; // vector<int> a = buildVector(argc, argv); // cout << mscTest.minRotateSortArray(a) << endl; // mscTest.findMinIntCombination(a); // mscTest.printNDigits(atoi(argv[1])); // mscTest.printUglyNum(15); // cout << mscTest.findLongestCommonSubarray(string(argv[1]), string(argv[2])) << endl; // vector<int> pushV{1,2,3,4,5}; // cout << mscTest.findLastElmentInRemove_efficient(pushV, atoi(argv[1])) << endl; // mscTest.findContinuousSequence3(15); // cout << endl; // mscTest.findContinuousSequence2(10, 15); // mscTest.ArrayToOddEvenArray(pushV); // vector<int> popV{4,5,3,1,2}; // cout << mscTest.checkPushPop(pushV, popV) << endl; }
vector<vector<int> > levelOrder(TreeNode *root) { buildVector(root, 0); return res; }
//*************************************************************** void CToolCreateEntity::updateArray(CEntityCL *clonee) { //H_AUTO(R2_CToolCreateEntity_updateArray) if (!clonee) { nlassert(!_ArrayElements.empty()); nlassert(_ArrayElements[0] != NULL); clonee = _ArrayElements[0]->getEntity(); if (!clonee) { return; } } CVector extent = _ArrayEnd - _ArrayOrigin; uint arraySize = 1; float arrayStepLength = 1.f; if (!_ArrayElements.empty() && _ArrayElements[0]) { arrayStepLength = 2.f * _ArrayElements[0]->getSelectionDecalRadius(); arraySize = (uint) floorf(extent.norm() / arrayStepLength) + 1; arraySize = std::min(arraySize, (uint) 16); } while (!getEditor().verifyRoomLeft(0, arraySize)) { -- arraySize; if (arraySize == 0) { TSmartPtr hold(this); cancel(); return; } } _ArrayElements.resize(std::max(arraySize, uint(_ArrayElements.size()))); CVector delta = arrayStepLength * extent.normed(); float angle = _ArrayDefaultAngle; if (arraySize > 1) { angle = - (float) atan2(extent.x, extent.y); } bool newEntityCreated = false; uint numCreatedEntity = 0; for (uint k = 0; k < _ArrayElements.size(); ++k) { CVector pos = _ArrayOrigin + (float) k * delta; if (!_ArrayElements[k]) { if (k < arraySize) { nlwarning("NEW ENTITY"); // create new element std::string instanceId = cloneEntityIntoScenario(clonee, pos, angle, false, /*new action*/ true /*create ghost*/); CInstance *inst = getEditor().getInstanceFromId(instanceId); if (inst) { _ArrayElements[k] = dynamic_cast<CDisplayerVisualEntity *>(inst->getDisplayerVisual()); if (_ArrayElements[k]) { _ArrayElements[k]->setDisplayMode(CDisplayerVisual::DisplayModeArray); } } newEntityCreated = true; ++ numCreatedEntity; } } if (_ArrayElements[k]) { bool active = k < arraySize; // do a kind of 'reserve' on the list of entities : don't delete entities in excess, but hide them instead if (active != _ArrayElements[k]->getActive()) { _ArrayElements[k]->setActive(active); if (active) { newEntityCreated = true; _ArrayElements[k]->setDisplayMode(CDisplayerVisual::DisplayModeArray); } } if (active) { // update pos & angle TInstanceId instanceId = _ArrayElements[k]->getDisplayedInstance()->getId(); CVector worldPos = _ArrayElements[k]->getWorldPos(); if (pos != worldPos) { CObject *newPos = buildVector(pos, _ArrayElements[k]->getDisplayedInstance()->getPosInstanceId()); getEditor().getDMC().requestSetNode(instanceId, "Position", newPos); delete newPos; } if (angle != _ArrayElements[k]->getAngle()) { CObjectNumber *angleObject = new CObjectNumber(angle); getEditor().getDMC().requestSetNode(instanceId, "Angle", angleObject); delete angleObject; } } } } if (newEntityCreated) { nlwarning("Num created entity = %d", numCreatedEntity); getEditor().getEntitySorter()->clipEntitiesByDist(); } }
int main() { /* Setup Allegro/AllegroGL */ if (allegro_init()) return 1; if (install_allegro_gl()) return 1; if (install_keyboard() < 0) { allegro_message("Unable to install keyboard\n"); return 1; } if (install_mouse() == -1) { allegro_message("Unable to install mouse\n"); return 1; } if (install_timer() < 0) { allegro_message("Unable to install timers\n"); return 1; } /* lock timer */ LOCK_VARIABLE(rotation_counter); LOCK_FUNCTION(rotation_counter_handler); /* set desktop resolution */ DESKTOP_W = GetSystemMetrics(SM_CXVIRTUALSCREEN); DESKTOP_H = GetSystemMetrics(SM_CYVIRTUALSCREEN); /* get monitor resolution/count */ int monitor_count; MONITOR *monitors = get_monitors(&monitor_count); /* generate point data */ PLACE places[POINT_COUNT]; int c; for (c = 1; c < POINT_COUNT - 1; c++) { places[c].x = sin((M_PI * (GLfloat)c) / 10.0f) * 200.0f; places[c].y = cos((M_PI * (GLfloat)c) / 10.0f) * 200.0f; } places[0].x = 0.01; places[0].y = 200.0f; places[POINT_COUNT - 1].x = 0.01; places[POINT_COUNT - 1].y = -200.0f; /* setup display */ allegro_gl_set(AGL_Z_DEPTH, 8); allegro_gl_set(AGL_COLOR_DEPTH, 16); allegro_gl_set(AGL_SUGGEST, AGL_Z_DEPTH | AGL_COLOR_DEPTH); glDepthFunc(GL_LEQUAL); if (set_gfx_mode(GFX_OPENGL_WINDOWED_BORDERLESS, DESKTOP_W, DESKTOP_H, 0, 0)) { set_gfx_mode(GFX_TEXT, 0, 0, 0, 0); allegro_message("Unable to set graphic mode\n%s\n", allegro_error); return 1; } /* move window so it covers the desktop */ position_window(0, 0); /* fake information to use if only 1 monitor */ MONITOR fake = {0, 512, 512, 512}; /* setup lighting model */ glShadeModel(GL_FLAT); glEnable(GL_LIGHT0); glEnable(GL_COLOR_MATERIAL); GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 }; glLightfv(GL_LIGHT0, GL_POSITION, light_position); GLfloat ambient[] = { 0.1f, 0.1f, 0.1f }; glLightfv(GL_LIGHT0, GL_AMBIENT, ambient); int selected = -1; /* the point currently being moved */ GLfloat rotation[3] = {0, 0, 0}; /* the rotation of the mesh */ install_int(rotation_counter_handler, 20); /* install the rotation handler */ /* enter main program loop */ while(!key[KEY_ESC]) { while (rotation_counter > 0) { /* rotate the mesh */ rotation[0] += M_PI / 24.0f; rotation[1] += M_PI / 16.0f; rotation[2] += M_PI / 8.0f; rotation_counter--; } /* clear the buffers */ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* process monitor 0 */ MONITOR *m = &monitors[0]; /* adjust mouse so its relative to the monitor */ int mx = (mouse_x - m->x) - (m->w / 2); int my = (mouse_y - m->y) - (m->h / 2); /* if the left mouse is pushed, find a close point */ if (mouse_b & 1) { if (selected == -1) { GLfloat distance = 10; for (c = 0; c < POINT_COUNT; c++) { GLfloat dx = mx - places[c].x; GLfloat dy = my - places[c].y; GLfloat d = sqrt(dx * dx + dy * dy); if (d < distance) { distance = d; selected = c; } } } } else selected = -1; /* move selected point */ if (selected >= 0) { places[selected].x = mx; places[selected].y = my; } /* center the viewport on monitor */ glViewport(m->x, DESKTOP_H - m->h - m->y, m->w, m->h); /* setup viewport projection */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(-m->w / 2, m->w / 2, m->h / 2, -m->h / 2); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); /* draw points */ glColor3ub(0, 255, 0); glBegin(GL_LINE_STRIP); for (c = 0; c < POINT_COUNT; c++) { glVertex2f(places[c].x, places[c].y); } glEnd(); glColor3ub(255, 255, 255); for (c = 0; c < POINT_COUNT; c++) { draw_square(places[c].x, places[c].y, 10); } /* draw vertical line */ glBegin(GL_LINE_STRIP); glVertex2f(0.0f, -m->h); glVertex2f(0.0f, m->h); glEnd(); /* draw the mouse */ glColor3ub(255, 255, 255); draw_square(mx, my, 20); /* process viewport 1 */ /* select second monitor */ if (monitor_count > 1) { /* if 2nd monitor exists use it */ m = &monitors[1]; } else { /* use fake monitor */ m = &fake; } /* adjust mouse so its relative to the monitor*/ mx = (mouse_x - m->x) - (m->w / 2); my = (mouse_y - m->y) - (m->h / 2); /* center the viewport on the monitor*/ glViewport(m->x, DESKTOP_H - m->h - m->y, m->w, m->h); /* setup viewport projection */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0f, (float)m->w / (float)m->h, 0.1f, 2000.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); /* turn on lighting and depth testing */ glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); /* move mesh so its visible */ glTranslatef(0.0f, 0.0f, -1000.0f); /* rotate mesh */ glRotatef(rotation[0], 1.0f, 0.0f, 0.0f); glRotatef(rotation[1], 0.0f, 1.0f, 0.0f); glRotatef(rotation[2], 0.0f, 0.0f, 1.0f); GLfloat p1[3] = {0, 0, 0}; GLfloat p2[3] = {0, 0, 0}; GLfloat p3[3] = {0, 0, 0}; GLfloat p4[3] = {0, 0, 0}; GLfloat vec1[3]; GLfloat vec2[3]; GLfloat normal[3]; /* draw mesh to screen */ glColor3ub(0, 255, 0); for (c = 0; c < (POINT_COUNT - 1); c++) { GLfloat a1 = 0; GLfloat a2 = M_PI / 16.0f; GLfloat d1 = places[c].x; GLfloat d2 = places[c + 1].x; p1[0] = sin(a1) * d1; p1[1] = places[c].y; p1[2] = cos(a1) * d1; p2[0] = sin(a2) * d1; p2[1] = places[c].y; p2[2] = cos(a2) * d1; p3[0] = sin(a2) * d2; p3[1] = places[c + 1].y; p3[2] = cos(a2) * d2; p4[0] = sin(a1) * d2; p4[1] = places[c + 1].y; p4[2] = cos(a1) * d2; buildVector(vec1, p1, p2); buildVector(vec2, p1, p4); cross_product_f(vec2[0], vec2[1], vec2[2], vec1[0], vec1[1], vec1[2], &normal[0], &normal[1], &normal[2]); normalize_vector_f(&normal[0], &normal[1], &normal[2]); glBegin(GL_QUAD_STRIP); glNormal3fv(normal); glVertex3fv(p1); glVertex3fv(p4); int s = 0; for (s = 1; s < 32; s++) { a2 = (M_PI * (GLfloat)(s + 1)) / 16.0f; d1 = places[c].x; d2 = places[c + 1].x; copyPoint(p1, p2); copyPoint(p4, p3); p2[0] = sin(a2) * d1; p2[1] = places[c].y; p2[2] = cos(a2) * d1; p3[0] = sin(a2) * d2; p3[1] = places[c + 1].y; p3[2] = cos(a2) * d2; buildVector(vec1, p1, p2); buildVector(vec2, p1, p4); cross_product_f(vec2[0], vec2[1], vec2[2], vec1[0], vec1[1], vec1[2], &normal[0], &normal[1], &normal[2]); normalize_vector_f(&normal[0], &normal[1], &normal[2]); glNormal3fv(normal); glVertex3fv(p2); glVertex3fv(p3); } glEnd(); } /* turn off lighting and depth testing */ glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); /* if not using the fake monitor */ if (m != &fake) { /* setup viewport projection */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(-m->w / 2, m->w / 2, m->h / 2, -m->h / 2); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); /* draw the mouse */ glColor3ub(255, 255, 255); draw_square(mx, my, 20); } /* flip the contents to the screen */ allegro_gl_flip(); } free(monitors); return 0; }
//*************************************************************** std::string CToolCreateEntity::cloneEntityIntoScenario(CEntityCL *clonee, const NLMISC::CVector &createPosition, float createAngle, bool newAction, bool createGhost ) { //H_AUTO(R2_CToolCreateEntity_cloneEntityIntoScenario) if (!clonee) return ""; std::string instanceId; bool isBotObject = isBotObjectSheet(clonee->sheetId()); if (!getEditor().verifyRoomLeft(isBotObject ? 0 : 1, isBotObject ? 1 : 0)) { return ""; } std::string className; // if class is given in the palette node, then use it. Default to 'Npc' else CObject *paletteNode = getDMC().getPaletteElement(_PaletteId); if (paletteNode && paletteNode->findIndex("Class") != -1) { className = getString(paletteNode, "Class"); } if (className.empty()) { className = "Npc"; } ucstring readableName; // retrieve name from the palette id CLuaState &ls = getEditor().getLua(); getEditor().getEnv()["PaletteIdToTranslation"][_PaletteId].push(); if (ls.isString(-1)) { readableName.fromUtf8(ls.toString(-1)); } if (readableName.empty()) { // if no name found then give a default one readableName = CI18N::get(isBotObject ? "uiR2EDNameBotObject" : "uiR2EDNameNPC"); } // except for creatures, posfix the name with a number std::string creaturePaletteRoot = "palette.entities.creatures"; if (_PaletteId.substr(0, creaturePaletteRoot.size()) != creaturePaletteRoot) { readableName = getEditor().genInstanceName(readableName); } else { className = "NpcCreature"; // is Plant std::string sheetClient = getString(paletteNode, "SheetClient"); getEditor().getLua().push(sheetClient); if (getEditor().getEnv().callMethodByNameNoThrow("isNPCPlant", 1, 1)) { CLuaObject result(getEditor().getLua()); bool isPlant = result.toBoolean(); if (isPlant) className = "NpcPlant"; } } if (newAction) { getDMC().newAction(NLMISC::CI18N::get("uiR2EDCreateAction") + readableName); } // send network commands to create entity on server std::auto_ptr<CObject> desc(getDMC().newComponent(className)); if (desc.get()) { // TMP FIX : if the created entity is a custom npc, then retrieve look from the clonee visual properties if (className == "NpcCustom") { SPropVisualA vA; SPropVisualB vB; SPropVisualC vC; const string propNameA = toString("SERVER:Entities:E%d:P%d", clonee->slot(), CLFECOMMON::PROPERTY_VPA); const string propNameB = toString("SERVER:Entities:E%d:P%d", clonee->slot(), CLFECOMMON::PROPERTY_VPB); const string propNameC = toString("SERVER:Entities:E%d:P%d", clonee->slot(), CLFECOMMON::PROPERTY_VPC); CCDBNodeLeaf *leafA = CInterfaceManager::getInstance()->getDbProp(propNameA); CCDBNodeLeaf *leafB = CInterfaceManager::getInstance()->getDbProp(propNameB); CCDBNodeLeaf *leafC = CInterfaceManager::getInstance()->getDbProp(propNameC); if (!leafA) { nlwarning("Can't find DB leaf %s", propNameA.c_str()); return ""; } if (!leafB) { nlwarning("Can't find DB leaf %s", propNameB.c_str()); return ""; } if (!leafC) { nlwarning("Can't find DB leaf %s", propNameC.c_str()); return ""; } vA.PropertyA = leafA->getValue64(); vB.PropertyB = leafB->getValue64(); vC.PropertyC = leafC->getValue64(); nlassert(desc->isTable()); CObjectTable *props = (CObjectTable *) desc.get(); props->set("GabaritHeight", (double)vC.PropertySubData.CharacterHeight); props->set("GabaritTorsoWidth", (double)vC.PropertySubData.TorsoWidth); props->set("GabaritArmsWidth", (double)vC.PropertySubData.ArmsWidth); props->set("GabaritLegsWidth", (double)vC.PropertySubData.LegsWidth); props->set("GabaritBreastSize", (double)vC.PropertySubData.BreastSize); props->set("HairColor", (double)vA.PropertySubData.HatColor); props->set("Tattoo", (double)vC.PropertySubData.Tattoo); props->set("EyesColor", (double)vC.PropertySubData.EyesColor); props->set("MorphTarget1", (double)vC.PropertySubData.MorphTarget1); props->set("MorphTarget2", (double)vC.PropertySubData.MorphTarget2); props->set("MorphTarget3", (double)vC.PropertySubData.MorphTarget3); props->set("MorphTarget4", (double)vC.PropertySubData.MorphTarget4); props->set("MorphTarget5", (double)vC.PropertySubData.MorphTarget5); props->set("MorphTarget6", (double)vC.PropertySubData.MorphTarget6); props->set("MorphTarget7", (double)vC.PropertySubData.MorphTarget7); props->set("MorphTarget8", (double)vC.PropertySubData.MorphTarget8); props->set("Sex", (double)vA.PropertySubData.Sex); CVisualSlotManager * vsManager = CVisualSlotManager::getInstance(); NLMISC::CSheetId * sheetId = NULL; if(vA.PropertySubData.HatModel == 0) { props->set("HatModel", 0); } else { sheetId = vsManager->index2Sheet((uint32)vA.PropertySubData.HatModel, SLOTTYPE::HEAD_SLOT); if (sheetId) { props->set("HairType", (double)sheetId->asInt()); } } if(vA.PropertySubData.JacketModel == 0) { props->set("JacketModel", 0); } else { sheetId = vsManager->index2Sheet((uint32)vA.PropertySubData.JacketModel, SLOTTYPE::CHEST_SLOT); if (sheetId) { props->set("JacketModel", (double)sheetId->asInt()); } } if(vA.PropertySubData.TrouserModel == 0) { props->set("TrouserModel", 0); } else { sheetId = vsManager->index2Sheet((uint32)vA.PropertySubData.TrouserModel, SLOTTYPE::LEGS_SLOT); if (sheetId) { props->set("TrouserModel", (double)sheetId->asInt()); } } if(vB.PropertySubData.FeetModel == 0) { props->set("FeetModel", 0); } else { sheetId = vsManager->index2Sheet((uint32)vB.PropertySubData.FeetModel, SLOTTYPE::FEET_SLOT); if (sheetId) { props->set("FeetModel", (double)sheetId->asInt()); } } if(vB.PropertySubData.HandsModel == 0) { props->set("HandsModel", 0); } else { sheetId = vsManager->index2Sheet((uint32)vB.PropertySubData.HandsModel, SLOTTYPE::HANDS_SLOT); if (sheetId) { props->set("HandsModel", (double)sheetId->asInt()); } } if(vA.PropertySubData.ArmModel == 0) { props->set("ArmModel", 0); } else { sheetId = vsManager->index2Sheet((uint32)vA.PropertySubData.ArmModel, SLOTTYPE::ARMS_SLOT); if (sheetId) { props->set("ArmModel", (double)sheetId->asInt()); } } double weaponRH=0, weaponLH=0; if(vA.PropertySubData.WeaponRightHand == 0) { props->set("WeaponRightHand", 0); } else { sheetId = vsManager->index2Sheet((uint32)vA.PropertySubData.WeaponRightHand, SLOTTYPE::RIGHT_HAND_SLOT); if (sheetId) { weaponRH = (double)sheetId->asInt(); } props->set("WeaponRightHand", weaponRH); } if(vA.PropertySubData.WeaponLeftHand == 0) { props->set("WeaponLeftHand", 0); } else { sheetId = vsManager->index2Sheet((uint32)vA.PropertySubData.WeaponLeftHand, SLOTTYPE::LEFT_HAND_SLOT); if (sheetId) { weaponLH = (double)sheetId->asInt(); } props->set("WeaponLeftHand", weaponLH); } props->set("JacketColor", (double)vA.PropertySubData.JacketColor); props->set("TrouserColor", (double)vA.PropertySubData.TrouserColor); props->set("FeetColor", (double)vB.PropertySubData.FeetColor); props->set("HandsColor", (double)vB.PropertySubData.HandsColor); props->set("ArmColor", (double)vA.PropertySubData.ArmColor); CPlayerR2CL * player = (CPlayerR2CL*)dynamic_cast<CPlayerR2CL*>(clonee); if(player != NULL) { std::string race, gender, sheetClient; switch(player->people()) { case EGSPD::CPeople::Fyros: sheetClient = "basic_fyros_"; race = "Fyros"; break; case EGSPD::CPeople::Matis: sheetClient = "basic_matis_"; race = "Matis"; break; case EGSPD::CPeople::Tryker: sheetClient = "basic_tryker_"; race = "Tryker"; break; case EGSPD::CPeople::Zorai: sheetClient = "basic_zorai_"; race = "Zorai"; break; default: nlwarning("CToolCreateEntity::commit unknown people"); } switch(player->getGender()) { case GSGENDER::female: sheetClient = sheetClient+"female.creature"; gender = "female"; break; case GSGENDER::male: sheetClient = sheetClient+"male.creature"; gender = "male"; break; default: nlwarning("CToolCreateEntity::commit unknown gender"); } props->set("SheetClient", sheetClient); // random name getEditor().getLua().push(race); getEditor().getLua().push(gender); if (getEditor().getEnv().callMethodByNameNoThrow("randomNPCName", 2, 1)) { CLuaObject result(getEditor().getLua()); std::string name = result.toString(); props->set("Name", name); } } getEditor().getLua().push(getString(paletteNode, "Equipment")); getEditor().getLua().push(weaponRH); getEditor().getLua().push(weaponLH); getEditor().getLua().push(getString(paletteNode, "Sheet")); getEditor().getLua().push(getString(paletteNode, "SheetModel")); if (getEditor().getEnv().callMethodByNameNoThrow("searchSheet", 5, 1)) { CLuaObject result(getEditor().getLua()); std::string sheet = result.toString(); props->set("Sheet", sheet); } else { nlwarning("SearchSheet failed : Palette Id = %s", _PaletteId.c_str()); return ""; } } else { desc->set("Name", readableName.toUtf8()); } desc->set("Base", _PaletteId); desc->setObject("Position", buildVector(CVectorD(createPosition))); desc->set("Angle", createAngle); //desc->set("Name", readableName.toUtf8()); instanceId = getString(desc.get(), "InstanceId"); if (!instanceId.empty()) { if (!createGhost) { // selection asked when instance is created getEditor().setCookie(instanceId, "Select", true); } else { getEditor().setCookie(instanceId, "GhostDuplicate", true); } } // send creation command // tmp : static npc counter // add in component list of default feature if (getEditor().getDefaultFeature()) { std::string targetInstanceId; // if object is a bot object, it is considered to be permanent content // and should be created in the base act CInstance *targetAct = isBotObject ? getEditor().getBaseAct() : getEditor().getCurrentAct(); if (!targetAct) { nlwarning("Can't find act when creating an entity"); } else { if (_AutoGroup.getGroupingCandidate()) { nlassert(!createGhost); // either autogroup or arraymode, both at the same time not supported _AutoGroup.group(desc.get(), createPosition); } else { // create standalone desc->setGhost(createGhost); getDMC().requestInsertNode(getEditor().getDefaultFeature(targetAct)->getId(), "Components", -1, "", desc.get()); } } } } return instanceId; }
//*************************************************************** void CAutoGroup::group(CObject *newEntityDesc, const NLMISC::CVectorD &createPosition) { //H_AUTO(R2_CAutoGroup_group) CInstance *destGroup = getGroupingCandidate(); if (!destGroup || !_AutoGroupEnabled) return; _AutoGroupEnabled = false; // force user to call 'update' again clear(); // remove any activity, dialog, or event in the copy CObject *behav = newEntityDesc->findAttr("Behavior"); if (behav) { behav->setObject("Actions", new CObjectTable()); behav->setObject("Activities", new CObjectTable()); behav->setObject("ChatSequences", new CObjectTable()); newEntityDesc->setObject("ActivitiesId", new CObjectTable()); } nlassert(newEntityDesc); nlassert(destGroup); std::string targetGroupId; if (destGroup->isKindOf("NpcGrpFeature")) { // make relative to newgroup and insert CVectorD relPos = createPosition; CDisplayerVisual *vd = destGroup->getDisplayerVisual(); if (vd) { relPos = relPos - vd->getWorldPos(); } newEntityDesc->setObject("Position", buildVector(relPos)); targetGroupId = destGroup->getId(); } else { // other is a standalone entity -> create a new group std::auto_ptr<CObject> newGroup(getEditor().getDMC().newComponent("NpcGrpFeature")); if (!newGroup.get()) { nlwarning("Syntax error in r2_features_npc_group.lua."); getEditor().getDMC().getActionHistoric().endAction(); getEditor().getDMC().flushActions(); return; } ucstring readableName; CLuaState &ls = getEditor().getLua(); R2::getEditor().getEnv()["PaletteIdToGroupTranslation"][newEntityDesc->getAttr("Base")->toString()].push(); if (ls.isString(-1)) readableName.fromUtf8(ls.toString(-1)); ucstring ucGroupName = ucstring(readableName + " " + CI18N::get("uiR2EDNameGroup").toUtf8()); newGroup->set("Name", getEditor().genInstanceName(ucGroupName).toUtf8()); getEditor().getDMC().requestInsertNode(destGroup->getParentAct()->getId(), "Features", -1, "", newGroup.get()); targetGroupId = getString(newGroup.get(), "InstanceId"); // move target instance in that group (becomes the leader) getEditor().getDMC().requestMoveNode(destGroup->getId(), "", -1, targetGroupId, "Components", -1); } // move newly created entity into target group getEditor().getDMC().requestInsertNode(targetGroupId, "Components", -1, "", newEntityDesc); getEditor().getDMC().getActionHistoric().endAction(); getEditor().getDMC().flushActions(); }
RBFSystem *RBFSystem::FastFitting(std::vector<glm::vec4> &points,float smoothNess,float accuracy,int minInnerSize,float outerSize,int coarseGridSize, int maxIterations){ if(points.size()==0) return new RBFSystem(); if(points.size()<=minInnerSize*2){ return CreateFromPoints<KernelType>(points,smoothNess); } RBFSystem *sg = new RBFSystem(); TmpPointer<RBFSystem> s1 = new RBFSystem(); TmpPointer<RBFSystem> s2 = new RBFSystem(); std::vector<__rbf_SubSpace<Solver>> subspace; std::vector<__rbf_SubSpace<Solver>> tmpSpaces; __rbf_SubSpace<Solver> coarseGrid; tmpSpaces.push_back(__rbf_SubSpace<Solver>()); __rbf_Residual residual(points.size()); BoundingAABB aabb(glm::vec3(points.at(0)),glm::vec3(points.at(0))); //K3DTree<int> tree; // int i=0; for(auto p = points.begin();p!=points.end();++p){ //tree.insert(glm::vec3(*p),i); tmpSpaces[0].innerAABB.extend(glm::vec3(*p)); tmpSpaces[0].Inner.push_back(i); KernelType *k = new KernelType(p->x,p->y,p->z); KernelType *k2 = new KernelType(p->x,p->y,p->z); k->_weight = 0; k2->_weight = 0; sg->_kernels.push_back(k); s1->_kernels.push_back(new KernelType(p->x,p->y,p->z)); s2->_kernels.push_back(k2); residual[i++] = p->w; } s2->_min = s1->_min = sg->_min = glm::vec3(0,0,0); s2->_max = s1->_max = sg->_max = glm::vec3(1,1,1); #ifdef RBF_DEBUG std::cout << "Creating subpaces "; StopClock sw(true); #endif //Subdivde space while(!tmpSpaces.empty()){ __rbf_SubSpace<Solver> sub0,sub1; __rbf_Subdived(points,minInnerSize,tmpSpaces[0],sub0,sub1); if(sub0.sizeInner()>=2*minInnerSize){ //We can split again without invalidate minInnerSize tmpSpaces.push_back(sub0); }else{ subspace.push_back(sub0); } if(sub1.sizeInner()>=2*minInnerSize){ //We can split again without invalidate minInnerSize tmpSpaces.push_back(sub1); }else{ subspace.push_back(sub1); } tmpSpaces.erase(tmpSpaces.begin()); //remove the splited subspace } #ifdef RBF_DEBUG sw.stop(); std::cout << "..Inner points done, now adding outerpoints to each subspace.." << std::endl; #endif //add points to outer space for(auto s = subspace.begin();s!=subspace.end();++s){ auto p0 = s->innerAABB.getPosition(glm::vec3(-outerSize,-outerSize,-outerSize)); auto p1 = s->innerAABB.getPosition(glm::vec3(1+outerSize,1+outerSize,1+outerSize)); s->outerAABB = BoundingAABB(p0,p1); } for(unsigned int i = 0;i<points.size();i++){ glm::vec3 p = glm::vec3(points[i]); for(auto s = subspace.begin();s!=subspace.end();++s){ if(s->outerAABB.inside(p) && !s->innerAABB.inside(p)){ s->Outer.push_back(i); } } } #ifdef RBF_DEBUG sw.stop(); std::cout << "..Done, ( " << sw.getFractionElapsedSeconds() << " sec)" << std::endl; std::cout << '\t' << "Number of subspaces: " << subspace.size() << std::endl; std::cout << "Building coarseGrid "; sw.reset();sw.start(); #endif //Choose a coarse grid for(auto s = subspace.begin();s!=subspace.end();++s){ //TODO, check for best way of doing this unsigned int i; int left = coarseGridSize; int size = s->sizeInner(); for(i = 0;i<s->sizeInner();i++){ if(Random::getRandomGenerator()->getFloat() <= float(left) / size--){ coarseGrid.innerAABB.extend(glm::vec3(s->sampleInner(points,i))); coarseGrid.Inner.push_back(s->Inner[i]); left--; }else{ /* coarseGrid.outerAABB.extend(glm::vec3(s->sampleInner(points,i))); coarseGrid.Outer.push_back(s->Inner[i]);//*/ } } } #ifdef RBF_DEBUG sw.stop(); std::cout << "..Done, ( " << sw.getFractionElapsedSeconds() << " sec)" << std::endl; std::cout << '\t' << "Coarse Grid Size: " << coarseGrid.sizeInner() << "+" << coarseGrid.sizeOuter() << std::endl; std::cout << "Building solvers "; sw.reset();sw.start(); #endif try{ coarseGrid.buildMatrix(&*s1,points,smoothNess,true); }catch(...){ std::cerr << "Failed build solver for coarse grid ; " << coarseGrid.sizeInner() << " " << coarseGrid.sizeOuter() << std::endl; return 0; } #ifdef RBF_DEBUG sw.stop(); std::cout << '\t' << "Coarse Grid Solver done: ( " << sw.getFractionElapsedSeconds() << " sec)" << std::endl; sw.reset();sw.start(); #endif int ii = 0; //for(auto s = subspace.begin();s!=subspace.end();++s){ for(int ii = 0;ii<subspace.size();ii++){ auto s = &subspace[ii]; try{ s->buildMatrix(&*s1,points,smoothNess,!true); //ii++; #ifdef RBF_DEBUG sw.stop(); std::cout << '\t' << "Subspace Solver "<< ii << "/" << subspace.size() <<" done("<< s->sizeInner() <<"/ " << s->sizeOuter() <<" ): ( " << sw.getFractionElapsedSeconds() << " sec)" << std::endl; sw.reset();sw.start(); #endif }catch(...){ std::cerr << "Failed build solver for subspace "<< ii << "; " << s->sizeInner() << " " << s->sizeOuter() << std::endl; //return 0; } } //#ifdef RBF_DEBUG // sw.stop(); // std::cout << '\t' << "subspace Solvers done: ( " << sw.getFractionElapsedSeconds() << " sec)" << std::endl; // sw.reset();sw.start(); //#endif std::cout << sg->meanSqError(points) << std::endl; int _maxIterations = maxIterations;//TODO maybe remove maxIterations when stable do{ #ifdef RBF_DEBUG sw.stop(); std::cout << "Starting iteration: "; sw.reset();sw.start(); #endif for(auto s = subspace.begin();s!=subspace.end();++s){//(3) s->buildVector(residual); //(4) Eigen::VectorXf x = s->S.solve(s->b); //(4) int size = s->sizeInner(); //(4) for(int i = 0;i<size;i++){ //(4) s1->_kernels[s->Inner[i]]->setWeight(x(i)); //(4) } //(4) } //(5) //TODO missing (6)? int pointssize = points.size(); for(int i = 0;i<pointssize;i++){ //(8) residual[i] = residual[i] - s1->eval(glm::vec3(points[i])); } //(9) coarseGrid.buildVector(residual,true); Eigen::VectorXf x1 = coarseGrid.S.solve(coarseGrid.b); for(int i = 0;i<pointssize;i++){ s2->_kernels[i]->_weight = 0; } for(int i = 0;i<coarseGrid.sizeInner();i++){ // s2->_kernels[coarseGrid.Inner[i]]->setWeight(x1(i)); //(4) } for(int i = 0;i<pointssize;i++){ sg->_kernels[i]->_weight += s1->_kernels[i]->_weight + s2->_kernels[i]->_weight; } //* sg->_trend._c[0] += x1(coarseGrid.sizeInner()+0); //sg->_trend._c[1] += x1(coarseGrid.sizeInner()+1); //sg->_trend._c[2] += x1(coarseGrid.sizeInner()+2); //sg->_trend._c[3] += x1(coarseGrid.sizeInner()+3); //*/ for(int i = 0;i<pointssize;i++){ residual[i] = points[i].w - sg->eval(glm::vec3(points[i])); if(!(residual[i]==residual[i])){ //std::cout << residual[i] << std::endl; } } std::cout << "Iterations:" << maxIterations - _maxIterations << " mean sq error: " << sg->meanSqError(points) << std::endl; //std::cout << sg->meanSqError(points) << std::endl; #ifdef RBF_DEBUG sw.stop(); std::cout << "...DONE ( " << sw.getFractionElapsedSeconds() << " sec) " ; sw.reset();sw.start(); #endif }while(--_maxIterations&&residual.notDone(accuracy)); std::cout << "Iterations:" << maxIterations - _maxIterations << " mean sq error: " << sg->meanSqError(points) << std::endl; return sg; }
//addParticle. sprays out more particles void particleSpray(){ buildVector(); }
void testSearch(int argc, char ** argv) { Search t; vector<int> A = buildVector(argc, argv); pair<int, int> ret = t.findSubtractionPairInSortedArray(A, -3); cout << ret.first << " " << ret.second << endl; }