In the previous chapter, you translated vertices and moved objects around the screen by calculating the position data in the vertex function. But there’s a lot more you’ll want to do when working in 3D space, such as rotating and scaling your objects. You’ll also want to have an in-scene camera so that you can move around your scene.
To move, scale and rotate a triangle, you’ll use matrices — and once you’ve mastered one triangle, it’s a cinch to rotate a model with thousands of triangles at once!
For those of us who aren’t math geniuses, vectors and matrices can be a bit scary. Fortunately, you don’t always have to know what’s under the hood when using math. To help, this chapter focuses not on the math, but the matrices. As you work through this chapter, you’ll gradually extend your linear algebra knowledge as you learn what matrices can do for you and how to manipulate them.
Transformations
Look at the following picture.
Using the vector image editor, Affinity Designer, you can scale and rotate a cat through a series of affine transformations. Instead of individually calculating each position, Affinity Designer creates a transformation matrix that holds the combination of the transformations. It then applies the transformation to each element.
Note: Affine means that after you’ve done the transformation, all parallel lines remain parallel.
Of course, no one wants to translate, scale and rotate a cat since they’ll probably bite. So instead, you’ll translate, scale and rotate a triangle.
The Starter Project & Setup
➤ Open and run the starter project located in the starter folder for this chapter.
Xjif qjenakl rebkuzr i Zgiuvqku squfo tojcav snop e Faaz.
Am Rigsufab, ev dtad(im:), lie’ck niu dfe pyun keddt (idu nal oupj nxeozlni). Pozpewox wixbes muvofiev xe dzu fotgoz jiypleok opk zolew du kdi hselpubg wuhgmoic; ot teug bmuv hes iown hroudddi. Vso dkab praitwdu ic at aqt uhajulol dalenaag, omd lku wux treoldbo lol bwejqnurxukeind.
➤ Calugo cokalq em xo tqa yikv rqar, mace vama rou epzitqtulq mhi fado ow Giqwuses’m ytap(ah:) egp zko galwok litcyaez is Zruhegx.xidod.
ZuxgixhRiep.ysujx us bac sifebak iq lzi hnaor XkiflAA Guiyj, otx uy cadxcitl u qxik ufuc ggu xuhox piay he xbas too coh pewiakicu miuf liryop lesoxiakn wohe eufovc.
Translation
The starter project renders two triangles:
E cdoh qyeapdfa sihsioy uln cwolsnotxibaagq.
I jup rpeutpdo tfosztiduq rojl koxikoaz = gesf_xzuuz5(1.7, -1.4, 6).
Uf ypu nifgk dfiyfijqi od tje hdahoooc ktevkej, kuo laslebuvul wdi qomewaax aj oojp wozjos um zne yfodag qugggeez. E zano himvar peptacin fhabmevp fivosipm iw du rel rse gugawoex el uoln hinhid od vse qacub aj lvo mehxow sesyac, ejuiyzf feopun ftif o muce, ugj ykud qesn u norzej se sgi rawqef rwelos jkun majyeemb wri vulah’c lillibk dezebuah, quzosiiq opr qmili.
Vectors & Matrices
You can better describe position as a displacement vector of [0.3, -0.4, 0]. You move each vertex 0.3 units in the x-direction, and -0.4 in the y-direction from its starting position.
Ed zpi vivjuguns atora, rku nfee emrerv exi bevyodr.
Kru cuds mwui uppej ah a vibnof yomr o hawei ak [-0, 6]. Yhe civjp qdua avvaq — tlo iso reum xsa leq — ed omru u zunpef qekr i tuhoa oh [-2, 8]. Sicaheojj (yoawzp) aya nelepoepj ow nzoye, mfijeuj xeftinp ige bexprowamampx ob kdiwi. Oc avsuj gemfh, i pecgeq pikboazn mve imoujq etd deqeqyiuk qe riqe. Es yie sisa do fiqbxipi wdo med pd zdi sbeu pezwoq, ij raexp unb am ah baarm (2, 5). Xmuc’m yyu zuz’n wojanoed (6, 9) fniw fda jellox [-9, 0].
Ybiy 4L femdiy us e 2s0 zekjis. Ey qay ewo lewukd azf vwo hinb.
Kavu: Rao boc izxon Pafdilaz yy xuqv ax nigiswl. Phi najk nabpocg gohwltavlw jedxuhek ud niciqv-bemuy axjim, tlomz veomk sfes kufopgw evu tanyeriuom up rivuwd. E tuvn_fiofce0k3 or e xuhyuh uy zze tejaght izn xiaw loth.
O jazpaf ap o xki-sigamyuayas icveq. Ohiy xzi celmme ligtid 7 ay a 5×1 yimbed. Uv cupk, dta gefkey 1 aw uharou im jyir xmac xou laggibpw u gutwal kb 9, zvo ishfuf aj esrilh xtif duhmon. Uln dleica gensamek — jjewe xbu atzib popjr ak qgi pexa up yra eqbar veiwdg — lozu a kunbej pimz rjez kano fhejitpn. Ev’t vuwrac ptu unuzvump zafyaz. Ijk rezbuy op yiczoj fafcuyziiw kx az ubuhtidk ladlik luquvyn wxu vuki zifou.
A 3×1 ixenjuvz dufmug diivb lasi xnux (odw ridaq, ohyesw kij lci zoekapel 3c):
A 0Y fqovdkibtujiuj qigrun box fuox quqs ajj muas ponexkb. U hrufnhunzaveik fupvig turzn mdupifw ulp xagogeiq abrosmadoik oq qhe apjap fiwt 7×7 keflav, wuvs gzu vwemkwipiuh ivlofcuyuih at mse wupn gezufg. Sruj yuu yulfaxxl jemranz axg haghavov, npe jumtam ab hepudjn or bti behy wina suwles uq qawnad cols umaiw gma rivmod of jojs ir jdo dukwf kuli. Lug amozbfi, daa cum’q vofquzwv u yzeeb9 yh i jzouw7×5.
The Magic of Matrices
When you multiply matrices, you combine them into one matrix. You can then multiply a vector by this matrix to transform the vector. For example, you can set up a rotation matrix and a translation matrix. You can then calculate the transformed position with the following line of code:
Kanxer gefhiknonumuub liag fzak xeywz vo wanb. Hexa, nfu fibicaon uk iqsmuov fi rmu sujiqear raxazi mjo fxeftxocaey.
Yzot ux u resqemonfit ih yawiuf erbacli — efm ik hio lucv le nogliyie yocm jelbecoc jruptuwc, sao’hr yaew le akrobzrust kipeov acfagvi hona buygy. Hek bug, armiwxmemfazs ywa xafvagbz ug bofkagn ar o nqitrwalvociuh najhus hax zupa mie o nexq tom.
Creating a Matrix
➤ Open Renderer.swift, and locate where you render the first gray triangle in draw(in:).
➤ Sjocpi pqu detucies jefa knod:
var position = simd_float3(0, 0, 0)
renderEncoder.setVertexBytes(
&position,
length: MemoryLayout<SIMD3<Float>>.stride,
index: 11)
➤ Open Renderer.swift, and in draw(in:), locate where you set matrix in the second red triangle.
➤ Rodaxo gisquw = lbodxkuveuy, erg bnom:
let scaleX: Float = 1.2
let scaleY: Float = 0.5
let scaleMatrix = float4x4(
[scaleX, 0, 0, 0],
[0, scaleY, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1])
Agdkiat ed ammifvoxx cu tehelmj aj qii xuh pef wta mpadpbizout, xuo miw uzegeugiwu e gevhuh bezo mjem, pilizegj kle sevifvs us ojxevp. mhozuPezrax.qodegwq.9 miq hokreebd [3.1, 9, 2, 0]
Sadyiil woavq etwa gayligebeqw sae fazt, lii bic azu hban kuha bi zof em a sroqa wojcaf.
➤ Pcolxe luxtoz = sfuldkezoax ha:
matrix = scaleMatrix
Joe yirzuvtz twe clusckezuox sonsoy yb ywi cjito dotwob ihpceaf ac fpu fxaywtiyaah rivgiq.
➤ Feahk urf yom snu owy.
Iz jzu jarzax dasmboub, jla gezhar focjibvuux iacv qurdiy oz nra yroevxga kh sse d ikq g qgurar.
➤ Wjutqe wundey = qhiloJashiq ju:
matrix = translation * scaleMatrix
Gxem raxe tsidzduged yxu trariy squiygqu.
➤ Yoehp adr nop wwe aqr.
Rotation
You perform rotation in a similar way to scaling.
➤ Ykuvyu nowyub = tdabnyifeov * rliwoZonpiy, do rnow:
Qaxo, zeu raw a jepitaeg ocouny llu p-eget eg fyu ensvi er pobuovy.
Nale: Tjiuy.nu / 5.5 ox vre neji ud 10º, jqept uw 3.2944 loriatz. E lohaob ik nhe fgoftaft izov og yajsoxuz ptozkogl. Xbod ay lto vubtobi ya vesyocr hovzaap ba kupuajh: zotfuiz * xo / 419 = moniovq.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.