├── .gitignore
├── Cargo.toml
├── LICENSE
├── ORIGINAL_README.md
├── README.md
└── src
├── framerate
└── mod.rs
├── ldn
├── latency_slider
│ └── mod.rs
├── mod.rs
└── net
│ ├── interface.rs
│ └── mod.rs
├── lib.rs
└── utils
└── mod.rs
/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | Cargo.lock
3 | yuzu_build.ps1
4 | ryujinx_build.ps1
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "local-latency-slider"
3 | version = "3.1.0"
4 | authors = ["blu-dev", "saad-script"]
5 | edition = "2021"
6 |
7 | [package.metadata.skyline]
8 | titleid = "01006A800016E000" # Smash Ultimate
9 |
10 | [lib]
11 | crate-type = ["cdylib"]
12 |
13 | [dependencies]
14 | ninput = { git = "https://github.com/blu-dev/ninput" }
15 | skyline = { git = "https://github.com/ultimate-research/skyline-rs" }
16 | libc-nnsdk = { git = "https://github.com/ultimate-research/libc-nnsdk" }
17 |
18 | [profile.dev]
19 | panic = "abort"
20 |
21 | [profile.release]
22 | panic = "abort"
23 | lto = true
24 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/ORIGINAL_README.md:
--------------------------------------------------------------------------------
1 | Well, I suppose that the cat is out of the bag, yeah? Someone has ported the input latency adjustment part of HDR to vanilla.
2 |
3 | Since I co-authored this feature, I think it is fair that I explain how it works so that misinformation about it being "fair" or anything like that doesn't spread.
4 |
5 | # Client Side Only
6 | Honestly, we aren't quite sure why the SSBU development team did not synchronize this between players, it should have been one of the key things they did synchronize to ensure fair play.
7 |
8 | The easiest way to explain this is:
9 | - Player A: Has the mod and has set their latency to 2 frames.
10 | - Player B: Does not have the mod, Smash Ultimate assigns them 5 frames by default.
11 |
12 | Assuming there is no stuttering in this game, Player A is about to play the *same exact game* as player B, but with 3 frames less (48 milliseconds) delay than player B.
13 |
14 | This is very problematic. It means that in any online situation, one player can have a very real and very influential advantage.
15 |
16 | 48ms is far less than the average human reaction time, for sure. However in vanilla Ultimate online, you are guaranteed a minimum of 10 frames of input delay: 2 frames from the game being triple buffered, 4 frames from the Nintendo Switch's input drivers being slow, and 4 frames as the bare minimum amount you can get online. When are dealing with a reference value of 10 frames, any single frame makes a big impact on both game feel and ability to react. This advantage is real, and will hurt competition.
17 |
18 | It is important to note, as much confusion has presented itself, that instead of the 10f base that you have in Vanilla Ultimate, you can now have a 7f base for input delay. The input slider value replaces the 4f provided by ultimate.
19 |
20 | # "How does it not lag?"
21 | This gets a little bit complex, but bare with me.
22 |
23 | It is not feasible, in a production environment, to synchronize enough information between all parties in order to properly get one-way ping. This means that when your ping is calculated, it is calculated as a round trip time between you and the other party. What does this mean?
24 |
25 | It means that the ping that you see is calculated via something like this:
26 | ```
27 | roundtrip_ping = your_ping_to_them + their_ping_to_you
28 | ```
29 | `your_ping_to_them` and `their_ping_to_you` we don't know the value of, only their sum.
30 |
31 | So we do the next best thing and average it, the ping you get reported is
32 | ```
33 | your_ping = roundtrip_ping / 2 = (your_ping_to_them + their_ping_to_you) / 2
34 | ```
35 | So let's think about what that means if your calculated ping to another player is supposedly 120ms
36 | ```
37 | your_ping = 120ms
38 | 120ms = roundtrip_ping / 2
39 | 240ms = roundtrip_ping
40 | 240ms = your_ping_to_them + their_ping_to_you
41 | ```
42 |
43 | With those last two values, anything that properly sums to 240ms are valid, meaning one player could have `40ms` one-way ping and the other could have `200ms` one-way ping. This allows players to have different input latency on client side. Ideally they would be synchronized online to whichever one is higher to ensure fair play, however it's a safe assumption on the Ultimate devs' side of things that the roundtrip ping would be the same between both players and therefore both values of input latency would be identical
44 |
45 | # So why does this matter?
46 | When we released this for HewDraw Remix (please just call it HDR guys I beg), there were a few things that we had going in our environment that we could, not necessarily safely, but fairly ignore the glaring issues with introducing something like this:
47 | - It was included in the HDR plugin, so it could not be disabled or enabled directly
48 | - HDR disables the quickplay button, meaning you cannot play quickplay at all.
49 | - HDR immediately desyncs if the other player in a battle arena does not have HDR installed.
50 |
51 | All of these combined ensure that in any situation where you are able to use the online latency adjuster, the other player(s) are able to use it as well.
52 |
53 | That's no longer the case.
54 |
55 | The released plugin (which, as a side note, violated HDR license by not including the modified source code. they also attributed the feature to the wrong plugin, good job random GameBanana user) was advertised to be able to work on quickplay as long as you set the latency in an arena first. You can play with literally anybody, whether that is MkLeo or little Timmy who just got a Switch for Christmas. Playing with *anybody* and giving yourself an advantage is the problem here.
56 |
57 | # "So you care about competitive integrity?"
58 | Hell no. I don't, basically none of the HDR team does (at least for WiFi tournaments). But you know who does? Nintendo.
59 |
60 | You know who hosts tournaments, even if they are basically for scraps, on WiFi? Nintendo.
61 |
62 | This kind of modding could also very easily be considered illegal in Japan, (where it would have a much bigger impact as their network infrastructure and geographical location is much better for this kind of mod), so it is entirely likely that if this gets spread around and used for illegitimate reasons, Nintendo will take action against the users, and if they update Smash again likely against the modding scene.
63 |
64 | It's frustrating that something I've worked on even has the potential to bring about this result but it is what it is, there's no going back at this point.
65 |
66 | This Twitter thread does a great job explaining what I am too emotionally exhausted to present: https://twitter.com/willy_crescent/status/1602701257365389312
67 |
68 | # "How many frames does it actually save?"
69 | In offline Ultimate, there are 6 frames of input delay on a good monitor. 2 of those are from the game's graphics pipeline being triple-buffered, and the other 4 are from the Nintendo Switch's input drivers.
70 |
71 | When playing online, Ultimate assigns you a bare minimum of 4 frames of additional input delay, with more being added on depending on the ping (see above) you have to the other player(s) you are playing with.
72 |
73 | The mod allows you to pick any number for those additional frames, between 0 and 25. If both players have a good connection, i.e. fiber + LAN or something equivalent, and are somewhat close geographically, you can set that number down to 2f consistently, sometimes 1f. I (AZ) can play with someone else (CA) consistently on 2f and then when my internet is having a good day I can play on 1f.
74 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | I took blue-dev's code for the original arena latency slider mod and modified it so that it only works with local online. I also added in options to change the game's framerate to get even lower input delay. You can see the [original readme](./ORIGINAL_README.md) to get details as to how exactly the mod changes the online latency.
2 |
3 | ## Installation
4 |
5 | 1) Make sure you have the latest [skyline](https://github.com/skyline-dev/skyline/releases) installed on yuzu:
6 | ```
7 | %yuzu_folder%/sdmc/atmosphere/contents/01006A800016E000/exefs/
8 | ├── subsdk9
9 | └── main.npdm
10 | ```
11 | 2) Download the latest `liblocal_latency_slider.nro` from the [releases](https://github.com/saad-script/local-latency-slider/releases) page.
12 | Place it in the corresponding folder. This is how it should look:
13 | ```
14 | %yuzu_folder%/sdmc/atmosphere/contents/01006A800016E000/romfs/skyline/plugins/liblocal_latency_slider.nro
15 | ```
16 |
17 | ## Usage
18 |
19 | - This mod is intended for use with the yuzu emulator. Some functionality like the framerate options may not work on a real switch or other emulators.
20 | - This mod will only work in local online modes. It is intended to be used with yuzu's LDN capabilities to provide an online experience that is very close to the feel of playing offline (and sometimes even identical to offline!)
21 | - Make sure that yuzu's speed limit is set to 100%. Make sure the previous 120 fps cheat is disabled/removed.
22 | - Due to a current yuzu bug, make sure to connect to LDN **after** launching smash. Otherwise yuzu will crash when loading the game.
23 | - As a QOL feature, new smash LDN rooms will be set to have 2 players by default. (You can increase/decrease this yourself)
24 | - The top of the character select screen will display your selected framerate and delay. It will also show the ping of the room (determined by the average ping of all opponent players). Red = Unstable Connection, Yellow = Playable Connection, Green = Stable Connection.
25 | - Under each player you can see their selected framerate and delay. You can also see the ping of each individual players (see bullet point below).
26 | - In the character select screen, you can do any of the following:
27 | - Use DPAD left/right to change the online delay set by the game.
28 | - Use DPAD up/down to change the target framerate. 120 fps removes 3f of delay, 180 fps removes 4 frames of delay, and 240 fps removes 4.5 frames of delay.
29 | - Press X to toggle VSYNC on/off (only available when playing on 60 fps). This is useful if you dont have a PC capable of reaching higher framerates like 120 fps, but still want to enjoy the lower delay. This can remove upto 3 frames of delay.
30 | - Press either the left or right control stick to view the individual pings of opponent players. Altervatively, if you are playing on a gamecube controller you can press L + R at the same time to show the individual pings. (Displayed under each connected player)
31 |
32 | ## Troubleshooting & FAQ
33 |
34 | - "I can't enter the local online menu"
35 | - Ensure that you have the latest skyline is installed. Previous versions had a bug that did not allow you to enter to local wireless menu.
36 | - "Yuzu crashes when launching the game"
37 | - Make sure to connect to LDN **after** launching smash. If the issue still persists you may have to delete your shaders.
38 | - "I set the online delay to a low value but the game still feels very slow and stuttery"
39 | - Setting the delay too low will cause that. Set the delay based on your proximity to your opponent. Also, both of you should be wired to ethernet on a good network/IPS. You should never set the delay lower than 2f, as that has never worked even on computers wired directly to the same network.
40 | - "The game seems to speeds up randomly"
41 | - Make sure your computer is actually capable of reaching the target framerate. If you have the target framerate set to 120 fps, your PC should be able to maintain a solid 120 fps in game. Also make sure that yuzu's speed limit is set to 100% and that you are not using the previous 120 fps cheat.
42 | - "There are random stutters that occur in game"
43 | - Shader stutters will happen the first time you do a move/action in yuzu. Yuzu will compile and store these shaders so the next time you do the move, it won't stutter. The more you play the less these stutter will happen. It is recommended that you dedicate a game where you and your opponent will hit each other with all of your moves, so in subsequent games these stutters won't occur.
44 |
45 | Check out the [NA](https://discord.gg/jE9hTsmbjD) or [EU](https://discord.gg/yuzu-smash-meet-up-1051577844318339172) yuzu smash discord for more information and also matchmaking!
46 |
47 |
48 | ## Known Issues
49 | - If a players yuzu crashes, or disconnects unexpectedly, the room ping and opponent info (framerate, delay, ping) may not show the correct values or may show under the wrong person. To fix this, the room host will have to exit the room by backing out into the local online menu and create a room again.
50 | - If 2 or more players are playing on the same yuzu, the opponent info (framerate, delay, ping) may show under the wrong person or not show at all.
51 | - If you notice any other issues, you can report them here or in the discord servers mentioned above.
52 | - If you know how to solve these issues, contributions are always welcome.
53 |
--------------------------------------------------------------------------------
/src/framerate/mod.rs:
--------------------------------------------------------------------------------
1 | use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
2 |
3 | use crate::ldn;
4 | use crate::utils;
5 | use skyline::hooks::InlineCtx;
6 |
7 | const DEFAULT_TARGET_FRAMERATE: u32 = 60;
8 | const MAX_TARGET_FRAMERATE: u32 = 240;
9 | const TARGET_FRAMERATE_INC: u32 = 60;
10 |
11 | #[derive(Debug)]
12 | pub struct FramerateConfig {
13 | target_framerate: AtomicU32,
14 | is_vsync_enabled: AtomicBool,
15 | }
16 |
17 | impl FramerateConfig {
18 | pub fn load_from(&self, framerate_config: &FramerateConfig) {
19 | self.target_framerate.store(
20 | framerate_config.target_framerate.load(Ordering::SeqCst),
21 | Ordering::SeqCst,
22 | );
23 | self.is_vsync_enabled.store(
24 | framerate_config.is_vsync_enabled.load(Ordering::SeqCst),
25 | Ordering::SeqCst,
26 | );
27 | }
28 | pub const fn default() -> Self {
29 | FramerateConfig {
30 | target_framerate: AtomicU32::new(60),
31 | is_vsync_enabled: AtomicBool::new(true),
32 | }
33 | }
34 | }
35 |
36 | impl Clone for FramerateConfig {
37 | fn clone(&self) -> Self {
38 | FramerateConfig {
39 | target_framerate: AtomicU32::new(self.target_framerate.load(Ordering::SeqCst)),
40 | is_vsync_enabled: AtomicBool::new(self.is_vsync_enabled.load(Ordering::SeqCst)),
41 | }
42 | }
43 | }
44 |
45 | impl ToString for FramerateConfig {
46 | fn to_string(&self) -> String {
47 | let vsync_indicator = match self.is_vsync_enabled.load(Ordering::SeqCst) {
48 | true => "",
49 | false => "++",
50 | };
51 | format!(
52 | "{} FPS{}",
53 | self.target_framerate.load(Ordering::SeqCst),
54 | vsync_indicator
55 | )
56 | }
57 | }
58 |
59 | static FRAMERATE_CONFIG: FramerateConfig = FramerateConfig::default();
60 |
61 | #[skyline::hook(offset = 0x135caf8, inline)]
62 | unsafe fn on_game_speed_calc(_: &InlineCtx) {
63 | if !ldn::is_local_online() {
64 | return;
65 | }
66 | set_internal_framerate(3600 / FRAMERATE_CONFIG.target_framerate.load(Ordering::SeqCst));
67 | }
68 |
69 | #[skyline::hook(offset = 0x374779c, inline)]
70 | unsafe fn scene_update(_: &InlineCtx) {
71 | static mut PREV_TICK: Option = None;
72 | if !ldn::is_local_online() {
73 | return;
74 | }
75 | let target_framerate = FRAMERATE_CONFIG.target_framerate.load(Ordering::SeqCst);
76 | let vsync_enabled = FRAMERATE_CONFIG.is_vsync_enabled.load(Ordering::SeqCst);
77 | set_framerate_target(target_framerate);
78 | set_vsync_enabled(vsync_enabled);
79 | if vsync_enabled {
80 | return;
81 | }
82 | let target_ticks = utils::get_tick_freq() / target_framerate as u64;
83 | if let Some(prev_tick) = PREV_TICK {
84 | loop {
85 | let elapsed_ticks = skyline::nn::os::GetSystemTick() - prev_tick;
86 | if elapsed_ticks >= target_ticks {
87 | break;
88 | }
89 | }
90 | }
91 | PREV_TICK = Some(skyline::nn::os::GetSystemTick());
92 | }
93 |
94 | unsafe fn set_swap_interval(swap_interval: i32) {
95 | let base_addr = skyline::hooks::getRegionAddress(skyline::hooks::Region::Text) as u64;
96 | let r = *((base_addr + 0x6d43430) as *const u64);
97 | let r = *((r + 0x10) as *const u64);
98 | let r = (r + 0xF14) as *mut i32;
99 | *r = swap_interval;
100 | }
101 |
102 | unsafe fn set_internal_framerate(internal_framerate: u32) {
103 | let base_addr = skyline::hooks::getRegionAddress(skyline::hooks::Region::Text) as u64;
104 | let internal_frame_rate_addr = base_addr + 0x523d004;
105 | *(internal_frame_rate_addr as *mut u32) = internal_framerate
106 | }
107 |
108 | pub fn set_framerate_target(target_framerate: u32) {
109 | unsafe {
110 | FRAMERATE_CONFIG
111 | .target_framerate
112 | .store(target_framerate, Ordering::SeqCst);
113 | set_internal_framerate(3600 / target_framerate);
114 | }
115 | }
116 |
117 | pub fn set_vsync_enabled(vsync_enabled: bool) {
118 | unsafe {
119 | let target_framerate = FRAMERATE_CONFIG.target_framerate.load(Ordering::SeqCst);
120 | FRAMERATE_CONFIG
121 | .is_vsync_enabled
122 | .store(vsync_enabled, Ordering::SeqCst);
123 | match (vsync_enabled, target_framerate == 60) {
124 | (true, false) => set_swap_interval(((target_framerate as f64 / 60.0) * 100.0) as i32),
125 | (false, _) => set_swap_interval(10000),
126 | _ => set_swap_interval(1),
127 | }
128 | }
129 | }
130 |
131 | pub fn get_framerate_config() -> &'static FramerateConfig {
132 | &FRAMERATE_CONFIG
133 | }
134 |
135 | pub fn poll() {
136 | let pressed_buttons = utils::poll_buttons(&[
137 | ninput::Buttons::UP,
138 | ninput::Buttons::DOWN,
139 | ninput::Buttons::X,
140 | ]);
141 | let mut target_framerate = FRAMERATE_CONFIG.target_framerate.load(Ordering::SeqCst);
142 | let vsync_enabled = FRAMERATE_CONFIG.is_vsync_enabled.load(Ordering::SeqCst);
143 | match pressed_buttons {
144 | ninput::Buttons::UP => {
145 | if vsync_enabled {
146 | target_framerate += TARGET_FRAMERATE_INC;
147 | }
148 | }
149 | ninput::Buttons::DOWN => {
150 | if vsync_enabled {
151 | target_framerate -= TARGET_FRAMERATE_INC;
152 | }
153 | }
154 | ninput::Buttons::X => {
155 | if target_framerate == DEFAULT_TARGET_FRAMERATE {
156 | FRAMERATE_CONFIG
157 | .is_vsync_enabled
158 | .store(!vsync_enabled, Ordering::SeqCst);
159 | }
160 | }
161 | _ => (),
162 | }
163 | let new_target_framerate =
164 | target_framerate.clamp(DEFAULT_TARGET_FRAMERATE, MAX_TARGET_FRAMERATE);
165 | FRAMERATE_CONFIG
166 | .target_framerate
167 | .store(new_target_framerate, Ordering::SeqCst);
168 | }
169 |
170 | pub fn install() {
171 | skyline::install_hooks!(scene_update, on_game_speed_calc);
172 | }
173 |
--------------------------------------------------------------------------------
/src/ldn/latency_slider/mod.rs:
--------------------------------------------------------------------------------
1 | use std::sync::atomic::{AtomicI8, Ordering};
2 |
3 | use skyline::hooks::InlineCtx;
4 |
5 | use crate::ldn;
6 | use crate::utils;
7 |
8 | const MAX_INPUT_BUFFER: u8 = 25;
9 |
10 | #[derive(Debug)]
11 | pub struct Delay {
12 | buffer: AtomicI8,
13 | last_auto: AtomicI8,
14 | }
15 |
16 | impl Delay {
17 | fn next(&self) {
18 | let prev_delay = self.buffer.load(Ordering::SeqCst);
19 | self.buffer.store(
20 | (prev_delay + 1).min(MAX_INPUT_BUFFER as i8),
21 | Ordering::SeqCst,
22 | );
23 | }
24 | fn prev(&self) {
25 | let prev_delay = self.buffer.load(Ordering::SeqCst);
26 | self.buffer
27 | .store((prev_delay - 1).max(-1), Ordering::SeqCst);
28 | }
29 | pub fn load_from(&self, delay: &Delay) {
30 | self.buffer
31 | .store(delay.buffer.load(Ordering::SeqCst), Ordering::SeqCst);
32 | self.last_auto
33 | .store(delay.last_auto.load(Ordering::SeqCst), Ordering::SeqCst);
34 | }
35 | pub const fn default() -> Self {
36 | Delay {
37 | buffer: AtomicI8::new(4),
38 | last_auto: AtomicI8::new(-1),
39 | }
40 | }
41 | }
42 |
43 | impl Clone for Delay {
44 | fn clone(&self) -> Self {
45 | Delay {
46 | buffer: AtomicI8::new(self.buffer.load(Ordering::SeqCst)),
47 | last_auto: AtomicI8::new(self.last_auto.load(Ordering::SeqCst)),
48 | }
49 | }
50 | }
51 |
52 | impl ToString for Delay {
53 | fn to_string(&self) -> String {
54 | let buffer = self.buffer.load(Ordering::SeqCst);
55 | let last_auto = self.last_auto.load(Ordering::SeqCst);
56 | match (buffer >= 0, last_auto >= 0) {
57 | (false, false) => String::from("Auto"),
58 | (false, true) => format!("Auto ({}f)", last_auto).to_string(),
59 | (true, _) => format!("{}f", buffer).to_string(),
60 | }
61 | }
62 | }
63 |
64 | static CURRENT_INPUT_DELAY: Delay = Delay::default();
65 |
66 | #[skyline::hook(offset = 0x16ccc58, inline)]
67 | unsafe fn set_online_latency(ctx: &InlineCtx) {
68 | if ldn::is_local_online() {
69 | let auto = *(*ctx.registers[19].x.as_ref() as *mut u8);
70 | let buffer = CURRENT_INPUT_DELAY.buffer.load(Ordering::SeqCst);
71 | CURRENT_INPUT_DELAY
72 | .last_auto
73 | .store(auto as i8, Ordering::SeqCst);
74 | if buffer >= 0 {
75 | *(*ctx.registers[19].x.as_ref() as *mut u8) = buffer as u8;
76 | }
77 | }
78 | }
79 |
80 | pub fn current_input_delay() -> &'static Delay {
81 | &CURRENT_INPUT_DELAY
82 | }
83 |
84 | pub fn poll() {
85 | let pressed_buttons = utils::poll_buttons(&[ninput::Buttons::LEFT, ninput::Buttons::RIGHT]);
86 | match pressed_buttons {
87 | ninput::Buttons::LEFT => CURRENT_INPUT_DELAY.prev(),
88 | ninput::Buttons::RIGHT => CURRENT_INPUT_DELAY.next(),
89 | _ => (),
90 | }
91 | }
92 |
93 | pub(super) fn install() {
94 | skyline::install_hook!(set_online_latency);
95 | }
96 |
--------------------------------------------------------------------------------
/src/ldn/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod latency_slider;
2 | pub mod net;
3 |
4 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
5 |
6 | use crate::framerate;
7 | use crate::ldn::net::interface::{get_network_role, NetworkRole};
8 | use crate::utils::TextBoxExt;
9 | use skyline::hooks::InlineCtx;
10 | use skyline::nn::ui2d::Pane;
11 |
12 | static mut CUSTOM_CSS_NUM_PLAYERS_FLAG: bool = false;
13 |
14 | static LOCAL_ROOM_PANE_HANDLE: AtomicU64 = AtomicU64::new(0);
15 | // workaround for sv_information::is_ready_go() being unreliable for ldn in some cases
16 | static IN_GAME: AtomicBool = AtomicBool::new(false);
17 |
18 | #[skyline::hook(offset = 0x22d9d10, inline)]
19 | unsafe fn online_melee_any_scene_create(_: &InlineCtx) {
20 | LOCAL_ROOM_PANE_HANDLE.store(0, Ordering::SeqCst);
21 | framerate::set_framerate_target(60);
22 | framerate::set_vsync_enabled(true);
23 | }
24 |
25 | #[skyline::hook(offset = 0x22d9c40, inline)]
26 | unsafe fn bg_matchmaking_seq(_: &InlineCtx) {
27 | LOCAL_ROOM_PANE_HANDLE.store(0, Ordering::SeqCst);
28 | framerate::set_framerate_target(60);
29 | framerate::set_vsync_enabled(true);
30 | }
31 |
32 | #[skyline::hook(offset = 0x235a650, inline)]
33 | unsafe fn main_menu(_: &InlineCtx) {
34 | LOCAL_ROOM_PANE_HANDLE.store(0, Ordering::SeqCst);
35 | framerate::set_framerate_target(60);
36 | framerate::set_vsync_enabled(true);
37 | }
38 |
39 | // called on local online menu init
40 | #[skyline::hook(offset = 0x1bd45e0, inline)]
41 | unsafe fn store_local_menu_pane(ctx: &InlineCtx) {
42 | update_in_game_flag(false);
43 | CUSTOM_CSS_NUM_PLAYERS_FLAG = true;
44 | let handle = *((*((*ctx.registers[0].x.as_ref() + 8) as *const u64) + 0x10) as *const u64);
45 | LOCAL_ROOM_PANE_HANDLE.store(handle, Ordering::SeqCst);
46 | }
47 |
48 | #[skyline::hook(offset = 0x1bd7a80, inline)]
49 | unsafe fn update_local_menu(_: &InlineCtx) {
50 | let pane_handle = LOCAL_ROOM_PANE_HANDLE.load(Ordering::SeqCst) as *mut u64 as *mut Pane;
51 | if !pane_handle.is_null() {
52 | latency_slider::poll();
53 | let delay_str = latency_slider::current_input_delay().to_string();
54 | (*pane_handle)
55 | .as_textbox()
56 | .set_text_string(&format!("{}", delay_str));
57 | }
58 | }
59 |
60 | #[skyline::hook(offset = 0x1a26200)]
61 | unsafe fn css_player_pane_num_changed(param_1: i64, prev_num: i32, changed_by_player: u32) {
62 | if is_local_online()
63 | && CUSTOM_CSS_NUM_PLAYERS_FLAG
64 | && changed_by_player == 0
65 | && get_network_role() == NetworkRole::Host
66 | {
67 | CUSTOM_CSS_NUM_PLAYERS_FLAG = false;
68 | *((param_1 + 0x160) as *mut i32) = 2;
69 | }
70 | call_original!(param_1, prev_num, changed_by_player);
71 | }
72 |
73 | #[skyline::hook(offset = 0x1345558, inline)]
74 | unsafe fn on_match_start(_: &InlineCtx) {
75 | if !is_local_online() {
76 | return;
77 | }
78 | update_in_game_flag(true);
79 | }
80 |
81 | #[skyline::hook(offset = 0x1d68b94, inline)]
82 | unsafe fn on_match_end(_: &InlineCtx) {
83 | if !is_local_online() {
84 | return;
85 | }
86 | update_in_game_flag(false);
87 | }
88 |
89 | fn update_in_game_flag(new_in_game_flag: bool) {
90 | let _ = IN_GAME.compare_exchange(
91 | !new_in_game_flag,
92 | new_in_game_flag,
93 | Ordering::SeqCst,
94 | Ordering::SeqCst,
95 | );
96 | }
97 |
98 | pub fn is_local_online() -> bool {
99 | return LOCAL_ROOM_PANE_HANDLE.load(Ordering::SeqCst) > 0;
100 | }
101 |
102 | pub fn is_in_game() -> bool {
103 | IN_GAME.load(Ordering::SeqCst)
104 | }
105 |
106 | pub fn install() {
107 | skyline::install_hooks!(
108 | online_melee_any_scene_create,
109 | bg_matchmaking_seq,
110 | main_menu,
111 | store_local_menu_pane,
112 | update_local_menu,
113 | css_player_pane_num_changed,
114 | on_match_start,
115 | on_match_end,
116 | );
117 | latency_slider::install();
118 | net::install();
119 | }
120 |
--------------------------------------------------------------------------------
/src/ldn/net/interface.rs:
--------------------------------------------------------------------------------
1 | use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
2 | use std::sync::atomic::{AtomicBool, Ordering};
3 | use std::sync::Mutex;
4 | use std::time::Duration;
5 |
6 | use crate::framerate::{self, FramerateConfig};
7 | use crate::ldn::latency_slider::{self, Delay};
8 | use crate::utils;
9 |
10 | extern "C" {
11 | #[link_name = "\u{1}_ZN2nn3ldn14GetNetworkInfoEPNS0_11NetworkInfoE"]
12 | pub fn get_network_info(out_buffer_ptr: *mut NetworkInfo);
13 | }
14 |
15 | extern "C" {
16 | #[link_name = "\u{1}_ZN2nn3ldn13CreateNetworkERKNS0_13NetworkConfigERKNS0_14SecurityConfigERKNS0_10UserConfigE"]
17 | pub fn create_network(network_config: u64, security_config: u64, user_config: u64);
18 | }
19 |
20 | extern "C" {
21 | #[link_name = "\u{1}_ZN2nn3ldn7ConnectERKNS0_11NetworkInfoERKNS0_14SecurityConfigERKNS0_10UserConfigEiNS0_13ConnectOptionE"]
22 | pub fn connect_network(
23 | network_info: *mut NetworkInfo,
24 | security_config: u64,
25 | user_config: u64,
26 | local_comm_ver: i32,
27 | connect_option: u32,
28 | );
29 | }
30 |
31 | extern "C" {
32 | #[link_name = "\u{1}_ZN2nn3ldn10DisconnectEv"]
33 | pub fn disconnect_network();
34 | }
35 |
36 | extern "C" {
37 | #[link_name = "\u{1}_ZN2nn3ldn14DestroyNetworkEv"]
38 | pub fn destroy_network();
39 | }
40 |
41 | extern "C" {
42 | #[link_name = "\u{1}_ZN2nn3ldn8GetStateEv"]
43 | pub fn get_network_state() -> NetworkState;
44 | }
45 |
46 | extern "C" {
47 | #[link_name = "\u{1}_ZN2nn3ldn4ScanEPNS0_11NetworkInfoEPiiRKNS0_10ScanFilterEi"]
48 | pub fn scan_network(
49 | network_info: *mut NetworkInfo,
50 | num_networks_found: *mut i32,
51 | max_num_networks: i32,
52 | scan_filter: u64,
53 | _param_5: i32,
54 | );
55 |
56 | }
57 |
58 | extern "C" {
59 | #[link_name = "\u{1}_ZN2nn3ldn14GetIpv4AddressEPNS0_11Ipv4AddressEPNS0_10SubnetMaskE"]
60 | pub fn get_ipv4_address(ip_address: *mut RawIPv4Address, subnet_mask: *mut RawIPv4Address);
61 | }
62 |
63 | pub fn get_network_address(port: u16) -> SocketAddr {
64 | let ip_buffer = [0; 4].as_mut_ptr() as *mut RawIPv4Address;
65 | let subnet_buffer = [0; 4].as_mut_ptr() as *mut RawIPv4Address;
66 | unsafe {
67 | get_ipv4_address(ip_buffer, subnet_buffer);
68 | let ip = (*ip_buffer).to_socket_address(port);
69 | return ip;
70 | }
71 | }
72 |
73 | #[repr(C, align(4))]
74 | #[derive(Debug, Clone)]
75 | pub struct RawIPv4Address(pub [u8; 4]);
76 |
77 | impl RawIPv4Address {
78 | pub fn to_socket_address(&self, port: u16) -> SocketAddr {
79 | SocketAddr::new(
80 | IpAddr::V4(Ipv4Addr::new(self.0[3], self.0[2], self.0[1], self.0[0])),
81 | port,
82 | )
83 | }
84 | }
85 |
86 | pub fn try_get_network_info() -> std::io::Result> {
87 | unsafe {
88 | let state = get_network_state();
89 | match state {
90 | NetworkState::AccessPointCreated | NetworkState::StationConnected => {
91 | let mut network_info_buffer: [u8; 0x480] = [0; 0x480];
92 | let network_info_buffer = network_info_buffer.as_mut_ptr() as *mut NetworkInfo;
93 |
94 | get_network_info(network_info_buffer);
95 | Ok(Box::from_raw(network_info_buffer))
96 | }
97 | _ => Err(std::io::Error::new(
98 | std::io::ErrorKind::NotConnected,
99 | "Unable to get network info",
100 | )),
101 | }
102 | }
103 | }
104 |
105 | pub fn get_network_role() -> NetworkRole {
106 | unsafe {
107 | let state = get_network_state();
108 | match state {
109 | NetworkState::AccessPointCreated => NetworkRole::Host,
110 | NetworkState::StationConnected => NetworkRole::Client,
111 | _ => NetworkRole::None,
112 | }
113 | }
114 | }
115 |
116 | #[repr(C)]
117 | #[derive(Debug, Clone)]
118 | pub struct NodeInfo {
119 | pub ipv4_address: [u8; 4], // 0x0, 4 bytes
120 | pub mac_address: [u8; 6], // 0x4, 6 bytes
121 | pub node_id: u8, // 0xA, 1 byte
122 | pub is_connected: u8, // 0xB, 1 byte
123 | pub user_name: [u8; 33], // 0xC, 33 bytes (0x21 in decimal)
124 | _reserved_1: u8, // 0x2D, 1 byte
125 | pub local_communication_version: u16, // 0x2E, 2 bytes
126 | _reserved_2: [u8; 16], // 0x30, 16 bytes
127 | }
128 | #[repr(C)]
129 | #[derive(Debug, Clone)]
130 | pub struct NetworkInfo {
131 | pub local_communication_id: u64, // 0x0, 8 bytes
132 | _reserved_1: u16, // 0x8, 2 bytes
133 | pub arbitrary_user_data: u16, // 0xA, 2 bytes
134 | _reserved_2: u32, // 0xC, 4 bytes
135 | pub security_parameter_last: [u8; 16], // 0x10, 16 bytes
136 | pub mac_address: [u8; 6], // 0x20, 6 bytes
137 | pub ssid: [u8; 34], // 0x26, 34 bytes (0x22 in decimal)
138 | pub network_channel: i16, // 0x48, 2 bytes
139 | pub link_level: i8, // 0x4A, 1 byte
140 | pub action_frame_indicator: u8, // 0x4B, 1 byte
141 | _padding_1: [u8; 4], // 0x4C, 4 bytes
142 | pub security_parameter_first: [u8; 16], // 0x50, 16 bytes
143 | pub same_as_security_config: u16, // 0x60, 2 bytes
144 | pub accept_policy: u8, // 0x62, 1 byte
145 | pub action_frame_set: u8, // 0x63, 1 byte
146 | _padding_2: [u8; 2], // 0x64, 2 bytes
147 | pub maximum_participants: u8, // 0x66, 1 byte
148 | pub participant_num: u8, // 0x67, 1 byte
149 | pub node_info_array: [NodeInfo; 8], // 0x68, 0x200 (512 bytes, 8 * 64 bytes each)
150 | _reserved_3: [u8; 2], // 0x268, 2 bytes
151 | pub advertise_data_size: u16, // 0x26A, 2 bytes
152 | pub advertise_data: [u8; 384], // 0x26C, 0x180 (384 bytes)
153 | _reserved_4: [u8; 140], // 0x3EC, 140 bytes
154 | pub random_authentication_id: [u8; 8], // 0x478, 8 bytes
155 | }
156 |
157 | #[repr(u32)]
158 | #[derive(Debug)]
159 | #[allow(dead_code)]
160 | pub enum NetworkState {
161 | None = 0,
162 | Initialized = 1,
163 | AccessPoint = 2,
164 | AccessPointCreated = 3,
165 | Station = 4,
166 | StationConnected = 5,
167 | Error = 6,
168 | }
169 |
170 | #[derive(Debug, Clone, PartialEq)]
171 | pub enum NetworkRole {
172 | None,
173 | Host,
174 | Client,
175 | }
176 |
177 | #[derive(Debug, Clone, PartialEq)]
178 | pub enum NetworkThreadType {
179 | Listener,
180 | Sender,
181 | }
182 |
183 | #[repr(u8)]
184 | #[derive(Debug, Clone, PartialEq)]
185 | pub enum NetworkPacketType {
186 | Ping = 0,
187 | Pong = 1,
188 | }
189 |
190 | #[derive(Debug, Clone)]
191 | pub struct NetworkPacket {
192 | pub packet_type: NetworkPacketType,
193 | pub delay: Delay,
194 | pub framerate_config: FramerateConfig,
195 | timestamp: u64,
196 | }
197 |
198 | impl NetworkPacket {
199 | pub fn create_ping_packet() -> Self {
200 | let timestamp: u64;
201 | unsafe {
202 | timestamp = skyline::nn::os::GetSystemTick() as u64;
203 | }
204 | NetworkPacket {
205 | packet_type: NetworkPacketType::Ping,
206 | delay: latency_slider::current_input_delay().clone(),
207 | framerate_config: framerate::get_framerate_config().clone(),
208 | timestamp,
209 | }
210 | }
211 |
212 | pub fn create_pong_packet(packet: &NetworkPacket) -> Self {
213 | NetworkPacket {
214 | packet_type: NetworkPacketType::Pong,
215 | delay: latency_slider::current_input_delay().clone(),
216 | framerate_config: framerate::get_framerate_config().clone(),
217 | timestamp: packet.timestamp,
218 | }
219 | }
220 |
221 | pub fn get_time_elapsed(&self) -> Duration {
222 | utils::duration_since_tick(self.timestamp)
223 | }
224 |
225 | pub fn to_bytes(&self) -> &[u8] {
226 | unsafe {
227 | core::slice::from_raw_parts(
228 | self as *const Self as *const u8,
229 | core::mem::size_of::(),
230 | )
231 | }
232 | }
233 |
234 | pub fn from_bytes(bytes: &[u8]) -> Self {
235 | unsafe { std::ptr::read(bytes.as_ptr() as *const Self) }
236 | }
237 | }
238 |
239 | pub enum NetworkStability {
240 | Stable,
241 | Inconsistent,
242 | Unstable,
243 | }
244 |
245 | #[derive(Debug, Clone)]
246 | pub struct NetworkDiagnostics {
247 | pings: [u64; 100],
248 | counter: usize,
249 | sum: u64,
250 | filled: bool,
251 | }
252 |
253 | impl NetworkDiagnostics {
254 | pub const fn new() -> Self {
255 | NetworkDiagnostics {
256 | pings: [0; 100],
257 | counter: 0,
258 | sum: 0,
259 | filled: false,
260 | }
261 | }
262 |
263 | pub fn register_ping(&mut self, ping: u64) {
264 | self.sum -= self.pings[self.counter];
265 | self.sum += ping;
266 | self.pings[self.counter] = ping;
267 | self.counter = (self.counter + 1) % 100;
268 | if self.counter == 0 {
269 | self.filled = true;
270 | }
271 | }
272 |
273 | pub fn get_avg_ping(&self) -> Option {
274 | match (self.filled, self.counter == 0) {
275 | (true, _) => Some(self.sum / 100),
276 | (false, false) => Some(self.sum / self.counter as u64),
277 | (false, true) => None,
278 | }
279 | }
280 |
281 | pub fn get_network_stability(&self) -> NetworkStability {
282 | let avg = match self.get_avg_ping() {
283 | Some(a) => a,
284 | None => {
285 | return NetworkStability::Stable;
286 | }
287 | };
288 |
289 | let mut var_sum: u64 = 0;
290 | let end = if self.filled { 100 } else { self.counter + 1 };
291 | for i in 0..end {
292 | var_sum += (self.pings[i] - avg) * (self.pings[i] - avg)
293 | }
294 |
295 | let variance = if self.filled {
296 | var_sum as f64 / 99.0
297 | } else {
298 | var_sum as f64 / self.counter as f64
299 | };
300 |
301 | if variance <= 25.0 {
302 | return NetworkStability::Stable;
303 | } else if variance <= 100.0 {
304 | return NetworkStability::Inconsistent;
305 | } else {
306 | return NetworkStability::Unstable;
307 | }
308 | }
309 |
310 | pub fn reset(&mut self) {
311 | self.pings = [0; 100];
312 | self.counter = 0;
313 | self.sum = 0;
314 | self.filled = false;
315 | }
316 | }
317 |
318 | #[derive(Debug)]
319 | pub struct PlayerNetInfo {
320 | connected: AtomicBool,
321 | pub delay: Delay,
322 | pub framerate_config: FramerateConfig,
323 | pub net_diagnostics: Mutex,
324 | }
325 |
326 | impl PlayerNetInfo {
327 | pub const fn default() -> Self {
328 | PlayerNetInfo {
329 | connected: AtomicBool::new(false),
330 | delay: Delay::default(),
331 | framerate_config: FramerateConfig::default(),
332 | net_diagnostics: Mutex::new(NetworkDiagnostics::new()),
333 | }
334 | }
335 |
336 | pub fn set_connected(&self, connected: bool) {
337 | if let Ok(_updated) = self.connected.compare_exchange(
338 | !connected,
339 | connected,
340 | Ordering::SeqCst,
341 | Ordering::SeqCst,
342 | ) {
343 | if !connected {
344 | self.net_diagnostics.lock().unwrap().reset();
345 | }
346 | }
347 | }
348 |
349 | pub fn is_connected(&self) -> bool {
350 | return self.connected.load(Ordering::SeqCst);
351 | }
352 | }
353 |
354 | pub trait UdpSocketExt {
355 | fn read(&self, buf: &mut [u8], blocking: bool) -> std::io::Result<(NetworkPacket, SocketAddr)>;
356 | fn write(&self, addr: &SocketAddr, packet: NetworkPacket) -> std::io::Result;
357 | }
358 |
359 | impl UdpSocketExt for UdpSocket {
360 | fn read(
361 | &self,
362 | buf: &mut [u8],
363 | blocking: bool,
364 | ) -> std::io::Result<(NetworkPacket, std::net::SocketAddr)> {
365 | self.set_nonblocking(!blocking)?;
366 | let (num_bytes, src_addr) = match self.recv_from(buf) {
367 | Ok((num_bytes, src_addr)) => (num_bytes, src_addr),
368 | Err(e) => {
369 | if e.raw_os_error() == Some(11) {
370 | return Err(std::io::ErrorKind::WouldBlock.into());
371 | } else {
372 | return Err(e);
373 | }
374 | }
375 | };
376 |
377 | Ok((NetworkPacket::from_bytes(&buf[0..num_bytes]), src_addr))
378 | }
379 |
380 | fn write(&self, addr: &SocketAddr, packet: NetworkPacket) -> std::io::Result {
381 | self.send_to(packet.to_bytes(), addr)
382 | }
383 | }
384 |
--------------------------------------------------------------------------------
/src/ldn/net/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod interface;
2 |
3 | use interface::*;
4 | use std::net::{SocketAddr, UdpSocket};
5 | use std::sync::Mutex;
6 | use std::thread;
7 | use std::time::{Duration, Instant};
8 |
9 | use crate::ldn;
10 |
11 | const SEND_PORT: u16 = 3070;
12 | const LISTEN_PORT: u16 = 3080;
13 |
14 | static ROOM_NET_DIAGNOSTICS: Mutex = Mutex::new(NetworkDiagnostics::new());
15 | static PLAYER_NET_STATS: [PlayerNetInfo; 8] = [
16 | PlayerNetInfo::default(),
17 | PlayerNetInfo::default(),
18 | PlayerNetInfo::default(),
19 | PlayerNetInfo::default(),
20 | PlayerNetInfo::default(),
21 | PlayerNetInfo::default(),
22 | PlayerNetInfo::default(),
23 | PlayerNetInfo::default(),
24 | ];
25 |
26 | #[skyline::hook(replace = scan_network)]
27 | unsafe fn on_network_scan(
28 | network_info: *mut NetworkInfo,
29 | num_networks_found: *mut i32,
30 | max_num_networks: i32,
31 | scan_filter: u64,
32 | _param_5: i32,
33 | ) {
34 | println!("Scanning network...");
35 | call_original!(
36 | network_info,
37 | num_networks_found,
38 | max_num_networks,
39 | scan_filter,
40 | _param_5
41 | );
42 | println!(
43 | "Found: {}, Max: {}, ?: {}",
44 | *num_networks_found, max_num_networks, _param_5
45 | );
46 | }
47 |
48 | fn poll_listener(socket: &UdpSocket, buf: &mut [u8]) -> std::io::Result<()> {
49 | let (packet, mut src_addr) = match socket.read(buf, true) {
50 | Ok(p) => p,
51 | Err(e) => {
52 | return Err(e);
53 | }
54 | };
55 |
56 | match packet.packet_type {
57 | NetworkPacketType::Ping => {
58 | println!("Responding to Ping packet from {}...", src_addr.to_string());
59 | src_addr.set_port(LISTEN_PORT);
60 | let res_packet = NetworkPacket::create_pong_packet(&packet);
61 | socket.write(&src_addr, res_packet)?;
62 | }
63 | NetworkPacketType::Pong => {
64 | let curr_ping = packet.get_time_elapsed().as_millis();
65 | ROOM_NET_DIAGNOSTICS
66 | .lock()
67 | .unwrap()
68 | .register_ping(curr_ping as u64);
69 | println!("Got Pong packet ({}): {}", src_addr.to_string(), curr_ping);
70 |
71 | let network_info = try_get_network_info()?;
72 | // Check which player sent the packet and update the ping
73 | let (player_index, _node) =
74 | match network_info
75 | .node_info_array
76 | .iter()
77 | .enumerate()
78 | .find(|(_i, n)| {
79 | RawIPv4Address(n.ipv4_address).to_socket_address(LISTEN_PORT) == src_addr
80 | }) {
81 | Some(v) => v,
82 | None => {
83 | return Err(std::io::Error::new(
84 | std::io::ErrorKind::NotFound,
85 | "Unable to identify sender address",
86 | ))
87 | }
88 | };
89 |
90 | let player_net_info = &PLAYER_NET_STATS[player_index];
91 | player_net_info.set_connected(true);
92 | player_net_info.delay.load_from(&packet.delay);
93 | player_net_info
94 | .framerate_config
95 | .load_from(&packet.framerate_config);
96 | player_net_info
97 | .net_diagnostics
98 | .lock()
99 | .unwrap()
100 | .register_ping(curr_ping as u64);
101 | }
102 | }
103 |
104 | Ok(())
105 | }
106 |
107 | fn poll_sender(addr: &SocketAddr, socket: &UdpSocket) -> std::io::Result<()> {
108 | let network_info = try_get_network_info()?;
109 | let mut sent = false;
110 | for (i, node) in network_info.node_info_array.iter().enumerate() {
111 | if node.is_connected == 0 {
112 | PLAYER_NET_STATS[i].set_connected(false);
113 | continue;
114 | }
115 | let ping_addr = RawIPv4Address(node.ipv4_address).to_socket_address(LISTEN_PORT);
116 | if ping_addr.ip() == addr.ip() {
117 | continue;
118 | }
119 | let packet = NetworkPacket::create_ping_packet();
120 | if let Err(e) = socket.write(&ping_addr, packet) {
121 | eprintln!("Error sending ping packet to {}: {}", ping_addr, e);
122 | continue;
123 | }
124 | sent = true;
125 | }
126 | match sent {
127 | true => Ok(()),
128 | false => {
129 | ROOM_NET_DIAGNOSTICS.lock().unwrap().reset();
130 | Err(std::io::Error::new(
131 | std::io::ErrorKind::NotConnected,
132 | "No network nodes found",
133 | ))
134 | }
135 | }
136 | }
137 |
138 | fn network_loop(network_role: NetworkRole, thread_type: NetworkThreadType) {
139 | let port = match thread_type {
140 | NetworkThreadType::Listener => LISTEN_PORT,
141 | NetworkThreadType::Sender => SEND_PORT,
142 | };
143 | let addr = get_network_address(port);
144 | let socket = UdpSocket::bind(addr).expect("Unable to bind to socket");
145 | let mut buf = [0; 1024];
146 | while get_network_role() == network_role {
147 | let poll_start_timestamp = Instant::now();
148 | let r = match thread_type {
149 | NetworkThreadType::Listener => poll_listener(&socket, &mut buf),
150 | NetworkThreadType::Sender => poll_sender(&addr, &socket),
151 | };
152 | if let Err(e) = r {
153 | eprintln!("Error in {:?} thread: {:?}", thread_type, e);
154 | }
155 |
156 | //limit the rate the sender thread sends out packets
157 | if thread_type == NetworkThreadType::Sender {
158 | let packet_interval = match ldn::is_in_game() {
159 | true => Duration::from_secs_f64(0.5),
160 | false => Duration::from_secs_f64(0.1),
161 | };
162 | if poll_start_timestamp.elapsed() < packet_interval {
163 | thread::sleep(packet_interval - poll_start_timestamp.elapsed());
164 | }
165 | }
166 | }
167 | for player_net_stat in PLAYER_NET_STATS.iter() {
168 | player_net_stat.set_connected(false);
169 | }
170 | }
171 |
172 | unsafe fn spawn_network_threads(network_role: NetworkRole) {
173 | let network_role_clone = network_role.clone();
174 | thread::spawn(move || {
175 | skyline::nn::os::ChangeThreadPriority(skyline::nn::os::GetCurrentThread(), 5);
176 | network_loop(network_role, NetworkThreadType::Listener);
177 | println!(
178 | "Listener Network loop exited, with Network State: {:?}",
179 | get_network_state()
180 | );
181 | skyline::nn::os::ChangeThreadPriority(skyline::nn::os::GetCurrentThread(), 24);
182 | });
183 | thread::spawn(move || {
184 | skyline::nn::os::ChangeThreadPriority(skyline::nn::os::GetCurrentThread(), 5);
185 | network_loop(network_role_clone, NetworkThreadType::Sender);
186 | println!(
187 | "Sender Network loop exited, with Network State: {:?}",
188 | get_network_state()
189 | );
190 | skyline::nn::os::ChangeThreadPriority(skyline::nn::os::GetCurrentThread(), 24);
191 | });
192 | }
193 |
194 | #[skyline::hook(replace = create_network)]
195 | unsafe fn on_network_created(network_config: u64, security_config: u64, user_config: u64) {
196 | println!("Creating network...");
197 | call_original!(network_config, security_config, user_config);
198 | spawn_network_threads(NetworkRole::Host);
199 | }
200 |
201 | #[skyline::hook(replace = connect_network)]
202 | unsafe fn on_network_connected(
203 | network_info: *mut NetworkInfo,
204 | security_config: u64,
205 | user_config: u64,
206 | local_comm_ver: i32,
207 | connect_option: u32,
208 | ) {
209 | println!("Connecting to network...");
210 | call_original!(
211 | network_info,
212 | security_config,
213 | user_config,
214 | local_comm_ver,
215 | connect_option
216 | );
217 | spawn_network_threads(NetworkRole::Client);
218 | }
219 |
220 | #[skyline::hook(replace = disconnect_network)]
221 | unsafe fn on_network_disconnected() {
222 | call_original!();
223 | println!("Network Disconnected");
224 | }
225 |
226 | #[skyline::hook(replace = destroy_network)]
227 | unsafe fn on_network_destroyed() {
228 | call_original!();
229 | println!("Network Destroyed");
230 | }
231 |
232 | pub fn get_player_net_info<'a>(player_index: usize) -> &'static PlayerNetInfo {
233 | &PLAYER_NET_STATS[player_index]
234 | }
235 |
236 | pub fn get_room_net_diag<'a>() -> std::sync::MutexGuard<'a, NetworkDiagnostics> {
237 | ROOM_NET_DIAGNOSTICS.lock().unwrap()
238 | }
239 |
240 | pub(super) fn install() {
241 | skyline::install_hooks!(
242 | on_network_scan,
243 | on_network_created,
244 | on_network_connected,
245 | on_network_disconnected,
246 | on_network_destroyed
247 | );
248 | }
249 |
--------------------------------------------------------------------------------
/src/lib.rs:
--------------------------------------------------------------------------------
1 | mod framerate;
2 | mod ldn;
3 | mod utils;
4 |
5 | use skyline::nn::ui2d::Pane;
6 |
7 | use utils::{PaneExt, TextBoxExt};
8 |
9 | #[skyline::hook(offset = 0x1a12f60)]
10 | unsafe fn update_css(arg: u64) {
11 | if ldn::is_local_online() {
12 | ldn::latency_slider::poll();
13 | framerate::poll();
14 | let delay_str = ldn::latency_slider::current_input_delay().to_string();
15 | let framerate_config = framerate::get_framerate_config();
16 | let room_net_diag = ldn::net::get_room_net_diag();
17 | let ping_str = match room_net_diag.get_avg_ping() {
18 | Some(ping) => format!(" {}ms", ping),
19 | None => String::from(""),
20 | };
21 | let banner_display_str = format!(
22 | "Buffer: {} [{}]{}\0",
23 | delay_str,
24 | framerate_config.to_string(),
25 | ping_str
26 | );
27 | let (r, g, b, a) = match room_net_diag.get_network_stability() {
28 | ldn::net::interface::NetworkStability::Stable => (0, 255, 0, 255),
29 | ldn::net::interface::NetworkStability::Inconsistent => (255, 255, 0, 255),
30 | ldn::net::interface::NetworkStability::Unstable => (255, 0, 0, 255),
31 | };
32 | drop(room_net_diag);
33 |
34 | // pointer to p1's title text pane
35 | let p1_pane = (*((*((arg + 0xe58) as *const u64) + 0x10) as *const u64)) as *mut Pane;
36 | let p1_pane = &mut *p1_pane;
37 | p1_pane.as_textbox().set_default_material_colors();
38 | p1_pane.as_textbox().set_color(r, g, b, a);
39 | p1_pane.as_textbox().set_text_string(&banner_display_str);
40 |
41 | let p1_pane_bg = p1_pane.parent().unwrap().traverse_backward(2).unwrap();
42 | p1_pane_bg.set_visible(false);
43 |
44 | let p2_pane = p1_pane_bg
45 | .parent()
46 | .unwrap()
47 | .parent()
48 | .unwrap()
49 | .prev()
50 | .unwrap();
51 | p2_pane.as_textbox().set_default_material_colors();
52 | p2_pane.as_textbox().set_color(r, g, b, a);
53 | p2_pane.as_textbox().set_text_string(&banner_display_str);
54 |
55 | let panel_root = p2_pane.parent().unwrap().traverse_forward(4).unwrap();
56 |
57 | for player_index in 0..8 {
58 | let player_panel_root = panel_root
59 | .get_child(&format!("set_panel_{}p", player_index + 1), false)
60 | .unwrap();
61 |
62 | let player_panel = player_panel_root.children().unwrap();
63 |
64 | let player_panel_name = player_panel
65 | .get_child(&format!("set_btn_panel"), false)
66 | .unwrap();
67 | let player_panel_name = player_panel_name.children().unwrap().next().unwrap();
68 | let player_panel_name = player_panel_name
69 | .get_child(&format!("set_txt_00"), true)
70 | .unwrap();
71 |
72 | let player_net_info = ldn::net::get_player_net_info(player_index);
73 | match player_net_info.is_connected() {
74 | true => {
75 | let is_stick_pressed = ninput::any::is_press(ninput::Buttons::STICK_L)
76 | || ninput::any::is_press(ninput::Buttons::STICK_R);
77 | let is_triggers_pressed = ninput::any::is_press(ninput::Buttons::L)
78 | && ninput::any::is_press(ninput::Buttons::R);
79 | if is_stick_pressed || is_triggers_pressed {
80 | let avg_ping = match player_net_info
81 | .net_diagnostics
82 | .lock()
83 | .unwrap()
84 | .get_avg_ping()
85 | {
86 | Some(p) => format!("{}ms", p),
87 | None => String::from("???"),
88 | };
89 | player_panel_name
90 | .as_textbox()
91 | .set_text_string(&format!("{}", avg_ping));
92 | } else {
93 | player_panel_name.as_textbox().set_text_string(&format!(
94 | "{}, {}",
95 | player_net_info.framerate_config.to_string(),
96 | player_net_info.delay.to_string()
97 | ));
98 | }
99 | }
100 | false => {
101 | player_panel_name
102 | .as_textbox()
103 | .set_text_string(&format!("P{}", player_index + 1));
104 | }
105 | }
106 | }
107 | }
108 | call_original!(arg);
109 | }
110 |
111 | #[skyline::main(name = "local-latency-slider")]
112 | pub fn main() {
113 | if !utils::is_yuzu_emulator() {
114 | skyline::error::show_error(
115 | 1,
116 | "Compatibility Error",
117 | "Local Latency Slider mod is currently only supported on yuzu emulator",
118 | );
119 | return;
120 | }
121 |
122 | framerate::install();
123 | ldn::install();
124 | skyline::install_hook!(update_css);
125 | }
126 |
--------------------------------------------------------------------------------
/src/utils/mod.rs:
--------------------------------------------------------------------------------
1 | use skyline::nn::os::Tick;
2 | use skyline::nn::ui2d::{Pane, TextBox};
3 | use std::time::{Duration, Instant};
4 |
5 | extern "C" {
6 | #[link_name = "\u{1}_ZN2nn2os22GetSystemTickFrequencyEv"]
7 | pub fn get_tick_freq() -> u64;
8 | }
9 |
10 | #[inline]
11 | pub fn duration_since_tick(tick: Tick) -> Duration {
12 | let elapsed_ticks = unsafe { skyline::nn::os::GetSystemTick() } - tick;
13 | Duration::from_secs_f64(elapsed_ticks as f64 / unsafe { get_tick_freq() } as f64)
14 | }
15 |
16 | pub fn is_yuzu_emulator() -> bool {
17 | unsafe {
18 | let base_address = skyline::hooks::getRegionAddress(skyline::hooks::Region::Text) as u64;
19 | return base_address == 0x80004000;
20 | }
21 | }
22 |
23 | pub fn poll_buttons(buttons: &[ninput::Buttons]) -> ninput::Buttons {
24 | static mut PRESS_COOLDOWN: Option = None;
25 | for button in buttons {
26 | let is_pressed = ninput::any::is_press(*button);
27 | unsafe {
28 | match (PRESS_COOLDOWN, is_pressed) {
29 | (Some(t), _) => {
30 | if t.elapsed().as_millis() > 167 {
31 | PRESS_COOLDOWN = None;
32 | }
33 | }
34 | (None, true) => {
35 | PRESS_COOLDOWN = Some(Instant::now());
36 | return *button;
37 | }
38 | _ => PRESS_COOLDOWN = None,
39 | }
40 | }
41 | }
42 | return ninput::Buttons::empty();
43 | }
44 |
45 | #[skyline::from_offset(0x37a1f10)]
46 | fn set_text_string(pane: *mut Pane, string: *const u8);
47 |
48 | #[skyline::from_offset(0x59970)]
49 | fn find_pane_by_name_recursive(pane: *const Pane, s: *const u8) -> *mut Pane;
50 |
51 | pub trait PaneExt {
52 | fn next(&self) -> Option<&mut Pane>;
53 | fn prev(&self) -> Option<&mut Pane>;
54 | fn parent(&self) -> Option<&mut Pane>;
55 | fn children(&self) -> Option<&mut Pane>;
56 | fn traverse_forward(&self, steps: usize) -> Option<&mut Pane>;
57 | fn traverse_backward(&self, steps: usize) -> Option<&mut Pane>;
58 | fn get_child(&self, name: &str, recursive: bool) -> Option<&mut Pane>;
59 | }
60 |
61 | impl PaneExt for Pane {
62 | fn next(&self) -> Option<&mut Pane> {
63 | unsafe {
64 | let node = self.link.next;
65 | let pane = ((node as *mut u64).sub(1)) as *mut Pane;
66 | match pane.is_null()
67 | || ((*pane).children_list.next.is_null() && (*pane).children_list.prev.is_null())
68 | {
69 | true => None,
70 | false => Some(&mut *pane),
71 | }
72 | }
73 | }
74 |
75 | fn prev(&self) -> Option<&mut Pane> {
76 | unsafe {
77 | let node = self.link.prev;
78 | let pane = ((node as *mut u64).sub(1)) as *mut Pane;
79 | match pane.is_null()
80 | || ((*pane).children_list.next.is_null() && (*pane).children_list.prev.is_null())
81 | {
82 | true => None,
83 | false => Some(&mut *pane),
84 | }
85 | }
86 | }
87 |
88 | fn parent(&self) -> Option<&mut Pane> {
89 | unsafe {
90 | let p = self.parent;
91 | match p.is_null() {
92 | true => None,
93 | false => Some(&mut *p),
94 | }
95 | }
96 | }
97 |
98 | fn children(&self) -> Option<&mut Pane> {
99 | unsafe {
100 | let node = self.children_list.next;
101 | let pane = ((node as *mut u64).sub(1)) as *mut Pane;
102 | match pane.is_null()
103 | || ((*pane).children_list.next.is_null() && (*pane).children_list.prev.is_null())
104 | {
105 | true => None,
106 | false => Some(&mut *pane),
107 | }
108 | }
109 | }
110 |
111 | fn traverse_forward(&self, steps: usize) -> Option<&mut Pane> {
112 | let mut i = 0;
113 | let mut current = self.next();
114 | while let Some(p) = current {
115 | i += 1;
116 | if i == steps {
117 | return Some(p);
118 | }
119 | current = p.next();
120 | }
121 | return None;
122 | }
123 |
124 | fn traverse_backward(&self, steps: usize) -> Option<&mut Pane> {
125 | let mut i = 0;
126 | let mut current = self.prev();
127 | while let Some(p) = current {
128 | i += 1;
129 | if i == steps {
130 | return Some(p);
131 | }
132 | current = p.prev();
133 | }
134 | return None;
135 | }
136 |
137 | fn get_child(&self, name: &str, recursive: bool) -> Option<&mut Pane> {
138 | if recursive {
139 | let child = unsafe {
140 | find_pane_by_name_recursive(self as *const Pane, format!("{}\0", name).as_ptr())
141 | };
142 | match child.is_null() {
143 | true => return None,
144 | false => return unsafe { Some(&mut *child) },
145 | }
146 | }
147 |
148 | let mut current = self.children();
149 | while let Some(p) = current {
150 | if p.get_name() == name {
151 | return Some(p);
152 | }
153 | current = p.next();
154 | }
155 | return None;
156 | }
157 | }
158 |
159 | pub trait TextBoxExt {
160 | fn set_text_string(&mut self, text: &str);
161 | }
162 |
163 | impl TextBoxExt for TextBox {
164 | fn set_text_string(&mut self, text: &str) {
165 | unsafe {
166 | set_text_string(
167 | self as *mut TextBox as *mut Pane,
168 | format!("{}\0", text).as_ptr(),
169 | );
170 | }
171 | }
172 | }
173 |
--------------------------------------------------------------------------------