Search Results

Search found 614 results on 25 pages for 'vectors'.

Page 7/25 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Euler rotation of direction vector

    - by Tom Savage
    I have defined an object in 3D space with position, rotation and scale values (all defined as 3D vectors). It also has upwards and forwards direction vectors. When I rotate the object, I need these direction vectors to rotate with it. Assuming my up vector is (0, 1, 0) and my forwards vector is (0, 0, 1) at zero rotation, how might I achieve this?

    Read the article

  • yet another logic.

    - by Sunil
    I'm working on a research problem out of curiosity and I don't know how to program the logic that I've in mind. Let me explain it to you : I've 4 vectors say for example, v1 = 1 1 1 1 v2 = 2 2 2 2 v3 = 3 3 3 3 v4 = 4 4 4 4 Now what I want to do is to add them combination-wise. i.e v12 = v1+v2 v13 = v1+v3 v14 = v1+v4 v23 = v2+v3 v24 = v2+v4 v34 = v3+v4 Till this step it is just fine. The problem/trick is now, at the end of each iteration I give the obtained vectors into a black box function and it returns only few of the vectors say v12, v13 and v34. Now, I want to add each of these vectors one vector from v1,v2,v3,v4 which it hasn't added before. For example v3 and v4 hasn't been added to v12 so I want to create v123 and v124. similarly for all the vectors like, v12 should become : v123 = v12+v3 v124 = v12+v4 v13 should become : v132 // this should not occur because I already have v123 v134 = v13+v4; v14,v23 and v24 cannot be considered because it was deleted in the black box function so all we have in our hands to work with is v12,v13 and v34. v34 should become : v341 // cannot occur because we have 134 v342 = v34+v2 It is important that I do not do all at one step at the start like for example I can do (4 choose 3) 4C3 and finish it off but I want to do it step by step at each iteration. I've asked a modified version of this question before (without including the black box function) and got answers here. Can anybody tell me how to do it when the black box function is included ? A modification of the previous answer would also be great. Thanks in advance.

    Read the article

  • Convert vector interpolation to quaternion interpolation? (Catmull-Rom)

    - by edA-qa mort-ora-y
    I have some existing code which does catmull-rom interpolation on two vectors (facing and up). I'm converting this to use quaternions instead (to replace the two vectors). Is there a general way to convert the vector based interpolation to a quaternion one? The approach I'm using now is to exact the axis and angle from the quanternion. I then interpolate each of those independently and convert back to a quaternion. Is there a more direct method?

    Read the article

  • Would it be a good idea to work on letting people add arrays of numbers in javascript?

    - by OneThreeSeven
    I am a very mathematically oriented programmer, and I happen to be doing a lot of java script these days. I am really disappointed in the math aspects of javascript: the Math object is almost a joke because it has so few methods you can't use ^ for exponentiation the + operator is very limited, you cant add array's of numbers or do scalar multiplication on arrays Now I have written some pretty basic extensions to the Math object and have considered writing a library of advanced Math features, amazingly there doesn't seem to be any sort of standard library already out even for calculus, although there is one for vectors and matricies I was able find. The notation for working with vectors and matricies is really bad when you can't use the + operator on arrays, and you cant do scalar multiplication. For example, here is a hideous expression for subtracting two vectors, A - B: Math.vectorAddition(A,Math.scalarMultiplication(-1,B)); I have been looking for some kind of open-source project to contribute to for awhile, and even though my C++ is a bit rusty I would very much like to get into the code for V8 engine and extend the + operator to work on arrays, to get scalar multiplication to work, and possibly to get the ^ operator to work for exponentiation. These things would greatly enhance the utility of any mathematical javascript framework. I really don't know how to get involved in something like the V8 engine other than download the code and start working on it. Of course I'm afraid that since V8 is chrome specific, that without browser cross-compatibility a fundamental change of this type is likely to be rejected for V8. I was hoping someone could either tell me why this is a bad idea, or else give me some pointers about how to proceed at this point to get some kind of approval to add these features. Thanks!

    Read the article

  • C# vector class - Interpolation design decision

    - by Benjamin
    Currently I'm working on a vector class in C# and now I'm coming to the point, where I've to figure out, how i want to implement the functions for interpolation between two vectors. At first I came up with implementing the functions directly into the vector class... public class Vector3D { public static Vector3D LinearInterpolate(Vector3D vector1, Vector3D vector2, double factor) { ... } public Vector3D LinearInterpolate(Vector3D other, double factor { ... } } (I always offer both: a static method with two vectors as parameters and one non-static, with only one vector as parameter) ...but then I got the idea to use extension methods (defined in a seperate class called "Interpolation" for example), since interpolation isn't really a thing only available for vectors. So this could be another solution: public class Vector3D { ... } public static class Interpolation { public static Vector3D LinearInterpolate(this Vector3D vector, Vector3D other, double factor) { ... } } So here an example how you'd use the different possibilities: { var vec1 = new Vector3D(5, 3, 1); var vec2 = new Vector3D(4, 2, 0); Vector3D vec3; vec3 = vec1.LinearInterpolate(vec2, 0.5); //1 vec3 = Vector3D.LinearInterpolate(vec1, vec2, 0.5); //2 //or with extension-methods vec3 = vec1.LinearInterpolate(vec2, 0.5); //3 (same as 1) vec3 = Interpolation.LinearInterpolation(vec1, vec2, 0.5); //4 } So I really don't know which design is better. Also I don't know if there's an ultimate rule for things like this or if it's just about what someone personally prefers. But I really would like to hear your opinions, what's better (and if possible why ).

    Read the article

  • Collision within a poly

    - by G1i1ch
    For an html5 engine I'm making, for speed I'm using a path poly. I'm having trouble trying to find ways to get collision with the walls of the poly. To make it simple I just have a vector for the object and an array of vectors for the poly. I'm using Cartesian vectors and they're 2d. Say poly = [[550,0],[169,523],[-444,323],[-444,-323],[169,-523]], it's just a pentagon I generated. The object that will collide is object, object.pos is it's position and object.vel is it's velocity. They're both 2d vectors too. I've had some success to get it to find a collision, but it's just black box code I ripped from a c++ example. It's very obscure inside and all it does though is return true/false and doesn't return what vertices are collided or collision point, I'd really like to be able to understand this and make my own so I can have more meaningful collision. I'll tackle that later though. Again the question is just how does one find a collision to walls of a poly given you know the poly vertices and the object's position + velocity? If more info is needed please let me know. And if all anyone can do is point me to the right direction that's great.

    Read the article

  • Trouble with SAT style vector projection in C#/XNA

    - by ssb
    Simply put I'm having a hard time working out how to work with XNA's Vector2 types while maintaining spatial considerations. I'm working with separating axis theorem and trying to project vectors onto an arbitrary axis to check if those projections overlap, but the severe lack of XNA-specific help online combined with pseudo code everywhere that omits key parts of the algorithm, googling has left me little help. I'm aware of HOW to project a vector, but the way that I know of doing it involves the two vectors starting from the same point. Particularly here: http://www.metanetsoftware.com/technique/tutorialA.html So let's say I have a simple rectangle, and I store each of its corners in a list of Vector2s. How would I go about projecting that onto an arbitrary axis? The crux of my problem is that taking the dot product of say, a vector2 of (1, 0) and a vector2 of (50, 50) won't get me the dot product I'm looking for.. or will it? Because that (50, 50) won't be the vector of the polygon's vertex but from whatever XNA calculates. It's getting the calculation from the right starting point that's throwing me off. I'm sorry if this is unclear, but my brain is fried from trying to think about this. I need a better understanding of how XNA calculates Vector2s as actual vectors and not just as random points.

    Read the article

  • Spatial Rotation in Gmod Expression2.

    - by Fascia
    I'm using expression2 to program behavior in Garry's mod (http://wiki.garrysmod.com/?title=Wire_Expression2) Okay so, to set the precedent. In Gmod I have a block and I am at a complete loss of how to get it to rotate around the 3 up, down and right vectors (Which are local. ie; if I pitch it 45 degrees the forward vector is 0.707, 0.707, 0). Essentially, From the 3 vectors I'd like to be able to get local Pitch/Roll/Yaw. By Local Pitch Roll Yaw I mean that they are completely independent of one another allowing true 3d rotation. So for example; if I place my craft so its nose is parallel to the floor the X,Y,Z would be 0,0,0. If I turn it parallel to the floor (World and Local Yaw) 90 degrees it's now 0, 0, 90. If I then pitch it (World Roll, Local Pitch) it 180 degrees it's now 180, 0, 90. I've already explored quaternions however I don't believe I should post my code here as I think I was re-inventing the wheel. I know I didn't explain that well but I believe the problem is pretty generic. Any help anyone could offer is greatly appreciated. Oh, I'd like to avoid gimblelock too. Essentially calculating the rotation around each of the crafts up/forward/right vectors using the up/forward/right vectors. To simply the question a generic implementation rather than one specific to Gmod is absolutely fine.

    Read the article

  • Loops on a Matlab program

    - by lebland-matlab
    I have 3 sets of 10 vectors each, and I want to take 2 vectors from the first set , 2 vectors from the second set and 3 vectors from the third set . My goal is to make a loop to implement the following program, knowing that after each calculation, the result shall be saved in a new file. My problem is that I can not handle the indices included in the strings. I try to use multiple loops to scan the 3 sets in the order of indices. loops should contain the following program clc; clear all; load('C:\Users\Documents\MATLAB\myFile\matrice_F.mat'); load('C:\Users\Documents\MATLAB\myFile\matrice_G.mat'); F = m_F; G = m_G; load('C:\Users\Documents\MATLAB\myFile\matrice_J.mat'); load('C:\Users\Documents\MATLAB\myFile\matrice_K.mat'); J = m_J; K = m_K; load('C:\Users\Documents\MATLAB\myFile\matrice_N.mat'); load('C:\Users\Documents\MATLAB\myFile\matrice_O.mat'); load('C:\Users\Documents\MATLAB\myFile\matrice_P.mat'); N = m_N ; O = m_O; P = m_P; [A,B,C,D,E] = myFun(F,G,J,K,N,O,P); file_name = 'matrice_final.mat'; save(file_name,'A','B','C','D','E');

    Read the article

  • What is a truly empty std::vector in C++?

    - by RyanG
    I've got a two vectors in class A that contain other class objects B and C. I know exactly how many elements these vectors are supposed to hold at maximum. In the initializer list of class A's constructor, I initialize these vectors to their max sizes (constants). If I understand this correctly, I now have a vector of objects of class B that have been initialized using their default constructor. Right? When I wrote this code, I thought this was the only way to deal with things. However, I've since learned about std::vector.reserve() and I'd like to achieve something different. I'd like to allocate memory for these vectors to grow as large as possible because adding to them is controlled by user-input, so I don't want frequent resizings. However, I iterate through this vector many, many times per second and I only currently work on objects I've flagged as "active". To have to check a boolean member of class B/C on ever iteration is silly. I don't want these objects to even BE there for my iterators to see when I run through this list. Is reserving the max space ahead of time and using push_back to add a new object to the vector a solution to this?

    Read the article

  • multidimensional vector rotation and angle computation -- how?

    - by macias
    Input: two multidimensional (for example dim=8) vectors a and b. I need to find out the "directed" angle (0-2*Pi, not 0-Pi) between those vectors a and b. And if they are not parallel I need to rotate vector b in plane a,b by "directed" angle L. If they are parallel, plane does not matter, but angle of rotation is still the same L. For 2d and 3d this is quite easy, but for more dimensions I am lost, I didn't find anything on google, and I prefer using some already proved&tested equations (avoiding errors introduced by my calculations :-D). Thank you in advance for tips, links, etc. Edit: dimension of the space is the same as dimension of the vectors.

    Read the article

  • std::vector optimisation required

    - by marcp
    I've written a routine that uses std::vector<double> rather heavily. It runs rather slowly and AQTime seems to imply that I am constructing mountains of vectors but I'm not sure why I would be. For some context, my sample run iterates 10 times. Each iteration copies 3 c arrays of ~400 points into vectors and creates 3 new same sized vectors for output. Each output point might be the result of summing up to 20 points from 2 of the input vectors, which works out to a worst case of 10*400*3*2*20 = 480,000 dereferences. Incredibly the profiler indicates that some of the std:: methods are being called 46 MILLION times. I suspect I'm doing something wrong! Some code: vector<double>gdbChannel::GetVector() { if (fHaveDoubleData & (fLength > 0)) { double * pD = getDoublePointer(); vector<double>v(pD, pD + fLength); return v; } else { throw(Exception("attempt to retrieve vector on empty line")); ; } } void gdbChannel::SaveVector(GX_HANDLE _hLine, const vector<double> & V) { if (hLine != _hLine) { GetLine(_hLine, V.size(), true); } GX_DOUBLE * pData = getDoublePointer(); memcpy(pData, &V[0], V.size()*sizeof(V[0])); ReplaceData(); } ///This routine gets called 10 times bool SpecRatio::DoWork(GX_HANDLE_PTR pLine) { if (!(hKin.GetLine(*pLine, true) && hUin.GetLine(*pLine, true) && hTHin.GetLine(*pLine, true))) { return true; } vector<double>vK = hKin.GetVector(); vector<double>vU = hUin.GetVector(); vector<double>vTh = hTHin.GetVector(); if ((vK.size() == 0) || (vU.size() == 0) || (vTh.size() == 0)) { return true; } ///TODO: confirm all vectors the same lenghth len = vK.size(); vUK.clear(); // these 3 vectors are declared as private class members vUTh.clear(); vThK.clear(); vUK.reserve(len); vUTh.reserve(len); vThK.reserve(len); // TODO: ensure everything is same fidincr, fidstart and length for (int i = 0; i < len; i++) { if (vK.at(i) < MinK) { vUK.push_back(rDUMMY); vUTh.push_back(rDUMMY); vThK.push_back(rDUMMY); } else { vUK.push_back(RatioPoint(vU, vK, i, UMin, KMin)); vUTh.push_back(RatioPoint(vU, vTh, i, UMin, ThMin)); vThK.push_back(RatioPoint(vTh, vK, i, ThMin, KMin)); } } hUKout.setFidParams(hKin); hUKout.SaveVector(*pLine, vUK); hUTHout.setFidParams(hKin); hUTHout.SaveVector(*pLine, vUTh); hTHKout.setFidParams(hKin); hTHKout.SaveVector(*pLine, vThK); return TestError(); } double SpecRatio::VValue(vector<double>V, int Index) { double result; if ((Index < 0) || (Index >= len)) { result = 0; } else { try { result = V.at(Index); if (OasisUtils::isDummy(result)) { result = 0; } } catch (out_of_range) { result = 0; } } return result; } double SpecRatio::RatioPoint(vector<double>Num, vector<double>Denom, int Index, double NumMin, double DenomMin) { double num = VValue(Num, Index); double denom = VValue(Denom, Index); int s = 0; // Search equalled 10 in this case while (((num < NumMin) || (denom < DenomMin)) && (s < Search)) { num += VValue(Num, Index - s) + VValue(Num, Index + s); denom += VValue(Denom, Index - s) + VValue(Denom, Index + s); s++; } if ((num < NumMin) || (denom < DenomMin)) { return rDUMMY; } else { return num / denom; } } The top AQTime offenders are: std::_Uninit_copy , double *, std::allocator 3.65 secs and 115731 Hits std::_Construct 1.69 secs and 46450637 Hits std::_Vector_const_iterator ::operator !=1.66 secs and 46566395 Hits and so on... std::allocator<double>::construct, operator new, std::_Vector_const_iterator<double, std::allocator<double> >::operator ++, std::_Vector_const_iterator<double, std::allocator<double> >::operator * std::_Vector_const_iterator<double, std::allocator<double> >::operator == each get called over 46 million times. I'm obviously doing something wrong to cause all these objects to be created. Can anyone see my error(s)?

    Read the article

  • How to interpolate rotations?

    - by uhuu
    I have two vectors describing rotations; a start rotation A and a target rotation B. How would I best go about interpolating A by a factor F to approach B? Using a simple lerp on the vectors fails to work when more than one dimension needs to be interpolated (i.e. produces undesirable rotations). Maybe building quaternions from the rotation vectors and using slerp is the way to go. But how, then, could I extract a vector describing the new rotation from the resulting quaternion? Thanks in advance.

    Read the article

  • Fastest way to find the rotation of a vector

    - by kriss
    I have two 2D vectors, say u and v, defined by cartesian coordinates. Imagine that vectors are needles of a clock. I'm looking for the fastest way to find out, using python, if v is after or before u (or in other words find out in wich half plane is v, regarding to position of u). For the purpose of the problem if vectors are aligned answer should be before. It seems easy using some trigonometry, but I believe there should be a faster way using coordinates only. My test case: def after(u, v): """code here""" after((4,2), (6, 1)) : True after((4,2), (3, 3)) : False after((4,2), (2, 1)) : False after((4,2), (3, -3)) : True after((4,2), (-2, -5)) : True after((4,2), (-4, -2)) : False

    Read the article

  • When is BIG, big enough for a database?

    - by David ???
    I'm developing a Java application that has performance at its core. I have a list of some 40,000 "final" objects, i.e., I have an initialization input data of 40,000 vectors. This data is unchanged throughout the program's run. I am always preforming lookups against a single ID property to retrieve the proper vectors. Currently I am using a HashMap over a sub-sample of a 1,000 vectors, but I'm not sure it will scale to production. When is BIG, actually big enough for a use of DB? One more thing, an SQLite DB is a viable option as no concurrency is involved, so I guess the "threshold" for db use, is perhaps lower.

    Read the article

  • ASSIMP in my program is much slower to import than ASSIMP view program

    - by Marco
    The problem is really simple: if I try to load with the function aiImportFileExWithProperties a big model in my software (around 200.000 vertices), it takes more than one minute. If I try to load the very same model with ASSIMP view, it takes 2 seconds. For this comparison, both my software and Assimp view are using the dll version of the library at 64 bit, compiled by myself (Assimp64.dll). This is the relevant piece of code in my software // default pp steps unsigned int ppsteps = aiProcess_CalcTangentSpace | // calculate tangents and bitangents if possible aiProcess_JoinIdenticalVertices | // join identical vertices/ optimize indexing aiProcess_ValidateDataStructure | // perform a full validation of the loader's output aiProcess_ImproveCacheLocality | // improve the cache locality of the output vertices aiProcess_RemoveRedundantMaterials | // remove redundant materials aiProcess_FindDegenerates | // remove degenerated polygons from the import aiProcess_FindInvalidData | // detect invalid model data, such as invalid normal vectors aiProcess_GenUVCoords | // convert spherical, cylindrical, box and planar mapping to proper UVs aiProcess_TransformUVCoords | // preprocess UV transformations (scaling, translation ...) aiProcess_FindInstances | // search for instanced meshes and remove them by references to one master aiProcess_LimitBoneWeights | // limit bone weights to 4 per vertex aiProcess_OptimizeMeshes | // join small meshes, if possible; aiProcess_SplitByBoneCount | // split meshes with too many bones. Necessary for our (limited) hardware skinning shader 0; cout << "Loading " << pFile << "... "; aiPropertyStore* props = aiCreatePropertyStore(); aiSetImportPropertyInteger(props,AI_CONFIG_IMPORT_TER_MAKE_UVS,1); aiSetImportPropertyFloat(props,AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE,80.f); aiSetImportPropertyInteger(props,AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); aiSetImportPropertyInteger(props,AI_CONFIG_GLOB_MEASURE_TIME,1); //aiSetImportPropertyInteger(props,AI_CONFIG_PP_PTV_KEEP_HIERARCHY,1); // Call ASSIMPs C-API to load the file scene = (aiScene*)aiImportFileExWithProperties(pFile.c_str(), ppsteps | /* default pp steps */ aiProcess_GenSmoothNormals | // generate smooth normal vectors if not existing aiProcess_SplitLargeMeshes | // split large, unrenderable meshes into submeshes aiProcess_Triangulate | // triangulate polygons with more than 3 edges //aiProcess_ConvertToLeftHanded | // convert everything to D3D left handed space aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives 0, NULL, props); aiReleasePropertyStore(props); if(!scene){ cout << aiGetErrorString() << endl; return 0; } this is the relevant piece of code in assimp view code // default pp steps unsigned int ppsteps = aiProcess_CalcTangentSpace | // calculate tangents and bitangents if possible aiProcess_JoinIdenticalVertices | // join identical vertices/ optimize indexing aiProcess_ValidateDataStructure | // perform a full validation of the loader's output aiProcess_ImproveCacheLocality | // improve the cache locality of the output vertices aiProcess_RemoveRedundantMaterials | // remove redundant materials aiProcess_FindDegenerates | // remove degenerated polygons from the import aiProcess_FindInvalidData | // detect invalid model data, such as invalid normal vectors aiProcess_GenUVCoords | // convert spherical, cylindrical, box and planar mapping to proper UVs aiProcess_TransformUVCoords | // preprocess UV transformations (scaling, translation ...) aiProcess_FindInstances | // search for instanced meshes and remove them by references to one master aiProcess_LimitBoneWeights | // limit bone weights to 4 per vertex aiProcess_OptimizeMeshes | // join small meshes, if possible; aiProcess_SplitByBoneCount | // split meshes with too many bones. Necessary for our (limited) hardware skinning shader 0; aiPropertyStore* props = aiCreatePropertyStore(); aiSetImportPropertyInteger(props,AI_CONFIG_IMPORT_TER_MAKE_UVS,1); aiSetImportPropertyFloat(props,AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE,g_smoothAngle); aiSetImportPropertyInteger(props,AI_CONFIG_PP_SBP_REMOVE,nopointslines ? aiPrimitiveType_LINE | aiPrimitiveType_POINT : 0 ); aiSetImportPropertyInteger(props,AI_CONFIG_GLOB_MEASURE_TIME,1); //aiSetImportPropertyInteger(props,AI_CONFIG_PP_PTV_KEEP_HIERARCHY,1); // Call ASSIMPs C-API to load the file g_pcAsset->pcScene = (aiScene*)aiImportFileExWithProperties(g_szFileName, ppsteps | /* configurable pp steps */ aiProcess_GenSmoothNormals | // generate smooth normal vectors if not existing aiProcess_SplitLargeMeshes | // split large, unrenderable meshes into submeshes aiProcess_Triangulate | // triangulate polygons with more than 3 edges aiProcess_ConvertToLeftHanded | // convert everything to D3D left handed space aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives 0, NULL, props); aiReleasePropertyStore(props); As you can see the code is nearly identical because I copied from assimp view. What could be the reason for such a difference in performance? The two software are using the same dll Assimp64.dll (compiled in my computer with vc++ 2010 express) and the same function aiImportFileExWithProperties to load the model, so I assume that the actual code employed is the same. How is it possible that the function aiImportFileExWithProperties is 100 times slower when called by my sotware than when called by assimp view? What am I missing? I am not good with dll, dynamic and static libraries so I might be missing something obvious. ------------------------------ UPDATE I found out the reason why the code is going slower. Basically I was running my software with "Start debugging" in VC++ 2010 Express. If I run the code outside VC++ 2010 I get same performance of assimp view. However now I have a new question. Why does the dll perform slower in VC++ debugging? I compiled it in release mode without debugging information. Is there any way to have the dll go fast in debugmode i.e. not debugging the dll? Because I am interested in debugging only my own code, not the dll that I assume is already working fine. I do not want to wait 2 minutes every time I want to load my software to debug. Does this request make sense?

    Read the article

  • Normals vs Normal maps

    - by KaiserJohaan
    I am using Assimp asset importer (http://assimp.sourceforge.net/lib_html/index.html) to parse 3d models. So far, I've simply pulled out the normal vectors which are defined for each vertex in my meshes. Yet I have also found various tutorials on normal maps... As I understand it for normal maps, the normal vectors are stored in each texel of a normal map, and you pull these out of the normal texture in the shader. Why is there two ways to get the normals, which one is considered best-practice and why?

    Read the article

  • Can the Clojure set and maps syntax be added to other Lisp dialects?

    - by Cedric Martin
    In addition to create list using parentheses, Clojure allows to create vectors using [ ], maps using { } and sets using #{ }. Lisp is always said to be a very extensible language in which you can easily create DSLs etc. But is Lisp so extensible that you can take any Lisp dialect and relatively easily add support for Clojure's vectors, maps and sets (which are all functions in Clojure)? I'm not necessarily asking about cons or similar actually working on these functions: what I'd like to know is if the other could be modified so that the source code would look like Clojure's source code (that is: using matching [ ], { } and #{ } in addition to ( )). Note that if it cannot be done this is not a criticism of Lisp: what I'd like to know is, technically, what should be done or what cannot be done if one were to add such a thing.

    Read the article

  • Applications: The mathematics of movement, Part 1

    - by TechTwaddle
    Before you continue reading this post, a suggestion; if you haven’t read “Programming Windows Phone 7 Series” by Charles Petzold, go read it. Now. If you find 150+ pages a little too long, at least go through Chapter 5, Principles of Movement, especially the section “A Brief Review of Vectors”. This post is largely inspired from this chapter. At this point I assume you know what vectors are, how they are represented using the pair (x, y), what a unit vector is, and given a vector how you would normalize the vector to get a unit vector. Our task in this post is simple, a marble is drawn at a point on the screen, the user clicks at a random point on the device, say (destX, destY), and our program makes the marble move towards that point and stop when it is reached. The tricky part of this task is the word “towards”, it adds a direction to our problem. Making a marble bounce around the screen is simple, all you have to do is keep incrementing the X and Y co-ordinates by a certain amount and handle the boundary conditions. Here, however, we need to find out exactly how to increment the X and Y values, so that the marble appears to move towards the point where the user clicked. And this is where vectors can be so helpful. The code I’ll show you here is not ideal, we’ll be working with C# on Windows Mobile 6.x, so there is no built-in vector class that I can use, though I could have written one and done all the math inside the class. I think it is trivial to the actual problem that we are trying to solve and can be done pretty easily once you know what’s going on behind the scenes. In other words, this is an excuse for me being lazy. The first approach, uses the function Atan2() to solve the “towards” part of the problem. Atan2() takes a point (x, y) as input, Atan2(y, x), note that y goes first, and then it returns an angle in radians. What angle you ask. Imagine a line from the origin (0, 0), to the point (x, y). The angle which Atan2 returns is the angle the positive X-axis makes with that line, measured clockwise. The figure below makes it clear, wiki has good details about Atan2(), give it a read. The pair (x, y) also denotes a vector. A vector whose magnitude is the length of that line, which is Sqrt(x*x + y*y), and a direction ?, as measured from positive X axis clockwise. If you’ve read that chapter from Charles Petzold’s book, this much should be clear. Now Sine and Cosine of the angle ? are special. Cosine(?) divides x by the vectors length (adjacent by hypotenuse), thus giving us a unit vector along the X direction. And Sine(?) divides y by the vectors length (opposite by hypotenuse), thus giving us a unit vector along the Y direction. Therefore the vector represented by the pair (cos(?), sin(?)), is the unit vector (or normalization) of the vector (x, y). This unit vector has a length of 1 (remember sin2(?) + cos2(?) = 1 ?), and a direction which is the same as vector (x, y). Now if I multiply this unit vector by some amount, then I will always get a point which is a certain distance away from the origin, but, more importantly, the point will always be on that line. For example, if I multiply the unit vector with the length of the line, I get the point (x, y). Thus, all we have to do to move the marble towards our destination point, is to multiply the unit vector by a certain amount each time and draw the marble, and the marble will magically move towards the click point. Now time for some code. The application, uses a timer based frame draw method to draw the marble on the screen. The timer is disabled initially and whenever the user clicks on the screen, the timer is enabled. The callback function for the timer follows the standard Update and Draw cycle. private double totLenToTravelSqrd = 0; private double startPosX = 0, startPosY = 0; private double destX = 0, destY = 0; private void Form1_MouseUp(object sender, MouseEventArgs e) {     destX = e.X;     destY = e.Y;     double x = marble1.x - destX;     double y = marble1.y - destY;     //calculate the total length to be travelled     totLenToTravelSqrd = x * x + y * y;     //store the start position of the marble     startPosX = marble1.x;     startPosY = marble1.y;     timer1.Enabled = true; } private void timer1_Tick(object sender, EventArgs e) {     UpdatePosition();     DrawMarble(); } Form1_MouseUp() method is called when ever the user touches and releases the screen. In this function we save the click point in destX and destY, this is the destination point for the marble and we also enable the timer. We store a few more values which we will use in the UpdatePosition() method to detect when the marble has reached the destination and stop the timer. So we store the start position of the marble and the square of the total length to be travelled. I’ll leave out the term ‘sqrd’ when speaking of lengths from now on. The time out interval of the timer is set to 40ms, thus giving us a frame rate of about ~25fps. In the timer callback, we update the marble position and draw the marble. We know what DrawMarble() does, so here, we’ll only look at how UpdatePosition() is implemented; private void UpdatePosition() {     //the vector (x, y)     double x = destX - marble1.x;     double y = destY - marble1.y;     double incrX=0, incrY=0;     double distanceSqrd=0;     double speed = 6;     //distance between destination and current position, before updating marble position     distanceSqrd = x * x + y * y;     double angle = Math.Atan2(y, x);     //Cos and Sin give us the unit vector, 6 is the value we use to magnify the unit vector along the same direction     incrX = speed * Math.Cos(angle);     incrY = speed * Math.Sin(angle);     marble1.x += incrX;     marble1.y += incrY;     //check for bounds     if ((int)marble1.x < MinX + marbleWidth / 2)     {         marble1.x = MinX + marbleWidth / 2;     }     else if ((int)marble1.x > (MaxX - marbleWidth / 2))     {         marble1.x = MaxX - marbleWidth / 2;     }     if ((int)marble1.y < MinY + marbleHeight / 2)     {         marble1.y = MinY + marbleHeight / 2;     }     else if ((int)marble1.y > (MaxY - marbleHeight / 2))     {         marble1.y = MaxY - marbleHeight / 2;     }     //distance between destination and current point, after updating marble position     x = destX - marble1.x;     y = destY - marble1.y;     double newDistanceSqrd = x * x + y * y;     //length from start point to current marble position     x = startPosX - (marble1.x);     y = startPosY - (marble1.y);     double lenTraveledSqrd = x * x + y * y;     //check for end conditions     if ((int)lenTraveledSqrd >= (int)totLenToTravelSqrd)     {         System.Console.WriteLine("Stopping because destination reached");         timer1.Enabled = false;     }     else if (Math.Abs((int)distanceSqrd - (int)newDistanceSqrd) < 4)     {         System.Console.WriteLine("Stopping because no change in Old and New position");         timer1.Enabled = false;     } } Ok, so in this function, first we subtract the current marble position from the destination point to give us a vector. The first three lines of the function construct this vector (x, y). The vector (x, y) has the same length as the line from (marble1.x, marble1.y) to (destX, destY) and is in the direction pointing from (marble1.x, marble1.y) to (destX, destY). Note that marble1.x and marble1.y denote the center point of the marble. Then we use Atan2() to get the angle which this vector makes with the positive X axis and use Cosine() and Sine() of that angle to get the unit vector along that same direction. We multiply this unit vector with 6, to get the values which the position of the marble should be incremented by. This variable, speed, can be experimented with and determines how fast the marble moves towards the destination. After this, we check for bounds to make sure that the marble stays within the screen limits and finally we check for the end condition and stop the timer. The end condition has two parts to it. The first case is the normal case, where the user clicks well inside the screen. Here, we stop when the total length travelled by the marble is greater than or equal to the total length to be travelled. Simple enough. The second case is when the user clicks on the very corners of the screen. Like I said before, the values marble1.x and marble1.y denote the center point of the marble. When the user clicks on the corner, the marble moves towards the point, and after some time tries to go outside of the screen, this is when the bounds checking comes into play and corrects the marble position so that the marble stays inside the screen. In this case the marble will never travel a distance of totLenToTravelSqrd, because of the correction is its position. So here we detect the end condition when there is not much change in marbles position. I use the value 4 in the second condition above. After experimenting with a few values, 4 seemed to work okay. There is a small thing missing in the code above. In the normal case, case 1, when the update method runs for the last time, marble position over shoots the destination point. This happens because the position is incremented in steps (which are not small enough), so in this case too, we should have corrected the marble position, so that the center point of the marble sits exactly on top of the destination point. I’ll add this later and update the post. This has been a pretty long post already, so I’ll leave you with a video of how this program looks while running. Notice in the video that the marble moves like a bot, without any grace what so ever. And that is because the speed of the marble is fixed at 6. In the next post we will see how to make the marble move a little more elegantly. And also, if Atan2(), Sine() and Cosine() are a little too much to digest, we’ll see how to achieve the same effect without using them, in the next to next post maybe. Ciao!

    Read the article

  • Tangent basis calculation problem

    - by Kirill Daybov
    I have the problem with seams with calculating a tangent basis in my application. I'm using a seems to be right algorithm, but it gives wrong result on the seams. What am I doing wrong? Is there a problem with an algorithm, or with the model? The designer says that our models with our normal maps are rendered correctly in Xoliul Shader Plugin in 3Ds Max, so there should be a way to calculate correct tangent basis programmatically. Here's an example of the problem I'm talking about. Steps, I've already taken: - Tried different algorithm (from Gamasutra, I can't post the link because I don't have enough reputation yet). I got wrong, much worse, results; - Tried to average basis vectors for vertexes are used in multiple faces; - Tried to average basis vectors for vertexes that have same world coordinates (this would be obviously wrong solution, but I've tried it anyway).

    Read the article

  • determine collision angle on a rotating body

    - by jorb
    update: new diagram and updated description I have a contact listener set up to try and determine the side that a collision happened at relative to the a bodies rotation. One way to solve this is to find the value of the yellow angle between the red and blue vectors drawn above. The angle can be found by taking the arc cosine of the dot product of the two vectors (Evan pointed this out). One of my points of confusion is the difference in domain of the atan2 function html canvas coordinates and the Box2d rotation information. I know I have to account for this somehow... SS below questions: Does Box2D provide these angles more directly in the collision information? Am I even on the right track? If so, any hints? I have the following javascript so far: Ship.prototype.onCollide = function (other_ent,cx,cy) { var pos = this.body.GetPosition(); //collision position relative to body var d_cx = pos.x - cx; var d_cy = pos.y - cy; //length of initial vector var len = Math.sqrt(Math.pow(pos.x -cx,2) + Math.pow(pos.y-cy,2)); //body angle - can over rotate hence mod 2*Pi var ang = this.body.GetAngle() % (Math.PI * 2); //vector representing body's angle - same magnitude as the first var b_vx = len * Math.cos(ang); var b_vy = len * Math.sin(ang); //dot product of the two vectors var dot_prod = d_cx * b_vx + d_cy * b_vy; //new calculation of difference in angle - NOT WORKING! var d_ang = Math.acos(dot_prod); var side; if (Math.abs(d_ang) < Math.PI/2 ) side = "front"; else side = "back"; console.log("length",len); console.log("pos:",pos.x,pos.y); console.log("offs:",d_cx,d_cy); console.log("body vec",b_vx,b_vy); console.log("body angle:",ang); console.log("dot product",dot_prod); console.log("result:",d_ang); console.log("side",side); console.log("------------------------"); }

    Read the article

  • Bridge made out of blocks at an angle

    - by Pozzuh
    I'm having a bit of trouble with the math behind my project. I want the player to be able to select 2 points (vectors). With these 2 points a floor should be created. When these points are parallel to the x-axis it's easy, just calculate the amount of blocks needed by a simple division, loop through that amount (in x and y) and keep increasing the coordinate by the size of that block. The trouble starts when the 2 vectors aren't parallel to an axis, for example at an angle of 45 degrees. How do I handle the math behind this? If I wasn't completely clear, I made this awesome drawing in paint to demonstrate what I want to achieve. The 2 red dots would be the player selected locations. (The blocks indeed aren't square.) http://i.imgur.com/pzhFMEs.png.

    Read the article

  • Translate along local axis

    - by Aaron
    I have an object with a position matrix and a rotation matrix (derived from a quaternion, but I digress). I'm able to translate this object along world-relative vectors, but I'm trying to figure out how to translate it along local-relative vectors. So if the object is tilted 45 degrees around its Z-axis the vector (1, 0, 0) would make it move to the upper right. For world-space translations I simply turn the movement vector into a matrix and multiply it by the position matrix: position_mat = translation_mat * position_mat. For local-space translations I'd think I'd have to use the rotation matrix into that formula, but I see the object spin around instead when I apply a translation over time no matter where I multiply the rotation matrix.

    Read the article

  • Vector normalization gives very imprecise results

    - by Kipras
    When I normalize vectors I receive very strange results. The lengths of the normalized vectors range from 1.0 to almost 1.5. The functions are all written by me, but I just can't find a mistake in my algorithm. When I normalize I just divide all components of the vector by the vector's length. public double length(){ return Math.sqrt(x*x + y*y); } public void normalize(){ if(length() > 0){ x /= length(); y /= length(); } } Is this supposed to happen? I mean I can see the length ranging from 0.9 to 1.1 at worst, but this is just overwhelming. Cheers

    Read the article

  • Matlab - binary vector with high concentration of 1s (or 0s)

    - by JohnIdol
    What's the best way to generate a number X of random binary vectors of size N with concentration of 1s (or, simmetrically, of 0s) that spans from very low to very high? Using randint or unidrnd (as in this question) will generate binary vectors with uniform distributions, which is not what I need in this case. Any help appreciated!

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >