Mass Battle Frameworkv1.20.0

处理器该切多细 How Fine Should a Processor Be?

QUERY & FILTERING

细切与合并的取舍,以及那个每次遍历都要付的固定代价 · 2026-11-21Fine-grained versus consolidated, and the fixed cost every pass pays · 2026-11-21

系列这些文章写给人和他的 agent 一起看。这套文档怎么读 →SeriesThese posts are for you and your agent. How to read these docs →

两种切法 Two Ways to Cut It

"一个处理器只做一件事",听着无懈可击:职责单一、查询更窄、分支更少。不少公开分享也是这么教的,把逻辑切碎,一条规则一个处理器。

"One processor, one job" sounds airtight: single responsibility, narrower queries, fewer branches. A lot of public advice teaches exactly that, cut the logic up and give every rule its own processor.

我们没这么干。MassBattle 的处理器切得很粗,整套运行时只有十几个,最大那个一个人扛完整条移动栈。算术摆在那儿:三笔账,粗切都更划算,第三笔最关键,细切要生效就得频繁改 tag,而频繁改 tag 会让帧时间发抖。

We did not. MassBattle's processors are cut coarsely: the runtime has a dozen or so, and the largest one carries the whole movement stack alone. The arithmetic favours it. Three bills came out cheaper this way, and the third is the one that decided it: fine cuts only pay off if you keep changing tags, and changing tags makes frame time shudder.

它实际长什么样 What It Actually Looks Like

先给数字,免得读起来像凭感觉。运行时的处理器一共十几支,合计四万两千行左右:

Numbers first, so this does not read like a feeling. The runtime has a dozen-odd processors totalling roughly forty-two thousand lines:

处理器Processor规模Size它一个人管什么What it covers on its own
移动处理器Movement 约 9,800 行(定点版另有一份约 9,600 行)about 9,800 lines (the fixed-point twin is another ~9,600) 意图、交通规则、避障、寻路推进、倾斜与着地、碰撞结算,四层移动全在里面Intent, traffic rules, avoidance, path following, tilt and grounding, collision: all four movement layers in one place
渲染处理器Render 约 5,000 行about 5,000 lines 动画状态推进、取槽、批次打包、材质通道、LOD 选择Animation state, slot selection, batch packing, material channels, LOD choice
反应处理器Reaction 约 1,200 行about 1,200 lines 子类型/队伍标签交换、控制模式同步成旗标、寿命与掉出边界死亡、伤害结果处理、血条计时Subtype/team tag swapping, control-mode-to-flag sync, lifespan and KillZ death, damage-result processing, health-bar timers

反应处理器最说明问题:那五件事在逻辑上互不相干,可它们要的是同一批实体、同一批片段、同一次遍历。拆成五个处理器,同一批实体就得被数五遍。

The reaction processor is the clearest case: those five jobs have nothing to do with each other logically, but they need the same entities, the same fragments, the same single pass. Split them into five processors and the same entities get visited five times.

理由一:每次遍历都有固定代价 Reason One: Every Pass Has a Fixed Cost

这条更硬。遍历本身不免费:走到每个块、取每个实体的位置、把片段指针准备好,哪怕你一行逻辑都不做,也得走完。profiling 里看到的量级是五万到十万个实体,空走一遍大约一百二十到两百微秒。

This one is harder. Traversal is not free: touching every chunk, reading every entity's position, setting up fragment pointers. The pass costs the same even when the logic does nothing. Profiling puts an empty pass over fifty to a hundred thousand entities at 120–200 microseconds.

算一下就明白它为什么重要:十个"什么都不干"的处理器就是十趟遍历,大约一到两毫秒;十万单位,每个处理器再取几个片段,很容易到三四毫秒。这份固定开销每帧都在,它不看你的玩法多复杂,只看你切了几刀。

Do the arithmetic: ten processors that "do nothing" are ten passes, roughly one to two milliseconds. At a hundred thousand units, with a few fragments fetched per processor, it climbs to three to four milliseconds without much effort. That fixed cost comes every frame. It does not follow how complex your gameplay is; it follows how many pieces you cut the pass into.

取舍就很简单:这一趟反正要走完,能顺手做完的事就一起做完。多出来的分支是几十条判断;多出来的一趟遍历是十万个实体的簿记。后者贵得多。

The trade-off is simple: the pass is being paid for anyway, so finish everything you can inside it. The extra branches are a few dozen comparisons. The extra pass is bookkeeping over a hundred thousand entities, and that costs far more.

理由二:切细之后,项目会先崩在管理上 Reason Two: Fine Grains Break the Project Before the Frame

"分支少一点更快"这话没错,可它只是性能的一部分。我们还量到另一件事:分支多不等于慢。这套处理器里塞着大量条件判断,照样跑十万单位六十帧。先出问题的是另一头:管理。

"Fewer branches is faster" is true, but it is one part of performance. The other thing we measured: more branches does not mean slow. These processors are stuffed with conditionals and still hold a hundred thousand units at sixty frames. What breaks first is on the other end: manageability.

演示里切细很优雅,功能少,分支也少。做成游戏就不一样了,各种模式、各种条件都得兜住:每个变化单独成一个处理器,处理器数量会随功能组合爆炸,它们的顺序、依赖、谁在谁之前跑,也会变成没人敢动的东西。

Fine grains look elegant in a demo: few features, few branches. A game is different; you have to hold every mode and every condition. Give each variation its own processor and the count explodes with feature combinations, and their order, their dependencies, who runs before whom, become things nobody dares touch.

同类逻辑放在一起还有个好处:它读起来是一条流程。一个单位从意图到落地,在一处就能读完,不用"这段在处理器 A、那段在处理器 G、第三步在处理器 R"。对着一段连续的代码调手感,比对着五个文件的调用关系调快得多。

Keeping like logic together has another benefit: it reads as one flow. A unit's movement from intent to grounding can be read in one place, with no "this part is in processor A, that part in G, step three in R". Tuning feel against one contiguous stretch of code beats tracing five files.

理由三:细切要配 tag,而 tag 换来换去帧率就抖 Reason Three: Fine Cuts Need Tags, and Tag Churn Shudders

这条最容易忽略,也是我们真正放弃细切的原因。细切的处理器想真省下工作,就得把"这一趟跟我无关的实体"挡在查询外面,而这只能靠tag:被击中有个"正在被击中"的 tag,每种行为一个自己的 tag。行为换一次,tag 就得换一次。

This is the one people overlook, and it is why we actually gave up fine cuts. For a finely cut processor to save real work, it has to keep the entities that do not concern it out of its query, and that only works through tags: a "being hit" tag for hits, one tag per behaviour. Change behaviour once and a tag changes once.

问题是每次 tag 变更都是一次原型迁移。实体要从一个原型搬到另一个,把它在块里的东西整块带过去。我们的一个单位在块里占到 KB 量级,其中相当一部分片段不可平凡拷贝(带容器,要自己定义比较和赋值),迁移只能逐元素拷贝构造。这样的搬家一帧里来几千回,就是肉眼可见的卡顿。

The trouble is that every tag change is an archetype migration. The entity moves from one archetype to another, carrying everything it holds in the chunk. One of our units takes up kilobytes in a chunk, and a fair share of its fragments are not trivially copyable (they own containers, with their own comparison and assignment), so the migration is an element-wise copy construction. Several thousand of those in one frame is a hitch you can see.

更糟的是它偏偏发生在最不该发生的时候:战斗越激烈,行为切换越频繁、挨打的单位越多,而这正是你最需要画面稳的时刻。所以这里盯的是抖动。

Worse, it lands exactly when it should not: the heavier the fight, the more behaviour switches and the more units taking hits, which is precisely when you need the picture steady. What matters here is jitter.

"稳"比"高"值钱:稳定的 30 帧,看着比忽高忽低的 60 帧更顺。你平时看的视频基本都是 30 帧,没人觉得卡;同样的 30 帧加一点波动,立刻就觉得卡。人眼对帧时间的变化,比对那个数值本身敏感得多。

Steady is worth more than high: a stable 30 looks smoother than a 60 that jumps around. The video you watch is mostly 30 and nobody calls it choppy. Add a little variance to that same 30 and it reads as stutter straight away. The eye is far more sensitive to change in frame time than to the number.

这条路我们走过。早期的开源版本就是增删 tag,后来更激进,直接增删片段。激烈场面里帧率不稳,平均数字看着还行,手感很差。最后的选择是多用 flag、少用 tag。

We have been down that road. An early open-source version added and removed tags, then went further and added and removed fragments outright. Frame rate went unstable in heavy fights; the average number looked fine and the feel was poor. The final choice was more flags, fewer tags.

代价得认:状态不进 tag,查询就没法按状态分桶,一个处理器往往要把所有单位走一遍,哪怕只有一部分跟它有关。所以"粗处理器"和"少用 tag"是一套配套的决定,拆不开:放弃了用 tag 换剪枝,就得靠"一趟里多做几件事"把钱赚回来。

The cost has to be owned: with states kept out of tags, queries cannot be bucketed by state, so a processor usually walks every unit, including the ones it does not care about. That makes "coarse processors" and "few tags" one coupled decision, not two separate trade-offs. Give up pruning by tag and you have to earn it back by doing several jobs in one pass.

换来的是开销更好预测:遍历遍数固定在几趟,不随战斗激烈程度变化,慢了,但稳。人越多,这么切越划算。

The payoff is predictability: the pass count is a fixed few and does not grow with the intensity of the fight. Slower, but steady. That trade looks best at high unit counts.

理由四:一趟并行波,而不是六次 Reason Four: One Parallel Wave, Not Six

还有一条,要真正多线程跑起来才看得见。一个查询不必只匹配一种原型:把字段声明成可选(有就读,没有也算匹配),一次查询就能跨过好几种原型,单位、减益、特效、投射物、掉落、宿主全进同一张候选表。同类的活就能攒到一趟里做。

One more reason only appears once you actually run multi-threaded. A query does not have to match one archetype: declare the fields as optional (read them if present, still match if not) and a single query spans several archetypes. Agents, debuffs, effects, projectiles, loot, hosts, all in one candidate table. Similar work can then be gathered into one pass.

拆成几个查询,各走各的并行波,要付两笔账:

Split into several queries, each with its own parallel wave, and you pay twice:

一、负载不均。不同类别的单位,每个要做的活差别很大。分开跑,一波里大部分线程早干完了,只剩一小撮还在算,profiler 上看得清清楚楚:一条线程很晚收工,其余在空等。合在一起,快活慢活混在一锅,每个线程的总量反而接近,收工时间也接近。

One: uneven load. Units of different categories cost very different amounts of work. Run them separately and in any given wave most threads finish early while a few are still crunching. The profiler shows it plainly: one thread finishes late, the rest idle. Run them together and cheap work mixes with expensive work, so each thread's total comes out close, and so does the finish time.

二、每一波都有调度和屏障开销。并行不免费:分发任务、等所有线程到齐再往下走,都要付钱。更亏的是小类别的波尾,活太少,十个线程只喂得饱六个,剩下四个空转。波次越多,浪费越多。

Two: every wave pays dispatch and barrier cost. Parallelism is not free. Handing out tasks and waiting for every thread to arrive costs something. Worse is the tail of a small category's wave: not enough work, so ten threads feed only six and four spin idle. More waves, more of that waste.

我们的网络处理器就是照这个改的。原来六个分类各走一次并行波,现在合成一个统一查询:所有锁步实体都带的那个总标签做锚点,再用"属于哪个大类"的标签做门限,其余片段全部声明为可选,一次波覆盖全部大类。代码里把取舍写得挺直白,旧六个查询就是"六次顺序并行波,每波都有调度与屏障开销,而小类别让 worker 在波尾闲置"。

Our network processor is the worked example. It used to run six per-category waves; now it runs one unified query, anchored on the tag every lockstep entity carries for life, gated on the "which main category" tags, with every other fragment declared optional. One wave covers all categories. The trade-off is written plainly in the code: the old six queries meant "six sequential parallel waves, per-wave dispatch and barrier overhead, and small categories leaving workers idle at each wave tail".

合并之后多出一件事:进来的一块是哪一类,得判一下。这一步不需要每个实体判一次。块本来就是同质的,一整块属于同一个原型,所以大类分支每块只选一次,块里所有实体走同一条路。

Merging adds one step: work out which category a chunk belongs to. That step does not happen per entity. A chunk is homogeneous, all of one archetype, so the category branch is chosen once per chunk and every entity in it follows the same path.

所以判"合还是分",多问一句:这几类活各走各的并行波,会不会让线程在波尾空等?会,就攒到一趟里。几类成本差不多,或者数量都小到填不满线程,合与分差别不大,按好读来选就行。

So "merge or split" gets one more question: if these categories each ran their own parallel wave, would threads idle at the tail? If yes, gather them into one pass. If the costs are similar, or everything is too small to fill the threads, it hardly matters either way; pick whichever reads better.

合并的代价,和我们怎么兜 What Consolidation Costs, and How We Hold It

合并不是白拿,最直接的代价是分支和代码体积:一个处理器里躺着很多"这一帧用不上"的路径。我们的办法是让这些路径尽量便宜:

Consolidation is not free. The most direct cost is branches and code size: one processor holds many paths this frame will not touch. We keep those paths cheap:

一、按块早退。判断放在块一级:一整块都不需要这段逻辑,直接跳过整块,不逐个实体判。二、热数据内联,冷数据外置。每帧都要读的字段放在片段里,事件型的数据用数组挂在共享片段上。三、阶段编排固定。顺序写死成若干阶段,每个阶段结束冲刷一次,谁先谁后有据可查,不靠添加顺序碰运气。四、不重复取片段。同一趟里取过一次的指针,一路往下传。

One: early-out at the block level. The test sits a level up: when a whole chunk does not need this piece of logic, skip the chunk instead of testing each entity. Two: hot data inline, cold data outside. Fields read every frame live in the fragment; event-shaped data hangs off a shared fragment as arrays. Three: a fixed stage order. The order is a written-down sequence of stages, each flushing at its end, so precedence is on paper instead of an accident of registration order. Four: no repeated fetching. A pointer taken once in a pass is passed down.

什么时候仍然该切 When Splitting Is Still Right

粗切不是教条。下面几种情况,切开的收益是实打实的:

Coarse is not a rule to follow blindly. In these cases splitting pays off for real:

查询集合不同。两段逻辑要的根本不是同一批实体(一个是全部单位,另一个只有投射物),合在一起就得每帧问"这个实体该不该走这条";分开之后,各自那条查询直接整块跳过绝大多数实体。还有:需要不同片段集合、需要跑在不同阶段、或者其中一段能独立并行的,切开都比合着便宜。

Different query sets. If the two pieces work on different entities altogether (one covers all units, the other only projectiles), merging forces a per-entity "should this one take this path" test. Split, and each query skips whole chunks for almost everyone. Also: different fragment sets, a different stage in the frame, or one piece that can run in parallel on its own. There splitting is cheaper.

MassBattle 就是这么切的:按"实体集合 + 片段集合"切,不按"逻辑上是不是一件事"切。同集合、同片段、同阶段的放一处;集合不同的坚决分开。分开的那份能整块跳过,合起来的那份只能逐个判断。

That is how MassBattle cuts: by entity set and fragment set, not by "is this one logical job". Same set, same fragments, same stage, one place. Different sets, split: the split piece skips whole chunks, the merged one tests entity by entity.

判据 The Test

判断该不该新开一个处理器,问三件事:① 它要遍历的实体集合,和已有处理器是同一批吗?② 它需要上次遍历已经付过的那笔固定开销吗?③ 和现有的活跑在同一条并行波里,会不会让线程在波尾空等?前两个都答"是",就塞进去;②答"否",就老实开新的,因为分不出来的时候,付两次遍历的钱比多写几十行判断贵得多。要是你发现自己在为了让它"少看一点实体"去加状态 tag,基本可以停手:你是在拿帧时间稳定性换平均帧率,通常不划算。

To decide whether a new processor is warranted, ask three things: ① does it walk the same entity set an existing processor already walks? ② does it need the fixed cost that pass already paid? ③ sharing one parallel wave with the existing work, would threads idle at the tail? If the first two are yes, put it inside an existing one. If ② is no, open a new one: when you cannot share the pass, paying for traversal twice costs far more than a few dozen extra comparisons. And if you catch yourself adding a state tag so the new piece can "see fewer entities", stop. You are trading frame-time stability for average frame rate, and that trade usually loses.

Leroy Works · Mass Battle Framework 作者
联系:Discord · QQ 群 916358710 · Fab · 全部联系方式

Leroy Works — author of Mass Battle Framework
Contact: Discord · QQ group 916358710 · Fab · all channels